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