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