Files
mtusi2026lab2/student-tests/test_redis_down.py
2026-11-21 20:08:45 +03:00

168 lines
6.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Автотест отказа Redis (хранилища сессий).
Зеркалит student-tests/test_postgres_down.py: проверяется тот же контракт
отказа, но деградирует Redis, а не PostgreSQL.
При остановленном Redis API:
* /health/live остаётся 200 (процесс жив), /health/ready — 503;
* анонимный запрос получает 401 (аутентификация не зависит от Redis);
* запрос с прежним токеном получает 503 в общем формате ошибки, а не 401
(«нет сессии») и не 500 — недоступность не превращается в отказ доступа;
* чтение и запись с токеном — 503 за ограниченное время;
* после возврата Redis readiness 200, прежний токен снова работает,
подтверждённые данные читаются, неподтверждённая запись отсутствует.
Запуск (стек должен быть поднят):
python student-tests/test_redis_down.py
"""
import base64
import uuid
from _harness import (
RESPONSE_BUDGET_SECONDS,
assert_error_payload,
assert_within_budget,
call,
container_id,
start_service,
stop_service,
wait_healthy,
wait_ready,
)
def register_and_login(username, password):
"""Создать пользователя, войти, вернуть (token, user_id)."""
status, payload, _ = call(
"POST",
"/api/v1/users",
body={
"username": username,
"display_name": "Redis Down Test",
"password": password,
},
)
assert status == 201, "register failed: %s %s" % (status, payload)
user_id = payload["id"]
credential = base64.b64encode(
("%s:%s" % (username, password)).encode()
).decode()
status, payload, _ = call(
"POST",
"/api/v1/auth/sessions",
headers={"Authorization": "Basic " + credential},
)
assert status == 201, "login failed: %s %s" % (status, payload)
return payload["token"], user_id
def main():
redis_container = container_id("redis")
wait_healthy(redis_container)
wait_ready()
suffix = uuid.uuid4().hex[:8]
token, user_id = register_and_login("redisdown_" + suffix, "RedisDownPass123")
auth = {"Authorization": "Bearer " + token}
status, me, _ = call("GET", "/api/v1/users/me", headers=auth)
assert status == 200, "token must work before the outage: %s %s" % (status, me)
status, chat, _ = call(
"POST",
"/api/v1/chats",
body={"title": "Redis outage", "member_ids": [user_id]},
headers=auth,
)
assert status == 201, "chat creation failed: %s %s" % (status, chat)
status, message, _ = call(
"POST",
"/api/v1/chats/%s/messages" % chat["id"],
body={"text": "подтверждено до отказа Redis"},
headers=auth,
)
assert status == 201, "message creation failed: %s %s" % (status, message)
print("Setup: user, session, chat and message created")
try:
stop_service("redis")
print("Redis stopped")
status, payload, elapsed = call("GET", "/health/ready")
assert_within_budget(elapsed, "readiness with Redis down")
assert status == 503, "readiness must be 503, got %s %s" % (status, payload)
assert_error_payload(payload, "unavailable")
print(
"readiness: 503 in %.2fs (budget %.0fs)"
% (elapsed, RESPONSE_BUDGET_SECONDS)
)
status, payload, elapsed = call("GET", "/health/live")
assert status == 200, "liveness must stay 200, got %s" % status
print("liveness: 200")
status, payload, elapsed = call("GET", "/api/v1/users/me")
assert status == 401, (
"anonymous request must stay 401, got %s %s" % (status, payload)
)
assert_within_budget(elapsed, "anonymous request with Redis down")
print("anonymous request: 401 (missing credentials, not a store failure)")
status, payload, elapsed = call("GET", "/api/v1/users/me", headers=auth)
assert_within_budget(elapsed, "authenticated request with Redis down")
assert status == 503, (
"authenticated request must be 503, got %s %s" % (status, payload)
)
assert_error_payload(payload, "unavailable")
print("authenticated request: 503 in %.2fs (not 401: session may exist)" % elapsed)
status, payload, elapsed = call(
"POST",
"/api/v1/chats/%s/messages" % chat["id"],
body={"text": "во время отказа Redis"},
headers=auth,
)
assert status == 503, (
"write during outage must be 503, got %s %s" % (status, payload)
)
assert_within_budget(elapsed, "write with Redis down")
print("write during outage: 503 in %.2fs, message not acknowledged" % elapsed)
finally:
start_service("redis")
wait_healthy(redis_container)
print("Redis restarted")
wait_ready()
print("readiness after recovery: 200")
status, payload, elapsed = call("GET", "/api/v1/users/me", headers=auth)
assert status == 200, (
"existing token must work after recovery, got %s %s" % (status, payload)
)
assert_within_budget(elapsed, "authenticated request after recovery")
print("existing token after recovery: 200 (session survived in AOF)")
status, page, elapsed = call(
"GET", "/api/v1/chats/%s/messages?limit=100" % chat["id"], headers=auth
)
assert status == 200, "history read failed after recovery: %s" % status
assert_within_budget(elapsed, "history read after recovery")
identifiers = [item["id"] for item in page["items"]]
assert message["id"] in identifiers, "confirmed message disappeared after outage"
assert len(identifiers) == len(set(identifiers)), "history contains duplicates"
texts = [item["text"] for item in page["items"]]
assert "во время отказа Redis" not in texts, (
"unacknowledged message must not appear in history"
)
print("confirmed message preserved, unacknowledged write absent")
print("PASS: Redis outage handled with bounded 503 and full recovery")
if __name__ == "__main__":
main()