|
| 1 | +""" |
| 2 | +Licensed to the Apache Software Foundation (ASF) under one |
| 3 | +or more contributor license agreements. See the NOTICE file |
| 4 | +distributed with this work for additional information |
| 5 | +regarding copyright ownership. The ASF licenses this file |
| 6 | +to you under the Apache License, Version 2.0 (the |
| 7 | +"License"); you may not use this file except in compliance |
| 8 | +with the License. You may obtain a copy of the License at |
| 9 | +
|
| 10 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +
|
| 12 | +Unless required by applicable law or agreed to in writing, software |
| 13 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +See the License for the specific language governing permissions and |
| 16 | +limitations under the License. |
| 17 | +""" |
| 18 | + |
| 19 | +import time |
| 20 | +import unittest |
| 21 | +import requests |
| 22 | +from requests.exceptions import ConnectionError, ConnectTimeout, Timeout |
| 23 | +from urllib3.exceptions import NewConnectionError, MaxRetryError |
| 24 | + |
| 25 | +from pypaimon.api.client import ExponentialRetry |
| 26 | + |
| 27 | + |
| 28 | +class TestExponentialRetryStrategy(unittest.TestCase): |
| 29 | + |
| 30 | + def setUp(self): |
| 31 | + self.retry_strategy = ExponentialRetry(max_retries=5) |
| 32 | + |
| 33 | + def test_basic_retry(self): |
| 34 | + retry = ExponentialRetry._ExponentialRetry__create_retry_strategy(5) |
| 35 | + |
| 36 | + self.assertEqual(retry.total, 5) |
| 37 | + self.assertEqual(retry.read, 5) |
| 38 | + self.assertEqual(retry.connect, 0) # Connection errors should not retry |
| 39 | + |
| 40 | + self.assertIn(429, retry.status_forcelist) # Too Many Requests |
| 41 | + self.assertIn(503, retry.status_forcelist) # Service Unavailable |
| 42 | + self.assertNotIn(404, retry.status_forcelist) |
| 43 | + |
| 44 | + def test_no_retry_on_connect_error(self): |
| 45 | + session = requests.Session() |
| 46 | + session.mount("http://", self.retry_strategy.adapter) |
| 47 | + session.mount("https://", self.retry_strategy.adapter) |
| 48 | + session.timeout = (1, 1) |
| 49 | + |
| 50 | + start_time = time.time() |
| 51 | + |
| 52 | + try: |
| 53 | + session.get("http://192.168.255.255:9999", timeout=(1, 1)) |
| 54 | + self.fail("Expected ConnectionError") |
| 55 | + except (ConnectionError, ConnectTimeout, Timeout, NewConnectionError, MaxRetryError): |
| 56 | + elapsed = time.time() - start_time |
| 57 | + self.assertLess( |
| 58 | + elapsed, 5.0, |
| 59 | + f"Connection error took {elapsed:.2f}s, should fail quickly without retry" |
| 60 | + ) |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == '__main__': |
| 64 | + unittest.main() |
0 commit comments