lab2: fix cache revocation, DB timeouts, add failure tests
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-03 12:12:45 +03:00
parent c69143c215
commit ead398e9ba
12 changed files with 477 additions and 77 deletions
+100
View File
@@ -0,0 +1,100 @@
"""Проверка отказа Valkey и корректности logout при недоступном кэше."""
from __future__ import annotations
import base64, json, subprocess, sys, time, urllib.error, urllib.request, uuid
BASE = "http://localhost:8080"
COMPOSE = ["docker", "compose", "--env-file", ".env"]
def call(method, path, headers=None, body=None):
data = None
h = dict(headers or {})
if body is not None:
data = json.dumps(body).encode()
h["Content-Type"] = "application/json"
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
try:
r = urllib.request.urlopen(req, timeout=10)
raw = r.read()
return r.code, json.loads(raw) if raw else None
except urllib.error.HTTPError as e:
raw = e.read()
try:
return e.code, json.loads(raw) if raw else None
except Exception:
return e.code, None
def stop_cache():
subprocess.run(COMPOSE + ["stop", "cache"], check=True)
def start_cache():
subprocess.run(COMPOSE + ["start", "cache"], check=True)
def restart_api():
subprocess.run(COMPOSE + ["restart", "api"], check=True)
def wait_ready(deadline=60):
end = time.monotonic() + deadline
while time.monotonic() < end:
try:
code, _ = call("GET", "/health/ready")
if code == 200:
return
except Exception:
pass
time.sleep(1)
raise SystemExit("API did not become ready")
def main():
username = "cf_" + uuid.uuid4().hex[:10]
password = "cache-fail-pass-1234567890"
code, _ = call("POST", "/api/v1/users", body={
"username": username, "display_name": "Cache Fail", "password": password,
})
assert code == 201, code
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
code, session = call("POST", "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + cred})
assert code == 201, code
token = session["token"]
# Токен работает
code, _ = call("GET", "/api/v1/users/me",
headers={"Authorization": "Bearer " + token})
assert code == 200, code
# Останавливаем Valkey
stop_cache()
time.sleep(2)
# API должно работать в degraded mode
code, _ = call("GET", "/api/v1/users/me",
headers={"Authorization": "Bearer " + token})
assert code == 200, f"degraded mode failed: {code}"
print("PASS: API works with Valkey down (degraded mode)")
# Logout при недоступном Valkey должен вернуть 204
code, _ = call("DELETE", "/api/v1/auth/sessions/current",
headers={"Authorization": "Bearer " + token})
assert code == 204, f"logout with cache down returned {code}"
print("PASS: logout with cache down returned 204")
# Токен немедленно недействителен (проверка через БД)
code, _ = call("GET", "/api/v1/users/me",
headers={"Authorization": "Bearer " + token})
assert code == 401, f"revoked token still works with cache down: {code}"
print("PASS: revoked token rejected while cache down")
# Поднимаем Valkey, рестартуем API — критический регресс-тест
start_cache()
time.sleep(2)
restart_api()
wait_ready()
code, _ = call("GET", "/api/v1/users/me",
headers={"Authorization": "Bearer " + token})
assert code == 401, f"REGRESSION: revoked token resurrected after cache restart: {code}"
print("PASS: revoked token still 401 after cache restart (regression fixed)")
if __name__ == "__main__":
main()
+127
View File
@@ -0,0 +1,127 @@
"""Проверка отказа PostgreSQL: таймаут запроса и восстановление."""
from __future__ import annotations
import base64, json, subprocess, sys, time, urllib.error, urllib.request, uuid
BASE = "http://localhost:8080"
COMPOSE = ["docker", "compose", "--env-file", ".env"]
def call(method, path, headers=None, body=None, timeout=10):
data = None
h = dict(headers or {})
if body is not None:
data = json.dumps(body).encode()
h["Content-Type"] = "application/json"
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
try:
r = urllib.request.urlopen(req, timeout=timeout)
raw = r.read()
return r.code, json.loads(raw) if raw else None
except urllib.error.HTTPError as e:
raw = e.read()
try:
return e.code, json.loads(raw) if raw else None
except Exception:
return e.code, None
def stop_db():
"""Останавливает контейнер Postgres. TCP-соединения рвутся, psycopg
получает ошибку мгновенно — это честный сценарий 'БД упала'."""
subprocess.run(COMPOSE + ["stop", "postgres"], check=True)
def start_db():
"""Поднимает Postgres. Не падает, если уже запущен."""
subprocess.run(COMPOSE + ["start", "postgres"],
capture_output=True, check=False)
time.sleep(3)
def restart_api():
"""Пересоздаёт API, чтобы пул соединений не держал мёртвые сессии."""
subprocess.run(COMPOSE + ["restart", "api"],
capture_output=True, check=False)
def wait_ready(deadline=60):
end = time.monotonic() + deadline
while time.monotonic() < end:
try:
code, _ = call("GET", "/health/ready", timeout=5)
if code == 200:
return
except Exception:
pass
time.sleep(1)
raise SystemExit("API did not become ready")
def ensure_clean_state():
"""Возвращает стек в рабочее состояние, если предыдущий запуск оставил
Postgres остановленным или пул API в плохом состоянии."""
subprocess.run(COMPOSE + ["start", "postgres"],
capture_output=True, check=False)
time.sleep(3)
# API перезапускаем, потому что после stop Postgres пул мог забиться
# мёртвыми соединениями, и первый запрос упадёт по PoolTimeout.
restart_api()
wait_ready()
def main():
ensure_clean_state()
# Регистрация и логин — до всякого stop, чтобы тест не падал на подготовке
username = "dbf_" + uuid.uuid4().hex[:10]
password = "db-fail-pass-1234567890"
code, _ = call("POST", "/api/v1/users", body={
"username": username, "display_name": "DB Fail", "password": password,
})
assert code == 201, f"failed to create user before stop: {code}"
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
code, session = call("POST", "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + cred})
assert code == 201, f"failed to login before stop: {code}"
token = session["token"]
stop_db()
try:
time.sleep(0.5)
# Запрос к БД должен упасть быстро (TCP порван, psycopg сразу
# получает ошибку соединения). Проверяем < 8 секунд.
start = time.monotonic()
try:
code, _ = call("GET", "/api/v1/users/me",
headers={"Authorization": "Bearer " + token}, timeout=15)
except Exception as exc:
elapsed = time.monotonic() - start
raise SystemExit(f"request hung: {elapsed:.1f}s, {type(exc).__name__}")
elapsed = time.monotonic() - start
assert elapsed < 8, f"request took {elapsed:.1f}s (>8s), DB down not handled fast enough"
assert code in (500, 503), f"expected 500/503 during DB down, got {code}"
print(f"PASS: DB down returned {code} in {elapsed:.1f}s (<8s)")
# health/ready должен вернуть 503, пока БД недоступна
code, _ = call("GET", "/health/ready", timeout=15)
assert code == 503, f"expected 503 from ready, got {code}"
print("PASS: /health/ready returned 503 during DB down")
finally:
# Гарантированно поднимаем Postgres даже при падении выше.
start_db()
# Перезапускаем API, чтобы пул пересоздал соединения с вернувшейся БД.
restart_api()
wait_ready()
# Проверяем, что данные и сессия сохранены после восстановления.
code, _ = call("GET", "/api/v1/users/me",
headers={"Authorization": "Bearer " + token})
assert code == 200, f"session lost after DB recovery: {code}"
print("PASS: session and data preserved after DB recovery")
if __name__ == "__main__":
main()