forked from Alishahryar1/free-claude-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_strict_sliding_window.py
More file actions
76 lines (54 loc) · 2.13 KB
/
Copy pathtest_strict_sliding_window.py
File metadata and controls
76 lines (54 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""Direct tests for :class:`core.rate_limit.StrictSlidingWindowLimiter`."""
import asyncio
import time
import pytest
import free_claude_code.core.rate_limit as rate_limit_module
from free_claude_code.core.rate_limit import StrictSlidingWindowLimiter
@pytest.mark.asyncio
async def test_strict_window_allows_burst_then_blocks():
lim = StrictSlidingWindowLimiter(rate_limit=2, rate_window=0.2)
await lim.acquire()
await lim.acquire()
start = time.monotonic()
await lim.acquire()
assert time.monotonic() - start >= 0.15
@pytest.mark.asyncio
async def test_strict_window_async_context_manager():
lim = StrictSlidingWindowLimiter(rate_limit=1, rate_window=0.15)
async def run():
async with lim:
pass
await run()
start = time.monotonic()
await run()
assert time.monotonic() - start >= 0.1
@pytest.mark.asyncio
async def test_rejected_conditional_acquisition_does_not_consume_capacity():
lim = StrictSlidingWindowLimiter(rate_limit=1, rate_window=60)
assert await lim.acquire_if(lambda: False) is False
await asyncio.wait_for(lim.acquire(), timeout=0.1)
@pytest.mark.asyncio
async def test_conditional_acquisition_records_predicate_commit_time(
monkeypatch: pytest.MonkeyPatch,
) -> None:
now = 0.0
sleep_delays: list[float] = []
lim = StrictSlidingWindowLimiter(rate_limit=1, rate_window=10)
def advance_during_condition() -> bool:
nonlocal now
now = 100.0
return True
async def advance_during_sleep(delay: float) -> None:
nonlocal now
sleep_delays.append(delay)
now += delay
monkeypatch.setattr(rate_limit_module.time, "monotonic", lambda: now)
monkeypatch.setattr(rate_limit_module.asyncio, "sleep", advance_during_sleep)
assert await lim.acquire_if(advance_during_condition) is True
await lim.acquire()
assert sleep_delays == [10.0]
def test_strict_window_rejects_invalid_config():
with pytest.raises(ValueError):
StrictSlidingWindowLimiter(rate_limit=0, rate_window=1.0)
with pytest.raises(ValueError):
StrictSlidingWindowLimiter(rate_limit=1, rate_window=0.0)