55 lines
1.7 KiB
Python
55 lines
1.7 KiB
Python
"""Cache mémoire de GET /api/dashboard (#245, épopée perf #240)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from backend.routers import config as config_router
|
|
|
|
|
|
def _count_calls(monkeypatch):
|
|
calls = {"n": 0}
|
|
original = config_router._compute_dashboard
|
|
|
|
def counting(user):
|
|
calls["n"] += 1
|
|
return original(user)
|
|
|
|
monkeypatch.setattr(config_router, "_compute_dashboard", counting)
|
|
return calls
|
|
|
|
|
|
def test_dashboard_second_call_served_from_cache(client, monkeypatch):
|
|
config_router.invalidate_dashboard_cache()
|
|
calls = _count_calls(monkeypatch)
|
|
|
|
first = client.get("/api/dashboard")
|
|
second = client.get("/api/dashboard")
|
|
|
|
assert first.status_code == 200
|
|
assert second.status_code == 200
|
|
assert second.json() == first.json()
|
|
assert calls["n"] == 1 # un seul calcul pour deux appels
|
|
|
|
|
|
def test_dashboard_cache_invalidation_recomputes(client, monkeypatch):
|
|
config_router.invalidate_dashboard_cache()
|
|
calls = _count_calls(monkeypatch)
|
|
|
|
assert client.get("/api/dashboard").status_code == 200
|
|
config_router.invalidate_dashboard_cache()
|
|
assert client.get("/api/dashboard").status_code == 200
|
|
assert calls["n"] == 2
|
|
|
|
|
|
def test_dashboard_cache_ttl_expiry(client, monkeypatch):
|
|
import time
|
|
|
|
config_router.invalidate_dashboard_cache()
|
|
calls = _count_calls(monkeypatch)
|
|
assert client.get("/api/dashboard").status_code == 200
|
|
# Vieillir artificiellement l'entrée au-delà du TTL.
|
|
for key, (ts, value) in list(config_router._dashboard_cache.items()):
|
|
config_router._dashboard_cache[key] = (ts - config_router._DASHBOARD_TTL_SECONDS - 1, value)
|
|
assert client.get("/api/dashboard").status_code == 200
|
|
assert calls["n"] == 2
|
|
_ = time # (garde-fou d'import)
|