Merge branch '21356-clean-imports'
[arvados.git] / sdk / python / tests / test_retry.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 import itertools
6 import unittest
7
8 from unittest import mock
9
10 import arvados.errors as arv_error
11 import arvados.retry as arv_retry
12
13 class RetryLoopTestMixin(object):
14     @staticmethod
15     def loop_success(result):
16         # During the tests, we use integers that look like HTTP status
17         # codes as loop results.  Then we define simplified HTTP
18         # heuristics here to decide whether the result is success (True),
19         # permanent failure (False), or temporary failure (None).
20         if result < 400:
21             return True
22         elif result < 500:
23             return False
24         else:
25             return None
26
27     def run_loop(self, num_retries, *results, **kwargs):
28         responses = itertools.chain(results, itertools.repeat(None))
29         retrier = arv_retry.RetryLoop(num_retries, self.loop_success,
30                                       **kwargs)
31         for tries_left, response in zip(retrier, responses):
32             retrier.save_result(response)
33         return retrier
34
35     def check_result(self, retrier, expect_success, last_code):
36         self.assertIs(retrier.success(), expect_success,
37                       "loop success flag is incorrect")
38         self.assertEqual(last_code, retrier.last_result())
39
40
41 class RetryLoopTestCase(unittest.TestCase, RetryLoopTestMixin):
42     def test_zero_retries_and_success(self):
43         retrier = self.run_loop(0, 200)
44         self.check_result(retrier, True, 200)
45
46     def test_zero_retries_and_tempfail(self):
47         retrier = self.run_loop(0, 500, 501)
48         self.check_result(retrier, None, 500)
49
50     def test_zero_retries_and_permfail(self):
51         retrier = self.run_loop(0, 400, 201)
52         self.check_result(retrier, False, 400)
53
54     def test_one_retry_with_immediate_success(self):
55         retrier = self.run_loop(1, 200, 201)
56         self.check_result(retrier, True, 200)
57
58     def test_one_retry_with_delayed_success(self):
59         retrier = self.run_loop(1, 500, 201)
60         self.check_result(retrier, True, 201)
61
62     def test_one_retry_with_no_success(self):
63         retrier = self.run_loop(1, 500, 501, 502)
64         self.check_result(retrier, None, 501)
65
66     def test_one_retry_but_permfail(self):
67         retrier = self.run_loop(1, 400, 201)
68         self.check_result(retrier, False, 400)
69
70     def test_two_retries_with_immediate_success(self):
71         retrier = self.run_loop(2, 200, 201, 202)
72         self.check_result(retrier, True, 200)
73
74     def test_two_retries_with_success_after_one(self):
75         retrier = self.run_loop(2, 500, 201, 502)
76         self.check_result(retrier, True, 201)
77
78     def test_two_retries_with_success_after_two(self):
79         retrier = self.run_loop(2, 500, 501, 202, 503)
80         self.check_result(retrier, True, 202)
81
82     def test_two_retries_with_no_success(self):
83         retrier = self.run_loop(2, 500, 501, 502, 503)
84         self.check_result(retrier, None, 502)
85
86     def test_two_retries_with_permfail(self):
87         retrier = self.run_loop(2, 500, 401, 202)
88         self.check_result(retrier, False, 401)
89
90     def test_save_result_before_start_is_error(self):
91         retrier = arv_retry.RetryLoop(0)
92         self.assertRaises(arv_error.AssertionError, retrier.save_result, 1)
93
94     def test_save_result_after_end_is_error(self):
95         retrier = arv_retry.RetryLoop(0)
96         for count in retrier:
97             pass
98         self.assertRaises(arv_error.AssertionError, retrier.save_result, 1)
99
100
101 @mock.patch('time.time', side_effect=itertools.count())
102 @mock.patch('time.sleep')
103 class RetryLoopBackoffTestCase(unittest.TestCase, RetryLoopTestMixin):
104     def run_loop(self, num_retries, *results, **kwargs):
105         kwargs.setdefault('backoff_start', 8)
106         return super(RetryLoopBackoffTestCase, self).run_loop(
107             num_retries, *results, **kwargs)
108
109     def check_backoff(self, sleep_mock, sleep_count, multiplier=1):
110         # Figure out how much time we actually spent sleeping.
111         sleep_times = [arglist[0][0] for arglist in sleep_mock.call_args_list
112                        if arglist[0][0] > 0]
113         self.assertEqual(sleep_count, len(sleep_times),
114                          "loop did not back off correctly")
115         last_wait = 0
116         for this_wait in sleep_times:
117             self.assertGreater(this_wait, last_wait * multiplier,
118                                "loop did not grow backoff times correctly")
119             last_wait = this_wait
120
121     def test_no_backoff_with_no_retries(self, sleep_mock, time_mock):
122         self.run_loop(0, 500, 201)
123         self.check_backoff(sleep_mock, 0)
124
125     def test_no_backoff_after_success(self, sleep_mock, time_mock):
126         self.run_loop(1, 200, 501)
127         self.check_backoff(sleep_mock, 0)
128
129     def test_no_backoff_after_permfail(self, sleep_mock, time_mock):
130         self.run_loop(1, 400, 201)
131         self.check_backoff(sleep_mock, 0)
132
133     def test_backoff_before_success(self, sleep_mock, time_mock):
134         self.run_loop(5, 500, 501, 502, 203, 504)
135         self.check_backoff(sleep_mock, 3)
136
137     def test_backoff_before_permfail(self, sleep_mock, time_mock):
138         self.run_loop(5, 500, 501, 502, 403, 504)
139         self.check_backoff(sleep_mock, 3)
140
141     def test_backoff_all_tempfail(self, sleep_mock, time_mock):
142         self.run_loop(3, 500, 501, 502, 503, 504)
143         self.check_backoff(sleep_mock, 3)
144
145     def test_backoff_multiplier(self, sleep_mock, time_mock):
146         self.run_loop(5, 500, 501, 502, 503, 504, 505,
147                       backoff_start=5, backoff_growth=10, max_wait=1000000000)
148         self.check_backoff(sleep_mock, 5, 9)
149
150
151 class CheckHTTPResponseSuccessTestCase(unittest.TestCase):
152     def results_map(self, *codes):
153         for code in codes:
154             yield code, arv_retry.check_http_response_success(code)
155
156     def check(assert_name):
157         def check_method(self, expected, *codes):
158             assert_func = getattr(self, assert_name)
159             for code, actual in self.results_map(*codes):
160                 assert_func(expected, actual,
161                             "{} status flagged {}".format(code, actual))
162                 if assert_name != 'assertIs':
163                     self.assertTrue(
164                         actual is True or actual is False or actual is None,
165                         "{} status returned {}".format(code, actual))
166         return check_method
167
168     check_is = check('assertIs')
169     check_is_not = check('assertIsNot')
170
171     def test_obvious_successes(self):
172         self.check_is(True, *list(range(200, 207)))
173
174     def test_obvious_stops(self):
175         self.check_is(False, 422, 424, 426, 428, 431,
176                       *list(range(400, 408)) + list(range(410, 420)))
177
178     def test_obvious_retries(self):
179         self.check_is(None, 500, 502, 503, 504)
180
181     def test_4xx_retries(self):
182         self.check_is(None, 408, 409, 423)
183
184     def test_5xx_failures(self):
185         self.check_is(False, 501, *list(range(505, 512)))
186
187     def test_1xx_not_retried(self):
188         self.check_is_not(None, 100, 101)
189
190     def test_redirects_not_retried(self):
191         self.check_is_not(None, *list(range(300, 309)))
192
193     def test_wacky_code_retries(self):
194         self.check_is(None, 0, 99, 600, -200)
195
196
197 class RetryMethodTestCase(unittest.TestCase):
198     class Tester(object):
199         def __init__(self):
200             self.num_retries = 1
201
202         @arv_retry.retry_method
203         def check(self, a, num_retries=None, z=0):
204             return (a, num_retries, z)
205
206
207     def test_positional_arg_raises(self):
208         # unsupported use -- make sure we raise rather than ignore
209         with self.assertRaises(TypeError):
210             self.assertEqual((3, 2, 0), self.Tester().check(3, 2))
211
212     def test_keyword_arg_passed(self):
213         self.assertEqual((4, 3, 0), self.Tester().check(num_retries=3, a=4))
214
215     def test_not_specified(self):
216         self.assertEqual((0, 1, 0), self.Tester().check(0))
217
218     def test_not_specified_with_other_kwargs(self):
219         self.assertEqual((1, 1, 1), self.Tester().check(1, z=1))
220
221     def test_bad_call(self):
222         with self.assertRaises(TypeError):
223             self.Tester().check(num_retries=2)
224
225
226 if __name__ == '__main__':
227     unittest.main()