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