"""Test: when Redis is down, protected endpoints return 503, not 500.""" import subprocess import time import urllib.error import urllib.request import uuid BASE = "http://localhost:8080" def call(method, path, headers=None): h = {"Accept": "application/json"} h.update(headers or {}) req = urllib.request.Request(BASE + path, headers=h, method=method) try: with urllib.request.urlopen(req, timeout=10) as resp: return resp.status, resp.read().decode() except urllib.error.HTTPError as e: return e.code, e.read().decode() def stop_redis(): subprocess.run(["docker", "compose", "stop", "redis"], check=True, capture_output=True) def start_redis(): subprocess.run(["docker", "compose", "start", "redis"], check=True, capture_output=True) # Ждём, пока Redis станет healthy for _ in range(30): p = subprocess.run( ["docker", "inspect", "--format={{.State.Health.Status}}", "mtusi2026lab2-redis-1"], capture_output=True, text=True, ) if p.stdout.strip() == "healthy": return time.sleep(1) raise RuntimeError("redis did not become healthy") def main(): # Проверяем, что без токена всё ещё 401 (не 500) try: stop_redis() time.sleep(2) # 1. Аноним не должен пройти (401, не 503 — токена нет) status, body = call("GET", "/api/v1/users/me") assert status == 401, f"anonymous request without token should be 401, got {status} {body}" print("Anonymous without token: 401 (correct)") # 2. С фиктивным токеном — 503 (Redis недоступен), не 500 status, body = call("GET", "/api/v1/users/me", headers={ "Authorization": "Bearer faketoken12345", }) assert status == 503, f"with fake token and Redis down should be 503, got {status} {body}" print("With token, Redis down: 503 (correct)") print("PASS: Redis unavailability handled correctly") finally: start_redis() print("Redis restarted") if __name__ == "__main__": main()