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