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