|
2 | 2 |
|
3 | 3 | import asyncio |
4 | 4 | import time |
| 5 | +from types import SimpleNamespace |
5 | 6 |
|
6 | 7 | import pytest |
7 | 8 |
|
| 9 | +import ml4t.data.utils.async_rate_limit as rate_limit |
8 | 10 | from ml4t.data.utils.async_rate_limit import ( |
9 | 11 | AsyncAdaptiveRateLimiter, |
10 | 12 | AsyncRateLimiter, |
@@ -165,22 +167,24 @@ async def make_call(): |
165 | 167 |
|
166 | 168 |
|
167 | 169 | @pytest.mark.asyncio |
168 | | -async def test_time_until_reset(): |
169 | | - """Test time until reset calculation.""" |
| 170 | +async def test_time_until_reset_tracks_elapsed_time_and_expiration(monkeypatch): |
| 171 | + """Prevent countdown errors without assuming an event-loop wake-up deadline.""" |
| 172 | + now = 100.0 |
| 173 | + monkeypatch.setattr(rate_limit, "time", SimpleNamespace(time=lambda: now)) |
170 | 174 | limiter = AsyncRateLimiter(max_calls=2, period=1.0) |
171 | 175 |
|
172 | | - # Initially should be 0 |
173 | 176 | assert limiter.time_until_reset() == 0.0 |
174 | | - |
175 | | - # After acquiring |
176 | 177 | await limiter.acquire() |
177 | | - time_remaining = limiter.time_until_reset() |
178 | | - assert 0.9 < time_remaining <= 1.0 |
| 178 | + assert limiter.time_until_reset() == pytest.approx(1.0) |
179 | 179 |
|
180 | | - # Wait a bit |
181 | | - await asyncio.sleep(0.5) |
182 | | - time_remaining = limiter.time_until_reset() |
183 | | - assert 0.4 < time_remaining <= 0.5 |
| 180 | + now = 100.5 |
| 181 | + assert limiter.time_until_reset() == pytest.approx(0.5) |
| 182 | + now = 100.625 |
| 183 | + assert limiter.time_until_reset() == pytest.approx(0.375) |
| 184 | + now = 101.0 |
| 185 | + assert limiter.time_until_reset() == 0.0 |
| 186 | + now = 101.5 |
| 187 | + assert limiter.time_until_reset() == 0.0 |
184 | 188 |
|
185 | 189 |
|
186 | 190 | @pytest.mark.asyncio |
|
0 commit comments