forked from mtusi2026/mtusi2026lab2
исправления
This commit is contained in:
@@ -1,65 +1,167 @@
|
||||
"""Test: when Redis is down, protected endpoints return 503, not 500."""
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
"""Автотест отказа 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
|
||||
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
from _harness import (
|
||||
RESPONSE_BUDGET_SECONDS,
|
||||
assert_error_payload,
|
||||
assert_within_budget,
|
||||
call,
|
||||
container_id,
|
||||
start_service,
|
||||
stop_service,
|
||||
wait_healthy,
|
||||
wait_ready,
|
||||
)
|
||||
|
||||
|
||||
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 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"]
|
||||
|
||||
|
||||
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")
|
||||
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():
|
||||
# Проверяем, что без токена всё ещё 401 (не 500)
|
||||
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_redis()
|
||||
time.sleep(2)
|
||||
stop_service("redis")
|
||||
print("Redis stopped")
|
||||
|
||||
# 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)")
|
||||
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)
|
||||
)
|
||||
|
||||
# 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")
|
||||
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_redis()
|
||||
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()
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user