"""Automatic resilience checks: expiry, Redis/DB unavailability. Requires Docker: test stops the service, checks API behaviour, restarts it. Run: pytest student-tests/test_resilience.py -v -s """ import base64 import subprocess import time import uuid import httpx BASE = "http://localhost:8080" COMPOSE = ["docker", "compose", "--env-file", ".env"] def _register_and_login(client: httpx.Client) -> dict: username = "res_" + uuid.uuid4().hex[:10] password = "Test-password-" + uuid.uuid4().hex[:8] r = client.post( f"{BASE}/api/v1/users", json={ "username": username, "display_name": "Res", "password": password, }, ) assert r.status_code == 201, r.text user = r.json() credential = base64.b64encode( (username + ":" + password).encode("utf-8") ).decode("ascii") r = client.post( f"{BASE}/api/v1/auth/sessions", headers={"Authorization": "Basic " + credential}, ) assert r.status_code == 201, r.text session = r.json() return { "id": user["id"], "username": username, "password": password, "token": session["token"], } def _wait_ready(timeout: float = 60.0) -> None: deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: with httpx.Client(timeout=2) as c: r = c.get(f"{BASE}/health/ready") if r.status_code == 200: return except Exception: pass time.sleep(1) raise RuntimeError("API did not become ready in time") def _compose(*args: str) -> None: subprocess.run(COMPOSE + list(args), check=True) def test_expiry_invalidates_session(monkeypatch): """Session expires when SESSION_TTL_SECONDS is very small.""" _compose("up", "-d", "--build", "api") _wait_ready() with httpx.Client(timeout=5) as c: actor = _register_and_login(c) r = c.get( f"{BASE}/api/v1/users/me", headers={"Authorization": "Bearer " + actor["token"]}, ) assert r.status_code == 200 # Restart API with 2-second TTL _compose("stop", "api") subprocess.run( ["docker", "compose", "--env-file", ".env", "rm", "-f", "api"], check=False, ) subprocess.run( [ "docker", "compose", "--env-file", ".env", "run", "-d", "--name", "api-short-ttl", "-e", "SESSION_TTL_SECONDS=2", "-p", "127.0.0.1:8080:8080", "api", ], check=True, ) _wait_ready() with httpx.Client(timeout=5) as c: fresh = _register_and_login(c) r = c.get( f"{BASE}/api/v1/users/me", headers={"Authorization": "Bearer " + fresh["token"]}, ) assert r.status_code == 200 print("Waiting 4 seconds for expiry...") time.sleep(4) r = c.get( f"{BASE}/api/v1/users/me", headers={"Authorization": "Bearer " + fresh["token"]}, ) assert r.status_code == 401, f"expected 401 after expiry, got {r.status_code}" subprocess.run(["docker", "stop", "api-short-ttl"], check=False) subprocess.run(["docker", "rm", "api-short-ttl"], check=False) _compose("up", "-d", "--build", "api") _wait_ready() def test_redis_unavailable_returns_503(): """When Valkey is down, /health/ready returns 503.""" _compose("up", "-d", "--build") _wait_ready() _compose("stop", "valkey") time.sleep(3) try: with httpx.Client(timeout=5) as c: r = c.get(f"{BASE}/health/ready") assert r.status_code == 503, f"expected 503, got {r.status_code}" body = r.json() assert body["error"]["code"] == "unavailable" finally: _compose("start", "valkey") _wait_ready() def test_postgres_unavailable_returns_503(): """When PostgreSQL is down, /health/ready returns 503.""" _compose("up", "-d", "--build") _wait_ready() _compose("stop", "postgres") time.sleep(3) try: with httpx.Client(timeout=5) as c: r = c.get(f"{BASE}/health/ready") assert r.status_code == 503, f"expected 503, got {r.status_code}" body = r.json() assert body["error"]["code"] == "unavailable" finally: _compose("start", "postgres") _wait_ready()