Skip to content

Commit 764b3df

Browse files
author
Stefan Jansen
committed
test(rate-limit): verify countdown independently of scheduler latency
1 parent f8e6a38 commit 764b3df

1 file changed

Lines changed: 15 additions & 11 deletions

File tree

‎tests/test_async_rate_limit.py‎

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22

33
import asyncio
44
import time
5+
from types import SimpleNamespace
56

67
import pytest
78

9+
import ml4t.data.utils.async_rate_limit as rate_limit
810
from ml4t.data.utils.async_rate_limit import (
911
AsyncAdaptiveRateLimiter,
1012
AsyncRateLimiter,
@@ -165,22 +167,24 @@ async def make_call():
165167

166168

167169
@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))
170174
limiter = AsyncRateLimiter(max_calls=2, period=1.0)
171175

172-
# Initially should be 0
173176
assert limiter.time_until_reset() == 0.0
174-
175-
# After acquiring
176177
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)
179179

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
184188

185189

186190
@pytest.mark.asyncio

0 commit comments

Comments
 (0)