4823: Fix tests broken by prior refactoring. Renamed 'api.py' to 'apisetup.py'
[arvados.git] / sdk / python / tests / test_collections.py
1 # usage example:
2 #
3 # ARVADOS_API_TOKEN=abc ARVADOS_API_HOST=arvados.local python -m unittest discover
4
5 import arvados
6 import copy
7 import hashlib
8 import mock
9 import os
10 import pprint
11 import re
12 import tempfile
13 import unittest
14
15 import run_test_server
16 from arvados._ranges import Range, LocatorAndRange
17 from arvados.collection import Collection, CollectionReader
18 from arvados.arvfile import SYNC_EXPLICIT
19 import arvados_testutil as tutil
20
21 class TestResumableWriter(arvados.ResumableCollectionWriter):
22     KEEP_BLOCK_SIZE = 1024  # PUT to Keep every 1K.
23
24     def current_state(self):
25         return self.dump_state(copy.deepcopy)
26
27
28 class ArvadosCollectionsTest(run_test_server.TestCaseWithServers,
29                              tutil.ArvadosBaseTestCase):
30     MAIN_SERVER = {}
31
32     @classmethod
33     def setUpClass(cls):
34         super(ArvadosCollectionsTest, cls).setUpClass()
35         run_test_server.authorize_with('active')
36         cls.api_client = arvados.api('v1')
37         cls.keep_client = arvados.KeepClient(api_client=cls.api_client,
38                                              local_store=cls.local_store)
39
40     def write_foo_bar_baz(self):
41         cw = arvados.CollectionWriter(self.api_client)
42         self.assertEqual(cw.current_stream_name(), '.',
43                          'current_stream_name() should be "." now')
44         cw.set_current_file_name('foo.txt')
45         cw.write('foo')
46         self.assertEqual(cw.current_file_name(), 'foo.txt',
47                          'current_file_name() should be foo.txt now')
48         cw.start_new_file('bar.txt')
49         cw.write('bar')
50         cw.start_new_stream('baz')
51         cw.write('baz')
52         cw.set_current_file_name('baz.txt')
53         self.assertEqual(cw.manifest_text(),
54                          ". 3858f62230ac3c915f300c664312c63f+6 0:3:foo.txt 3:3:bar.txt\n" +
55                          "./baz 73feffa4b7f6bb68e44cf984c85f6e88+3 0:3:baz.txt\n",
56                          "wrong manifest: got {}".format(cw.manifest_text()))
57         cw.finish()
58         return cw.portable_data_hash()
59
60     def test_keep_local_store(self):
61         self.assertEqual(self.keep_client.put('foo'), 'acbd18db4cc2f85cedef654fccc4a4d8+3', 'wrong md5 hash from Keep.put')
62         self.assertEqual(self.keep_client.get('acbd18db4cc2f85cedef654fccc4a4d8+3'), 'foo', 'wrong data from Keep.get')
63
64     def test_local_collection_writer(self):
65         self.assertEqual(self.write_foo_bar_baz(),
66                          '23ca013983d6239e98931cc779e68426+114',
67                          'wrong locator hash: ' + self.write_foo_bar_baz())
68
69     def test_local_collection_reader(self):
70         foobarbaz = self.write_foo_bar_baz()
71         cr = arvados.CollectionReader(
72             foobarbaz + '+Xzizzle', self.api_client)
73         got = []
74         for s in cr.all_streams():
75             for f in s.all_files():
76                 got += [[f.size(), f.stream_name(), f.name(), f.read(2**26)]]
77         expected = [[3, '.', 'foo.txt', 'foo'],
78                     [3, '.', 'bar.txt', 'bar'],
79                     [3, './baz', 'baz.txt', 'baz']]
80         self.assertEqual(got,
81                          expected)
82         stream0 = cr.all_streams()[0]
83         self.assertEqual(stream0.readfrom(0, 0),
84                          '',
85                          'reading zero bytes should have returned empty string')
86         self.assertEqual(stream0.readfrom(0, 2**26),
87                          'foobar',
88                          'reading entire stream failed')
89         self.assertEqual(stream0.readfrom(2**26, 0),
90                          '',
91                          'reading zero bytes should have returned empty string')
92
93     def _test_subset(self, collection, expected):
94         cr = arvados.CollectionReader(collection, self.api_client)
95         for s in cr.all_streams():
96             for ex in expected:
97                 if ex[0] == s:
98                     f = s.files()[ex[2]]
99                     got = [f.size(), f.stream_name(), f.name(), "".join(f.readall(2**26))]
100                     self.assertEqual(got,
101                                      ex,
102                                      'all_files|as_manifest did not preserve manifest contents: got %s expected %s' % (got, ex))
103
104     def test_collection_manifest_subset(self):
105         foobarbaz = self.write_foo_bar_baz()
106         self._test_subset(foobarbaz,
107                           [[3, '.',     'bar.txt', 'bar'],
108                            [3, '.',     'foo.txt', 'foo'],
109                            [3, './baz', 'baz.txt', 'baz']])
110         self._test_subset((". %s %s 0:3:foo.txt 3:3:bar.txt\n" %
111                            (self.keep_client.put("foo"),
112                             self.keep_client.put("bar"))),
113                           [[3, '.', 'bar.txt', 'bar'],
114                            [3, '.', 'foo.txt', 'foo']])
115         self._test_subset((". %s %s 0:2:fo.txt 2:4:obar.txt\n" %
116                            (self.keep_client.put("foo"),
117                             self.keep_client.put("bar"))),
118                           [[2, '.', 'fo.txt', 'fo'],
119                            [4, '.', 'obar.txt', 'obar']])
120         self._test_subset((". %s %s 0:2:fo.txt 2:0:zero.txt 2:2:ob.txt 4:2:ar.txt\n" %
121                            (self.keep_client.put("foo"),
122                             self.keep_client.put("bar"))),
123                           [[2, '.', 'ar.txt', 'ar'],
124                            [2, '.', 'fo.txt', 'fo'],
125                            [2, '.', 'ob.txt', 'ob'],
126                            [0, '.', 'zero.txt', '']])
127
128     def test_collection_empty_file(self):
129         cw = arvados.CollectionWriter(self.api_client)
130         cw.start_new_file('zero.txt')
131         cw.write('')
132
133         self.assertEqual(cw.manifest_text(), ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:zero.txt\n")
134         self.check_manifest_file_sizes(cw.manifest_text(), [0])
135         cw = arvados.CollectionWriter(self.api_client)
136         cw.start_new_file('zero.txt')
137         cw.write('')
138         cw.start_new_file('one.txt')
139         cw.write('1')
140         cw.start_new_stream('foo')
141         cw.start_new_file('zero.txt')
142         cw.write('')
143         self.check_manifest_file_sizes(cw.manifest_text(), [0,1,0])
144
145     def test_no_implicit_normalize(self):
146         cw = arvados.CollectionWriter(self.api_client)
147         cw.start_new_file('b')
148         cw.write('b')
149         cw.start_new_file('a')
150         cw.write('')
151         self.check_manifest_file_sizes(cw.manifest_text(), [1,0])
152         self.check_manifest_file_sizes(
153             arvados.CollectionReader(
154                 cw.manifest_text()).manifest_text(normalize=True),
155             [0,1])
156
157     def check_manifest_file_sizes(self, manifest_text, expect_sizes):
158         cr = arvados.CollectionReader(manifest_text, self.api_client)
159         got_sizes = []
160         for f in cr.all_files():
161             got_sizes += [f.size()]
162         self.assertEqual(got_sizes, expect_sizes, "got wrong file sizes %s, expected %s" % (got_sizes, expect_sizes))
163
164     def test_normalized_collection(self):
165         m1 = """. 5348b82a029fd9e971a811ce1f71360b+43 0:43:md5sum.txt
166 . 085c37f02916da1cad16f93c54d899b7+41 0:41:md5sum.txt
167 . 8b22da26f9f433dea0a10e5ec66d73ba+43 0:43:md5sum.txt
168 """
169         self.assertEqual(arvados.CollectionReader(m1, self.api_client).manifest_text(normalize=True),
170                          """. 5348b82a029fd9e971a811ce1f71360b+43 085c37f02916da1cad16f93c54d899b7+41 8b22da26f9f433dea0a10e5ec66d73ba+43 0:127:md5sum.txt
171 """)
172
173         m2 = """. 204e43b8a1185621ca55a94839582e6f+67108864 b9677abbac956bd3e86b1deb28dfac03+67108864 fc15aff2a762b13f521baf042140acec+67108864 323d2a3ce20370c4ca1d3462a344f8fd+25885655 0:227212247:var-GS000016015-ASM.tsv.bz2
174 """
175         self.assertEqual(arvados.CollectionReader(m2, self.api_client).manifest_text(normalize=True), m2)
176
177         m3 = """. 5348b82a029fd9e971a811ce1f71360b+43 3:40:md5sum.txt
178 . 085c37f02916da1cad16f93c54d899b7+41 0:41:md5sum.txt
179 . 8b22da26f9f433dea0a10e5ec66d73ba+43 0:43:md5sum.txt
180 """
181         self.assertEqual(arvados.CollectionReader(m3, self.api_client).manifest_text(normalize=True),
182                          """. 5348b82a029fd9e971a811ce1f71360b+43 085c37f02916da1cad16f93c54d899b7+41 8b22da26f9f433dea0a10e5ec66d73ba+43 3:124:md5sum.txt
183 """)
184
185         m4 = """. 204e43b8a1185621ca55a94839582e6f+67108864 0:3:foo/bar
186 ./zzz 204e43b8a1185621ca55a94839582e6f+67108864 0:999:zzz
187 ./foo 323d2a3ce20370c4ca1d3462a344f8fd+25885655 0:3:bar
188 """
189         self.assertEqual(arvados.CollectionReader(m4, self.api_client).manifest_text(normalize=True),
190                          """./foo 204e43b8a1185621ca55a94839582e6f+67108864 323d2a3ce20370c4ca1d3462a344f8fd+25885655 0:3:bar 67108864:3:bar
191 ./zzz 204e43b8a1185621ca55a94839582e6f+67108864 0:999:zzz
192 """)
193
194         m5 = """. 204e43b8a1185621ca55a94839582e6f+67108864 0:3:foo/bar
195 ./zzz 204e43b8a1185621ca55a94839582e6f+67108864 0:999:zzz
196 ./foo 204e43b8a1185621ca55a94839582e6f+67108864 3:3:bar
197 """
198         self.assertEqual(arvados.CollectionReader(m5, self.api_client).manifest_text(normalize=True),
199                          """./foo 204e43b8a1185621ca55a94839582e6f+67108864 0:6:bar
200 ./zzz 204e43b8a1185621ca55a94839582e6f+67108864 0:999:zzz
201 """)
202
203         with self.data_file('1000G_ref_manifest') as f6:
204             m6 = f6.read()
205             self.assertEqual(arvados.CollectionReader(m6, self.api_client).manifest_text(normalize=True), m6)
206
207         with self.data_file('jlake_manifest') as f7:
208             m7 = f7.read()
209             self.assertEqual(arvados.CollectionReader(m7, self.api_client).manifest_text(normalize=True), m7)
210
211         m8 = """./a\\040b\\040c 59ca0efa9f5633cb0371bbc0355478d8+13 0:13:hello\\040world.txt
212 """
213         self.assertEqual(arvados.CollectionReader(m8, self.api_client).manifest_text(normalize=True), m8)
214
215     def test_locators_and_ranges(self):
216         blocks2 = [Range('a', 0, 10),
217                    Range('b', 10, 10),
218                    Range('c', 20, 10),
219                    Range('d', 30, 10),
220                    Range('e', 40, 10),
221                    Range('f', 50, 10)]
222
223         self.assertEqual(arvados.locators_and_ranges(blocks2,  2,  2), [LocatorAndRange('a', 10, 2, 2)])
224         self.assertEqual(arvados.locators_and_ranges(blocks2, 12, 2), [LocatorAndRange('b', 10, 2, 2)])
225         self.assertEqual(arvados.locators_and_ranges(blocks2, 22, 2), [LocatorAndRange('c', 10, 2, 2)])
226         self.assertEqual(arvados.locators_and_ranges(blocks2, 32, 2), [LocatorAndRange('d', 10, 2, 2)])
227         self.assertEqual(arvados.locators_and_ranges(blocks2, 42, 2), [LocatorAndRange('e', 10, 2, 2)])
228         self.assertEqual(arvados.locators_and_ranges(blocks2, 52, 2), [LocatorAndRange('f', 10, 2, 2)])
229         self.assertEqual(arvados.locators_and_ranges(blocks2, 62, 2), [])
230         self.assertEqual(arvados.locators_and_ranges(blocks2, -2, 2), [])
231
232         self.assertEqual(arvados.locators_and_ranges(blocks2,  0,  2), [LocatorAndRange('a', 10, 0, 2)])
233         self.assertEqual(arvados.locators_and_ranges(blocks2, 10, 2), [LocatorAndRange('b', 10, 0, 2)])
234         self.assertEqual(arvados.locators_and_ranges(blocks2, 20, 2), [LocatorAndRange('c', 10, 0, 2)])
235         self.assertEqual(arvados.locators_and_ranges(blocks2, 30, 2), [LocatorAndRange('d', 10, 0, 2)])
236         self.assertEqual(arvados.locators_and_ranges(blocks2, 40, 2), [LocatorAndRange('e', 10, 0, 2)])
237         self.assertEqual(arvados.locators_and_ranges(blocks2, 50, 2), [LocatorAndRange('f', 10, 0, 2)])
238         self.assertEqual(arvados.locators_and_ranges(blocks2, 60, 2), [])
239         self.assertEqual(arvados.locators_and_ranges(blocks2, -2, 2), [])
240
241         self.assertEqual(arvados.locators_and_ranges(blocks2,  9,  2), [LocatorAndRange('a', 10, 9, 1), LocatorAndRange('b', 10, 0, 1)])
242         self.assertEqual(arvados.locators_and_ranges(blocks2, 19, 2), [LocatorAndRange('b', 10, 9, 1), LocatorAndRange('c', 10, 0, 1)])
243         self.assertEqual(arvados.locators_and_ranges(blocks2, 29, 2), [LocatorAndRange('c', 10, 9, 1), LocatorAndRange('d', 10, 0, 1)])
244         self.assertEqual(arvados.locators_and_ranges(blocks2, 39, 2), [LocatorAndRange('d', 10, 9, 1), LocatorAndRange('e', 10, 0, 1)])
245         self.assertEqual(arvados.locators_and_ranges(blocks2, 49, 2), [LocatorAndRange('e', 10, 9, 1), LocatorAndRange('f', 10, 0, 1)])
246         self.assertEqual(arvados.locators_and_ranges(blocks2, 59, 2), [LocatorAndRange('f', 10, 9, 1)])
247
248
249         blocks3 = [Range('a', 0, 10),
250                   Range('b', 10, 10),
251                   Range('c', 20, 10),
252                   Range('d', 30, 10),
253                   Range('e', 40, 10),
254                   Range('f', 50, 10),
255                    Range('g', 60, 10)]
256
257         self.assertEqual(arvados.locators_and_ranges(blocks3,  2,  2), [LocatorAndRange('a', 10, 2, 2)])
258         self.assertEqual(arvados.locators_and_ranges(blocks3, 12, 2), [LocatorAndRange('b', 10, 2, 2)])
259         self.assertEqual(arvados.locators_and_ranges(blocks3, 22, 2), [LocatorAndRange('c', 10, 2, 2)])
260         self.assertEqual(arvados.locators_and_ranges(blocks3, 32, 2), [LocatorAndRange('d', 10, 2, 2)])
261         self.assertEqual(arvados.locators_and_ranges(blocks3, 42, 2), [LocatorAndRange('e', 10, 2, 2)])
262         self.assertEqual(arvados.locators_and_ranges(blocks3, 52, 2), [LocatorAndRange('f', 10, 2, 2)])
263         self.assertEqual(arvados.locators_and_ranges(blocks3, 62, 2), [LocatorAndRange('g', 10, 2, 2)])
264
265
266         blocks = [Range('a', 0, 10),
267                   Range('b', 10, 15),
268                   Range('c', 25, 5)]
269         self.assertEqual(arvados.locators_and_ranges(blocks, 1, 0), [])
270         self.assertEqual(arvados.locators_and_ranges(blocks, 0, 5), [LocatorAndRange('a', 10, 0, 5)])
271         self.assertEqual(arvados.locators_and_ranges(blocks, 3, 5), [LocatorAndRange('a', 10, 3, 5)])
272         self.assertEqual(arvados.locators_and_ranges(blocks, 0, 10), [LocatorAndRange('a', 10, 0, 10)])
273
274         self.assertEqual(arvados.locators_and_ranges(blocks, 0, 11), [LocatorAndRange('a', 10, 0, 10),
275                                                                       LocatorAndRange('b', 15, 0, 1)])
276         self.assertEqual(arvados.locators_and_ranges(blocks, 1, 11), [LocatorAndRange('a', 10, 1, 9),
277                                                                       LocatorAndRange('b', 15, 0, 2)])
278         self.assertEqual(arvados.locators_and_ranges(blocks, 0, 25), [LocatorAndRange('a', 10, 0, 10),
279                                                                       LocatorAndRange('b', 15, 0, 15)])
280
281         self.assertEqual(arvados.locators_and_ranges(blocks, 0, 30), [LocatorAndRange('a', 10, 0, 10),
282                                                                       LocatorAndRange('b', 15, 0, 15),
283                                                                       LocatorAndRange('c', 5, 0, 5)])
284         self.assertEqual(arvados.locators_and_ranges(blocks, 1, 30), [LocatorAndRange('a', 10, 1, 9),
285                                                                       LocatorAndRange('b', 15, 0, 15),
286                                                                       LocatorAndRange('c', 5, 0, 5)])
287         self.assertEqual(arvados.locators_and_ranges(blocks, 0, 31), [LocatorAndRange('a', 10, 0, 10),
288                                                                       LocatorAndRange('b', 15, 0, 15),
289                                                                       LocatorAndRange('c', 5, 0, 5)])
290
291         self.assertEqual(arvados.locators_and_ranges(blocks, 15, 5), [LocatorAndRange('b', 15, 5, 5)])
292
293         self.assertEqual(arvados.locators_and_ranges(blocks, 8, 17), [LocatorAndRange('a', 10, 8, 2),
294                                                                       LocatorAndRange('b', 15, 0, 15)])
295
296         self.assertEqual(arvados.locators_and_ranges(blocks, 8, 20), [LocatorAndRange('a', 10, 8, 2),
297                                                                       LocatorAndRange('b', 15, 0, 15),
298                                                                       LocatorAndRange('c', 5, 0, 3)])
299
300         self.assertEqual(arvados.locators_and_ranges(blocks, 26, 2), [LocatorAndRange('c', 5, 1, 2)])
301
302         self.assertEqual(arvados.locators_and_ranges(blocks, 9, 15), [LocatorAndRange('a', 10, 9, 1),
303                                                                       LocatorAndRange('b', 15, 0, 14)])
304         self.assertEqual(arvados.locators_and_ranges(blocks, 10, 15), [LocatorAndRange('b', 15, 0, 15)])
305         self.assertEqual(arvados.locators_and_ranges(blocks, 11, 15), [LocatorAndRange('b', 15, 1, 14),
306                                                                        LocatorAndRange('c', 5, 0, 1)])
307
308     class MockKeep(object):
309         def __init__(self, content, num_retries=0):
310             self.content = content
311
312         def get(self, locator, num_retries=0):
313             return self.content[locator]
314
315     def test_stream_reader(self):
316         keepblocks = {'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+10': 'abcdefghij',
317                       'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb+15': 'klmnopqrstuvwxy',
318                       'cccccccccccccccccccccccccccccccc+5': 'z0123'}
319         mk = self.MockKeep(keepblocks)
320
321         sr = arvados.StreamReader([".", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+10", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb+15", "cccccccccccccccccccccccccccccccc+5", "0:30:foo"], mk)
322
323         content = 'abcdefghijklmnopqrstuvwxyz0123456789'
324
325         self.assertEqual(sr.readfrom(0, 30), content[0:30])
326         self.assertEqual(sr.readfrom(2, 30), content[2:30])
327
328         self.assertEqual(sr.readfrom(2, 8), content[2:10])
329         self.assertEqual(sr.readfrom(0, 10), content[0:10])
330
331         self.assertEqual(sr.readfrom(0, 5), content[0:5])
332         self.assertEqual(sr.readfrom(5, 5), content[5:10])
333         self.assertEqual(sr.readfrom(10, 5), content[10:15])
334         self.assertEqual(sr.readfrom(15, 5), content[15:20])
335         self.assertEqual(sr.readfrom(20, 5), content[20:25])
336         self.assertEqual(sr.readfrom(25, 5), content[25:30])
337         self.assertEqual(sr.readfrom(30, 5), '')
338
339     def test_extract_file(self):
340         m1 = """. 5348b82a029fd9e971a811ce1f71360b+43 0:43:md5sum.txt
341 . 085c37f02916da1cad16f93c54d899b7+41 0:41:md6sum.txt
342 . 8b22da26f9f433dea0a10e5ec66d73ba+43 0:43:md7sum.txt
343 . 085c37f02916da1cad16f93c54d899b7+41 5348b82a029fd9e971a811ce1f71360b+43 8b22da26f9f433dea0a10e5ec66d73ba+43 47:80:md8sum.txt
344 . 085c37f02916da1cad16f93c54d899b7+41 5348b82a029fd9e971a811ce1f71360b+43 8b22da26f9f433dea0a10e5ec66d73ba+43 40:80:md9sum.txt
345 """
346
347         m2 = arvados.CollectionReader(m1, self.api_client).manifest_text(normalize=True)
348
349         self.assertEqual(m2,
350                          ". 5348b82a029fd9e971a811ce1f71360b+43 085c37f02916da1cad16f93c54d899b7+41 8b22da26f9f433dea0a10e5ec66d73ba+43 0:43:md5sum.txt 43:41:md6sum.txt 84:43:md7sum.txt 6:37:md8sum.txt 84:43:md8sum.txt 83:1:md9sum.txt 0:43:md9sum.txt 84:36:md9sum.txt\n")
351         files = arvados.CollectionReader(
352             m2, self.api_client).all_streams()[0].files()
353
354         self.assertEqual(files['md5sum.txt'].as_manifest(),
355                          ". 5348b82a029fd9e971a811ce1f71360b+43 0:43:md5sum.txt\n")
356         self.assertEqual(files['md6sum.txt'].as_manifest(),
357                          ". 085c37f02916da1cad16f93c54d899b7+41 0:41:md6sum.txt\n")
358         self.assertEqual(files['md7sum.txt'].as_manifest(),
359                          ". 8b22da26f9f433dea0a10e5ec66d73ba+43 0:43:md7sum.txt\n")
360         self.assertEqual(files['md9sum.txt'].as_manifest(),
361                          ". 085c37f02916da1cad16f93c54d899b7+41 5348b82a029fd9e971a811ce1f71360b+43 8b22da26f9f433dea0a10e5ec66d73ba+43 40:80:md9sum.txt\n")
362
363     def test_write_directory_tree(self):
364         cwriter = arvados.CollectionWriter(self.api_client)
365         cwriter.write_directory_tree(self.build_directory_tree(
366                 ['basefile', 'subdir/subfile']))
367         self.assertEqual(cwriter.manifest_text(),
368                          """. c5110c5ac93202d8e0f9e381f22bac0f+8 0:8:basefile
369 ./subdir 1ca4dec89403084bf282ad31e6cf7972+14 0:14:subfile\n""")
370
371     def test_write_named_directory_tree(self):
372         cwriter = arvados.CollectionWriter(self.api_client)
373         cwriter.write_directory_tree(self.build_directory_tree(
374                 ['basefile', 'subdir/subfile']), 'root')
375         self.assertEqual(
376             cwriter.manifest_text(),
377             """./root c5110c5ac93202d8e0f9e381f22bac0f+8 0:8:basefile
378 ./root/subdir 1ca4dec89403084bf282ad31e6cf7972+14 0:14:subfile\n""")
379
380     def test_write_directory_tree_in_one_stream(self):
381         cwriter = arvados.CollectionWriter(self.api_client)
382         cwriter.write_directory_tree(self.build_directory_tree(
383                 ['basefile', 'subdir/subfile']), max_manifest_depth=0)
384         self.assertEqual(cwriter.manifest_text(),
385                          """. 4ace875ffdc6824a04950f06858f4465+22 0:8:basefile 8:14:subdir/subfile\n""")
386
387     def test_write_directory_tree_with_limited_recursion(self):
388         cwriter = arvados.CollectionWriter(self.api_client)
389         cwriter.write_directory_tree(
390             self.build_directory_tree(['f1', 'd1/f2', 'd1/d2/f3']),
391             max_manifest_depth=1)
392         self.assertEqual(cwriter.manifest_text(),
393                          """. bd19836ddb62c11c55ab251ccaca5645+2 0:2:f1
394 ./d1 50170217e5b04312024aa5cd42934494+13 0:8:d2/f3 8:5:f2\n""")
395
396     def test_write_directory_tree_with_zero_recursion(self):
397         cwriter = arvados.CollectionWriter(self.api_client)
398         content = 'd1/d2/f3d1/f2f1'
399         blockhash = hashlib.md5(content).hexdigest() + '+' + str(len(content))
400         cwriter.write_directory_tree(
401             self.build_directory_tree(['f1', 'd1/f2', 'd1/d2/f3']),
402             max_manifest_depth=0)
403         self.assertEqual(
404             cwriter.manifest_text(),
405             ". {} 0:8:d1/d2/f3 8:5:d1/f2 13:2:f1\n".format(blockhash))
406
407     def test_write_one_file(self):
408         cwriter = arvados.CollectionWriter(self.api_client)
409         with self.make_test_file() as testfile:
410             cwriter.write_file(testfile.name)
411             self.assertEqual(
412                 cwriter.manifest_text(),
413                 ". 098f6bcd4621d373cade4e832627b4f6+4 0:4:{}\n".format(
414                     os.path.basename(testfile.name)))
415
416     def test_write_named_file(self):
417         cwriter = arvados.CollectionWriter(self.api_client)
418         with self.make_test_file() as testfile:
419             cwriter.write_file(testfile.name, 'foo')
420             self.assertEqual(cwriter.manifest_text(),
421                              ". 098f6bcd4621d373cade4e832627b4f6+4 0:4:foo\n")
422
423     def test_write_multiple_files(self):
424         cwriter = arvados.CollectionWriter(self.api_client)
425         for letter in 'ABC':
426             with self.make_test_file(letter) as testfile:
427                 cwriter.write_file(testfile.name, letter)
428         self.assertEqual(
429             cwriter.manifest_text(),
430             ". 902fbdd2b1df0c4f70b4a5d23525e932+3 0:1:A 1:1:B 2:1:C\n")
431
432     def test_basic_resume(self):
433         cwriter = TestResumableWriter()
434         with self.make_test_file() as testfile:
435             cwriter.write_file(testfile.name, 'test')
436             resumed = TestResumableWriter.from_state(cwriter.current_state())
437         self.assertEquals(cwriter.manifest_text(), resumed.manifest_text(),
438                           "resumed CollectionWriter had different manifest")
439
440     def test_resume_fails_when_missing_dependency(self):
441         cwriter = TestResumableWriter()
442         with self.make_test_file() as testfile:
443             cwriter.write_file(testfile.name, 'test')
444         self.assertRaises(arvados.errors.StaleWriterStateError,
445                           TestResumableWriter.from_state,
446                           cwriter.current_state())
447
448     def test_resume_fails_when_dependency_mtime_changed(self):
449         cwriter = TestResumableWriter()
450         with self.make_test_file() as testfile:
451             cwriter.write_file(testfile.name, 'test')
452             os.utime(testfile.name, (0, 0))
453             self.assertRaises(arvados.errors.StaleWriterStateError,
454                               TestResumableWriter.from_state,
455                               cwriter.current_state())
456
457     def test_resume_fails_when_dependency_is_nonfile(self):
458         cwriter = TestResumableWriter()
459         cwriter.write_file('/dev/null', 'empty')
460         self.assertRaises(arvados.errors.StaleWriterStateError,
461                           TestResumableWriter.from_state,
462                           cwriter.current_state())
463
464     def test_resume_fails_when_dependency_size_changed(self):
465         cwriter = TestResumableWriter()
466         with self.make_test_file() as testfile:
467             cwriter.write_file(testfile.name, 'test')
468             orig_mtime = os.fstat(testfile.fileno()).st_mtime
469             testfile.write('extra')
470             testfile.flush()
471             os.utime(testfile.name, (orig_mtime, orig_mtime))
472             self.assertRaises(arvados.errors.StaleWriterStateError,
473                               TestResumableWriter.from_state,
474                               cwriter.current_state())
475
476     def test_resume_fails_with_expired_locator(self):
477         cwriter = TestResumableWriter()
478         state = cwriter.current_state()
479         # Add an expired locator to the state.
480         state['_current_stream_locators'].append(''.join([
481                     'a' * 32, '+1+A', 'b' * 40, '@', '10000000']))
482         self.assertRaises(arvados.errors.StaleWriterStateError,
483                           TestResumableWriter.from_state, state)
484
485     def test_arbitrary_objects_not_resumable(self):
486         cwriter = TestResumableWriter()
487         with open('/dev/null') as badfile:
488             self.assertRaises(arvados.errors.AssertionError,
489                               cwriter.write_file, badfile)
490
491     def test_arbitrary_writes_not_resumable(self):
492         cwriter = TestResumableWriter()
493         self.assertRaises(arvados.errors.AssertionError,
494                           cwriter.write, "badtext")
495
496     def test_read_arbitrary_data_with_collection_reader(self):
497         # arv-get relies on this to do "arv-get {keep-locator} -".
498         self.write_foo_bar_baz()
499         self.assertEqual(
500             'foobar',
501             arvados.CollectionReader(
502                 '3858f62230ac3c915f300c664312c63f+6'
503                 ).manifest_text())
504
505
506 class CollectionTestMixin(tutil.ApiClientMock):
507     API_COLLECTIONS = run_test_server.fixture('collections')
508     DEFAULT_COLLECTION = API_COLLECTIONS['foo_file']
509     DEFAULT_DATA_HASH = DEFAULT_COLLECTION['portable_data_hash']
510     DEFAULT_MANIFEST = DEFAULT_COLLECTION['manifest_text']
511     DEFAULT_UUID = DEFAULT_COLLECTION['uuid']
512     ALT_COLLECTION = API_COLLECTIONS['bar_file']
513     ALT_DATA_HASH = ALT_COLLECTION['portable_data_hash']
514     ALT_MANIFEST = ALT_COLLECTION['manifest_text']
515
516     def api_client_mock(self, status=200):
517         client = super(CollectionTestMixin, self).api_client_mock()
518         self.mock_keep_services(client, status=status, service_type='proxy', count=1)
519         return client
520
521
522 @tutil.skip_sleep
523 class CollectionReaderTestCase(unittest.TestCase, CollectionTestMixin):
524     def mock_get_collection(self, api_mock, code, body):
525         body = self.API_COLLECTIONS.get(body)
526         self._mock_api_call(api_mock.collections().get, code, body)
527
528     def api_client_mock(self, status=200):
529         client = super(CollectionReaderTestCase, self).api_client_mock()
530         self.mock_get_collection(client, status, 'foo_file')
531         return client
532
533     def test_init_no_default_retries(self):
534         client = self.api_client_mock(200)
535         reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
536         reader.manifest_text()
537         client.collections().get().execute.assert_called_with(num_retries=0)
538
539     def test_uuid_init_success(self):
540         client = self.api_client_mock(200)
541         reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client,
542                                           num_retries=3)
543         self.assertEqual(self.DEFAULT_COLLECTION['manifest_text'],
544                          reader.manifest_text())
545         client.collections().get().execute.assert_called_with(num_retries=3)
546
547     def test_uuid_init_failure_raises_api_error(self):
548         client = self.api_client_mock(500)
549         with self.assertRaises(arvados.errors.ApiError):
550             reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
551
552     def test_locator_init(self):
553         client = self.api_client_mock(200)
554         # Ensure Keep will not return anything if asked.
555         with tutil.mock_get_responses(None, 404):
556             reader = arvados.CollectionReader(self.DEFAULT_DATA_HASH,
557                                               api_client=client)
558             self.assertEqual(self.DEFAULT_MANIFEST, reader.manifest_text())
559
560     def test_locator_init_fallback_to_keep(self):
561         # crunch-job needs this to read manifests that have only ever
562         # been written to Keep.
563         client = self.api_client_mock(200)
564         self.mock_get_collection(client, 404, None)
565         with tutil.mock_get_responses(self.DEFAULT_MANIFEST, 200):
566             reader = arvados.CollectionReader(self.DEFAULT_DATA_HASH,
567                                               api_client=client)
568             self.assertEqual(self.DEFAULT_MANIFEST, reader.manifest_text())
569
570     def test_uuid_init_no_fallback_to_keep(self):
571         # Do not look up a collection UUID in Keep.
572         client = self.api_client_mock(404)
573         with tutil.mock_get_responses(self.DEFAULT_MANIFEST, 200):
574             with self.assertRaises(arvados.errors.ApiError):
575                 reader = arvados.CollectionReader(self.DEFAULT_UUID,
576                                                   api_client=client)
577
578     def test_try_keep_first_if_permission_hint(self):
579         # To verify that CollectionReader tries Keep first here, we
580         # mock API server to return the wrong data.
581         client = self.api_client_mock(200)
582         with tutil.mock_get_responses(self.ALT_MANIFEST, 200):
583             self.assertEqual(
584                 self.ALT_MANIFEST,
585                 arvados.CollectionReader(
586                     self.ALT_DATA_HASH + '+Affffffffffffffffffffffffffffffffffffffff@fedcba98',
587                     api_client=client).manifest_text())
588
589     def test_init_num_retries_propagated(self):
590         # More of an integration test...
591         client = self.api_client_mock(200)
592         reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client,
593                                           num_retries=3)
594         with tutil.mock_get_responses('foo', 500, 500, 200):
595             self.assertEqual('foo',
596                              ''.join(f.read(9) for f in reader.all_files()))
597
598     def test_read_nonnormalized_manifest_with_collection_reader(self):
599         # client should be able to use CollectionReader on a manifest without normalizing it
600         client = self.api_client_mock(500)
601         nonnormal = ". acbd18db4cc2f85cedef654fccc4a4d8+3+Aabadbadbee@abeebdee 0:3:foo.txt 1:0:bar.txt 0:3:foo.txt\n"
602         reader = arvados.CollectionReader(
603             nonnormal,
604             api_client=client, num_retries=0)
605         # Ensure stripped_manifest() doesn't mangle our manifest in
606         # any way other than stripping hints.
607         self.assertEqual(
608             re.sub('\+[^\d\s\+]+', '', nonnormal),
609             reader.stripped_manifest())
610         # Ensure stripped_manifest() didn't mutate our reader.
611         self.assertEqual(nonnormal, reader.manifest_text())
612         # Ensure the files appear in the order given in the manifest.
613         self.assertEqual(
614             [[6, '.', 'foo.txt'],
615              [0, '.', 'bar.txt']],
616             [[f.size(), f.stream_name(), f.name()]
617              for f in reader.all_streams()[0].all_files()])
618
619     def test_read_empty_collection(self):
620         client = self.api_client_mock(200)
621         self.mock_get_collection(client, 200, 'empty')
622         reader = arvados.CollectionReader('d41d8cd98f00b204e9800998ecf8427e+0',
623                                           api_client=client)
624         self.assertEqual('', reader.manifest_text())
625
626     def test_api_response(self):
627         client = self.api_client_mock()
628         reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
629         self.assertEqual(self.DEFAULT_COLLECTION, reader.api_response())
630
631     def test_api_response_with_collection_from_keep(self):
632         client = self.api_client_mock()
633         self.mock_get_collection(client, 404, 'foo')
634         with tutil.mock_get_responses(self.DEFAULT_MANIFEST, 200):
635             reader = arvados.CollectionReader(self.DEFAULT_DATA_HASH,
636                                               api_client=client)
637             api_response = reader.api_response()
638         self.assertIsNone(api_response)
639
640     def check_open_file(self, coll_file, stream_name, file_name, file_size):
641         self.assertFalse(coll_file.closed, "returned file is not open")
642         self.assertEqual(stream_name, coll_file.stream_name())
643         self.assertEqual(file_name, coll_file.name())
644         self.assertEqual(file_size, coll_file.size())
645
646     def test_open_collection_file_one_argument(self):
647         client = self.api_client_mock(200)
648         reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
649         cfile = reader.open('./foo')
650         self.check_open_file(cfile, '.', 'foo', 3)
651
652     def test_open_deep_file(self):
653         coll_name = 'collection_with_files_in_subdir'
654         client = self.api_client_mock(200)
655         self.mock_get_collection(client, 200, coll_name)
656         reader = arvados.CollectionReader(
657             self.API_COLLECTIONS[coll_name]['uuid'], api_client=client)
658         cfile = reader.open('./subdir2/subdir3/file2_in_subdir3.txt')
659         self.check_open_file(cfile, './subdir2/subdir3', 'file2_in_subdir3.txt',
660                              32)
661
662     def test_open_nonexistent_stream(self):
663         client = self.api_client_mock(200)
664         reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
665         self.assertRaises(IOError, reader.open, './nonexistent/foo')
666
667     def test_open_nonexistent_file(self):
668         client = self.api_client_mock(200)
669         reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
670         self.assertRaises(IOError, reader.open, 'nonexistent')
671
672
673 @tutil.skip_sleep
674 class CollectionWriterTestCase(unittest.TestCase, CollectionTestMixin):
675     def mock_keep(self, body, *codes, **headers):
676         headers.setdefault('x-keep-replicas-stored', 2)
677         return tutil.mock_put_responses(body, *codes, **headers)
678
679     def foo_writer(self, **kwargs):
680         kwargs.setdefault('api_client', self.api_client_mock())
681         writer = arvados.CollectionWriter(**kwargs)
682         writer.start_new_file('foo')
683         writer.write('foo')
684         return writer
685
686     def test_write_whole_collection(self):
687         writer = self.foo_writer()
688         with self.mock_keep(self.DEFAULT_DATA_HASH, 200, 200):
689             self.assertEqual(self.DEFAULT_DATA_HASH, writer.finish())
690
691     def test_write_no_default(self):
692         writer = self.foo_writer()
693         with self.mock_keep(None, 500):
694             with self.assertRaises(arvados.errors.KeepWriteError):
695                 writer.finish()
696
697     def test_write_insufficient_replicas_via_proxy(self):
698         writer = self.foo_writer(replication=3)
699         with self.mock_keep(None, 200, headers={'x-keep-replicas-stored': 2}):
700             with self.assertRaises(arvados.errors.KeepWriteError):
701                 writer.manifest_text()
702
703     def test_write_insufficient_replicas_via_disks(self):
704         client = mock.MagicMock(name='api_client')
705         with self.mock_keep(
706                 None, 200, 200,
707                 **{'x-keep-replicas-stored': 1}) as keepmock:
708             self.mock_keep_services(client, status=200, service_type='disk', count=2)
709             writer = self.foo_writer(api_client=client, replication=3)
710             with self.assertRaises(arvados.errors.KeepWriteError):
711                 writer.manifest_text()
712
713     def test_write_three_replicas(self):
714         client = mock.MagicMock(name='api_client')
715         with self.mock_keep(
716                 None, 500, 500, 500, 200, 200, 200,
717                 **{'x-keep-replicas-stored': 1}) as keepmock:
718             self.mock_keep_services(client, status=200, service_type='disk', count=6)
719             writer = self.foo_writer(api_client=client, replication=3)
720             writer.manifest_text()
721             # keepmock is the mock session constructor; keepmock.return_value
722             # is the mock session object, and keepmock.return_value.put is the
723             # actual mock method of interest.
724             self.assertEqual(6, keepmock.return_value.put.call_count)
725
726     def test_write_whole_collection_through_retries(self):
727         writer = self.foo_writer(num_retries=2)
728         with self.mock_keep(self.DEFAULT_DATA_HASH,
729                             500, 500, 200, 500, 500, 200):
730             self.assertEqual(self.DEFAULT_DATA_HASH, writer.finish())
731
732     def test_flush_data_retries(self):
733         writer = self.foo_writer(num_retries=2)
734         foo_hash = self.DEFAULT_MANIFEST.split()[1]
735         with self.mock_keep(foo_hash, 500, 200):
736             writer.flush_data()
737         self.assertEqual(self.DEFAULT_MANIFEST, writer.manifest_text())
738
739     def test_one_open(self):
740         client = self.api_client_mock()
741         writer = arvados.CollectionWriter(client)
742         with writer.open('out') as out_file:
743             self.assertEqual('.', writer.current_stream_name())
744             self.assertEqual('out', writer.current_file_name())
745             out_file.write('test data')
746             data_loc = hashlib.md5('test data').hexdigest() + '+9'
747         self.assertTrue(out_file.closed, "writer file not closed after context")
748         self.assertRaises(ValueError, out_file.write, 'extra text')
749         with self.mock_keep(data_loc, 200) as keep_mock:
750             self.assertEqual(". {} 0:9:out\n".format(data_loc),
751                              writer.manifest_text())
752
753     def test_open_writelines(self):
754         client = self.api_client_mock()
755         writer = arvados.CollectionWriter(client)
756         with writer.open('six') as out_file:
757             out_file.writelines(['12', '34', '56'])
758             data_loc = hashlib.md5('123456').hexdigest() + '+6'
759         with self.mock_keep(data_loc, 200) as keep_mock:
760             self.assertEqual(". {} 0:6:six\n".format(data_loc),
761                              writer.manifest_text())
762
763     def test_open_flush(self):
764         client = self.api_client_mock()
765         data_loc1 = hashlib.md5('flush1').hexdigest() + '+6'
766         data_loc2 = hashlib.md5('flush2').hexdigest() + '+6'
767         with self.mock_keep((data_loc1, 200), (data_loc2, 200)) as keep_mock:
768             writer = arvados.CollectionWriter(client)
769             with writer.open('flush_test') as out_file:
770                 out_file.write('flush1')
771                 out_file.flush()
772                 out_file.write('flush2')
773             self.assertEqual(". {} {} 0:12:flush_test\n".format(data_loc1,
774                                                                 data_loc2),
775                              writer.manifest_text())
776
777     def test_two_opens_same_stream(self):
778         client = self.api_client_mock()
779         writer = arvados.CollectionWriter(client)
780         with writer.open('.', '1') as out_file:
781             out_file.write('1st')
782         with writer.open('.', '2') as out_file:
783             out_file.write('2nd')
784         data_loc = hashlib.md5('1st2nd').hexdigest() + '+6'
785         with self.mock_keep(data_loc, 200) as keep_mock:
786             self.assertEqual(". {} 0:3:1 3:3:2\n".format(data_loc),
787                              writer.manifest_text())
788
789     def test_two_opens_two_streams(self):
790         client = self.api_client_mock()
791         data_loc1 = hashlib.md5('file').hexdigest() + '+4'
792         data_loc2 = hashlib.md5('indir').hexdigest() + '+5'
793         with self.mock_keep((data_loc1, 200), (data_loc2, 200)) as keep_mock:
794             writer = arvados.CollectionWriter(client)
795             with writer.open('file') as out_file:
796                 out_file.write('file')
797             with writer.open('./dir', 'indir') as out_file:
798                 out_file.write('indir')
799             expected = ". {} 0:4:file\n./dir {} 0:5:indir\n".format(
800                 data_loc1, data_loc2)
801             self.assertEqual(expected, writer.manifest_text())
802
803     def test_dup_open_fails(self):
804         client = self.api_client_mock()
805         writer = arvados.CollectionWriter(client)
806         file1 = writer.open('one')
807         self.assertRaises(arvados.errors.AssertionError, writer.open, 'two')
808
809
810 class NewCollectionTestCase(unittest.TestCase, CollectionTestMixin):
811
812     def test_init_manifest(self):
813         m1 = """. 5348b82a029fd9e971a811ce1f71360b+43 0:43:md5sum.txt
814 . 085c37f02916da1cad16f93c54d899b7+41 0:41:md5sum.txt
815 . 8b22da26f9f433dea0a10e5ec66d73ba+43 0:43:md5sum.txt
816 """
817         self.assertEqual(m1, CollectionReader(m1).manifest_text(normalize=False))
818         self.assertEqual(". 5348b82a029fd9e971a811ce1f71360b+43 085c37f02916da1cad16f93c54d899b7+41 8b22da26f9f433dea0a10e5ec66d73ba+43 0:127:md5sum.txt\n", CollectionReader(m1).manifest_text(normalize=True))
819
820
821     def test_remove(self):
822         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n')
823         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n", c.manifest_text())
824         self.assertIn("count1.txt", c)
825         c.remove("count1.txt")
826         self.assertNotIn("count1.txt", c)
827         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n", c.manifest_text())
828
829     def test_remove_in_subdir(self):
830         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
831         c.remove("foo/count2.txt")
832         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n", c.manifest_text())
833
834     def test_remove_empty_subdir(self):
835         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
836         c.remove("foo/count2.txt")
837         c.remove("foo")
838         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n", c.manifest_text())
839
840     def test_remove_nonempty_subdir(self):
841         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
842         with self.assertRaises(IOError):
843             c.remove("foo")
844         c.remove("foo", recursive=True)
845         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n", c.manifest_text())
846
847     def test_copy_to_file_in_dir(self):
848         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
849         c.copy("count1.txt", "foo/count2.txt")
850         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n", c.manifest_text())
851
852     def test_copy_file(self):
853         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
854         c.copy("count1.txt", "count2.txt")
855         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n", c.manifest_text())
856
857     def test_copy_to_existing_dir(self):
858         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
859         c.copy("count1.txt", "foo")
860         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n", c.manifest_text())
861
862     def test_copy_to_new_dir(self):
863         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
864         c.copy("count1.txt", "foo/")
865         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n", c.manifest_text())
866
867     def test_clone(self):
868         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
869         cl = c.clone()
870         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n", cl.manifest_text())
871
872     def test_diff_del_add(self):
873         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
874         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
875         d = c2.diff(c1)
876         self.assertEqual(d, [('del', './count2.txt', c2["count2.txt"]),
877                              ('add', './count1.txt', c1["count1.txt"])])
878         d = c1.diff(c2)
879         self.assertEqual(d, [('del', './count1.txt', c1["count1.txt"]),
880                              ('add', './count2.txt', c2["count2.txt"])])
881         self.assertNotEqual(c1.manifest_text(), c2.manifest_text())
882         c1.apply(d)
883         self.assertEqual(c1.manifest_text(), c2.manifest_text())
884
885     def test_diff_same(self):
886         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
887         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
888         d = c2.diff(c1)
889         self.assertEqual(d, [])
890         d = c1.diff(c2)
891         self.assertEqual(d, [])
892
893         self.assertEqual(c1.manifest_text(), c2.manifest_text())
894         c1.apply(d)
895         self.assertEqual(c1.manifest_text(), c2.manifest_text())
896
897     def test_diff_mod(self):
898         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
899         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt\n')
900         d = c2.diff(c1)
901         self.assertEqual(d, [('mod', './count1.txt', c2["count1.txt"], c1["count1.txt"])])
902         d = c1.diff(c2)
903         self.assertEqual(d, [('mod', './count1.txt', c1["count1.txt"], c2["count1.txt"])])
904
905         self.assertNotEqual(c1.manifest_text(), c2.manifest_text())
906         c1.apply(d)
907         self.assertEqual(c1.manifest_text(), c2.manifest_text())
908
909     def test_diff_add(self):
910         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
911         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt 10:20:count2.txt\n')
912         d = c2.diff(c1)
913         self.assertEqual(d, [('del', './count2.txt', c2["count2.txt"])])
914         d = c1.diff(c2)
915         self.assertEqual(d, [('add', './count2.txt', c2["count2.txt"])])
916
917         self.assertNotEqual(c1.manifest_text(), c2.manifest_text())
918         c1.apply(d)
919         self.assertEqual(c1.manifest_text(), c2.manifest_text())
920
921     def test_diff_add_in_subcollection(self):
922         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
923         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
924         d = c2.diff(c1)
925         self.assertEqual(d, [('del', './foo', c2["foo"])])
926         d = c1.diff(c2)
927         self.assertEqual(d, [('add', './foo', c2["foo"])])
928
929         self.assertNotEqual(c1.manifest_text(), c2.manifest_text())
930         c1.apply(d)
931         self.assertEqual(c1.manifest_text(), c2.manifest_text())
932
933     def test_diff_del_add_in_subcollection(self):
934         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
935         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 5348b82a029fd9e971a811ce1f71360b+43 0:3:count3.txt\n')
936
937         d = c2.diff(c1)
938         self.assertEqual(d, [('del', './foo/count3.txt', c2.find("foo/count3.txt")),
939                              ('add', './foo/count2.txt', c1.find("foo/count2.txt"))])
940         d = c1.diff(c2)
941         self.assertEqual(d, [('del', './foo/count2.txt', c1.find("foo/count2.txt")),
942                              ('add', './foo/count3.txt', c2.find("foo/count3.txt"))])
943
944         self.assertNotEqual(c1.manifest_text(), c2.manifest_text())
945         c1.apply(d)
946         self.assertEqual(c1.manifest_text(), c2.manifest_text())
947
948     def test_diff_mod_in_subcollection(self):
949         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
950         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:3:foo\n')
951         d = c2.diff(c1)
952         self.assertEqual(d, [('mod', './foo', c2["foo"], c1["foo"])])
953         d = c1.diff(c2)
954         self.assertEqual(d, [('mod', './foo', c1["foo"], c2["foo"])])
955
956         self.assertNotEqual(c1.manifest_text(), c2.manifest_text())
957         c1.apply(d)
958         self.assertEqual(c1.manifest_text(), c2.manifest_text())
959
960     def test_conflict_keep_local_change(self):
961         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
962         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
963         d = c1.diff(c2)
964         self.assertEqual(d, [('del', './count1.txt', c1["count1.txt"]),
965                              ('add', './count2.txt', c2["count2.txt"])])
966         with c1.open("count1.txt", "w") as f:
967             f.write("zzzzz")
968
969         # c1 changed, so it should not be deleted.
970         c1.apply(d)
971         self.assertEqual(c1.manifest_text(), ". 95ebc3c7b3b9f1d2c40fec14415d3cb8+5 5348b82a029fd9e971a811ce1f71360b+43 0:5:count1.txt 5:10:count2.txt\n")
972
973     def test_conflict_mod(self):
974         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt')
975         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt')
976         d = c1.diff(c2)
977         self.assertEqual(d, [('mod', './count1.txt', c1["count1.txt"], c2["count1.txt"])])
978         with c1.open("count1.txt", "w") as f:
979             f.write("zzzzz")
980
981         # c1 changed, so c2 mod will go to a conflict file
982         c1.apply(d)
983         self.assertTrue(re.match(r"\. 95ebc3c7b3b9f1d2c40fec14415d3cb8\+5 5348b82a029fd9e971a811ce1f71360b\+43 0:5:count1.txt 5:10:count1.txt~conflict-\d\d\d\d-\d\d-\d\d-\d\d:\d\d:\d\d~$",
984                                  c1.manifest_text()))
985
986     def test_conflict_add(self):
987         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
988         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt\n')
989         d = c1.diff(c2)
990         self.assertEqual(d, [('del', './count2.txt', c1["count2.txt"]),
991                              ('add', './count1.txt', c2["count1.txt"])])
992         with c1.open("count1.txt", "w") as f:
993             f.write("zzzzz")
994
995         # c1 added count1.txt, so c2 add will go to a conflict file
996         c1.apply(d)
997         self.assertTrue(re.match(r"\. 95ebc3c7b3b9f1d2c40fec14415d3cb8\+5 5348b82a029fd9e971a811ce1f71360b\+43 0:5:count1.txt 5:10:count1.txt~conflict-\d\d\d\d-\d\d-\d\d-\d\d:\d\d:\d\d~$",
998                                  c1.manifest_text()))
999
1000     def test_conflict_del(self):
1001         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt')
1002         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt')
1003         d = c1.diff(c2)
1004         self.assertEqual(d, [('mod', './count1.txt', c1["count1.txt"], c2["count1.txt"])])
1005         c1.remove("count1.txt")
1006
1007         # c1 deleted, so c2 mod will go to a conflict file
1008         c1.apply(d)
1009         self.assertTrue(re.match(r"\. 5348b82a029fd9e971a811ce1f71360b\+43 0:10:count1.txt~conflict-\d\d\d\d-\d\d-\d\d-\d\d:\d\d:\d\d~$",
1010                                  c1.manifest_text()))
1011
1012     def test_notify(self):
1013         c1 = Collection()
1014         events = []
1015         c1.subscribe(lambda event, collection, name, item: events.append((event, collection, name, item)))
1016         f = c1.open("foo.txt", "w")
1017         self.assertEqual(events[0], (arvados.collection.ADD, c1, "foo.txt", f.arvadosfile))
1018
1019     def test_open_w(self):
1020         c1 = Collection(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n")
1021         self.assertEqual(c1["count1.txt"].size(), 10)
1022         c1.open("count1.txt", "w").close()
1023         self.assertEqual(c1["count1.txt"].size(), 0)
1024
1025
1026 class CollectionCreateUpdateTest(run_test_server.TestCaseWithServers):
1027     MAIN_SERVER = {}
1028     KEEP_SERVER = {}
1029
1030     def create_count_txt(self):
1031         # Create an empty collection, save it to the API server, then write a
1032         # file, but don't save it.
1033
1034         c = Collection()
1035         c.save_new("CollectionCreateUpdateTest", ensure_unique_name=True)
1036         self.assertEquals(c.portable_data_hash(), "d41d8cd98f00b204e9800998ecf8427e+0")
1037         self.assertEquals(c.api_response()["portable_data_hash"], "d41d8cd98f00b204e9800998ecf8427e+0" )
1038
1039         with c.open("count.txt", "w") as f:
1040             f.write("0123456789")
1041
1042         self.assertEquals(c.manifest_text(), ". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n")
1043
1044         return c
1045
1046     def test_create_and_save(self):
1047         c = self.create_count_txt()
1048         c.save()
1049         self.assertTrue(re.match(r"^\. 781e5e245d69b566979b86e28d23f2c7\+10\+A[a-f0-9]{40}@[a-f0-9]{8} 0:10:count.txt$",
1050                                  c.manifest_text()))
1051
1052
1053     def test_create_and_save_new(self):
1054         c = self.create_count_txt()
1055         c.save_new()
1056         self.assertTrue(re.match(r"^\. 781e5e245d69b566979b86e28d23f2c7\+10\+A[a-f0-9]{40}@[a-f0-9]{8} 0:10:count.txt$",
1057                                  c.manifest_text()))
1058
1059     def test_create_diff_apply(self):
1060         c1 = self.create_count_txt()
1061         c1.save()
1062
1063         c2 = Collection(c1._manifest_locator)
1064         with c2.open("count.txt", "w") as f:
1065             f.write("abcdefg")
1066
1067         diff = c1.diff(c2)
1068
1069         self.assertEqual(diff[0], (arvados.collection.MOD, u'./count.txt', c1["count.txt"], c2["count.txt"]))
1070
1071         c1.apply(diff)
1072         self.assertEqual(c1.portable_data_hash(), c2.portable_data_hash())
1073
1074     def test_diff_apply_with_token(self):
1075         baseline = CollectionReader(". 781e5e245d69b566979b86e28d23f2c7+10+A715fd31f8111894f717eb1003c1b0216799dd9ec@54f5dd1a 0:10:count.txt\n")
1076         c = Collection(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n")
1077         other = CollectionReader(". 7ac66c0f148de9519b8bd264312c4d64+7+A715fd31f8111894f717eb1003c1b0216799dd9ec@54f5dd1a 0:7:count.txt\n")
1078
1079         diff = baseline.diff(other)
1080         self.assertEqual(diff, [('mod', u'./count.txt', c["count.txt"], other["count.txt"])])
1081
1082         c.apply(diff)
1083
1084         self.assertEqual(c.manifest_text(), ". 7ac66c0f148de9519b8bd264312c4d64+7+A715fd31f8111894f717eb1003c1b0216799dd9ec@54f5dd1a 0:7:count.txt\n")
1085
1086
1087     def test_create_and_update(self):
1088         c1 = self.create_count_txt()
1089         c1.save()
1090
1091         c2 = arvados.collection.Collection(c1._manifest_locator)
1092         with c2.open("count.txt", "w") as f:
1093             f.write("abcdefg")
1094
1095         c2.save()
1096
1097         self.assertNotEqual(c1.portable_data_hash(), c2.portable_data_hash())
1098         c1.update()
1099         self.assertEqual(c1.portable_data_hash(), c2.portable_data_hash())
1100
1101
1102     def test_create_and_update_with_conflict(self):
1103         c1 = self.create_count_txt()
1104         c1.save()
1105
1106         with c1.open("count.txt", "w") as f:
1107             f.write("XYZ")
1108
1109         c2 = arvados.collection.Collection(c1._manifest_locator)
1110         with c2.open("count.txt", "w") as f:
1111             f.write("abcdefg")
1112
1113         c2.save()
1114
1115         c1.update()
1116         self.assertTrue(re.match(r"\. e65075d550f9b5bf9992fa1d71a131be\+3 7ac66c0f148de9519b8bd264312c4d64\+7\+A[a-f0-9]{40}@[a-f0-9]{8} 0:3:count.txt 3:7:count.txt~conflict-\d\d\d\d-\d\d-\d\d-\d\d:\d\d:\d\d~$", c1.manifest_text()))
1117
1118
1119 if __name__ == '__main__':
1120     unittest.main()