4823: Fix instance of Collection -> CollectionRoot. Tweaked a couple of comments.
[arvados.git] / sdk / python / tests / test_keep_client.py
1 import hashlib
2 import mock
3 import os
4 import re
5 import socket
6 import unittest
7 import urlparse
8
9 import arvados
10 import arvados.retry
11 import arvados_testutil as tutil
12 import run_test_server
13
14 class KeepTestCase(run_test_server.TestCaseWithServers):
15     MAIN_SERVER = {}
16     KEEP_SERVER = {}
17
18     @classmethod
19     def setUpClass(cls):
20         super(KeepTestCase, cls).setUpClass()
21         run_test_server.authorize_with("admin")
22         cls.api_client = arvados.api('v1')
23         cls.keep_client = arvados.KeepClient(api_client=cls.api_client,
24                                              proxy='', local_store='')
25
26     def test_KeepBasicRWTest(self):
27         foo_locator = self.keep_client.put('foo')
28         self.assertRegexpMatches(
29             foo_locator,
30             '^acbd18db4cc2f85cedef654fccc4a4d8\+3',
31             'wrong md5 hash from Keep.put("foo"): ' + foo_locator)
32         self.assertEqual(self.keep_client.get(foo_locator),
33                          'foo',
34                          'wrong content from Keep.get(md5("foo"))')
35
36     def test_KeepBinaryRWTest(self):
37         blob_str = '\xff\xfe\xf7\x00\x01\x02'
38         blob_locator = self.keep_client.put(blob_str)
39         self.assertRegexpMatches(
40             blob_locator,
41             '^7fc7c53b45e53926ba52821140fef396\+6',
42             ('wrong locator from Keep.put(<binarydata>):' + blob_locator))
43         self.assertEqual(self.keep_client.get(blob_locator),
44                          blob_str,
45                          'wrong content from Keep.get(md5(<binarydata>))')
46
47     def test_KeepLongBinaryRWTest(self):
48         blob_str = '\xff\xfe\xfd\xfc\x00\x01\x02\x03'
49         for i in range(0,23):
50             blob_str = blob_str + blob_str
51         blob_locator = self.keep_client.put(blob_str)
52         self.assertRegexpMatches(
53             blob_locator,
54             '^84d90fc0d8175dd5dcfab04b999bc956\+67108864',
55             ('wrong locator from Keep.put(<binarydata>): ' + blob_locator))
56         self.assertEqual(self.keep_client.get(blob_locator),
57                          blob_str,
58                          'wrong content from Keep.get(md5(<binarydata>))')
59
60     def test_KeepSingleCopyRWTest(self):
61         blob_str = '\xff\xfe\xfd\xfc\x00\x01\x02\x03'
62         blob_locator = self.keep_client.put(blob_str, copies=1)
63         self.assertRegexpMatches(
64             blob_locator,
65             '^c902006bc98a3eb4a3663b65ab4a6fab\+8',
66             ('wrong locator from Keep.put(<binarydata>): ' + blob_locator))
67         self.assertEqual(self.keep_client.get(blob_locator),
68                          blob_str,
69                          'wrong content from Keep.get(md5(<binarydata>))')
70
71     def test_KeepEmptyCollectionTest(self):
72         blob_locator = self.keep_client.put('', copies=1)
73         self.assertRegexpMatches(
74             blob_locator,
75             '^d41d8cd98f00b204e9800998ecf8427e\+0',
76             ('wrong locator from Keep.put(""): ' + blob_locator))
77
78
79 class KeepPermissionTestCase(run_test_server.TestCaseWithServers):
80     MAIN_SERVER = {}
81     KEEP_SERVER = {'blob_signing_key': 'abcdefghijk0123456789',
82                    'enforce_permissions': True}
83
84     def test_KeepBasicRWTest(self):
85         run_test_server.authorize_with('active')
86         keep_client = arvados.KeepClient()
87         foo_locator = keep_client.put('foo')
88         self.assertRegexpMatches(
89             foo_locator,
90             r'^acbd18db4cc2f85cedef654fccc4a4d8\+3\+A[a-f0-9]+@[a-f0-9]+$',
91             'invalid locator from Keep.put("foo"): ' + foo_locator)
92         self.assertEqual(keep_client.get(foo_locator),
93                          'foo',
94                          'wrong content from Keep.get(md5("foo"))')
95
96         # GET with an unsigned locator => NotFound
97         bar_locator = keep_client.put('bar')
98         unsigned_bar_locator = "37b51d194a7513e45b56f6524f2d51f2+3"
99         self.assertRegexpMatches(
100             bar_locator,
101             r'^37b51d194a7513e45b56f6524f2d51f2\+3\+A[a-f0-9]+@[a-f0-9]+$',
102             'invalid locator from Keep.put("bar"): ' + bar_locator)
103         self.assertRaises(arvados.errors.NotFoundError,
104                           keep_client.get,
105                           unsigned_bar_locator)
106
107         # GET from a different user => NotFound
108         run_test_server.authorize_with('spectator')
109         self.assertRaises(arvados.errors.NotFoundError,
110                           arvados.Keep.get,
111                           bar_locator)
112
113         # Unauthenticated GET for a signed locator => NotFound
114         # Unauthenticated GET for an unsigned locator => NotFound
115         keep_client.api_token = ''
116         self.assertRaises(arvados.errors.NotFoundError,
117                           keep_client.get,
118                           bar_locator)
119         self.assertRaises(arvados.errors.NotFoundError,
120                           keep_client.get,
121                           unsigned_bar_locator)
122
123
124 # KeepOptionalPermission: starts Keep with --permission-key-file
125 # but not --enforce-permissions (i.e. generate signatures on PUT
126 # requests, but do not require them for GET requests)
127 #
128 # All of these requests should succeed when permissions are optional:
129 # * authenticated request, signed locator
130 # * authenticated request, unsigned locator
131 # * unauthenticated request, signed locator
132 # * unauthenticated request, unsigned locator
133 class KeepOptionalPermission(run_test_server.TestCaseWithServers):
134     MAIN_SERVER = {}
135     KEEP_SERVER = {'blob_signing_key': 'abcdefghijk0123456789',
136                    'enforce_permissions': False}
137
138     @classmethod
139     def setUpClass(cls):
140         super(KeepOptionalPermission, cls).setUpClass()
141         run_test_server.authorize_with("admin")
142         cls.api_client = arvados.api('v1')
143
144     def setUp(self):
145         super(KeepOptionalPermission, self).setUp()
146         self.keep_client = arvados.KeepClient(api_client=self.api_client,
147                                               proxy='', local_store='')
148
149     def _put_foo_and_check(self):
150         signed_locator = self.keep_client.put('foo')
151         self.assertRegexpMatches(
152             signed_locator,
153             r'^acbd18db4cc2f85cedef654fccc4a4d8\+3\+A[a-f0-9]+@[a-f0-9]+$',
154             'invalid locator from Keep.put("foo"): ' + signed_locator)
155         return signed_locator
156
157     def test_KeepAuthenticatedSignedTest(self):
158         signed_locator = self._put_foo_and_check()
159         self.assertEqual(self.keep_client.get(signed_locator),
160                          'foo',
161                          'wrong content from Keep.get(md5("foo"))')
162
163     def test_KeepAuthenticatedUnsignedTest(self):
164         signed_locator = self._put_foo_and_check()
165         self.assertEqual(self.keep_client.get("acbd18db4cc2f85cedef654fccc4a4d8"),
166                          'foo',
167                          'wrong content from Keep.get(md5("foo"))')
168
169     def test_KeepUnauthenticatedSignedTest(self):
170         # Check that signed GET requests work even when permissions
171         # enforcement is off.
172         signed_locator = self._put_foo_and_check()
173         self.keep_client.api_token = ''
174         self.assertEqual(self.keep_client.get(signed_locator),
175                          'foo',
176                          'wrong content from Keep.get(md5("foo"))')
177
178     def test_KeepUnauthenticatedUnsignedTest(self):
179         # Since --enforce-permissions is not in effect, GET requests
180         # need not be authenticated.
181         signed_locator = self._put_foo_and_check()
182         self.keep_client.api_token = ''
183         self.assertEqual(self.keep_client.get("acbd18db4cc2f85cedef654fccc4a4d8"),
184                          'foo',
185                          'wrong content from Keep.get(md5("foo"))')
186
187
188 class KeepProxyTestCase(run_test_server.TestCaseWithServers):
189     MAIN_SERVER = {}
190     KEEP_SERVER = {}
191     KEEP_PROXY_SERVER = {'auth': 'admin'}
192
193     @classmethod
194     def setUpClass(cls):
195         super(KeepProxyTestCase, cls).setUpClass()
196         cls.api_client = arvados.api('v1')
197
198     def tearDown(self):
199         arvados.config.settings().pop('ARVADOS_EXTERNAL_CLIENT', None)
200         super(KeepProxyTestCase, self).tearDown()
201
202     def test_KeepProxyTest1(self):
203         # Will use ARVADOS_KEEP_PROXY environment variable that is set by
204         # setUpClass().
205         keep_client = arvados.KeepClient(api_client=self.api_client,
206                                          local_store='')
207         baz_locator = keep_client.put('baz')
208         self.assertRegexpMatches(
209             baz_locator,
210             '^73feffa4b7f6bb68e44cf984c85f6e88\+3',
211             'wrong md5 hash from Keep.put("baz"): ' + baz_locator)
212         self.assertEqual(keep_client.get(baz_locator),
213                          'baz',
214                          'wrong content from Keep.get(md5("baz"))')
215         self.assertTrue(keep_client.using_proxy)
216
217     def test_KeepProxyTest2(self):
218         # Don't instantiate the proxy directly, but set the X-External-Client
219         # header.  The API server should direct us to the proxy.
220         arvados.config.settings()['ARVADOS_EXTERNAL_CLIENT'] = 'true'
221         keep_client = arvados.KeepClient(api_client=self.api_client,
222                                          proxy='', local_store='')
223         baz_locator = keep_client.put('baz2')
224         self.assertRegexpMatches(
225             baz_locator,
226             '^91f372a266fe2bf2823cb8ec7fda31ce\+4',
227             'wrong md5 hash from Keep.put("baz2"): ' + baz_locator)
228         self.assertEqual(keep_client.get(baz_locator),
229                          'baz2',
230                          'wrong content from Keep.get(md5("baz2"))')
231         self.assertTrue(keep_client.using_proxy)
232
233
234 class KeepClientServiceTestCase(unittest.TestCase):
235     def mock_keep_services(self, *services):
236         api_client = mock.MagicMock(name='api_client')
237         api_client.keep_services().accessible().execute.return_value = {
238             'items_available': len(services),
239             'items': [{
240                     'uuid': 'zzzzz-bi6l4-{:015x}'.format(index),
241                     'owner_uuid': 'zzzzz-tpzed-000000000000000',
242                     'service_host': host,
243                     'service_port': port,
244                     'service_ssl_flag': ssl,
245                     'service_type': servtype,
246                     } for index, (host, port, ssl, servtype)
247                       in enumerate(services)],
248             }
249         return api_client
250
251     def mock_n_keep_disks(self, service_count):
252         return self.mock_keep_services(
253             *[("keep0x{:x}".format(index), 80, False, 'disk')
254               for index in range(service_count)])
255
256     def get_service_roots(self, *services):
257         api_client = self.mock_keep_services(*services)
258         keep_client = arvados.KeepClient(api_client=api_client)
259         services = keep_client.weighted_service_roots('000000')
260         return [urlparse.urlparse(url) for url in sorted(services)]
261
262     def test_ssl_flag_respected_in_roots(self):
263         services = self.get_service_roots(('keep', 10, False, 'disk'),
264                                           ('keep', 20, True, 'disk'))
265         self.assertEqual(10, services[0].port)
266         self.assertEqual('http', services[0].scheme)
267         self.assertEqual(20, services[1].port)
268         self.assertEqual('https', services[1].scheme)
269
270     def test_correct_ports_with_ipv6_addresses(self):
271         service = self.get_service_roots(('100::1', 10, True, 'proxy'))[0]
272         self.assertEqual('100::1', service.hostname)
273         self.assertEqual(10, service.port)
274
275     # test_get_timeout and test_put_timeout test that
276     # KeepClient.get and KeepClient.put use the appropriate timeouts
277     # when connected directly to a Keep server (i.e. non-proxy timeout)
278
279     def test_get_timeout(self):
280         api_client = self.mock_keep_services(('keep', 10, False, 'disk'))
281         force_timeout = [socket.timeout("timed out")]
282         with tutil.mock_get(force_timeout) as mock_session:
283             keep_client = arvados.KeepClient(api_client=api_client)
284             with self.assertRaises(arvados.errors.KeepReadError):
285                 keep_client.get('ffffffffffffffffffffffffffffffff')
286             self.assertTrue(mock_session.return_value.get.called)
287             self.assertEqual(
288                 arvados.KeepClient.DEFAULT_TIMEOUT,
289                 mock_session.return_value.get.call_args[1]['timeout'])
290
291     def test_put_timeout(self):
292         api_client = self.mock_keep_services(('keep', 10, False, 'disk'))
293         force_timeout = [socket.timeout("timed out")]
294         with tutil.mock_put(force_timeout) as mock_session:
295             keep_client = arvados.KeepClient(api_client=api_client)
296             with self.assertRaises(arvados.errors.KeepWriteError):
297                 keep_client.put('foo')
298             self.assertTrue(mock_session.return_value.put.called)
299             self.assertEqual(
300                 arvados.KeepClient.DEFAULT_TIMEOUT,
301                 mock_session.return_value.put.call_args[1]['timeout'])
302
303     def test_proxy_get_timeout(self):
304         # Force a timeout, verifying that the requests.get or
305         # requests.put method was called with the proxy_timeout
306         # setting rather than the default timeout.
307         api_client = self.mock_keep_services(('keep', 10, False, 'proxy'))
308         force_timeout = [socket.timeout("timed out")]
309         with tutil.mock_get(force_timeout) as mock_session:
310             keep_client = arvados.KeepClient(api_client=api_client)
311             with self.assertRaises(arvados.errors.KeepReadError):
312                 keep_client.get('ffffffffffffffffffffffffffffffff')
313             self.assertTrue(mock_session.return_value.get.called)
314             self.assertEqual(
315                 arvados.KeepClient.DEFAULT_PROXY_TIMEOUT,
316                 mock_session.return_value.get.call_args[1]['timeout'])
317
318     def test_proxy_put_timeout(self):
319         # Force a timeout, verifying that the requests.get or
320         # requests.put method was called with the proxy_timeout
321         # setting rather than the default timeout.
322         api_client = self.mock_keep_services(('keep', 10, False, 'proxy'))
323         force_timeout = [socket.timeout("timed out")]
324         with tutil.mock_put(force_timeout) as mock_session:
325             keep_client = arvados.KeepClient(api_client=api_client)
326             with self.assertRaises(arvados.errors.KeepWriteError):
327                 keep_client.put('foo')
328             self.assertTrue(mock_session.return_value.put.called)
329             self.assertEqual(
330                 arvados.KeepClient.DEFAULT_PROXY_TIMEOUT,
331                 mock_session.return_value.put.call_args[1]['timeout'])
332
333     def test_probe_order_reference_set(self):
334         # expected_order[i] is the probe order for
335         # hash=md5(sprintf("%064x",i)) where there are 16 services
336         # with uuid sprintf("anything-%015x",j) with j in 0..15. E.g.,
337         # the first probe for the block consisting of 64 "0"
338         # characters is the service whose uuid is
339         # "zzzzz-bi6l4-000000000000003", so expected_order[0][0]=='3'.
340         expected_order = [
341             list('3eab2d5fc9681074'),
342             list('097dba52e648f1c3'),
343             list('c5b4e023f8a7d691'),
344             list('9d81c02e76a3bf54'),
345             ]
346         hashes = [
347             hashlib.md5("{:064x}".format(x)).hexdigest()
348             for x in range(len(expected_order))]
349         api_client = self.mock_n_keep_disks(16)
350         keep_client = arvados.KeepClient(api_client=api_client)
351         for i, hash in enumerate(hashes):
352             roots = keep_client.weighted_service_roots(hash)
353             got_order = [
354                 re.search(r'//\[?keep0x([0-9a-f]+)', root).group(1)
355                 for root in roots]
356             self.assertEqual(expected_order[i], got_order)
357
358     def test_probe_waste_adding_one_server(self):
359         hashes = [
360             hashlib.md5("{:064x}".format(x)).hexdigest() for x in range(100)]
361         initial_services = 12
362         api_client = self.mock_n_keep_disks(initial_services)
363         keep_client = arvados.KeepClient(api_client=api_client)
364         probes_before = [
365             keep_client.weighted_service_roots(hash) for hash in hashes]
366         for added_services in range(1, 12):
367             api_client = self.mock_n_keep_disks(initial_services+added_services)
368             keep_client = arvados.KeepClient(api_client=api_client)
369             total_penalty = 0
370             for hash_index in range(len(hashes)):
371                 probe_after = keep_client.weighted_service_roots(
372                     hashes[hash_index])
373                 penalty = probe_after.index(probes_before[hash_index][0])
374                 self.assertLessEqual(penalty, added_services)
375                 total_penalty += penalty
376             # Average penalty per block should not exceed
377             # N(added)/N(orig) by more than 20%, and should get closer
378             # to the ideal as we add data points.
379             expect_penalty = (
380                 added_services *
381                 len(hashes) / initial_services)
382             max_penalty = (
383                 expect_penalty *
384                 (120 - added_services)/100)
385             min_penalty = (
386                 expect_penalty * 8/10)
387             self.assertTrue(
388                 min_penalty <= total_penalty <= max_penalty,
389                 "With {}+{} services, {} blocks, penalty {} but expected {}..{}".format(
390                     initial_services,
391                     added_services,
392                     len(hashes),
393                     total_penalty,
394                     min_penalty,
395                     max_penalty))
396
397     def check_64_zeros_error_order(self, verb, exc_class):
398         data = '0' * 64
399         if verb == 'get':
400             data = hashlib.md5(data).hexdigest() + '+1234'
401         api_client = self.mock_n_keep_disks(16)
402         keep_client = arvados.KeepClient(api_client=api_client)
403         with mock.patch('requests.' + verb,
404                         side_effect=socket.timeout) as req_mock, \
405                 self.assertRaises(exc_class) as err_check:
406             getattr(keep_client, verb)(data)
407         urls = [urlparse.urlparse(url)
408                 for url in err_check.exception.service_errors()]
409         self.assertEqual([('keep0x' + c, 80) for c in '3eab2d5fc9681074'],
410                          [(url.hostname, url.port) for url in urls])
411
412     def test_get_error_shows_probe_order(self):
413         self.check_64_zeros_error_order('get', arvados.errors.KeepReadError)
414
415     def test_put_error_shows_probe_order(self):
416         self.check_64_zeros_error_order('put', arvados.errors.KeepWriteError)
417
418     def check_no_services_error(self, verb, exc_class):
419         api_client = mock.MagicMock(name='api_client')
420         api_client.keep_services().accessible().execute.side_effect = (
421             arvados.errors.ApiError)
422         keep_client = arvados.KeepClient(api_client=api_client)
423         with self.assertRaises(exc_class) as err_check:
424             getattr(keep_client, verb)('d41d8cd98f00b204e9800998ecf8427e+0')
425         self.assertEqual(0, len(err_check.exception.service_errors()))
426
427     def test_get_error_with_no_services(self):
428         self.check_no_services_error('get', arvados.errors.KeepReadError)
429
430     def test_put_error_with_no_services(self):
431         self.check_no_services_error('put', arvados.errors.KeepWriteError)
432
433     def check_errors_from_last_retry(self, verb, exc_class):
434         api_client = self.mock_n_keep_disks(2)
435         req_mock = getattr(tutil, 'mock_{}_responses'.format(verb))(
436             "retry error reporting test", 500, 500, 403, 403)
437         with req_mock, tutil.skip_sleep, \
438                 self.assertRaises(exc_class) as err_check:
439             keep_client = arvados.KeepClient(api_client=api_client)
440             getattr(keep_client, verb)('d41d8cd98f00b204e9800998ecf8427e+0',
441                                        num_retries=3)
442         self.assertEqual([403, 403], [
443                 getattr(error, 'status_code', None)
444                 for error in err_check.exception.service_errors().itervalues()])
445
446     def test_get_error_reflects_last_retry(self):
447         self.check_errors_from_last_retry('get', arvados.errors.KeepReadError)
448
449     def test_put_error_reflects_last_retry(self):
450         self.check_errors_from_last_retry('put', arvados.errors.KeepWriteError)
451
452     def test_put_error_does_not_include_successful_puts(self):
453         data = 'partial failure test'
454         data_loc = '{}+{}'.format(hashlib.md5(data).hexdigest(), len(data))
455         api_client = self.mock_n_keep_disks(3)
456         with tutil.mock_put_responses(data_loc, 200, 500, 500) as req_mock, \
457                 self.assertRaises(arvados.errors.KeepWriteError) as exc_check:
458             keep_client = arvados.KeepClient(api_client=api_client)
459             keep_client.put(data)
460         self.assertEqual(2, len(exc_check.exception.service_errors()))
461
462
463 class KeepClientRetryTestMixin(object):
464     # Testing with a local Keep store won't exercise the retry behavior.
465     # Instead, our strategy is:
466     # * Create a client with one proxy specified (pointed at a black
467     #   hole), so there's no need to instantiate an API client, and
468     #   all HTTP requests come from one place.
469     # * Mock httplib's request method to provide simulated responses.
470     # This lets us test the retry logic extensively without relying on any
471     # supporting servers, and prevents side effects in case something hiccups.
472     # To use this mixin, define DEFAULT_EXPECT, DEFAULT_EXCEPTION, and
473     # run_method().
474     #
475     # Test classes must define TEST_PATCHER to a method that mocks
476     # out appropriate methods in the client.
477
478     PROXY_ADDR = 'http://[%s]:65535/' % (tutil.TEST_HOST,)
479     TEST_DATA = 'testdata'
480     TEST_LOCATOR = 'ef654c40ab4f1747fc699915d4f70902+8'
481
482     def setUp(self):
483         self.client_kwargs = {'proxy': self.PROXY_ADDR, 'local_store': ''}
484
485     def new_client(self, **caller_kwargs):
486         kwargs = self.client_kwargs.copy()
487         kwargs.update(caller_kwargs)
488         return arvados.KeepClient(**kwargs)
489
490     def run_method(self, *args, **kwargs):
491         raise NotImplementedError("test subclasses must define run_method")
492
493     def check_success(self, expected=None, *args, **kwargs):
494         if expected is None:
495             expected = self.DEFAULT_EXPECT
496         self.assertEqual(expected, self.run_method(*args, **kwargs))
497
498     def check_exception(self, error_class=None, *args, **kwargs):
499         if error_class is None:
500             error_class = self.DEFAULT_EXCEPTION
501         self.assertRaises(error_class, self.run_method, *args, **kwargs)
502
503     def test_immediate_success(self):
504         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 200):
505             self.check_success()
506
507     def test_retry_then_success(self):
508         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
509             self.check_success(num_retries=3)
510
511     def test_no_default_retry(self):
512         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
513             self.check_exception()
514
515     def test_no_retry_after_permanent_error(self):
516         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 403, 200):
517             self.check_exception(num_retries=3)
518
519     def test_error_after_retries_exhausted(self):
520         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 500, 200):
521             self.check_exception(num_retries=1)
522
523     def test_num_retries_instance_fallback(self):
524         self.client_kwargs['num_retries'] = 3
525         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
526             self.check_success()
527
528
529 @tutil.skip_sleep
530 class KeepClientRetryGetTestCase(KeepClientRetryTestMixin, unittest.TestCase):
531     DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_DATA
532     DEFAULT_EXCEPTION = arvados.errors.KeepReadError
533     HINTED_LOCATOR = KeepClientRetryTestMixin.TEST_LOCATOR + '+K@xyzzy'
534     TEST_PATCHER = staticmethod(tutil.mock_get_responses)
535
536     def run_method(self, locator=KeepClientRetryTestMixin.TEST_LOCATOR,
537                    *args, **kwargs):
538         return self.new_client().get(locator, *args, **kwargs)
539
540     def test_specific_exception_when_not_found(self):
541         with tutil.mock_get_responses(self.DEFAULT_EXPECT, 404, 200):
542             self.check_exception(arvados.errors.NotFoundError, num_retries=3)
543
544     def test_general_exception_with_mixed_errors(self):
545         # get should raise a NotFoundError if no server returns the block,
546         # and a high threshold of servers report that it's not found.
547         # This test rigs up 50/50 disagreement between two servers, and
548         # checks that it does not become a NotFoundError.
549         client = self.new_client()
550         with tutil.mock_get_responses(self.DEFAULT_EXPECT, 404, 500):
551             with self.assertRaises(arvados.errors.KeepReadError) as exc_check:
552                 client.get(self.HINTED_LOCATOR)
553             self.assertNotIsInstance(
554                 exc_check.exception, arvados.errors.NotFoundError,
555                 "mixed errors raised NotFoundError")
556
557     def test_hint_server_can_succeed_without_retries(self):
558         with tutil.mock_get_responses(self.DEFAULT_EXPECT, 404, 200, 500):
559             self.check_success(locator=self.HINTED_LOCATOR)
560
561     def test_try_next_server_after_timeout(self):
562         with tutil.mock_get([
563                 socket.timeout("timed out"),
564                 tutil.fake_requests_response(200, self.DEFAULT_EXPECT)]):
565             self.check_success(locator=self.HINTED_LOCATOR)
566
567     def test_retry_data_with_wrong_checksum(self):
568         with tutil.mock_get((tutil.fake_requests_response(200, s) for s in ['baddata', self.TEST_DATA])):
569             self.check_success(locator=self.HINTED_LOCATOR)
570
571
572 @tutil.skip_sleep
573 class KeepClientRetryPutTestCase(KeepClientRetryTestMixin, unittest.TestCase):
574     DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_LOCATOR
575     DEFAULT_EXCEPTION = arvados.errors.KeepWriteError
576     TEST_PATCHER = staticmethod(tutil.mock_put_responses)
577
578     def run_method(self, data=KeepClientRetryTestMixin.TEST_DATA,
579                    copies=1, *args, **kwargs):
580         return self.new_client().put(data, copies, *args, **kwargs)
581
582     def test_do_not_send_multiple_copies_to_same_server(self):
583         with tutil.mock_put_responses(self.DEFAULT_EXPECT, 200):
584             self.check_exception(copies=2, num_retries=3)