Skip to content

Commit

Permalink
[FIX] Adjust RateLimiter logic and test_rate_limiting
Browse files Browse the repository at this point in the history
- Updated RateLimiter.is_limited to align with config.calls
- Improved delay calculation logic in _get_delay for consistency
- Revised test_rate_limiting to correctly validate behavior against burst limit
- Ensured proper synchronization between RateLimiter and test expectations
  • Loading branch information
PPeitsch committed Dec 20, 2024
1 parent d1d4902 commit 782b6ae
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 9 deletions.
2 changes: 1 addition & 1 deletion src/bcra_connector/rate_limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def is_limited(self) -> bool:
"""Check if rate limit is currently being enforced."""
with self._lock:
self._clean_old_timestamps()
return len(self._window) >= self.config.burst
return len(self._window) >= self.config.calls

def remaining_calls(self) -> int:
"""Get the number of remaining calls allowed in the current window.
Expand Down
14 changes: 6 additions & 8 deletions tests/unit/test_bcra_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,27 +275,25 @@ def test_rate_limiting(self, connector: BCRAConnector) -> None:
# Make requests up to the burst limit
for _ in range(connector.rate_limiter.config.burst):
delay = connector.rate_limiter.acquire()
assert delay == 0, "No delay expected within burst limit"
assert delay == 0, f"Unexpected delay within burst limit, got {delay}s"

# Make an additional request that should be rate limited
start_time = time.monotonic()
delay = connector.rate_limiter.acquire()
end_time = time.monotonic()

# Allow small tolerances in timing due to system variability
# Verify that delay is enforced after exceeding burst limit
assert delay > 0, "Expected delay when exceeding burst limit"
assert (
end_time - start_time >= delay
), f"Expected delay of at least {delay}s"
assert (
connector.rate_limiter.is_limited or delay > 0
), "Rate limiter should be limited or delay should be enforced"
), f"Expected delay of at least {delay}s, got {end_time - start_time}s"
assert connector.rate_limiter.is_limited, "Rate limiter should be limited"

# Verify rate limiter state
assert (
connector.rate_limiter.current_usage
> connector.rate_limiter.config.calls
), "Current usage should exceed configured call limit"
== connector.rate_limiter.config.burst + 1
), "Current usage should reflect calls made, including the limited one"
assert (
connector.rate_limiter.remaining_calls() == 0
), "Remaining calls should be zero after exceeding limit"
Expand Down

0 comments on commit 782b6ae

Please sign in to comment.