""" Отказы зависимостей: Valkey и PostgreSQL останавливаются через docker compose. Тесты меняют состояние стенда (stop/start контейнеров, volumes сохраняются), поэтому запускаются только явно: make test-failures (RUN_FAILURE_TESTS=1). """ import os import time from collections.abc import Iterator import httpx import pytest from helpers import assert_error, assert_unauthorized, auth, basic, compose pytestmark = pytest.mark.skipif( os.environ.get("RUN_FAILURE_TESTS") != "1", reason="останавливает контейнеры стенда: запускайте через make test-failures", ) READY_TIMEOUT_SEC = 60 # Ответ при упавшей зависимости должен быть быстрым, а не висеть до таймаута клиента BOUNDED_RESPONSE_SEC = 3 def wait_ready(api: httpx.Client) -> None: deadline = time.monotonic() + READY_TIMEOUT_SEC while time.monotonic() < deadline: try: if api.get("/health/ready").status_code == 200: return except httpx.TransportError: pass time.sleep(0.5) raise AssertionError("API не стал готов после восстановления зависимости") @pytest.fixture def valkey_stopped(api: httpx.Client) -> Iterator[None]: compose("stop", "valkey") try: yield finally: compose("start", "valkey") compose("up", "-d", "--wait", "valkey") wait_ready(api) @pytest.fixture def postgres_stopped(api: httpx.Client) -> Iterator[None]: compose("stop", "postgres") try: yield finally: compose("start", "postgres") compose("up", "-d", "--wait", "postgres") wait_ready(api) def test_valkey_down_cache_is_bypassed( api: httpx.Client, make_user, make_chat, send_message, valkey_stopped ) -> None: """Без Valkey всё работает через PostgreSQL: вход, Bearer, запись, logout""" alice = make_user("alice") started = time.monotonic() me = api.get("/api/v1/users/me", headers=auth(alice)) assert me.status_code == 200, me.text assert time.monotonic() - started < BOUNDED_RESPONSE_SEC chat = make_chat(alice, [alice]) send_message(alice, chat, "без кэша") assert api.get("/health/ready").status_code == 200 assert ( api.delete("/api/v1/auth/sessions/current", headers=auth(alice)).status_code == 204 ) assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice))) assert_unauthorized(api.get("/api/v1/users/me")) def test_logout_during_valkey_outage_is_not_resurrected( api: httpx.Client, make_user ) -> None: """ Сессия попала в кэш, затем Valkey упал и пользователь вышел. После подъёма Valkey (без persistence — пустой) отозванный токен не принимается. """ alice = make_user("alice") assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200 compose("stop", "valkey") try: response = api.delete("/api/v1/auth/sessions/current", headers=auth(alice)) assert response.status_code == 204 finally: compose("start", "valkey") compose("up", "-d", "--wait", "valkey") wait_ready(api) assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice))) def test_postgres_down_returns_bounded_503_and_no_anonymous_access( api: httpx.Client, make_user, postgres_stopped ) -> None: alice_token_unused = {"token": "x" * 43} started = time.monotonic() ready = api.get("/health/ready") assert_error(ready, 503, "unavailable") assert time.monotonic() - started < BOUNDED_RESPONSE_SEC # Анонимный запрос остаётся 401, неизвестный токен не принимается как доверенный assert_unauthorized(api.get("/api/v1/users/me")) unknown = api.get("/api/v1/users/me", headers=auth(alice_token_unused)) assert_error(unknown, 503, "unavailable") assert "asyncpg" not in unknown.text and "postgres" not in unknown.text.lower() body = {"username": "st_pg_down", "display_name": "x", "password": "P" * 12} assert_error(api.post("/api/v1/users", json=body), 503, "unavailable") login = api.post("/api/v1/auth/sessions", headers=basic("st_pg_down", "P" * 12)) assert_error(login, 503, "unavailable") def test_session_survives_postgres_restart(api: httpx.Client, make_user) -> None: alice = make_user("alice") compose("restart", "postgres") wait_ready(api) chats = api.get("/api/v1/chats", headers=auth(alice)) assert chats.status_code == 200, chats.text