11308: Merge branch 'master' into 11308-python3
[arvados.git] / sdk / python / tests / test_collections.py
1 from __future__ import absolute_import
2
3 from builtins import object
4 import arvados
5 import copy
6 import mock
7 import os
8 import pprint
9 import re
10 import sys
11 import tempfile
12 import unittest
13
14 from . import run_test_server
15 from arvados._ranges import Range, LocatorAndRange
16 from arvados.collection import Collection, CollectionReader
17 from . 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(b'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(b'bar')
48         cw.start_new_stream('baz')
49         cw.write(b'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(b'foo'), 'acbd18db4cc2f85cedef654fccc4a4d8+3', 'wrong md5 hash from Keep.put')
60         self.assertEqual(self.keep_client.get('acbd18db4cc2f85cedef654fccc4a4d8+3'), b'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', b'foo'],
76                     [3, '.', 'bar.txt', b'bar'],
77                     [3, './baz', 'baz.txt', b'baz']]
78         self.assertEqual(got,
79                          expected)
80         stream0 = cr.all_streams()[0]
81         self.assertEqual(stream0.readfrom(0, 0),
82                          b'',
83                          'reading zero bytes should have returned empty string')
84         self.assertEqual(stream0.readfrom(0, 2**26),
85                          b'foobar',
86                          'reading entire stream failed')
87         self.assertEqual(stream0.readfrom(2**26, 0),
88                          b'',
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', b'bar'],
106                            [3, '.',     'foo.txt', b'foo'],
107                            [3, './baz', 'baz.txt', b'baz']])
108         self._test_subset((". %s %s 0:3:foo.txt 3:3:bar.txt\n" %
109                            (self.keep_client.put(b"foo"),
110                             self.keep_client.put(b"bar"))),
111                           [[3, '.', 'bar.txt', b'bar'],
112                            [3, '.', 'foo.txt', b'foo']])
113         self._test_subset((". %s %s 0:2:fo.txt 2:4:obar.txt\n" %
114                            (self.keep_client.put(b"foo"),
115                             self.keep_client.put(b"bar"))),
116                           [[2, '.', 'fo.txt', b'fo'],
117                            [4, '.', 'obar.txt', b'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(b"foo"),
120                             self.keep_client.put(b"bar"))),
121                           [[2, '.', 'ar.txt', b'ar'],
122                            [2, '.', 'fo.txt', b'fo'],
123                            [2, '.', 'ob.txt', b'ob'],
124                            [0, '.', 'zero.txt', b'']])
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(b'')
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(b'')
136         cw.start_new_file('one.txt')
137         cw.write(b'1')
138         cw.start_new_stream('foo')
139         cw.start_new_file('zero.txt')
140         cw.write(b'')
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'b')
147         cw.start_new_file('a')
148         cw.write(b'')
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 = {
315             'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+10': b'abcdefghij',
316             'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb+15': b'klmnopqrstuvwxy',
317             'cccccccccccccccccccccccccccccccc+5': b'z0123',
318         }
319         mk = self.MockKeep(keepblocks)
320
321         sr = arvados.StreamReader([".", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+10", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb+15", "cccccccccccccccccccccccccccccccc+5", "0:30:foo"], mk)
322
323         content = b'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), b'')
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 = tutil.str_keep_locator(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.encode()) 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.assertEqual(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(b'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, fixturename):
525         body = self.API_COLLECTIONS.get(fixturename)
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_keep_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_keep_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_keep_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_keep_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_keep_responses('foo', 500, 500, 200):
595             self.assertEqual(b'foo',
596                              b''.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_keep_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', 'rb')
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', 'rb')
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_keep_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(b'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, **{'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                 "", 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             self.assertEqual(6, keepmock.call_count)
722
723     def test_write_whole_collection_through_retries(self):
724         writer = self.foo_writer(num_retries=2)
725         with self.mock_keep(self.DEFAULT_DATA_HASH,
726                             500, 500, 200, 500, 500, 200):
727             self.assertEqual(self.DEFAULT_DATA_HASH, writer.finish())
728
729     def test_flush_data_retries(self):
730         writer = self.foo_writer(num_retries=2)
731         foo_hash = self.DEFAULT_MANIFEST.split()[1]
732         with self.mock_keep(foo_hash, 500, 200):
733             writer.flush_data()
734         self.assertEqual(self.DEFAULT_MANIFEST, writer.manifest_text())
735
736     def test_one_open(self):
737         client = self.api_client_mock()
738         writer = arvados.CollectionWriter(client)
739         with writer.open('out') as out_file:
740             self.assertEqual('.', writer.current_stream_name())
741             self.assertEqual('out', writer.current_file_name())
742             out_file.write(b'test data')
743             data_loc = tutil.str_keep_locator('test data')
744         self.assertTrue(out_file.closed, "writer file not closed after context")
745         self.assertRaises(ValueError, out_file.write, 'extra text')
746         with self.mock_keep(data_loc, 200) as keep_mock:
747             self.assertEqual(". {} 0:9:out\n".format(data_loc),
748                              writer.manifest_text())
749
750     def test_open_writelines(self):
751         client = self.api_client_mock()
752         writer = arvados.CollectionWriter(client)
753         with writer.open('six') as out_file:
754             out_file.writelines(['12', '34', '56'])
755             data_loc = tutil.str_keep_locator('123456')
756         with self.mock_keep(data_loc, 200) as keep_mock:
757             self.assertEqual(". {} 0:6:six\n".format(data_loc),
758                              writer.manifest_text())
759
760     def test_open_flush(self):
761         client = self.api_client_mock()
762         data_loc1 = tutil.str_keep_locator('flush1')
763         data_loc2 = tutil.str_keep_locator('flush2')
764         with self.mock_keep((data_loc1, 200), (data_loc2, 200)) as keep_mock:
765             writer = arvados.CollectionWriter(client)
766             with writer.open('flush_test') as out_file:
767                 out_file.write(b'flush1')
768                 out_file.flush()
769                 out_file.write(b'flush2')
770             self.assertEqual(". {} {} 0:12:flush_test\n".format(data_loc1,
771                                                                 data_loc2),
772                              writer.manifest_text())
773
774     def test_two_opens_same_stream(self):
775         client = self.api_client_mock()
776         writer = arvados.CollectionWriter(client)
777         with writer.open('.', '1') as out_file:
778             out_file.write(b'1st')
779         with writer.open('.', '2') as out_file:
780             out_file.write(b'2nd')
781         data_loc = tutil.str_keep_locator('1st2nd')
782         with self.mock_keep(data_loc, 200) as keep_mock:
783             self.assertEqual(". {} 0:3:1 3:3:2\n".format(data_loc),
784                              writer.manifest_text())
785
786     def test_two_opens_two_streams(self):
787         client = self.api_client_mock()
788         data_loc1 = tutil.str_keep_locator('file')
789         data_loc2 = tutil.str_keep_locator('indir')
790         with self.mock_keep((data_loc1, 200), (data_loc2, 200)) as keep_mock:
791             writer = arvados.CollectionWriter(client)
792             with writer.open('file') as out_file:
793                 out_file.write(b'file')
794             with writer.open('./dir', 'indir') as out_file:
795                 out_file.write(b'indir')
796             expected = ". {} 0:4:file\n./dir {} 0:5:indir\n".format(
797                 data_loc1, data_loc2)
798             self.assertEqual(expected, writer.manifest_text())
799
800     def test_dup_open_fails(self):
801         client = self.api_client_mock()
802         writer = arvados.CollectionWriter(client)
803         file1 = writer.open('one')
804         self.assertRaises(arvados.errors.AssertionError, writer.open, 'two')
805
806
807 class CollectionOpenModes(run_test_server.TestCaseWithServers):
808
809     def test_open_binary_modes(self):
810         c = Collection()
811         for mode in ['wb', 'wb+', 'ab', 'ab+']:
812             with c.open('foo', 'wb') as f:
813                 f.write(b'foo')
814
815     def test_open_invalid_modes(self):
816         c = Collection()
817         for mode in ['+r', 'aa', '++', 'r+b', 'beer', '', None]:
818             with self.assertRaises(Exception):
819                 c.open('foo', mode)
820
821     def test_open_text_modes(self):
822         c = Collection()
823         with c.open('foo', 'wb') as f:
824             f.write('foo')
825         for mode in ['r', 'rt', 'r+', 'rt+', 'w', 'wt', 'a', 'at']:
826             if sys.version_info >= (3, 0):
827                 with self.assertRaises(NotImplementedError):
828                     c.open('foo', mode)
829             else:
830                 with c.open('foo', mode) as f:
831                     if mode[0] == 'r' and '+' not in mode:
832                         self.assertEqual('foo', f.read(3))
833                     else:
834                         f.write('bar')
835                         f.seek(-3, os.SEEK_CUR)
836                         self.assertEqual('bar', f.read(3))
837
838
839 class NewCollectionTestCase(unittest.TestCase, CollectionTestMixin):
840
841     def test_replication_desired_kept_on_load(self):
842         m = '. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n'
843         c1 = Collection(m, replication_desired=1)
844         c1.save_new()
845         loc = c1.manifest_locator()
846         c2 = Collection(loc)
847         self.assertEqual(c1.manifest_text, c2.manifest_text)
848         self.assertEqual(c1.replication_desired, c2.replication_desired)
849
850     def test_replication_desired_not_loaded_if_provided(self):
851         m = '. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n'
852         c1 = Collection(m, replication_desired=1)
853         c1.save_new()
854         loc = c1.manifest_locator()
855         c2 = Collection(loc, replication_desired=2)
856         self.assertEqual(c1.manifest_text, c2.manifest_text)
857         self.assertNotEqual(c1.replication_desired, c2.replication_desired)
858
859     def test_init_manifest(self):
860         m1 = """. 5348b82a029fd9e971a811ce1f71360b+43 0:43:md5sum.txt
861 . 085c37f02916da1cad16f93c54d899b7+41 0:41:md5sum.txt
862 . 8b22da26f9f433dea0a10e5ec66d73ba+43 0:43:md5sum.txt
863 """
864         self.assertEqual(m1, CollectionReader(m1).manifest_text(normalize=False))
865         self.assertEqual(". 5348b82a029fd9e971a811ce1f71360b+43 085c37f02916da1cad16f93c54d899b7+41 8b22da26f9f433dea0a10e5ec66d73ba+43 0:127:md5sum.txt\n", CollectionReader(m1).manifest_text(normalize=True))
866
867     def test_init_manifest_with_collision(self):
868         m1 = """. 5348b82a029fd9e971a811ce1f71360b+43 0:43:md5sum.txt
869 ./md5sum.txt 085c37f02916da1cad16f93c54d899b7+41 0:41:md5sum.txt
870 """
871         with self.assertRaises(arvados.errors.ArgumentError):
872             self.assertEqual(m1, CollectionReader(m1))
873
874     def test_init_manifest_with_error(self):
875         m1 = """. 0:43:md5sum.txt"""
876         with self.assertRaises(arvados.errors.ArgumentError):
877             self.assertEqual(m1, CollectionReader(m1))
878
879     def test_remove(self):
880         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n')
881         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n", c.portable_manifest_text())
882         self.assertIn("count1.txt", c)
883         c.remove("count1.txt")
884         self.assertNotIn("count1.txt", c)
885         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n", c.portable_manifest_text())
886         with self.assertRaises(arvados.errors.ArgumentError):
887             c.remove("")
888
889     def test_find(self):
890         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n')
891         self.assertIs(c.find("."), c)
892         self.assertIs(c.find("./count1.txt"), c["count1.txt"])
893         self.assertIs(c.find("count1.txt"), c["count1.txt"])
894         with self.assertRaises(IOError):
895             c.find("/.")
896         with self.assertRaises(arvados.errors.ArgumentError):
897             c.find("")
898         self.assertIs(c.find("./nonexistant.txt"), None)
899         self.assertIs(c.find("./nonexistantsubdir/nonexistant.txt"), None)
900
901     def test_remove_in_subdir(self):
902         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
903         c.remove("foo/count2.txt")
904         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n", c.portable_manifest_text())
905
906     def test_remove_empty_subdir(self):
907         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
908         c.remove("foo/count2.txt")
909         c.remove("foo")
910         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n", c.portable_manifest_text())
911
912     def test_remove_nonempty_subdir(self):
913         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
914         with self.assertRaises(IOError):
915             c.remove("foo")
916         c.remove("foo", recursive=True)
917         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n", c.portable_manifest_text())
918
919     def test_copy_to_file_in_dir(self):
920         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
921         c.copy("count1.txt", "foo/count2.txt")
922         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n", c.portable_manifest_text())
923
924     def test_copy_file(self):
925         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
926         c.copy("count1.txt", "count2.txt")
927         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n", c.portable_manifest_text())
928
929     def test_copy_to_existing_dir(self):
930         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
931         c.copy("count1.txt", "foo")
932         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())
933
934     def test_copy_to_new_dir(self):
935         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
936         c.copy("count1.txt", "foo/")
937         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n", c.portable_manifest_text())
938
939     def test_rename_file(self):
940         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
941         c.rename("count1.txt", "count2.txt")
942         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n", c.manifest_text())
943
944     def test_move_file_to_dir(self):
945         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
946         c.mkdirs("foo")
947         c.rename("count1.txt", "foo/count2.txt")
948         self.assertEqual("./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n", c.manifest_text())
949
950     def test_move_file_to_other(self):
951         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
952         c2 = Collection()
953         c2.rename("count1.txt", "count2.txt", source_collection=c1)
954         self.assertEqual("", c1.manifest_text())
955         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n", c2.manifest_text())
956
957     def test_clone(self):
958         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
959         cl = c.clone()
960         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n", cl.portable_manifest_text())
961
962     def test_diff_del_add(self):
963         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
964         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
965         d = c2.diff(c1)
966         self.assertEqual(sorted(d), [
967             ('add', './count1.txt', c1["count1.txt"]),
968             ('del', './count2.txt', c2["count2.txt"]),
969         ])
970         d = c1.diff(c2)
971         self.assertEqual(sorted(d), [
972             ('add', './count2.txt', c2["count2.txt"]),
973             ('del', './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_same(self):
980         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
981         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
982         d = c2.diff(c1)
983         self.assertEqual(d, [('tok', './count1.txt', c2["count1.txt"], c1["count1.txt"])])
984         d = c1.diff(c2)
985         self.assertEqual(d, [('tok', './count1.txt', c2["count1.txt"], c1["count1.txt"])])
986
987         self.assertEqual(c1.portable_manifest_text(), c2.portable_manifest_text())
988         c1.apply(d)
989         self.assertEqual(c1.portable_manifest_text(), c2.portable_manifest_text())
990
991     def test_diff_mod(self):
992         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
993         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt\n')
994         d = c2.diff(c1)
995         self.assertEqual(d, [('mod', './count1.txt', c2["count1.txt"], c1["count1.txt"])])
996         d = c1.diff(c2)
997         self.assertEqual(d, [('mod', './count1.txt', c1["count1.txt"], c2["count1.txt"])])
998
999         self.assertNotEqual(c1.portable_manifest_text(), c2.portable_manifest_text())
1000         c1.apply(d)
1001         self.assertEqual(c1.portable_manifest_text(), c2.portable_manifest_text())
1002
1003     def test_diff_add(self):
1004         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
1005         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt 10:20:count2.txt\n')
1006         d = c2.diff(c1)
1007         self.assertEqual(sorted(d), [
1008             ('del', './count2.txt', c2["count2.txt"]),
1009             ('tok', './count1.txt', c2["count1.txt"], c1["count1.txt"]),
1010         ])
1011         d = c1.diff(c2)
1012         self.assertEqual(sorted(d), [
1013             ('add', './count2.txt', c2["count2.txt"]),
1014             ('tok', './count1.txt', c2["count1.txt"], c1["count1.txt"]),
1015         ])
1016
1017         self.assertNotEqual(c1.portable_manifest_text(), c2.portable_manifest_text())
1018         c1.apply(d)
1019         self.assertEqual(c1.portable_manifest_text(), c2.portable_manifest_text())
1020
1021     def test_diff_add_in_subcollection(self):
1022         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
1023         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
1024         d = c2.diff(c1)
1025         self.assertEqual(sorted(d), [
1026             ('del', './foo', c2["foo"]),
1027             ('tok', './count1.txt', c2["count1.txt"], c1["count1.txt"]),
1028         ])
1029         d = c1.diff(c2)
1030         self.assertEqual(sorted(d), [
1031             ('add', './foo', c2["foo"]),
1032             ('tok', './count1.txt', c2["count1.txt"], c1["count1.txt"]),
1033         ])
1034         self.assertNotEqual(c1.portable_manifest_text(), c2.portable_manifest_text())
1035         c1.apply(d)
1036         self.assertEqual(c1.portable_manifest_text(), c2.portable_manifest_text())
1037
1038     def test_diff_del_add_in_subcollection(self):
1039         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
1040         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 5348b82a029fd9e971a811ce1f71360b+43 0:3:count3.txt\n')
1041         d = c2.diff(c1)
1042         self.assertEqual(sorted(d), [
1043             ('add', './foo/count2.txt', c1.find("foo/count2.txt")),
1044             ('del', './foo/count3.txt', c2.find("foo/count3.txt")),
1045             ('tok', './count1.txt', c2["count1.txt"], c1["count1.txt"]),
1046         ])
1047         d = c1.diff(c2)
1048         self.assertEqual(sorted(d), [
1049             ('add', './foo/count3.txt', c2.find("foo/count3.txt")),
1050             ('del', './foo/count2.txt', c1.find("foo/count2.txt")),
1051             ('tok', './count1.txt', c2["count1.txt"], c1["count1.txt"]),
1052         ])
1053
1054         self.assertNotEqual(c1.portable_manifest_text(), c2.portable_manifest_text())
1055         c1.apply(d)
1056         self.assertEqual(c1.portable_manifest_text(), c2.portable_manifest_text())
1057
1058     def test_diff_mod_in_subcollection(self):
1059         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
1060         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:3:foo\n')
1061         d = c2.diff(c1)
1062         self.assertEqual(sorted(d), [
1063             ('mod', './foo', c2["foo"], c1["foo"]),
1064             ('tok', './count1.txt', c2["count1.txt"], c1["count1.txt"]),
1065         ])
1066         d = c1.diff(c2)
1067         self.assertEqual(sorted(d), [
1068             ('mod', './foo', c1["foo"], c2["foo"]),
1069             ('tok', './count1.txt', c2["count1.txt"], c1["count1.txt"]),
1070         ])
1071
1072         self.assertNotEqual(c1.portable_manifest_text(), c2.portable_manifest_text())
1073         c1.apply(d)
1074         self.assertEqual(c1.portable_manifest_text(), c2.portable_manifest_text())
1075
1076     def test_conflict_keep_local_change(self):
1077         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
1078         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
1079         d = c1.diff(c2)
1080         self.assertEqual(sorted(d), [
1081             ('add', './count2.txt', c2["count2.txt"]),
1082             ('del', './count1.txt', c1["count1.txt"]),
1083         ])
1084         f = c1.open("count1.txt", "wb")
1085         f.write(b"zzzzz")
1086
1087         # c1 changed, so it should not be deleted.
1088         c1.apply(d)
1089         self.assertEqual(c1.portable_manifest_text(), ". 95ebc3c7b3b9f1d2c40fec14415d3cb8+5 5348b82a029fd9e971a811ce1f71360b+43 0:5:count1.txt 5:10:count2.txt\n")
1090
1091     def test_conflict_mod(self):
1092         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt')
1093         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt')
1094         d = c1.diff(c2)
1095         self.assertEqual(d, [('mod', './count1.txt', c1["count1.txt"], c2["count1.txt"])])
1096         f = c1.open("count1.txt", "wb")
1097         f.write(b"zzzzz")
1098
1099         # c1 changed, so c2 mod will go to a conflict file
1100         c1.apply(d)
1101         self.assertRegex(
1102             c1.portable_manifest_text(),
1103             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~$")
1104
1105     def test_conflict_add(self):
1106         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
1107         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt\n')
1108         d = c1.diff(c2)
1109         self.assertEqual(sorted(d), [
1110             ('add', './count1.txt', c2["count1.txt"]),
1111             ('del', './count2.txt', c1["count2.txt"]),
1112         ])
1113         f = c1.open("count1.txt", "wb")
1114         f.write(b"zzzzz")
1115
1116         # c1 added count1.txt, so c2 add will go to a conflict file
1117         c1.apply(d)
1118         self.assertRegex(
1119             c1.portable_manifest_text(),
1120             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~$")
1121
1122     def test_conflict_del(self):
1123         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt')
1124         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt')
1125         d = c1.diff(c2)
1126         self.assertEqual(d, [('mod', './count1.txt', c1["count1.txt"], c2["count1.txt"])])
1127         c1.remove("count1.txt")
1128
1129         # c1 deleted, so c2 mod will go to a conflict file
1130         c1.apply(d)
1131         self.assertRegex(
1132             c1.portable_manifest_text(),
1133             r"\. 5348b82a029fd9e971a811ce1f71360b\+43 0:10:count1\.txt~\d\d\d\d\d\d\d\d-\d\d\d\d\d\d~conflict~$")
1134
1135     def test_notify(self):
1136         c1 = Collection()
1137         events = []
1138         c1.subscribe(lambda event, collection, name, item: events.append((event, collection, name, item)))
1139         f = c1.open("foo.txt", "wb")
1140         self.assertEqual(events[0], (arvados.collection.ADD, c1, "foo.txt", f.arvadosfile))
1141
1142     def test_open_w(self):
1143         c1 = Collection(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n")
1144         self.assertEqual(c1["count1.txt"].size(), 10)
1145         c1.open("count1.txt", "wb").close()
1146         self.assertEqual(c1["count1.txt"].size(), 0)
1147
1148
1149 class NewCollectionTestCaseWithServers(run_test_server.TestCaseWithServers):
1150     def test_get_manifest_text_only_committed(self):
1151         c = Collection()
1152         with c.open("count.txt", "wb") as f:
1153             # One file committed
1154             with c.open("foo.txt", "wb") as foo:
1155                 foo.write(b"foo")
1156                 foo.flush() # Force block commit
1157             f.write(b"0123456789")
1158             # Other file not committed. Block not written to keep yet.
1159             self.assertEqual(
1160                 c._get_manifest_text(".",
1161                                      strip=False,
1162                                      normalize=False,
1163                                      only_committed=True),
1164                 '. acbd18db4cc2f85cedef654fccc4a4d8+3 0:0:count.txt 0:3:foo.txt\n')
1165             # And now with the file closed...
1166             f.flush() # Force block commit
1167         self.assertEqual(
1168             c._get_manifest_text(".",
1169                                  strip=False,
1170                                  normalize=False,
1171                                  only_committed=True),
1172             ". 781e5e245d69b566979b86e28d23f2c7+10 acbd18db4cc2f85cedef654fccc4a4d8+3 0:10:count.txt 10:3:foo.txt\n")
1173
1174     def test_only_small_blocks_are_packed_together(self):
1175         c = Collection()
1176         # Write a couple of small files,
1177         f = c.open("count.txt", "wb")
1178         f.write(b"0123456789")
1179         f.close(flush=False)
1180         foo = c.open("foo.txt", "wb")
1181         foo.write(b"foo")
1182         foo.close(flush=False)
1183         # Then, write a big file, it shouldn't be packed with the ones above
1184         big = c.open("bigfile.txt", "wb")
1185         big.write(b"x" * 1024 * 1024 * 33) # 33 MB > KEEP_BLOCK_SIZE/2
1186         big.close(flush=False)
1187         self.assertEqual(
1188             c.manifest_text("."),
1189             '. 2d303c138c118af809f39319e5d507e9+34603008 a8430a058b8fbf408e1931b794dbd6fb+13 0:34603008:bigfile.txt 34603008:10:count.txt 34603018:3:foo.txt\n')
1190
1191     def test_flush_after_small_block_packing(self):
1192         c = Collection()
1193         # Write a couple of small files,
1194         f = c.open("count.txt", "w")
1195         f.write("0123456789")
1196         f.close(flush=False)
1197         foo = c.open("foo.txt", "w")
1198         foo.write("foo")
1199         foo.close(flush=False)
1200
1201         self.assertEqual(
1202             c.manifest_text(),
1203             '. a8430a058b8fbf408e1931b794dbd6fb+13 0:10:count.txt 10:3:foo.txt\n')
1204
1205         f = c.open("count.txt", "r+")
1206         f.close(flush=True)
1207
1208         self.assertEqual(
1209             c.manifest_text(),
1210             '. a8430a058b8fbf408e1931b794dbd6fb+13 0:10:count.txt 10:3:foo.txt\n')
1211
1212     def test_write_after_small_block_packing2(self):
1213         c = Collection()
1214         # Write a couple of small files,
1215         f = c.open("count.txt", "w")
1216         f.write("0123456789")
1217         f.close(flush=False)
1218         foo = c.open("foo.txt", "w")
1219         foo.write("foo")
1220         foo.close(flush=False)
1221
1222         self.assertEqual(
1223             c.manifest_text(),
1224             '. a8430a058b8fbf408e1931b794dbd6fb+13 0:10:count.txt 10:3:foo.txt\n')
1225
1226         f = c.open("count.txt", "r+")
1227         f.write("abc")
1228         f.close(flush=False)
1229
1230         self.assertEqual(
1231             c.manifest_text(),
1232             '. 900150983cd24fb0d6963f7d28e17f72+3 a8430a058b8fbf408e1931b794dbd6fb+13 0:3:count.txt 6:7:count.txt 13:3:foo.txt\n')
1233
1234
1235     def test_small_block_packing_with_overwrite(self):
1236         c = Collection()
1237         c.open("b1", "w").close()
1238         c["b1"].writeto(0, "b1", 0)
1239
1240         c.open("b2", "w").close()
1241         c["b2"].writeto(0, "b2", 0)
1242
1243         c["b1"].writeto(0, "1b", 0)
1244
1245         self.assertEquals(c.manifest_text(), ". ed4f3f67c70b02b29c50ce1ea26666bd+4 0:2:b1 2:2:b2\n")
1246         self.assertEquals(c["b1"].manifest_text(), ". ed4f3f67c70b02b29c50ce1ea26666bd+4 0:2:b1\n")
1247         self.assertEquals(c["b2"].manifest_text(), ". ed4f3f67c70b02b29c50ce1ea26666bd+4 2:2:b2\n")
1248
1249
1250 class CollectionCreateUpdateTest(run_test_server.TestCaseWithServers):
1251     MAIN_SERVER = {}
1252     KEEP_SERVER = {}
1253
1254     def create_count_txt(self):
1255         # Create an empty collection, save it to the API server, then write a
1256         # file, but don't save it.
1257
1258         c = Collection()
1259         c.save_new("CollectionCreateUpdateTest", ensure_unique_name=True)
1260         self.assertEqual(c.portable_data_hash(), "d41d8cd98f00b204e9800998ecf8427e+0")
1261         self.assertEqual(c.api_response()["portable_data_hash"], "d41d8cd98f00b204e9800998ecf8427e+0" )
1262
1263         with c.open("count.txt", "wb") as f:
1264             f.write(b"0123456789")
1265
1266         self.assertEqual(c.portable_manifest_text(), ". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n")
1267
1268         return c
1269
1270     def test_create_and_save(self):
1271         c = self.create_count_txt()
1272         c.save()
1273         self.assertRegex(
1274             c.manifest_text(),
1275             r"^\. 781e5e245d69b566979b86e28d23f2c7\+10\+A[a-f0-9]{40}@[a-f0-9]{8} 0:10:count\.txt$",)
1276
1277     def test_create_and_save_new(self):
1278         c = self.create_count_txt()
1279         c.save_new()
1280         self.assertRegex(
1281             c.manifest_text(),
1282             r"^\. 781e5e245d69b566979b86e28d23f2c7\+10\+A[a-f0-9]{40}@[a-f0-9]{8} 0:10:count\.txt$",)
1283
1284     def test_create_diff_apply(self):
1285         c1 = self.create_count_txt()
1286         c1.save()
1287
1288         c2 = Collection(c1.manifest_locator())
1289         with c2.open("count.txt", "wb") as f:
1290             f.write(b"abcdefg")
1291
1292         diff = c1.diff(c2)
1293
1294         self.assertEqual(diff[0], (arvados.collection.MOD, u'./count.txt', c1["count.txt"], c2["count.txt"]))
1295
1296         c1.apply(diff)
1297         self.assertEqual(c1.portable_data_hash(), c2.portable_data_hash())
1298
1299     def test_diff_apply_with_token(self):
1300         baseline = CollectionReader(". 781e5e245d69b566979b86e28d23f2c7+10+A715fd31f8111894f717eb1003c1b0216799dd9ec@54f5dd1a 0:10:count.txt\n")
1301         c = Collection(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n")
1302         other = CollectionReader(". 7ac66c0f148de9519b8bd264312c4d64+7+A715fd31f8111894f717eb1003c1b0216799dd9ec@54f5dd1a 0:7:count.txt\n")
1303
1304         diff = baseline.diff(other)
1305         self.assertEqual(diff, [('mod', u'./count.txt', c["count.txt"], other["count.txt"])])
1306
1307         c.apply(diff)
1308
1309         self.assertEqual(c.manifest_text(), ". 7ac66c0f148de9519b8bd264312c4d64+7+A715fd31f8111894f717eb1003c1b0216799dd9ec@54f5dd1a 0:7:count.txt\n")
1310
1311
1312     def test_create_and_update(self):
1313         c1 = self.create_count_txt()
1314         c1.save()
1315
1316         c2 = arvados.collection.Collection(c1.manifest_locator())
1317         with c2.open("count.txt", "wb") as f:
1318             f.write(b"abcdefg")
1319
1320         c2.save()
1321
1322         self.assertNotEqual(c1.portable_data_hash(), c2.portable_data_hash())
1323         c1.update()
1324         self.assertEqual(c1.portable_data_hash(), c2.portable_data_hash())
1325
1326
1327     def test_create_and_update_with_conflict(self):
1328         c1 = self.create_count_txt()
1329         c1.save()
1330
1331         with c1.open("count.txt", "wb") as f:
1332             f.write(b"XYZ")
1333
1334         c2 = arvados.collection.Collection(c1.manifest_locator())
1335         with c2.open("count.txt", "wb") as f:
1336             f.write(b"abcdefg")
1337
1338         c2.save()
1339
1340         c1.update()
1341         self.assertRegex(
1342             c1.manifest_text(),
1343             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~$")
1344
1345
1346 if __name__ == '__main__':
1347     unittest.main()