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