|
19 | 19 |
|
20 | 20 | sys.path[0:0] = [""]
|
21 | 21 |
|
22 |
| -from test.asynchronous import AsyncIntegrationTest, async_client_context, unittest |
23 |
| - |
24 |
| -from pymongo.asynchronous.helpers import _MAX_RETRIES |
| 22 | +from test.asynchronous import ( |
| 23 | + AsyncIntegrationTest, |
| 24 | + AsyncPyMongoTestCase, |
| 25 | + async_client_context, |
| 26 | + unittest, |
| 27 | +) |
| 28 | + |
| 29 | +from pymongo.asynchronous import helpers |
| 30 | +from pymongo.asynchronous.helpers import _MAX_RETRIES, _RetryPolicy, _TokenBucket |
25 | 31 | from pymongo.errors import PyMongoError
|
26 | 32 |
|
27 | 33 | _IS_SYNC = False
|
@@ -173,5 +179,39 @@ async def test_limit_retry_command(self):
|
173 | 179 | self.assertIn("Retryable", str(error.exception))
|
174 | 180 |
|
175 | 181 |
|
| 182 | +class TestRetryPolicy(AsyncPyMongoTestCase): |
| 183 | + async def test_retry_policy(self): |
| 184 | + capacity = 10 |
| 185 | + retry_policy = _RetryPolicy(_TokenBucket(capacity=capacity)) |
| 186 | + self.assertEqual(retry_policy.attempts, helpers._MAX_RETRIES) |
| 187 | + self.assertEqual(retry_policy.backoff_initial, helpers._BACKOFF_INITIAL) |
| 188 | + self.assertEqual(retry_policy.backoff_max, helpers._BACKOFF_MAX) |
| 189 | + for i in range(1, helpers._MAX_RETRIES + 1): |
| 190 | + self.assertTrue(await retry_policy.should_retry(i)) |
| 191 | + self.assertFalse(await retry_policy.should_retry(helpers._MAX_RETRIES + 1)) |
| 192 | + for i in range(capacity - helpers._MAX_RETRIES): |
| 193 | + self.assertTrue(await retry_policy.should_retry(1)) |
| 194 | + # No tokens left, should not retry. |
| 195 | + self.assertFalse(await retry_policy.should_retry(1)) |
| 196 | + self.assertEqual(retry_policy.token_bucket.tokens, 0) |
| 197 | + |
| 198 | + # record_success should generate tokens. |
| 199 | + for _ in range(int(2 / helpers.DEFAULT_RETRY_TOKEN_RETURN)): |
| 200 | + await retry_policy.record_success(retry=False) |
| 201 | + self.assertAlmostEqual(retry_policy.token_bucket.tokens, 2) |
| 202 | + for i in range(2): |
| 203 | + self.assertTrue(await retry_policy.should_retry(1)) |
| 204 | + self.assertFalse(await retry_policy.should_retry(1)) |
| 205 | + |
| 206 | + # Recording a successful retry should return 1 additional token. |
| 207 | + await retry_policy.record_success(retry=True) |
| 208 | + self.assertAlmostEqual( |
| 209 | + retry_policy.token_bucket.tokens, 1 + helpers.DEFAULT_RETRY_TOKEN_RETURN |
| 210 | + ) |
| 211 | + self.assertTrue(await retry_policy.should_retry(1)) |
| 212 | + self.assertFalse(await retry_policy.should_retry(1)) |
| 213 | + self.assertAlmostEqual(retry_policy.token_bucket.tokens, helpers.DEFAULT_RETRY_TOKEN_RETURN) |
| 214 | + |
| 215 | + |
176 | 216 | if __name__ == "__main__":
|
177 | 217 | unittest.main()
|
0 commit comments