5207: Change expires_at column type from date to datetime.
[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_get_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_get_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_get_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_get_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_get_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_get_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_put_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, headers={'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                 None, 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             # keepmock is the mock session constructor; keepmock.return_value
721             # is the mock session object, and keepmock.return_value.put is the
722             # actual mock method of interest.
723             self.assertEqual(6, keepmock.return_value.put.call_count)
724
725     def test_write_whole_collection_through_retries(self):
726         writer = self.foo_writer(num_retries=2)
727         with self.mock_keep(self.DEFAULT_DATA_HASH,
728                             500, 500, 200, 500, 500, 200):
729             self.assertEqual(self.DEFAULT_DATA_HASH, writer.finish())
730
731     def test_flush_data_retries(self):
732         writer = self.foo_writer(num_retries=2)
733         foo_hash = self.DEFAULT_MANIFEST.split()[1]
734         with self.mock_keep(foo_hash, 500, 200):
735             writer.flush_data()
736         self.assertEqual(self.DEFAULT_MANIFEST, writer.manifest_text())
737
738     def test_one_open(self):
739         client = self.api_client_mock()
740         writer = arvados.CollectionWriter(client)
741         with writer.open('out') as out_file:
742             self.assertEqual('.', writer.current_stream_name())
743             self.assertEqual('out', writer.current_file_name())
744             out_file.write('test data')
745             data_loc = hashlib.md5('test data').hexdigest() + '+9'
746         self.assertTrue(out_file.closed, "writer file not closed after context")
747         self.assertRaises(ValueError, out_file.write, 'extra text')
748         with self.mock_keep(data_loc, 200) as keep_mock:
749             self.assertEqual(". {} 0:9:out\n".format(data_loc),
750                              writer.manifest_text())
751
752     def test_open_writelines(self):
753         client = self.api_client_mock()
754         writer = arvados.CollectionWriter(client)
755         with writer.open('six') as out_file:
756             out_file.writelines(['12', '34', '56'])
757             data_loc = hashlib.md5('123456').hexdigest() + '+6'
758         with self.mock_keep(data_loc, 200) as keep_mock:
759             self.assertEqual(". {} 0:6:six\n".format(data_loc),
760                              writer.manifest_text())
761
762     def test_open_flush(self):
763         client = self.api_client_mock()
764         data_loc1 = hashlib.md5('flush1').hexdigest() + '+6'
765         data_loc2 = hashlib.md5('flush2').hexdigest() + '+6'
766         with self.mock_keep((data_loc1, 200), (data_loc2, 200)) as keep_mock:
767             writer = arvados.CollectionWriter(client)
768             with writer.open('flush_test') as out_file:
769                 out_file.write('flush1')
770                 out_file.flush()
771                 out_file.write('flush2')
772             self.assertEqual(". {} {} 0:12:flush_test\n".format(data_loc1,
773                                                                 data_loc2),
774                              writer.manifest_text())
775
776     def test_two_opens_same_stream(self):
777         client = self.api_client_mock()
778         writer = arvados.CollectionWriter(client)
779         with writer.open('.', '1') as out_file:
780             out_file.write('1st')
781         with writer.open('.', '2') as out_file:
782             out_file.write('2nd')
783         data_loc = hashlib.md5('1st2nd').hexdigest() + '+6'
784         with self.mock_keep(data_loc, 200) as keep_mock:
785             self.assertEqual(". {} 0:3:1 3:3:2\n".format(data_loc),
786                              writer.manifest_text())
787
788     def test_two_opens_two_streams(self):
789         client = self.api_client_mock()
790         data_loc1 = hashlib.md5('file').hexdigest() + '+4'
791         data_loc2 = hashlib.md5('indir').hexdigest() + '+5'
792         with self.mock_keep((data_loc1, 200), (data_loc2, 200)) as keep_mock:
793             writer = arvados.CollectionWriter(client)
794             with writer.open('file') as out_file:
795                 out_file.write('file')
796             with writer.open('./dir', 'indir') as out_file:
797                 out_file.write('indir')
798             expected = ". {} 0:4:file\n./dir {} 0:5:indir\n".format(
799                 data_loc1, data_loc2)
800             self.assertEqual(expected, writer.manifest_text())
801
802     def test_dup_open_fails(self):
803         client = self.api_client_mock()
804         writer = arvados.CollectionWriter(client)
805         file1 = writer.open('one')
806         self.assertRaises(arvados.errors.AssertionError, writer.open, 'two')
807
808
809 class NewCollectionTestCase(unittest.TestCase, CollectionTestMixin):
810
811     def test_init_manifest(self):
812         m1 = """. 5348b82a029fd9e971a811ce1f71360b+43 0:43:md5sum.txt
813 . 085c37f02916da1cad16f93c54d899b7+41 0:41:md5sum.txt
814 . 8b22da26f9f433dea0a10e5ec66d73ba+43 0:43:md5sum.txt
815 """
816         self.assertEqual(m1, CollectionReader(m1).manifest_text(normalize=False))
817         self.assertEqual(". 5348b82a029fd9e971a811ce1f71360b+43 085c37f02916da1cad16f93c54d899b7+41 8b22da26f9f433dea0a10e5ec66d73ba+43 0:127:md5sum.txt\n", CollectionReader(m1).manifest_text(normalize=True))
818
819     def test_init_manifest_with_collision(self):
820         m1 = """. 5348b82a029fd9e971a811ce1f71360b+43 0:43:md5sum.txt
821 ./md5sum.txt 085c37f02916da1cad16f93c54d899b7+41 0:41:md5sum.txt
822 """
823         with self.assertRaises(arvados.errors.ArgumentError):
824             self.assertEqual(m1, CollectionReader(m1))
825
826     def test_init_manifest_with_error(self):
827         m1 = """. 0:43:md5sum.txt"""
828         with self.assertRaises(arvados.errors.ArgumentError):
829             self.assertEqual(m1, CollectionReader(m1))
830
831     def test_remove(self):
832         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n')
833         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n", c.manifest_text())
834         self.assertIn("count1.txt", c)
835         c.remove("count1.txt")
836         self.assertNotIn("count1.txt", c)
837         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n", c.manifest_text())
838         with self.assertRaises(arvados.errors.ArgumentError):
839             c.remove("")
840
841     def test_find(self):
842         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n')
843         self.assertIs(c.find("."), c)
844         self.assertIs(c.find("./count1.txt"), c["count1.txt"])
845         self.assertIs(c.find("count1.txt"), c["count1.txt"])
846         with self.assertRaises(IOError):
847             c.find("/.")
848         with self.assertRaises(arvados.errors.ArgumentError):
849             c.find("")
850
851     def test_remove_in_subdir(self):
852         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
853         c.remove("foo/count2.txt")
854         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n", c.manifest_text())
855
856     def test_remove_empty_subdir(self):
857         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
858         c.remove("foo/count2.txt")
859         c.remove("foo")
860         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n", c.manifest_text())
861
862     def test_remove_nonempty_subdir(self):
863         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
864         with self.assertRaises(IOError):
865             c.remove("foo")
866         c.remove("foo", recursive=True)
867         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n", c.manifest_text())
868
869     def test_copy_to_file_in_dir(self):
870         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
871         c.copy("count1.txt", "foo/count2.txt")
872         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n", c.manifest_text())
873
874     def test_copy_file(self):
875         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
876         c.copy("count1.txt", "count2.txt")
877         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n", c.manifest_text())
878
879     def test_copy_to_existing_dir(self):
880         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
881         c.copy("count1.txt", "foo")
882         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt 0:10:count2.txt\n", c.manifest_text())
883
884     def test_copy_to_new_dir(self):
885         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
886         c.copy("count1.txt", "foo/")
887         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n", c.manifest_text())
888
889     def test_clone(self):
890         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
891         cl = c.clone()
892         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n", cl.manifest_text())
893
894     def test_diff_del_add(self):
895         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
896         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
897         d = c2.diff(c1)
898         self.assertEqual(d, [('del', './count2.txt', c2["count2.txt"]),
899                              ('add', './count1.txt', c1["count1.txt"])])
900         d = c1.diff(c2)
901         self.assertEqual(d, [('del', './count1.txt', c1["count1.txt"]),
902                              ('add', './count2.txt', c2["count2.txt"])])
903         self.assertNotEqual(c1.manifest_text(), c2.manifest_text())
904         c1.apply(d)
905         self.assertEqual(c1.manifest_text(), c2.manifest_text())
906
907     def test_diff_same(self):
908         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
909         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
910         d = c2.diff(c1)
911         self.assertEqual(d, [])
912         d = c1.diff(c2)
913         self.assertEqual(d, [])
914
915         self.assertEqual(c1.manifest_text(), c2.manifest_text())
916         c1.apply(d)
917         self.assertEqual(c1.manifest_text(), c2.manifest_text())
918
919     def test_diff_mod(self):
920         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
921         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt\n')
922         d = c2.diff(c1)
923         self.assertEqual(d, [('mod', './count1.txt', c2["count1.txt"], c1["count1.txt"])])
924         d = c1.diff(c2)
925         self.assertEqual(d, [('mod', './count1.txt', c1["count1.txt"], c2["count1.txt"])])
926
927         self.assertNotEqual(c1.manifest_text(), c2.manifest_text())
928         c1.apply(d)
929         self.assertEqual(c1.manifest_text(), c2.manifest_text())
930
931     def test_diff_add(self):
932         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
933         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt 10:20:count2.txt\n')
934         d = c2.diff(c1)
935         self.assertEqual(d, [('del', './count2.txt', c2["count2.txt"])])
936         d = c1.diff(c2)
937         self.assertEqual(d, [('add', './count2.txt', c2["count2.txt"])])
938
939         self.assertNotEqual(c1.manifest_text(), c2.manifest_text())
940         c1.apply(d)
941         self.assertEqual(c1.manifest_text(), c2.manifest_text())
942
943     def test_diff_add_in_subcollection(self):
944         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
945         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
946         d = c2.diff(c1)
947         self.assertEqual(d, [('del', './foo', c2["foo"])])
948         d = c1.diff(c2)
949         self.assertEqual(d, [('add', './foo', c2["foo"])])
950
951         self.assertNotEqual(c1.manifest_text(), c2.manifest_text())
952         c1.apply(d)
953         self.assertEqual(c1.manifest_text(), c2.manifest_text())
954
955     def test_diff_del_add_in_subcollection(self):
956         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
957         c2 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n./foo 5348b82a029fd9e971a811ce1f71360b+43 0:3:count3.txt\n')
958
959         d = c2.diff(c1)
960         self.assertEqual(d, [('del', './foo/count3.txt', c2.find("foo/count3.txt")),
961                              ('add', './foo/count2.txt', c1.find("foo/count2.txt"))])
962         d = c1.diff(c2)
963         self.assertEqual(d, [('del', './foo/count2.txt', c1.find("foo/count2.txt")),
964                              ('add', './foo/count3.txt', c2.find("foo/count3.txt"))])
965
966         self.assertNotEqual(c1.manifest_text(), c2.manifest_text())
967         c1.apply(d)
968         self.assertEqual(c1.manifest_text(), c2.manifest_text())
969
970     def test_diff_mod_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 0:3:foo\n')
973         d = c2.diff(c1)
974         self.assertEqual(d, [('mod', './foo', c2["foo"], c1["foo"])])
975         d = c1.diff(c2)
976         self.assertEqual(d, [('mod', './foo', c1["foo"], c2["foo"])])
977
978         self.assertNotEqual(c1.manifest_text(), c2.manifest_text())
979         c1.apply(d)
980         self.assertEqual(c1.manifest_text(), c2.manifest_text())
981
982     def test_conflict_keep_local_change(self):
983         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n')
984         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count2.txt\n')
985         d = c1.diff(c2)
986         self.assertEqual(d, [('del', './count1.txt', c1["count1.txt"]),
987                              ('add', './count2.txt', c2["count2.txt"])])
988         with c1.open("count1.txt", "w") as f:
989             f.write("zzzzz")
990
991         # c1 changed, so it should not be deleted.
992         c1.apply(d)
993         self.assertEqual(c1.manifest_text(), ". 95ebc3c7b3b9f1d2c40fec14415d3cb8+5 5348b82a029fd9e971a811ce1f71360b+43 0:5:count1.txt 5:10:count2.txt\n")
994
995     def test_conflict_mod(self):
996         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt')
997         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt')
998         d = c1.diff(c2)
999         self.assertEqual(d, [('mod', './count1.txt', c1["count1.txt"], c2["count1.txt"])])
1000         with c1.open("count1.txt", "w") as f:
1001             f.write("zzzzz")
1002
1003         # c1 changed, so c2 mod will go to a conflict file
1004         c1.apply(d)
1005         self.assertRegexpMatches(c1.manifest_text(), 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~$")
1006
1007     def test_conflict_add(self):
1008         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count2.txt\n')
1009         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt\n')
1010         d = c1.diff(c2)
1011         self.assertEqual(d, [('del', './count2.txt', c1["count2.txt"]),
1012                              ('add', './count1.txt', c2["count1.txt"])])
1013         with c1.open("count1.txt", "w") as f:
1014             f.write("zzzzz")
1015
1016         # c1 added count1.txt, so c2 add will go to a conflict file
1017         c1.apply(d)
1018         self.assertRegexpMatches(c1.manifest_text(), 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~$")
1019
1020     def test_conflict_del(self):
1021         c1 = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt')
1022         c2 = Collection('. 5348b82a029fd9e971a811ce1f71360b+43 0:10:count1.txt')
1023         d = c1.diff(c2)
1024         self.assertEqual(d, [('mod', './count1.txt', c1["count1.txt"], c2["count1.txt"])])
1025         c1.remove("count1.txt")
1026
1027         # c1 deleted, so c2 mod will go to a conflict file
1028         c1.apply(d)
1029         self.assertRegexpMatches(c1.manifest_text(), r"\. 5348b82a029fd9e971a811ce1f71360b\+43 0:10:count1\.txt~conflict-\d\d\d\d-\d\d-\d\d-\d\d:\d\d:\d\d~$")
1030
1031     def test_notify(self):
1032         c1 = Collection()
1033         events = []
1034         c1.subscribe(lambda event, collection, name, item: events.append((event, collection, name, item)))
1035         f = c1.open("foo.txt", "w")
1036         self.assertEqual(events[0], (arvados.collection.ADD, c1, "foo.txt", f.arvadosfile))
1037
1038     def test_open_w(self):
1039         c1 = Collection(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt\n")
1040         self.assertEqual(c1["count1.txt"].size(), 10)
1041         c1.open("count1.txt", "w").close()
1042         self.assertEqual(c1["count1.txt"].size(), 0)
1043
1044
1045 class CollectionCreateUpdateTest(run_test_server.TestCaseWithServers):
1046     MAIN_SERVER = {}
1047     KEEP_SERVER = {}
1048
1049     def create_count_txt(self):
1050         # Create an empty collection, save it to the API server, then write a
1051         # file, but don't save it.
1052
1053         c = Collection()
1054         c.save_new("CollectionCreateUpdateTest", ensure_unique_name=True)
1055         self.assertEqual(c.portable_data_hash(), "d41d8cd98f00b204e9800998ecf8427e+0")
1056         self.assertEqual(c.api_response()["portable_data_hash"], "d41d8cd98f00b204e9800998ecf8427e+0" )
1057
1058         with c.open("count.txt", "w") as f:
1059             f.write("0123456789")
1060
1061         self.assertEqual(c.manifest_text(), ". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n")
1062
1063         return c
1064
1065     def test_create_and_save(self):
1066         c = self.create_count_txt()
1067         c.save()
1068         self.assertRegexpMatches(c.manifest_text(), r"^\. 781e5e245d69b566979b86e28d23f2c7\+10\+A[a-f0-9]{40}@[a-f0-9]{8} 0:10:count\.txt$",)
1069
1070
1071     def test_create_and_save_new(self):
1072         c = self.create_count_txt()
1073         c.save_new()
1074         self.assertRegexpMatches(c.manifest_text(), r"^\. 781e5e245d69b566979b86e28d23f2c7\+10\+A[a-f0-9]{40}@[a-f0-9]{8} 0:10:count\.txt$",)
1075
1076     def test_create_diff_apply(self):
1077         c1 = self.create_count_txt()
1078         c1.save()
1079
1080         c2 = Collection(c1.manifest_locator())
1081         with c2.open("count.txt", "w") as f:
1082             f.write("abcdefg")
1083
1084         diff = c1.diff(c2)
1085
1086         self.assertEqual(diff[0], (arvados.collection.MOD, u'./count.txt', c1["count.txt"], c2["count.txt"]))
1087
1088         c1.apply(diff)
1089         self.assertEqual(c1.portable_data_hash(), c2.portable_data_hash())
1090
1091     def test_diff_apply_with_token(self):
1092         baseline = CollectionReader(". 781e5e245d69b566979b86e28d23f2c7+10+A715fd31f8111894f717eb1003c1b0216799dd9ec@54f5dd1a 0:10:count.txt\n")
1093         c = Collection(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n")
1094         other = CollectionReader(". 7ac66c0f148de9519b8bd264312c4d64+7+A715fd31f8111894f717eb1003c1b0216799dd9ec@54f5dd1a 0:7:count.txt\n")
1095
1096         diff = baseline.diff(other)
1097         self.assertEqual(diff, [('mod', u'./count.txt', c["count.txt"], other["count.txt"])])
1098
1099         c.apply(diff)
1100
1101         self.assertEqual(c.manifest_text(), ". 7ac66c0f148de9519b8bd264312c4d64+7+A715fd31f8111894f717eb1003c1b0216799dd9ec@54f5dd1a 0:7:count.txt\n")
1102
1103
1104     def test_create_and_update(self):
1105         c1 = self.create_count_txt()
1106         c1.save()
1107
1108         c2 = arvados.collection.Collection(c1.manifest_locator())
1109         with c2.open("count.txt", "w") as f:
1110             f.write("abcdefg")
1111
1112         c2.save()
1113
1114         self.assertNotEqual(c1.portable_data_hash(), c2.portable_data_hash())
1115         c1.update()
1116         self.assertEqual(c1.portable_data_hash(), c2.portable_data_hash())
1117
1118
1119     def test_create_and_update_with_conflict(self):
1120         c1 = self.create_count_txt()
1121         c1.save()
1122
1123         with c1.open("count.txt", "w") as f:
1124             f.write("XYZ")
1125
1126         c2 = arvados.collection.Collection(c1.manifest_locator())
1127         with c2.open("count.txt", "w") as f:
1128             f.write("abcdefg")
1129
1130         c2.save()
1131
1132         c1.update()
1133         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~conflict-\d\d\d\d-\d\d-\d\d-\d\d:\d\d:\d\d~$")
1134
1135
1136 if __name__ == '__main__':
1137     unittest.main()