Files
devplacepy/tests/unit/services/giphy/limits.py
T

85 lines
2.5 KiB
Python

# retoor <retoor@molodetz.nl>
from devplacepy.services.giphy import limits
from devplacepy.services.giphy.limits import TtlCache, UserRateLimiter
def test_cache_returns_what_was_stored():
cache = TtlCache()
cache.put("a", {"x": 1})
assert cache.get("a") == {"x": 1}
assert cache.get("missing") is None
def test_cache_expires_entries(monkeypatch):
clock = [1000.0]
monkeypatch.setattr(limits.time, "monotonic", lambda: clock[0])
cache = TtlCache(ttl_seconds=10)
cache.put("a", 1)
clock[0] += 9
assert cache.get("a") == 1
clock[0] += 2
assert cache.get("a") is None
assert len(cache) == 0
def test_cache_never_exceeds_its_entry_cap():
cache = TtlCache(max_entries=8)
for index in range(500):
cache.put(index, index)
assert len(cache) <= 8
assert cache.get(499) == 499
assert cache.get(0) is None
def test_cache_evicts_the_least_recently_used():
cache = TtlCache(max_entries=2)
cache.put("a", 1)
cache.put("b", 2)
assert cache.get("a") == 1
cache.put("c", 3)
assert cache.get("b") is None
assert cache.get("a") == 1
def test_limiter_allows_exactly_the_cap_then_refuses():
limiter = UserRateLimiter(max_calls=5, window_seconds=60)
results = [limiter.allow("u1") for _ in range(8)]
assert results == [True] * 5 + [False] * 3
def test_limiter_is_per_user():
limiter = UserRateLimiter(max_calls=1, window_seconds=60)
assert limiter.allow("u1") is True
assert limiter.allow("u1") is False
assert limiter.allow("u2") is True
def test_limiter_window_slides(monkeypatch):
clock = [0.0]
monkeypatch.setattr(limits.time, "monotonic", lambda: clock[0])
limiter = UserRateLimiter(max_calls=2, window_seconds=60)
assert limiter.allow("u") and limiter.allow("u")
assert limiter.allow("u") is False
clock[0] += 61
assert limiter.allow("u") is True
def test_limiter_bounds_the_number_of_tracked_users():
limiter = UserRateLimiter(max_calls=1, window_seconds=60, max_tracked=16)
for index in range(1000):
limiter.allow(f"user-{index}")
assert len(limiter._calls) <= 16
def test_refused_calls_do_not_extend_the_window(monkeypatch):
clock = [0.0]
monkeypatch.setattr(limits.time, "monotonic", lambda: clock[0])
limiter = UserRateLimiter(max_calls=1, window_seconds=60)
assert limiter.allow("u") is True
for _ in range(50):
clock[0] += 1
assert limiter.allow("u") is False
clock[0] += 11
assert limiter.allow("u") is True