"""Отказы зависимостей: Redis (обход кэша) и PostgreSQL (ограниченная ошибка 503, без доверия анониму).""" import time from common import * def main(): alice = new_user("out") token = login(alice)["token"] chat = call("POST", "/api/v1/chats", {"title": "Отказы", "member_ids": [alice["id"]]}, bearer(token))[1] path = f"/api/v1/chats/{chat['id']}/messages" # --- Redis недоступен: работаем напрямую с PostgreSQL --- compose("stop", "redis") try: st, _, _, t = call("GET", "/api/v1/users/me", headers=bearer(token)) check(st == 200, f"redis down: valid token must still work via PostgreSQL, got {st}") check(call("POST", path, {"text": "без redis"}, bearer(token))[0] == 201, "redis down: write must work") check(call("GET", "/api/v1/users/me", headers=bearer("y" * 43))[0] == 401, "redis down: unknown token must be 401") new_token = login(alice)["token"] check(call("DELETE", "/api/v1/auth/sessions/current", headers=bearer(new_token))[0] == 204, "redis down: logout works") check(call("GET", "/api/v1/users/me", headers=bearer(new_token))[0] == 401, "redis down: revoked token must be 401") check(call("GET", "/health/ready")[0] == 200, "redis is not critical for readiness") st, _, _, t2 = call("GET", "/api/v1/users/me", headers=bearer(token)) check(st == 200 and t2 < 1, f"redis down: cache must be bypassed without waiting, took {t2:.2f}s") print(f"ok: redis stopped -> auth/read/write via PostgreSQL; first request {t:.2f}s " f"(until redis is marked down), next {t2:.3f}s; ready=200") finally: compose("start", "redis") time.sleep(6) # RETRY_AFTER: приложение снова начинает использовать Redis check(call("GET", "/api/v1/users/me", headers=bearer(token))[0] == 200, "after redis start") print("ok: redis started again -> cache used again") # --- PostgreSQL недоступен: ограниченная ошибка 503, аноним/неизвестный токен не проходят --- compose("stop", "postgres") try: st, body, _, t = call("POST", path, {"text": "без БД"}, bearer(token)) check(st == 503 and body["error"]["code"] == "unavailable", f"db down: write must be 503, got {st}") check(t < 12, f"db down: error must be bounded in time, took {t:.1f}s") st_anon = call("GET", path)[0] check(st_anon == 401, f"db down: anonymous must be 401, got {st_anon}") st_fake = call("GET", path, headers=bearer("z" * 43))[0] check(st_fake in (401, 503), f"db down: unknown token must never be 200, got {st_fake}") st_ready = call("GET", "/health/ready")[0] check(st_ready == 503, f"db down: readiness must be 503, got {st_ready}") print(f"ok: postgres stopped -> write 503 in {t:.2f}s, anonymous 401, unknown token {st_fake}, ready 503") finally: compose("start", "postgres") wait_ready() st, page, _, _ = call("GET", path + "?limit=100", headers=bearer(token)) check(st == 200 and [m["text"] for m in page["items"]] == ["без redis"], "after recovery: history intact, failed write absent") print("ok: postgres started again -> same token works, history intact") print("PASS: test_outage") run(main)