|
1 | 1 | import socket
|
| 2 | +import time |
2 | 3 | import unittest
|
3 | 4 | from unittest.mock import patch, MagicMock
|
4 | 5 | from urllib.error import URLError
|
@@ -27,6 +28,48 @@ def test_validation(self):
|
27 | 28 | api.poll_with_specified_overhead(lambda: True, overhead_rate=0.1, max_tries=1)
|
28 | 29 | api.poll_with_specified_overhead(lambda: True, overhead_rate=0.1, timeout=1, max_tries=1)
|
29 | 30 |
|
| 31 | + @patch('time.sleep', return_value=None) |
| 32 | + @patch('time.time') |
| 33 | + def test_initial_delay(self, mock_time, mock_sleep): |
| 34 | + start_time = 100 # Fixed start time |
| 35 | + increment_time = 0.0001 |
| 36 | + mock_time.side_effect = [start_time, start_time + increment_time] # Simulate time progression |
| 37 | + |
| 38 | + try: |
| 39 | + api.poll_with_specified_overhead(lambda: False, overhead_rate=0.1, max_tries=2) |
| 40 | + except Exception as e: |
| 41 | + pass # Ignore the exception for this test |
| 42 | + |
| 43 | + expected_sleep_time = (start_time + increment_time - start_time) * 0.1 |
| 44 | + mock_sleep.assert_called_with(expected_sleep_time) |
| 45 | + |
| 46 | + def test_max_delay_cap(self): |
| 47 | + with patch('time.sleep') as mock_sleep: |
| 48 | + try: |
| 49 | + api.poll_with_specified_overhead(lambda: False, overhead_rate=1, max_tries=2, start_time=time.time() - 200) |
| 50 | + except Exception: |
| 51 | + pass |
| 52 | + # Ensure that the maximum delay of 120 seconds is not exceeded |
| 53 | + mock_sleep.assert_called_with(120) |
| 54 | + |
| 55 | + def test_polling_success(self): |
| 56 | + with patch('time.sleep', return_value=None) as mock_sleep: |
| 57 | + api.poll_with_specified_overhead(lambda: True, overhead_rate=0.1) |
| 58 | + mock_sleep.assert_not_called() |
| 59 | + |
| 60 | + def test_negative_overhead_rate(self): |
| 61 | + with self.assertRaises(ValueError): |
| 62 | + api.poll_with_specified_overhead(lambda: True, overhead_rate=-0.1) |
| 63 | + |
| 64 | + def test_realistic_scenario(self): |
| 65 | + responses = [False, False, True] |
| 66 | + def side_effect(): |
| 67 | + return responses.pop(0) |
| 68 | + |
| 69 | + with patch('time.sleep') as mock_sleep: |
| 70 | + api.poll_with_specified_overhead(side_effect, overhead_rate=0.1, max_tries=3) |
| 71 | + # Ensure that `time.sleep` was called twice (for two false returns) |
| 72 | + self.assertEqual(mock_sleep.call_count, 2) |
30 | 73 |
|
31 | 74 | @patch('railib.rest.urlopen')
|
32 | 75 | class TestURLOpenWithRetry(unittest.TestCase):
|
|
0 commit comments