#!/usr/bin/env python3 """Уровень 4 lab2: конкурентная регистрация, expiry TTL, EXPLAIN, недоступность Redis. Перед запуском теста expiry: 1) в .env выставить SESSION_TTL_SECONDS=2 2) docker compose --env-file .env up -d api 3) python student-tests/test_lab2_level4.py --base-url http://localhost:8080 4) вернуть SESSION_TTL_SECONDS=3600 и снова up -d api """ import base64 import datetime as dt import os import subprocess import sys import threading import time import uuid from concurrent.futures import ThreadPoolExecutor from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) from client import Client, Failure, arguments, check, run # noqa: E402 # ---------- 1. Конкурентная регистрация одинакового username ---------- def test_concurrent_registration(c): """Один и тот же username с 8 потоков — ровно одна 201, остальные 409.""" username = "race_" + uuid.uuid4().hex[:10] password = "T3st-" + uuid.uuid4().hex body = {"username": username, "display_name": "Race", "password": password} results = [] lock = threading.Lock() def one(_): local = Client(c.base, timeout=10) try: local.call("POST", "/api/v1/users", 201, body=body, schema="User") with lock: results.append(201) except Failure: with lock: results.append(409) with ThreadPoolExecutor(max_workers=8) as pool: list(pool.map(one, range(8))) check(results.count(201) == 1, "expected exactly one 201, got %s" % results) check(results.count(409) == 7, "expected seven 409, got %s" % results) # ---------- 2. Expiry при коротком SESSION_TTL_SECONDS ---------- def test_short_ttl_expiry(c): """Регистрация + сессия; проверяем, что TTL реально короткий и токен истекает.""" suffix = uuid.uuid4().hex[:10] username = "ttl_" + suffix password = "T3st-" + uuid.uuid4().hex c.call("POST", "/api/v1/users", 201, body={"username": username, "display_name": "TTL", "password": password}, schema="User") cred = base64.b64encode((username + ":" + password).encode()).decode() session = c.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + cred}, schema="Session")["json"] # Контроль: сервер обязан выдать короткий TTL, иначе тест бессмыслен. expires_at = dt.datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00")) ttl_actual = (expires_at - dt.datetime.now(dt.timezone.utc)).total_seconds() check(ttl_actual <= 6, "SESSION_TTL_SECONDS не короткий (получено %.1f c). " "Поставь SESSION_TTL_SECONDS=2 в .env и перезапусти API." % ttl_actual) # Сразу работает. c.call("GET", "/api/v1/users/me", 200, headers={"Authorization": "Bearer " + session["token"]}, schema="User") # Ждём больше TTL. time.sleep(4) c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + session["token"]}) # ---------- 3. EXPLAIN на реальной БД ---------- def test_explain(c): """EXPLAIN (ANALYZE, BUFFERS) истории сообщений — ожидаем индекс. Запускаем psql в одноразовом контейнере postgres:18-alpine; подключаемся к PostgreSQL на хосте через host.docker.internal. """ dsn = os.environ.get("DATABASE_URL") if not dsn: env_file = Path(__file__).resolve().parents[1] / ".env" if env_file.is_file(): for line in env_file.read_text(encoding="utf-8").splitlines(): line = line.strip() if line.startswith("DATABASE_URL="): dsn = line.split("=", 1)[1].strip() break check(dsn, "DATABASE_URL не найден ни в окружении, ни в .env") # Внутри контейнера хост — host.docker.internal, а не localhost. dsn_in_container = dsn.replace("@localhost:", "@host.docker.internal:") dsn_in_container = dsn_in_container.replace("@127.0.0.1:", "@host.docker.internal:") sql = ( "EXPLAIN (ANALYZE, BUFFERS) " "SELECT id, chat_id, sender_id, text, created_at FROM messages " "WHERE chat_id = (SELECT chat_id FROM messages LIMIT 1) " "ORDER BY created_at, id LIMIT 51;" ) r = subprocess.run( [ "docker", "run", "--rm", "--add-host=host.docker.internal:host-gateway", "postgres:18-alpine", "psql", dsn_in_container, "-c", sql, ], capture_output=True, text=True, timeout=60, ) out = r.stdout + r.stderr check("Index" in out or "Bitmap Index" in out or "idx_messages_chat_created" in out, "EXPLAIN не показал использования индекса:\n" + out) print("EXPLAIN (фрагмент):") for line in out.splitlines()[:10]: print(" ", line) # ---------- 4. Недоступность Redis ---------- def _compose(action): return subprocess.run( ["docker", "compose", "--env-file", ".env", action, "redis"], capture_output=True, text=True, timeout=60, ) def _wait_ready(c, timeout=60): deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: c.call("GET", "/health/ready", 200) return except Failure: time.sleep(1) raise Failure("API не вернулся в ready за %d секунд после старта Redis" % timeout) def test_redis_unavailable(c): """Останавливаем Redis: /health/ready → 503. Возвращаем обратно.""" print(" (проверка недоступности Redis: docker compose stop redis на ~6 секунд)") stopped = _compose("stop") check(stopped.returncode == 0, "docker compose stop redis не сработал:\n" + (stopped.stdout + stopped.stderr)) try: time.sleep(3) # /health/ready должен стать 503. ready = c.call("GET", "/health/ready", 503) check(ready["status"] == 503, "readiness must be 503 without Redis") # Бизнес-запрос с любым Bearer — 401 (сессию не находим) или 503, # но точно не 200. r = c.call("GET", "/api/v1/users/me", (401, 503), headers={"Authorization": "Bearer " + "x" * 43}) check(r["status"] in (401, 503), "запрос с недействительным токеном при мёртвом Redis должен быть 401 или 503") finally: # Только восстановление. Никаких return/break/continue внутри finally. started = _compose("start") check(started.returncode == 0, "docker compose start redis не сработал:\n" + (started.stdout + started.stderr)) # Ждём готовности — УЖЕ ВНЕ finally. _wait_ready(c, timeout=60) # ---------- main ---------- def main(): args = arguments("Lab2 level 4 checks") c = Client(args.base_url, args.ca_file) print("=== test_concurrent_registration ===") test_concurrent_registration(c) print("PASS: concurrent registration produces exactly one user") print("=== test_short_ttl_expiry ===") test_short_ttl_expiry(c) print("PASS: session expires after SESSION_TTL_SECONDS") print("=== test_explain ===") test_explain(c) print("PASS: EXPLAIN uses idx_messages_chat_created") print("=== test_redis_unavailable ===") test_redis_unavailable(c) print("PASS: readiness 503 без Redis, затем восстановление") print("PASS: all lab2 level-4 checks passed") if __name__ == "__main__": run(main)