Merge branch 'master' into 6194-python-arvfile-large-write
[arvados.git] / sdk / python / tests / test_arvfile.py
1 #!/usr/bin/env python
2
3 import bz2
4 import gzip
5 import io
6 import mock
7 import os
8 import unittest
9 import hashlib
10
11 import arvados
12 from arvados._ranges import Range
13 from arvados.keep import KeepLocator
14 from arvados.collection import Collection, CollectionReader
15 from arvados.arvfile import ArvadosFile, ArvadosFileReader
16
17 import arvados_testutil as tutil
18 from test_stream import StreamFileReaderTestCase, StreamRetryTestMixin
19
20 class ArvadosFileWriterTestCase(unittest.TestCase):
21     class MockKeep(object):
22         def __init__(self, blocks):
23             self.blocks = blocks
24             self.requests = []
25         def get(self, locator, num_retries=0):
26             self.requests.append(locator)
27             return self.blocks.get(locator)
28         def get_from_cache(self, locator):
29             self.requests.append(locator)
30             return self.blocks.get(locator)
31         def put(self, data, num_retries=None):
32             pdh = "%s+%i" % (hashlib.md5(data).hexdigest(), len(data))
33             self.blocks[pdh] = str(data)
34             return pdh
35
36     class MockApi(object):
37         def __init__(self, b, r):
38             self.body = b
39             self.response = r
40         class MockCollections(object):
41             def __init__(self, b, r):
42                 self.body = b
43                 self.response = r
44             class Execute(object):
45                 def __init__(self, r):
46                     self.response = r
47                 def execute(self, num_retries=None):
48                     return self.response
49             def create(self, ensure_unique_name=False, body=None):
50                 if body != self.body:
51                     raise Exception("Body %s does not match expectation %s" % (body, self.body))
52                 return ArvadosFileWriterTestCase.MockApi.MockCollections.Execute(self.response)
53             def update(self, uuid=None, body=None):
54                 return ArvadosFileWriterTestCase.MockApi.MockCollections.Execute(self.response)
55         def collections(self):
56             return ArvadosFileWriterTestCase.MockApi.MockCollections(self.body, self.response)
57
58
59     def test_truncate(self):
60         keep = ArvadosFileWriterTestCase.MockKeep({"781e5e245d69b566979b86e28d23f2c7+10": "0123456789"})
61         api = ArvadosFileWriterTestCase.MockApi({"name":"test_truncate",
62                                                  "manifest_text":". 781e5e245d69b566979b86e28d23f2c7+10 0:8:count.txt\n"},
63                                                 {"uuid":"zzzzz-4zz18-mockcollection0",
64                                                  "manifest_text":". 781e5e245d69b566979b86e28d23f2c7+10 0:8:count.txt\n"})
65         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n',
66                              api_client=api, keep_client=keep) as c:
67             writer = c.open("count.txt", "r+")
68             self.assertEqual(writer.size(), 10)
69             self.assertEqual("0123456789", writer.read(12))
70
71             writer.truncate(8)
72
73             # Make sure reading off the end doesn't break
74             self.assertEqual("", writer.read(12))
75
76             self.assertEqual(writer.size(), 8)
77             writer.seek(0, os.SEEK_SET)
78             self.assertEqual("01234567", writer.read(12))
79
80             self.assertEqual(None, c.manifest_locator())
81             self.assertEqual(True, c.modified())
82             c.save_new("test_truncate")
83             self.assertEqual("zzzzz-4zz18-mockcollection0", c.manifest_locator())
84             self.assertEqual(False, c.modified())
85
86     def test_write_to_end(self):
87         keep = ArvadosFileWriterTestCase.MockKeep({"781e5e245d69b566979b86e28d23f2c7+10": "0123456789"})
88         api = ArvadosFileWriterTestCase.MockApi({"name":"test_append",
89                                                  "manifest_text": ". 781e5e245d69b566979b86e28d23f2c7+10 acbd18db4cc2f85cedef654fccc4a4d8+3 0:13:count.txt\n"},
90                                                 {"uuid":"zzzzz-4zz18-mockcollection0",
91                                                  "manifest_text": ". 781e5e245d69b566979b86e28d23f2c7+10 acbd18db4cc2f85cedef654fccc4a4d8+3 0:13:count.txt\n"})
92         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n',
93                              api_client=api, keep_client=keep) as c:
94             writer = c.open("count.txt", "r+")
95             self.assertEqual(writer.size(), 10)
96
97             writer.seek(5, os.SEEK_SET)
98             self.assertEqual("56789", writer.read(8))
99
100             writer.seek(10, os.SEEK_SET)
101             writer.write("foo")
102             self.assertEqual(writer.size(), 13)
103
104             writer.seek(5, os.SEEK_SET)
105             self.assertEqual("56789foo", writer.read(8))
106
107             self.assertEqual(None, c.manifest_locator())
108             self.assertEqual(True, c.modified())
109             self.assertEqual(None, keep.get("acbd18db4cc2f85cedef654fccc4a4d8+3"))
110
111             c.save_new("test_append")
112             self.assertEqual("zzzzz-4zz18-mockcollection0", c.manifest_locator())
113             self.assertEqual(False, c.modified())
114             self.assertEqual("foo", keep.get("acbd18db4cc2f85cedef654fccc4a4d8+3"))
115
116
117     def test_append(self):
118         keep = ArvadosFileWriterTestCase.MockKeep({"781e5e245d69b566979b86e28d23f2c7+10": "0123456789"})
119         c = Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n', keep_client=keep)
120         writer = c.open("count.txt", "a+")
121         self.assertEqual(writer.read(20), "0123456789")
122         writer.seek(0, os.SEEK_SET)
123
124         writer.write("hello")
125         self.assertEqual(writer.read(20), "0123456789hello")
126         writer.seek(0, os.SEEK_SET)
127
128         writer.write("world")
129         self.assertEqual(writer.read(20), "0123456789helloworld")
130
131         self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 fc5e038d38a57032085441e7fe7010b0+10 0:20:count.txt\n", c.portable_manifest_text())
132
133     def test_write_at_beginning(self):
134         keep = ArvadosFileWriterTestCase.MockKeep({"781e5e245d69b566979b86e28d23f2c7+10": "0123456789"})
135         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n',
136                              keep_client=keep) as c:
137             writer = c.open("count.txt", "r+")
138             self.assertEqual("0123456789", writer.readfrom(0, 13))
139             writer.seek(0, os.SEEK_SET)
140             writer.write("foo")
141             self.assertEqual(writer.size(), 10)
142             self.assertEqual("foo3456789", writer.readfrom(0, 13))
143             self.assertEqual(". acbd18db4cc2f85cedef654fccc4a4d8+3 781e5e245d69b566979b86e28d23f2c7+10 0:3:count.txt 6:7:count.txt\n", c.portable_manifest_text())
144
145     def test_write_empty(self):
146         keep = ArvadosFileWriterTestCase.MockKeep({})
147         with Collection(keep_client=keep) as c:
148             writer = c.open("count.txt", "w")
149             self.assertEqual(writer.size(), 0)
150             self.assertEqual(". d41d8cd98f00b204e9800998ecf8427e+0 0:0:count.txt\n", c.portable_manifest_text())
151
152     def test_save_manifest_text(self):
153         keep = ArvadosFileWriterTestCase.MockKeep({})
154         with Collection(keep_client=keep) as c:
155             writer = c.open("count.txt", "w")
156             writer.write("0123456789")
157             self.assertEqual('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n', c.portable_manifest_text())
158             self.assertNotIn('781e5e245d69b566979b86e28d23f2c7+10', keep.blocks)
159
160             self.assertEqual('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n', c.save_new(create_collection_record=False))
161             self.assertIn('781e5e245d69b566979b86e28d23f2c7+10', keep.blocks)
162
163     def test_get_manifest_text_commits(self):
164          keep = ArvadosFileWriterTestCase.MockKeep({})
165          with Collection(keep_client=keep) as c:
166              writer = c.open("count.txt", "w")
167              writer.write("0123456789")
168              self.assertEqual('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n', c.portable_manifest_text())
169              self.assertNotIn('781e5e245d69b566979b86e28d23f2c7+10', keep.blocks)
170              self.assertEqual('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n', c.manifest_text())
171              self.assertIn('781e5e245d69b566979b86e28d23f2c7+10', keep.blocks)
172
173
174     def test_write_in_middle(self):
175         keep = ArvadosFileWriterTestCase.MockKeep({"781e5e245d69b566979b86e28d23f2c7+10": "0123456789"})
176         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n',
177                              keep_client=keep) as c:
178             writer = c.open("count.txt", "r+")
179             self.assertEqual("0123456789", writer.readfrom(0, 13))
180             writer.seek(3, os.SEEK_SET)
181             writer.write("foo")
182             self.assertEqual(writer.size(), 10)
183             self.assertEqual("012foo6789", writer.readfrom(0, 13))
184             self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:count.txt 10:3:count.txt 6:4:count.txt\n", c.portable_manifest_text())
185
186     def test_write_at_end(self):
187         keep = ArvadosFileWriterTestCase.MockKeep({"781e5e245d69b566979b86e28d23f2c7+10": "0123456789"})
188         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n',
189                              keep_client=keep) as c:
190             writer = c.open("count.txt", "r+")
191             self.assertEqual("0123456789", writer.readfrom(0, 13))
192             writer.seek(7, os.SEEK_SET)
193             writer.write("foo")
194             self.assertEqual(writer.size(), 10)
195             self.assertEqual("0123456foo", writer.readfrom(0, 13))
196             self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 acbd18db4cc2f85cedef654fccc4a4d8+3 0:7:count.txt 10:3:count.txt\n", c.portable_manifest_text())
197
198     def test_write_across_segment_boundary(self):
199         keep = ArvadosFileWriterTestCase.MockKeep({"781e5e245d69b566979b86e28d23f2c7+10": "0123456789"})
200         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt 0:10:count.txt\n',
201                              keep_client=keep) as c:
202             writer = c.open("count.txt", "r+")
203             self.assertEqual("012345678901234", writer.readfrom(0, 15))
204             writer.seek(7, os.SEEK_SET)
205             writer.write("foobar")
206             self.assertEqual(writer.size(), 20)
207             self.assertEqual("0123456foobar34", writer.readfrom(0, 15))
208             self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 3858f62230ac3c915f300c664312c63f+6 0:7:count.txt 10:6:count.txt 3:7:count.txt\n", c.portable_manifest_text())
209
210     def test_write_across_several_segments(self):
211         keep = ArvadosFileWriterTestCase.MockKeep({"781e5e245d69b566979b86e28d23f2c7+10": "0123456789"})
212         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:4:count.txt 0:4:count.txt 0:4:count.txt',
213                              keep_client=keep) as c:
214             writer = c.open("count.txt", "r+")
215             self.assertEqual("012301230123", writer.readfrom(0, 15))
216             writer.seek(2, os.SEEK_SET)
217             writer.write("abcdefg")
218             self.assertEqual(writer.size(), 12)
219             self.assertEqual("01abcdefg123", writer.readfrom(0, 15))
220             self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 7ac66c0f148de9519b8bd264312c4d64+7 0:2:count.txt 10:7:count.txt 1:3:count.txt\n", c.portable_manifest_text())
221
222     def test_write_large(self):
223         keep = ArvadosFileWriterTestCase.MockKeep({})
224         api = ArvadosFileWriterTestCase.MockApi({"name":"test_write_large",
225                                                  "manifest_text": ". a5de24f4417cfba9d5825eadc2f4ca49+67108000 598cc1a4ccaef8ab6e4724d87e675d78+32892000 0:100000000:count.txt\n"},
226                                                 {"uuid":"zzzzz-4zz18-mockcollection0",
227                                                  "manifest_text": ". a5de24f4417cfba9d5825eadc2f4ca49+67108000 598cc1a4ccaef8ab6e4724d87e675d78+32892000 0:100000000:count.txt\n"})
228         with Collection('. ' + arvados.config.EMPTY_BLOCK_LOCATOR + ' 0:0:count.txt',
229                              api_client=api, keep_client=keep) as c:
230             writer = c.open("count.txt", "r+")
231             text = "0123456789" * 100
232             for b in xrange(0, 100000):
233                 writer.write(text)
234             self.assertEqual(writer.size(), 100000000)
235
236             self.assertEqual(None, c.manifest_locator())
237             self.assertEqual(True, c.modified())
238             c.save_new("test_write_large")
239             self.assertEqual("zzzzz-4zz18-mockcollection0", c.manifest_locator())
240             self.assertEqual(False, c.modified())
241
242
243     def test_large_write(self):
244         keep = ArvadosFileWriterTestCase.MockKeep({})
245         api = ArvadosFileWriterTestCase.MockApi({"name":"test_write_large",
246                                                  "manifest_text": ". 48dd23ea1645fd47d789804d71b5bb8e+67108864 b373ad0ffebb84efb524947b247ea89a+32891136 0:100000000:count.txt\n"},
247                                                 {"uuid":"zzzzz-4zz18-mockcollection0",
248                                                  "manifest_text": ". 48dd23ea1645fd47d789804d71b5bb8e+67108864 598cc1a4ccaef8ab6e4724d87e675d78+32891136 0:100000000:count.txt\n"})
249         with Collection('. ' + arvados.config.EMPTY_BLOCK_LOCATOR + ' 0:0:count.txt',
250                              api_client=api, keep_client=keep) as c:
251             writer = c.open("count.txt", "r+")
252             text = "0123456789" * 10000000
253             writer.write(text)
254             self.assertEqual(writer.size(), 100000000)
255
256             self.assertEqual(None, c.manifest_locator())
257             self.assertEqual(True, c.modified())
258             c.save_new("test_write_large")
259             self.assertEqual("zzzzz-4zz18-mockcollection0", c.manifest_locator())
260             self.assertEqual(False, c.modified())
261
262     def test_rewrite_on_empty_file(self):
263         keep = ArvadosFileWriterTestCase.MockKeep({})
264         with Collection('. ' + arvados.config.EMPTY_BLOCK_LOCATOR + ' 0:0:count.txt',
265                              keep_client=keep) as c:
266             writer = c.open("count.txt", "r+")
267             for b in xrange(0, 10):
268                 writer.seek(0, os.SEEK_SET)
269                 writer.write("0123456789")
270
271             self.assertEqual(writer.size(), 10)
272             self.assertEqual("0123456789", writer.readfrom(0, 20))
273             self.assertEqual(". 7a08b07e84641703e5f2c836aa59a170+100 90:10:count.txt\n", c.portable_manifest_text())
274             writer.flush()
275             self.assertEqual(writer.size(), 10)
276             self.assertEqual("0123456789", writer.readfrom(0, 20))
277             self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n", c.portable_manifest_text())
278
279     def test_rewrite_append_existing_file(self):
280         keep = ArvadosFileWriterTestCase.MockKeep({"781e5e245d69b566979b86e28d23f2c7+10": "0123456789"})
281         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt',
282                              keep_client=keep) as c:
283             writer = c.open("count.txt", "r+")
284             for b in xrange(0, 10):
285                 writer.seek(10, os.SEEK_SET)
286                 writer.write("abcdefghij")
287
288             self.assertEqual(writer.size(), 20)
289             self.assertEqual("0123456789abcdefghij", writer.readfrom(0, 20))
290             self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 ae5f43bab79cf0be33f025fa97ae7398+100 0:10:count.txt 100:10:count.txt\n", c.portable_manifest_text())
291
292             writer.arvadosfile.flush()
293             self.assertEqual(writer.size(), 20)
294             self.assertEqual("0123456789abcdefghij", writer.readfrom(0, 20))
295             self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 a925576942e94b2ef57a066101b48876+10 0:20:count.txt\n", c.portable_manifest_text())
296
297     def test_rewrite_over_existing_file(self):
298         keep = ArvadosFileWriterTestCase.MockKeep({"781e5e245d69b566979b86e28d23f2c7+10": "0123456789"})
299         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt',
300                              keep_client=keep) as c:
301             writer = c.open("count.txt", "r+")
302             for b in xrange(0, 10):
303                 writer.seek(5, os.SEEK_SET)
304                 writer.write("abcdefghij")
305
306             self.assertEqual(writer.size(), 15)
307             self.assertEqual("01234abcdefghij", writer.readfrom(0, 20))
308             self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 ae5f43bab79cf0be33f025fa97ae7398+100 0:5:count.txt 100:10:count.txt\n", c.portable_manifest_text())
309
310             writer.arvadosfile.flush()
311
312             self.assertEqual(writer.size(), 15)
313             self.assertEqual("01234abcdefghij", writer.readfrom(0, 20))
314             self.assertEqual(". 781e5e245d69b566979b86e28d23f2c7+10 a925576942e94b2ef57a066101b48876+10 0:5:count.txt 10:10:count.txt\n", c.portable_manifest_text())
315
316     def test_write_large_rewrite(self):
317         keep = ArvadosFileWriterTestCase.MockKeep({})
318         api = ArvadosFileWriterTestCase.MockApi({"name":"test_write_large",
319                                                  "manifest_text": ". 37400a68af9abdd76ca5bf13e819e42a+32892003 a5de24f4417cfba9d5825eadc2f4ca49+67108000 32892000:3:count.txt 32892006:67107997:count.txt 0:32892000:count.txt\n"},
320                                                 {"uuid":"zzzzz-4zz18-mockcollection0",
321                                                  "manifest_text": ". 37400a68af9abdd76ca5bf13e819e42a+32892003 a5de24f4417cfba9d5825eadc2f4ca49+67108000 32892000:3:count.txt 32892006:67107997:count.txt 0:32892000:count.txt\n"})
322         with Collection('. ' + arvados.config.EMPTY_BLOCK_LOCATOR + ' 0:0:count.txt',
323                              api_client=api, keep_client=keep) as c:
324             writer = c.open("count.txt", "r+")
325             text = ''.join(["0123456789" for a in xrange(0, 100)])
326             for b in xrange(0, 100000):
327                 writer.write(text)
328             writer.seek(0, os.SEEK_SET)
329             writer.write("foo")
330             self.assertEqual(writer.size(), 100000000)
331
332             self.assertEqual(None, c.manifest_locator())
333             self.assertEqual(True, c.modified())
334             c.save_new("test_write_large")
335             self.assertEqual("zzzzz-4zz18-mockcollection0", c.manifest_locator())
336             self.assertEqual(False, c.modified())
337
338     def test_create(self):
339         keep = ArvadosFileWriterTestCase.MockKeep({})
340         api = ArvadosFileWriterTestCase.MockApi({"name":"test_create",
341                                                  "manifest_text":". 2e9ec317e197819358fbc43afca7d837+8 0:8:count.txt\n"},
342                                                 {"uuid":"zzzzz-4zz18-mockcollection0",
343                                                  "manifest_text":". 2e9ec317e197819358fbc43afca7d837+8 0:8:count.txt\n"})
344         with Collection(api_client=api, keep_client=keep) as c:
345             writer = c.open("count.txt", "w+")
346             self.assertEqual(writer.size(), 0)
347             writer.write("01234567")
348             self.assertEqual(writer.size(), 8)
349
350             self.assertEqual(None, c.manifest_locator())
351             self.assertEqual(True, c.modified())
352             self.assertEqual(None, keep.get("2e9ec317e197819358fbc43afca7d837+8"))
353             c.save_new("test_create")
354             self.assertEqual("zzzzz-4zz18-mockcollection0", c.manifest_locator())
355             self.assertEqual(False, c.modified())
356             self.assertEqual("01234567", keep.get("2e9ec317e197819358fbc43afca7d837+8"))
357
358
359     def test_create_subdir(self):
360         keep = ArvadosFileWriterTestCase.MockKeep({})
361         api = ArvadosFileWriterTestCase.MockApi({"name":"test_create",
362                                                  "manifest_text":"./foo/bar 2e9ec317e197819358fbc43afca7d837+8 0:8:count.txt\n"},
363                                                 {"uuid":"zzzzz-4zz18-mockcollection0",
364                                                  "manifest_text":"./foo/bar 2e9ec317e197819358fbc43afca7d837+8 0:8:count.txt\n"})
365         with Collection(api_client=api, keep_client=keep) as c:
366             self.assertIsNone(c.api_response())
367             writer = c.open("foo/bar/count.txt", "w+")
368             writer.write("01234567")
369             c.save_new("test_create")
370             self.assertEqual(c.api_response(), api.response)
371
372     def test_overwrite(self):
373         keep = ArvadosFileWriterTestCase.MockKeep({"781e5e245d69b566979b86e28d23f2c7+10": "0123456789"})
374         api = ArvadosFileWriterTestCase.MockApi({"name":"test_overwrite",
375                                                  "manifest_text":". 2e9ec317e197819358fbc43afca7d837+8 0:8:count.txt\n"},
376                                                 {"uuid":"zzzzz-4zz18-mockcollection0",
377                                                  "manifest_text":". 2e9ec317e197819358fbc43afca7d837+8 0:8:count.txt\n"})
378         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n',
379                              api_client=api, keep_client=keep) as c:
380             writer = c.open("count.txt", "w+")
381             self.assertEqual(writer.size(), 0)
382             writer.write("01234567")
383             self.assertEqual(writer.size(), 8)
384
385             self.assertEqual(None, c.manifest_locator())
386             self.assertEqual(True, c.modified())
387             c.save_new("test_overwrite")
388             self.assertEqual("zzzzz-4zz18-mockcollection0", c.manifest_locator())
389             self.assertEqual(False, c.modified())
390
391     def test_file_not_found(self):
392         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n') as c:
393             with self.assertRaises(IOError):
394                 writer = c.open("nocount.txt", "r")
395
396     def test_cannot_open_directory(self):
397         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count.txt\n') as c:
398             with self.assertRaises(IOError):
399                 writer = c.open(".", "r")
400
401     def test_create_multiple(self):
402         keep = ArvadosFileWriterTestCase.MockKeep({})
403         api = ArvadosFileWriterTestCase.MockApi({"name":"test_create_multiple",
404                                                  "manifest_text":". 2e9ec317e197819358fbc43afca7d837+8 e8dc4081b13434b45189a720b77b6818+8 0:8:count1.txt 8:8:count2.txt\n"},
405                                                 {"uuid":"zzzzz-4zz18-mockcollection0",
406                                                  "manifest_text":". 2e9ec317e197819358fbc43afca7d837+8 e8dc4081b13434b45189a720b77b6818+8 0:8:count1.txt 8:8:count2.txt\n"})
407         with Collection(api_client=api, keep_client=keep) as c:
408             w1 = c.open("count1.txt", "w")
409             w2 = c.open("count2.txt", "w")
410             w1.write("01234567")
411             w2.write("abcdefgh")
412             self.assertEqual(w1.size(), 8)
413             self.assertEqual(w2.size(), 8)
414
415             self.assertEqual(None, c.manifest_locator())
416             self.assertEqual(True, c.modified())
417             self.assertEqual(None, keep.get("2e9ec317e197819358fbc43afca7d837+8"))
418             c.save_new("test_create_multiple")
419             self.assertEqual("zzzzz-4zz18-mockcollection0", c.manifest_locator())
420             self.assertEqual(False, c.modified())
421             self.assertEqual("01234567", keep.get("2e9ec317e197819358fbc43afca7d837+8"))
422
423
424 class ArvadosFileReaderTestCase(StreamFileReaderTestCase):
425     class MockParent(object):
426         class MockBlockMgr(object):
427             def __init__(self, blocks, nocache):
428                 self.blocks = blocks
429                 self.nocache = nocache
430
431             def block_prefetch(self, loc):
432                 pass
433
434             def get_block_contents(self, loc, num_retries=0, cache_only=False):
435                 if self.nocache and cache_only:
436                     return None
437                 return self.blocks[loc]
438
439         def __init__(self, blocks, nocache):
440             self.blocks = blocks
441             self.nocache = nocache
442             self.lock = arvados.arvfile.NoopLock()
443
444         def root_collection(self):
445             return self
446
447         def _my_block_manager(self):
448             return ArvadosFileReaderTestCase.MockParent.MockBlockMgr(self.blocks, self.nocache)
449
450
451     def make_count_reader(self, nocache=False):
452         stream = []
453         n = 0
454         blocks = {}
455         for d in ['01234', '34567', '67890']:
456             loc = '{}+{}'.format(hashlib.md5(d).hexdigest(), len(d))
457             blocks[loc] = d
458             stream.append(Range(loc, n, len(d)))
459             n += len(d)
460         af = ArvadosFile(ArvadosFileReaderTestCase.MockParent(blocks, nocache), stream=stream, segments=[Range(1, 0, 3), Range(6, 3, 3), Range(11, 6, 3)])
461         return ArvadosFileReader(af, "count.txt")
462
463     def test_read_block_crossing_behavior(self):
464         # read() needs to return all the data requested if possible, even if it
465         # crosses uncached blocks: https://arvados.org/issues/5856
466         sfile = self.make_count_reader(nocache=True)
467         self.assertEqual('12345678', sfile.read(8))
468
469     def test_successive_reads(self):
470         # Override StreamFileReaderTestCase.test_successive_reads
471         sfile = self.make_count_reader(nocache=True)
472         self.assertEqual('1234', sfile.read(4))
473         self.assertEqual('5678', sfile.read(4))
474         self.assertEqual('9', sfile.read(4))
475         self.assertEqual('', sfile.read(4))
476
477     def test_tell_after_block_read(self):
478         # Override StreamFileReaderTestCase.test_tell_after_block_read
479         sfile = self.make_count_reader(nocache=True)
480         self.assertEqual('12345678', sfile.read(8))
481         self.assertEqual(8, sfile.tell())
482
483     def test_prefetch(self):
484         keep = ArvadosFileWriterTestCase.MockKeep({"2e9ec317e197819358fbc43afca7d837+8": "01234567", "e8dc4081b13434b45189a720b77b6818+8": "abcdefgh"})
485         with Collection(". 2e9ec317e197819358fbc43afca7d837+8 e8dc4081b13434b45189a720b77b6818+8 0:16:count.txt\n", keep_client=keep) as c:
486             r = c.open("count.txt", "r")
487             self.assertEqual("0123", r.read(4))
488         self.assertIn("2e9ec317e197819358fbc43afca7d837+8", keep.requests)
489         self.assertIn("e8dc4081b13434b45189a720b77b6818+8", keep.requests)
490
491     def test__eq__from_manifest(self):
492         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt') as c1:
493             with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt') as c2:
494                 self.assertTrue(c1["count1.txt"] == c2["count1.txt"])
495                 self.assertFalse(c1["count1.txt"] != c2["count1.txt"])
496
497     def test__eq__from_writes(self):
498         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt') as c1:
499             with Collection() as c2:
500                 with c2.open("count1.txt", "w") as f:
501                     f.write("0123456789")
502
503                 self.assertTrue(c1["count1.txt"] == c2["count1.txt"])
504                 self.assertFalse(c1["count1.txt"] != c2["count1.txt"])
505
506     def test__ne__(self):
507         with Collection('. 781e5e245d69b566979b86e28d23f2c7+10 0:10:count1.txt') as c1:
508             with Collection() as c2:
509                 with c2.open("count1.txt", "w") as f:
510                     f.write("1234567890")
511
512                 self.assertTrue(c1["count1.txt"] != c2["count1.txt"])
513                 self.assertFalse(c1["count1.txt"] == c2["count1.txt"])
514
515
516 class ArvadosFileReadTestCase(unittest.TestCase, StreamRetryTestMixin):
517     def reader_for(self, coll_name, **kwargs):
518         stream = []
519         segments = []
520         n = 0
521         for d in self.manifest_for(coll_name).split():
522             try:
523                 k = KeepLocator(d)
524                 segments.append(Range(n, n, k.size))
525                 stream.append(Range(d, n, k.size))
526                 n += k.size
527             except ValueError:
528                 pass
529
530         blockmanager = arvados.arvfile._BlockManager(self.keep_client())
531         blockmanager.prefetch_enabled = False
532         col = Collection(keep_client=self.keep_client(), block_manager=blockmanager)
533         af = ArvadosFile(col,
534                          stream=stream,
535                          segments=segments)
536         return ArvadosFileReader(af, "test", **kwargs)
537
538     def read_for_test(self, reader, byte_count, **kwargs):
539         return reader.read(byte_count, **kwargs)
540
541
542 class ArvadosFileReadFromTestCase(ArvadosFileReadTestCase):
543     def read_for_test(self, reader, byte_count, **kwargs):
544         return reader.readfrom(0, byte_count, **kwargs)
545
546
547 class ArvadosFileReadAllTestCase(ArvadosFileReadTestCase):
548     def read_for_test(self, reader, byte_count, **kwargs):
549         return ''.join(reader.readall(**kwargs))
550
551
552 class ArvadosFileReadAllDecompressedTestCase(ArvadosFileReadTestCase):
553     def read_for_test(self, reader, byte_count, **kwargs):
554         return ''.join(reader.readall_decompressed(**kwargs))
555
556
557 class ArvadosFileReadlinesTestCase(ArvadosFileReadTestCase):
558     def read_for_test(self, reader, byte_count, **kwargs):
559         return ''.join(reader.readlines(**kwargs))
560
561 class BlockManagerTest(unittest.TestCase):
562     def test_bufferblock_append(self):
563         keep = ArvadosFileWriterTestCase.MockKeep({})
564         blockmanager = arvados.arvfile._BlockManager(keep)
565         bufferblock = blockmanager.alloc_bufferblock()
566         bufferblock.append("foo")
567
568         self.assertEqual(bufferblock.size(), 3)
569         self.assertEqual(bufferblock.buffer_view[0:3], "foo")
570         self.assertEqual(bufferblock.locator(), "acbd18db4cc2f85cedef654fccc4a4d8+3")
571
572         bufferblock.append("bar")
573
574         self.assertEqual(bufferblock.size(), 6)
575         self.assertEqual(bufferblock.buffer_view[0:6], "foobar")
576         self.assertEqual(bufferblock.locator(), "3858f62230ac3c915f300c664312c63f+6")
577
578         bufferblock.set_state(arvados.arvfile._BufferBlock.PENDING)
579         with self.assertRaises(arvados.errors.AssertionError):
580             bufferblock.append("bar")
581
582     def test_bufferblock_dup(self):
583         keep = ArvadosFileWriterTestCase.MockKeep({})
584         blockmanager = arvados.arvfile._BlockManager(keep)
585         bufferblock = blockmanager.alloc_bufferblock()
586         bufferblock.append("foo")
587
588         self.assertEqual(bufferblock.size(), 3)
589         self.assertEqual(bufferblock.buffer_view[0:3], "foo")
590         self.assertEqual(bufferblock.locator(), "acbd18db4cc2f85cedef654fccc4a4d8+3")
591         bufferblock.set_state(arvados.arvfile._BufferBlock.PENDING)
592
593         bufferblock2 = blockmanager.dup_block(bufferblock, None)
594         self.assertNotEqual(bufferblock.blockid, bufferblock2.blockid)
595
596         bufferblock2.append("bar")
597
598         self.assertEqual(bufferblock2.size(), 6)
599         self.assertEqual(bufferblock2.buffer_view[0:6], "foobar")
600         self.assertEqual(bufferblock2.locator(), "3858f62230ac3c915f300c664312c63f+6")
601
602         self.assertEqual(bufferblock.size(), 3)
603         self.assertEqual(bufferblock.buffer_view[0:3], "foo")
604         self.assertEqual(bufferblock.locator(), "acbd18db4cc2f85cedef654fccc4a4d8+3")
605
606     def test_bufferblock_get(self):
607         keep = ArvadosFileWriterTestCase.MockKeep({"781e5e245d69b566979b86e28d23f2c7+10": "0123456789"})
608         blockmanager = arvados.arvfile._BlockManager(keep)
609         bufferblock = blockmanager.alloc_bufferblock()
610         bufferblock.append("foo")
611
612         self.assertEqual(blockmanager.get_block_contents("781e5e245d69b566979b86e28d23f2c7+10", 1), "0123456789")
613         self.assertEqual(blockmanager.get_block_contents(bufferblock.blockid, 1), "foo")
614
615     def test_bufferblock_commit(self):
616         mockkeep = mock.MagicMock()
617         blockmanager = arvados.arvfile._BlockManager(mockkeep)
618         bufferblock = blockmanager.alloc_bufferblock()
619         bufferblock.owner = mock.MagicMock()
620         bufferblock.owner.flush.side_effect = lambda: blockmanager.commit_bufferblock(bufferblock)
621         bufferblock.append("foo")
622         blockmanager.commit_all()
623         self.assertTrue(bufferblock.owner.flush.called)
624         self.assertTrue(mockkeep.put.called)
625         self.assertEqual(bufferblock.state(), arvados.arvfile._BufferBlock.COMMITTED)
626         self.assertIsNone(bufferblock.buffer_view)
627
628
629     def test_bufferblock_commit_with_error(self):
630         mockkeep = mock.MagicMock()
631         mockkeep.put.side_effect = arvados.errors.KeepWriteError("fail")
632         blockmanager = arvados.arvfile._BlockManager(mockkeep)
633         bufferblock = blockmanager.alloc_bufferblock()
634         bufferblock.owner = mock.MagicMock()
635         bufferblock.owner.flush.side_effect = lambda: blockmanager.commit_bufferblock(bufferblock)
636         bufferblock.append("foo")
637         with self.assertRaises(arvados.errors.KeepWriteError) as err:
638             blockmanager.commit_all()
639         self.assertTrue(bufferblock.owner.flush.called)
640         self.assertEqual(str(err.exception), "Error writing some blocks: block acbd18db4cc2f85cedef654fccc4a4d8+3 raised KeepWriteError (fail)")
641         self.assertEqual(bufferblock.state(), arvados.arvfile._BufferBlock.PENDING)