3 # ARVADOS_API_TOKEN=abc ARVADOS_API_HOST=arvados.local python -m unittest discover
15 import run_test_server
16 import arvados_testutil as tutil
18 class TestResumableWriter(arvados.ResumableCollectionWriter):
19 KEEP_BLOCK_SIZE = 1024 # PUT to Keep every 1K.
21 def current_state(self):
22 return self.dump_state(copy.deepcopy)
25 class ArvadosCollectionsTest(run_test_server.TestCaseWithServers,
26 tutil.ArvadosBaseTestCase):
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)
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')
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')
47 cw.start_new_stream('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()))
55 return cw.portable_data_hash()
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')
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())
66 def test_local_collection_reader(self):
67 foobarbaz = self.write_foo_bar_baz()
68 cr = arvados.CollectionReader(
69 foobarbaz + '+Xzizzle', self.api_client)
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']]
79 stream0 = cr.all_streams()[0]
80 self.assertEqual(stream0.readfrom(0, 0),
82 'reading zero bytes should have returned empty string')
83 self.assertEqual(stream0.readfrom(0, 2**26),
85 'reading entire stream failed')
86 self.assertEqual(stream0.readfrom(2**26, 0),
88 'reading zero bytes should have returned empty string')
90 def _test_subset(self, collection, expected):
91 cr = arvados.CollectionReader(collection, self.api_client)
92 for s in cr.all_streams():
96 got = [f.size(), f.stream_name(), f.name(), "".join(f.readall(2**26))]
99 'all_files|as_manifest did not preserve manifest contents: got %s expected %s' % (got, ex))
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', '']])
125 def test_collection_empty_file(self):
126 cw = arvados.CollectionWriter(self.api_client)
127 cw.start_new_file('zero.txt')
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')
135 cw.start_new_file('one.txt')
137 cw.start_new_stream('foo')
138 cw.start_new_file('zero.txt')
140 self.check_manifest_file_sizes(cw.manifest_text(), [0,1,0])
142 def test_no_implicit_normalize(self):
143 cw = arvados.CollectionWriter(self.api_client)
144 cw.start_new_file('b')
146 cw.start_new_file('a')
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),
154 def check_manifest_file_sizes(self, manifest_text, expect_sizes):
155 cr = arvados.CollectionReader(manifest_text, self.api_client)
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))
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
166 self.assertEqual(arvados.CollectionReader(m1, self.api_client).manifest_text(normalize=True),
167 """. 5348b82a029fd9e971a811ce1f71360b+43 085c37f02916da1cad16f93c54d899b7+41 8b22da26f9f433dea0a10e5ec66d73ba+43 0:127:md5sum.txt
170 m2 = """. 204e43b8a1185621ca55a94839582e6f+67108864 b9677abbac956bd3e86b1deb28dfac03+67108864 fc15aff2a762b13f521baf042140acec+67108864 323d2a3ce20370c4ca1d3462a344f8fd+25885655 0:227212247:var-GS000016015-ASM.tsv.bz2
172 self.assertEqual(arvados.CollectionReader(m2, self.api_client).manifest_text(normalize=True), m2)
174 m3 = """. 5348b82a029fd9e971a811ce1f71360b+43 3:40:md5sum.txt
175 . 085c37f02916da1cad16f93c54d899b7+41 0:41:md5sum.txt
176 . 8b22da26f9f433dea0a10e5ec66d73ba+43 0:43:md5sum.txt
178 self.assertEqual(arvados.CollectionReader(m3, self.api_client).manifest_text(normalize=True),
179 """. 5348b82a029fd9e971a811ce1f71360b+43 085c37f02916da1cad16f93c54d899b7+41 8b22da26f9f433dea0a10e5ec66d73ba+43 3:124:md5sum.txt
182 m4 = """. 204e43b8a1185621ca55a94839582e6f+67108864 0:3:foo/bar
183 ./zzz 204e43b8a1185621ca55a94839582e6f+67108864 0:999:zzz
184 ./foo 323d2a3ce20370c4ca1d3462a344f8fd+25885655 0:3:bar
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
191 m5 = """. 204e43b8a1185621ca55a94839582e6f+67108864 0:3:foo/bar
192 ./zzz 204e43b8a1185621ca55a94839582e6f+67108864 0:999:zzz
193 ./foo 204e43b8a1185621ca55a94839582e6f+67108864 3:3:bar
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
200 with self.data_file('1000G_ref_manifest') as f6:
202 self.assertEqual(arvados.CollectionReader(m6, self.api_client).manifest_text(normalize=True), m6)
204 with self.data_file('jlake_manifest') as f7:
206 self.assertEqual(arvados.CollectionReader(m7, self.api_client).manifest_text(normalize=True), m7)
208 m8 = """./a\\040b\\040c 59ca0efa9f5633cb0371bbc0355478d8+13 0:13:hello\\040world.txt
210 self.assertEqual(arvados.CollectionReader(m8, self.api_client).manifest_text(normalize=True), m8)
212 def test_locators_and_ranges(self):
213 blocks2 = [['a', 10, 0],
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), [])
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), [])
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]])
246 blocks3 = [['a', 10, 0],
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]])
263 blocks = [['a', 10, 0],
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]])
271 self.assertEqual(arvados.locators_and_ranges(blocks, 0, 11), [['a', 10, 0, 10],
273 self.assertEqual(arvados.locators_and_ranges(blocks, 1, 11), [['a', 10, 1, 9],
275 self.assertEqual(arvados.locators_and_ranges(blocks, 0, 25), [['a', 10, 0, 10],
278 self.assertEqual(arvados.locators_and_ranges(blocks, 0, 30), [['a', 10, 0, 10],
281 self.assertEqual(arvados.locators_and_ranges(blocks, 1, 30), [['a', 10, 1, 9],
284 self.assertEqual(arvados.locators_and_ranges(blocks, 0, 31), [['a', 10, 0, 10],
288 self.assertEqual(arvados.locators_and_ranges(blocks, 15, 5), [['b', 15, 5, 5]])
290 self.assertEqual(arvados.locators_and_ranges(blocks, 8, 17), [['a', 10, 8, 2],
293 self.assertEqual(arvados.locators_and_ranges(blocks, 8, 20), [['a', 10, 8, 2],
297 self.assertEqual(arvados.locators_and_ranges(blocks, 26, 2), [['c', 5, 1, 2]])
299 self.assertEqual(arvados.locators_and_ranges(blocks, 9, 15), [['a', 10, 9, 1],
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],
305 class MockKeep(object):
306 def __init__(self, content, num_retries=0):
307 self.content = content
309 def get(self, locator, num_retries=0):
310 return self.content[locator]
312 def test_stream_reader(self):
313 keepblocks = {'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+10': 'abcdefghij',
314 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb+15': 'klmnopqrstuvwxy',
315 'cccccccccccccccccccccccccccccccc+5': 'z0123'}
316 mk = self.MockKeep(keepblocks)
318 sr = arvados.StreamReader([".", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+10", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb+15", "cccccccccccccccccccccccccccccccc+5", "0:30:foo"], mk)
320 content = 'abcdefghijklmnopqrstuvwxyz0123456789'
322 self.assertEqual(sr.readfrom(0, 30), content[0:30])
323 self.assertEqual(sr.readfrom(2, 30), content[2:30])
325 self.assertEqual(sr.readfrom(2, 8), content[2:10])
326 self.assertEqual(sr.readfrom(0, 10), content[0:10])
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), '')
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
344 m2 = arvados.CollectionReader(m1, self.api_client).manifest_text(normalize=True)
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()
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")
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""")
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')
373 cwriter.manifest_text(),
374 """./root c5110c5ac93202d8e0f9e381f22bac0f+8 0:8:basefile
375 ./root/subdir 1ca4dec89403084bf282ad31e6cf7972+14 0:14:subfile\n""")
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""")
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""")
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)
401 cwriter.manifest_text(),
402 ". {} 0:8:d1/d2/f3 8:5:d1/f2 13:2:f1\n".format(blockhash))
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)
409 cwriter.manifest_text(),
410 ". 098f6bcd4621d373cade4e832627b4f6+4 0:4:{}\n".format(
411 os.path.basename(testfile.name)))
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")
420 def test_write_multiple_files(self):
421 cwriter = arvados.CollectionWriter(self.api_client)
423 with self.make_test_file(letter) as testfile:
424 cwriter.write_file(testfile.name, letter)
426 cwriter.manifest_text(),
427 ". 902fbdd2b1df0c4f70b4a5d23525e932+3 0:1:A 1:1:B 2:1:C\n")
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")
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())
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())
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())
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')
468 os.utime(testfile.name, (orig_mtime, orig_mtime))
469 self.assertRaises(arvados.errors.StaleWriterStateError,
470 TestResumableWriter.from_state,
471 cwriter.current_state())
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)
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)
488 def test_arbitrary_writes_not_resumable(self):
489 cwriter = TestResumableWriter()
490 self.assertRaises(arvados.errors.AssertionError,
491 cwriter.write, "badtext")
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()
498 arvados.CollectionReader(
499 '3858f62230ac3c915f300c664312c63f+6'
503 class CollectionTestMixin(tutil.ApiClientMock):
504 API_COLLECTIONS = run_test_server.fixture('collections')
505 DEFAULT_COLLECTION = API_COLLECTIONS['foo_file']
506 DEFAULT_DATA_HASH = DEFAULT_COLLECTION['portable_data_hash']
507 DEFAULT_MANIFEST = DEFAULT_COLLECTION['manifest_text']
508 DEFAULT_UUID = DEFAULT_COLLECTION['uuid']
509 ALT_COLLECTION = API_COLLECTIONS['bar_file']
510 ALT_DATA_HASH = ALT_COLLECTION['portable_data_hash']
511 ALT_MANIFEST = ALT_COLLECTION['manifest_text']
513 def api_client_mock(self, status=200):
514 client = super(CollectionTestMixin, self).api_client_mock()
515 self.mock_keep_services(client, status=status, service_type='proxy', count=1)
520 class CollectionReaderTestCase(unittest.TestCase, CollectionTestMixin):
521 def mock_get_collection(self, api_mock, code, body):
522 body = self.API_COLLECTIONS.get(body)
523 self._mock_api_call(api_mock.collections().get, code, body)
525 def api_client_mock(self, status=200):
526 client = super(CollectionReaderTestCase, self).api_client_mock()
527 self.mock_get_collection(client, status, 'foo_file')
530 def test_init_no_default_retries(self):
531 client = self.api_client_mock(200)
532 reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
533 reader.manifest_text()
534 client.collections().get().execute.assert_called_with(num_retries=0)
536 def test_uuid_init_success(self):
537 client = self.api_client_mock(200)
538 reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client,
540 self.assertEqual(self.DEFAULT_COLLECTION['manifest_text'],
541 reader.manifest_text())
542 client.collections().get().execute.assert_called_with(num_retries=3)
544 def test_uuid_init_failure_raises_api_error(self):
545 client = self.api_client_mock(500)
546 reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
547 with self.assertRaises(arvados.errors.ApiError):
548 reader.manifest_text()
550 def test_locator_init(self):
551 client = self.api_client_mock(200)
552 # Ensure Keep will not return anything if asked.
553 with tutil.mock_get_responses(None, 404):
554 reader = arvados.CollectionReader(self.DEFAULT_DATA_HASH,
556 self.assertEqual(self.DEFAULT_MANIFEST, reader.manifest_text())
558 def test_locator_init_fallback_to_keep(self):
559 # crunch-job needs this to read manifests that have only ever
560 # been written to Keep.
561 client = self.api_client_mock(200)
562 self.mock_get_collection(client, 404, None)
563 with tutil.mock_get_responses(self.DEFAULT_MANIFEST, 200):
564 reader = arvados.CollectionReader(self.DEFAULT_DATA_HASH,
566 self.assertEqual(self.DEFAULT_MANIFEST, reader.manifest_text())
568 def test_uuid_init_no_fallback_to_keep(self):
569 # Do not look up a collection UUID in Keep.
570 client = self.api_client_mock(404)
571 reader = arvados.CollectionReader(self.DEFAULT_UUID,
573 with tutil.mock_get_responses(self.DEFAULT_MANIFEST, 200):
574 with self.assertRaises(arvados.errors.ApiError):
575 reader.manifest_text()
577 def test_try_keep_first_if_permission_hint(self):
578 # To verify that CollectionReader tries Keep first here, we
579 # mock API server to return the wrong data.
580 client = self.api_client_mock(200)
581 with tutil.mock_get_responses(self.ALT_MANIFEST, 200):
584 arvados.CollectionReader(
585 self.ALT_DATA_HASH + '+Affffffffffffffffffffffffffffffffffffffff@fedcba98',
586 api_client=client).manifest_text())
588 def test_init_num_retries_propagated(self):
589 # More of an integration test...
590 client = self.api_client_mock(200)
591 reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client,
593 with tutil.mock_get_responses('foo', 500, 500, 200):
594 self.assertEqual('foo',
595 ''.join(f.read(9) for f in reader.all_files()))
597 def test_read_nonnormalized_manifest_with_collection_reader(self):
598 # client should be able to use CollectionReader on a manifest without normalizing it
599 client = self.api_client_mock(500)
600 nonnormal = ". acbd18db4cc2f85cedef654fccc4a4d8+3+Aabadbadbee@abeebdee 0:3:foo.txt 1:0:bar.txt 0:3:foo.txt\n"
601 reader = arvados.CollectionReader(
603 api_client=client, num_retries=0)
604 # Ensure stripped_manifest() doesn't mangle our manifest in
605 # any way other than stripping hints.
607 re.sub('\+[^\d\s\+]+', '', nonnormal),
608 reader.stripped_manifest())
609 # Ensure stripped_manifest() didn't mutate our reader.
610 self.assertEqual(nonnormal, reader.manifest_text())
611 # Ensure the files appear in the order given in the manifest.
613 [[6, '.', 'foo.txt'],
614 [0, '.', 'bar.txt']],
615 [[f.size(), f.stream_name(), f.name()]
616 for f in reader.all_streams()[0].all_files()])
618 def test_read_empty_collection(self):
619 client = self.api_client_mock(200)
620 self.mock_get_collection(client, 200, 'empty')
621 reader = arvados.CollectionReader('d41d8cd98f00b204e9800998ecf8427e+0',
623 self.assertEqual('', reader.manifest_text())
625 def test_api_response(self):
626 client = self.api_client_mock()
627 reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
628 self.assertEqual(self.DEFAULT_COLLECTION, reader.api_response())
630 def test_api_response_with_collection_from_keep(self):
631 client = self.api_client_mock()
632 self.mock_get_collection(client, 404, 'foo')
633 with tutil.mock_get_responses(self.DEFAULT_MANIFEST, 200):
634 reader = arvados.CollectionReader(self.DEFAULT_DATA_HASH,
636 api_response = reader.api_response()
637 self.assertIsNone(api_response)
639 def check_open_file(self, coll_file, stream_name, file_name, file_size):
640 self.assertFalse(coll_file.closed, "returned file is not open")
641 self.assertEqual(stream_name, coll_file.stream_name())
642 self.assertEqual(file_name, coll_file.name())
643 self.assertEqual(file_size, coll_file.size())
645 def test_open_collection_file_one_argument(self):
646 client = self.api_client_mock(200)
647 reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
648 cfile = reader.open('./foo')
649 self.check_open_file(cfile, '.', 'foo', 3)
651 def test_open_collection_file_two_arguments(self):
652 client = self.api_client_mock(200)
653 reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
654 cfile = reader.open('.', 'foo')
655 self.check_open_file(cfile, '.', 'foo', 3)
657 def test_open_deep_file(self):
658 coll_name = 'collection_with_files_in_subdir'
659 client = self.api_client_mock(200)
660 self.mock_get_collection(client, 200, coll_name)
661 reader = arvados.CollectionReader(
662 self.API_COLLECTIONS[coll_name]['uuid'], api_client=client)
663 cfile = reader.open('./subdir2/subdir3/file2_in_subdir3.txt')
664 self.check_open_file(cfile, './subdir2/subdir3', 'file2_in_subdir3.txt',
667 def test_open_nonexistent_stream(self):
668 client = self.api_client_mock(200)
669 reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
670 self.assertRaises(ValueError, reader.open, './nonexistent', 'foo')
672 def test_open_nonexistent_file(self):
673 client = self.api_client_mock(200)
674 reader = arvados.CollectionReader(self.DEFAULT_UUID, api_client=client)
675 self.assertRaises(ValueError, reader.open, '.', 'nonexistent')
679 class CollectionWriterTestCase(unittest.TestCase, CollectionTestMixin):
680 def mock_keep(self, body, *codes, **headers):
681 headers.setdefault('x-keep-replicas-stored', 2)
682 return tutil.mock_put_responses(body, *codes, **headers)
684 def foo_writer(self, **kwargs):
685 kwargs.setdefault('api_client', self.api_client_mock())
686 writer = arvados.CollectionWriter(**kwargs)
687 writer.start_new_file('foo')
691 def test_write_whole_collection(self):
692 writer = self.foo_writer()
693 with self.mock_keep(self.DEFAULT_DATA_HASH, 200, 200):
694 self.assertEqual(self.DEFAULT_DATA_HASH, writer.finish())
696 def test_write_no_default(self):
697 writer = self.foo_writer()
698 with self.mock_keep(None, 500):
699 with self.assertRaises(arvados.errors.KeepWriteError):
702 def test_write_insufficient_replicas_via_proxy(self):
703 writer = self.foo_writer(replication=3)
704 with self.mock_keep(None, 200, headers={'x-keep-replicas-stored': 2}):
705 with self.assertRaises(arvados.errors.KeepWriteError):
706 writer.manifest_text()
708 def test_write_insufficient_replicas_via_disks(self):
709 client = mock.MagicMock(name='api_client')
710 self.mock_keep_services(client, status=200, service_type='disk', count=2)
711 writer = self.foo_writer(api_client=client, replication=3)
714 **{'x-keep-replicas-stored': 1}) as keepmock:
715 with self.assertRaises(arvados.errors.KeepWriteError):
716 writer.manifest_text()
718 def test_write_three_replicas(self):
719 client = mock.MagicMock(name='api_client')
720 self.mock_keep_services(client, status=200, service_type='disk', count=6)
721 writer = self.foo_writer(api_client=client, replication=3)
723 None, 200, 500, 200, 500, 200, 200,
724 **{'x-keep-replicas-stored': 1}) as keepmock:
725 writer.manifest_text()
726 self.assertEqual(5, keepmock.call_count)
728 def test_write_whole_collection_through_retries(self):
729 writer = self.foo_writer(num_retries=2)
730 with self.mock_keep(self.DEFAULT_DATA_HASH,
731 500, 500, 200, 500, 500, 200):
732 self.assertEqual(self.DEFAULT_DATA_HASH, writer.finish())
734 def test_flush_data_retries(self):
735 writer = self.foo_writer(num_retries=2)
736 foo_hash = self.DEFAULT_MANIFEST.split()[1]
737 with self.mock_keep(foo_hash, 500, 200):
739 self.assertEqual(self.DEFAULT_MANIFEST, writer.manifest_text())
741 def test_one_open(self):
742 client = self.api_client_mock()
743 writer = arvados.CollectionWriter(client)
744 with writer.open('out') as out_file:
745 self.assertEqual('.', writer.current_stream_name())
746 self.assertEqual('out', writer.current_file_name())
747 out_file.write('test data')
748 data_loc = hashlib.md5('test data').hexdigest() + '+9'
749 self.assertTrue(out_file.closed, "writer file not closed after context")
750 self.assertRaises(ValueError, out_file.write, 'extra text')
751 with self.mock_keep(data_loc, 200) as keep_mock:
752 self.assertEqual(". {} 0:9:out\n".format(data_loc),
753 writer.manifest_text())
755 def test_open_writelines(self):
756 client = self.api_client_mock()
757 writer = arvados.CollectionWriter(client)
758 with writer.open('six') as out_file:
759 out_file.writelines(['12', '34', '56'])
760 data_loc = hashlib.md5('123456').hexdigest() + '+6'
761 with self.mock_keep(data_loc, 200) as keep_mock:
762 self.assertEqual(". {} 0:6:six\n".format(data_loc),
763 writer.manifest_text())
765 def test_open_flush(self):
766 client = self.api_client_mock()
767 writer = arvados.CollectionWriter(client)
768 with writer.open('flush_test') as out_file:
769 out_file.write('flush1')
770 data_loc1 = hashlib.md5('flush1').hexdigest() + '+6'
771 with self.mock_keep(data_loc1, 200) as keep_mock:
773 out_file.write('flush2')
774 data_loc2 = hashlib.md5('flush2').hexdigest() + '+6'
775 with self.mock_keep(data_loc2, 200) as keep_mock:
776 self.assertEqual(". {} {} 0:12:flush_test\n".format(data_loc1,
778 writer.manifest_text())
780 def test_two_opens_same_stream(self):
781 client = self.api_client_mock()
782 writer = arvados.CollectionWriter(client)
783 with writer.open('.', '1') as out_file:
784 out_file.write('1st')
785 with writer.open('.', '2') as out_file:
786 out_file.write('2nd')
787 data_loc = hashlib.md5('1st2nd').hexdigest() + '+6'
788 with self.mock_keep(data_loc, 200) as keep_mock:
789 self.assertEqual(". {} 0:3:1 3:3:2\n".format(data_loc),
790 writer.manifest_text())
792 def test_two_opens_two_streams(self):
793 client = self.api_client_mock()
794 writer = arvados.CollectionWriter(client)
795 with writer.open('file') as out_file:
796 out_file.write('file')
797 data_loc1 = hashlib.md5('file').hexdigest() + '+4'
798 with self.mock_keep(data_loc1, 200) as keep_mock:
799 with writer.open('./dir', 'indir') as out_file:
800 out_file.write('indir')
801 data_loc2 = hashlib.md5('indir').hexdigest() + '+5'
802 with self.mock_keep(data_loc2, 200) as keep_mock:
803 expected = ". {} 0:4:file\n./dir {} 0:5:indir\n".format(
804 data_loc1, data_loc2)
805 self.assertEqual(expected, writer.manifest_text())
807 def test_dup_open_fails(self):
808 client = self.api_client_mock()
809 writer = arvados.CollectionWriter(client)
810 file1 = writer.open('one')
811 self.assertRaises(arvados.errors.AssertionError, writer.open, 'two')
814 if __name__ == '__main__':