обновила тесты
This commit is contained in:
@@ -1,9 +1,18 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Уровень 4 lab2: конкурентная регистрация, expiry TTL, недоступность Redis, EXPLAIN."""
|
"""Уровень 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 base64
|
||||||
|
import datetime as dt
|
||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
import threading
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
@@ -13,18 +22,19 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
|||||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 1. Конкурентная регистрация одинакового username ----------
|
||||||
def test_concurrent_registration(c):
|
def test_concurrent_registration(c):
|
||||||
"""Один и тот же username с 8 потоков — ровно одна 201, остальные 409."""
|
"""Один и тот же username с 8 потоков — ровно одна 201, остальные 409."""
|
||||||
username = "race_" + uuid.uuid4().hex[:10]
|
username = "race_" + uuid.uuid4().hex[:10]
|
||||||
password = "T3st-" + uuid.uuid4().hex
|
password = "T3st-" + uuid.uuid4().hex
|
||||||
body = {"username": username, "display_name": "Race", "password": password}
|
body = {"username": username, "display_name": "Race", "password": password}
|
||||||
results = []
|
results = []
|
||||||
lock = __import__("threading").Lock()
|
lock = threading.Lock()
|
||||||
|
|
||||||
def one(_):
|
def one(_):
|
||||||
local = Client(c.base, timeout=10)
|
local = Client(c.base, timeout=10)
|
||||||
try:
|
try:
|
||||||
local.call("POST", "/api/v1/users", 201, body=body)
|
local.call("POST", "/api/v1/users", 201, body=body, schema="User")
|
||||||
with lock:
|
with lock:
|
||||||
results.append(201)
|
results.append(201)
|
||||||
except Failure:
|
except Failure:
|
||||||
@@ -37,80 +47,151 @@ def test_concurrent_registration(c):
|
|||||||
check(results.count(409) == 7, "expected seven 409, got %s" % results)
|
check(results.count(409) == 7, "expected seven 409, got %s" % results)
|
||||||
|
|
||||||
|
|
||||||
def test_short_ttl_expiry(c, base_url):
|
# ---------- 2. Expiry при коротком SESSION_TTL_SECONDS ----------
|
||||||
"""Регистрация + сессия с TTL=2с; через 4с токен недействителен."""
|
def test_short_ttl_expiry(c):
|
||||||
|
"""Регистрация + сессия; проверяем, что TTL реально короткий и токен истекает."""
|
||||||
suffix = uuid.uuid4().hex[:10]
|
suffix = uuid.uuid4().hex[:10]
|
||||||
username = "ttl_" + suffix
|
username = "ttl_" + suffix
|
||||||
password = "T3st-" + uuid.uuid4().hex
|
password = "T3st-" + uuid.uuid4().hex
|
||||||
c.call("POST", "/api/v1/users", 201,
|
c.call("POST", "/api/v1/users", 201,
|
||||||
body={"username": username, "display_name": "TTL", "password": password})
|
body={"username": username, "display_name": "TTL", "password": password},
|
||||||
|
schema="User")
|
||||||
cred = base64.b64encode((username + ":" + password).encode()).decode()
|
cred = base64.b64encode((username + ":" + password).encode()).decode()
|
||||||
session = c.call("POST", "/api/v1/auth/sessions", 201,
|
session = c.call("POST", "/api/v1/auth/sessions", 201,
|
||||||
headers={"Authorization": "Basic " + cred})["json"]
|
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,
|
c.call("GET", "/api/v1/users/me", 200,
|
||||||
headers={"Authorization": "Bearer " + session["token"]})
|
headers={"Authorization": "Bearer " + session["token"]},
|
||||||
# Ждём больше TTL
|
schema="User")
|
||||||
|
|
||||||
|
# Ждём больше TTL.
|
||||||
time.sleep(4)
|
time.sleep(4)
|
||||||
c.call("GET", "/api/v1/users/me", 401,
|
c.call("GET", "/api/v1/users/me", 401,
|
||||||
headers={"Authorization": "Bearer " + session["token"]})
|
headers={"Authorization": "Bearer " + session["token"]})
|
||||||
|
|
||||||
|
|
||||||
def test_redis_unavailable(c, base_url):
|
# ---------- 3. EXPLAIN на реальной БД ----------
|
||||||
"""Останавливаем Redis — /health/ready отдаёт 503, Bearer не проходит."""
|
|
||||||
print(" (проверка недоступности Redis: docker stop mtusi-redis на 5 секунд)")
|
|
||||||
r = subprocess.run(["docker", "stop", "mtusi-redis"], capture_output=True, text=True, timeout=30)
|
|
||||||
check(r.returncode == 0, "cannot stop Redis container")
|
|
||||||
try:
|
|
||||||
time.sleep(3)
|
|
||||||
ready = c.call("GET", "/health/ready", 503)
|
|
||||||
check(ready["status"] == 503, "readiness must be 503 without Redis")
|
|
||||||
c.call("GET", "/api/v1/users/me", 401,
|
|
||||||
headers={"Authorization": "Bearer " + "x" * 43})
|
|
||||||
finally:
|
|
||||||
subprocess.run(["docker", "start", "mtusi-redis"], capture_output=True, text=True, timeout=30)
|
|
||||||
time.sleep(4)
|
|
||||||
c.call("GET", "/health/ready", 200)
|
|
||||||
|
|
||||||
|
|
||||||
def test_explain(c):
|
def test_explain(c):
|
||||||
"""EXPLAIN (ANALYZE, BUFFERS) по запросу истории — индекс используется."""
|
"""EXPLAIN (ANALYZE, BUFFERS) истории сообщений — ожидаем индекс.
|
||||||
# Просим psql через docker exec выполнить EXPLAIN.
|
|
||||||
|
Запускаем 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 = (
|
sql = (
|
||||||
"EXPLAIN (ANALYZE, BUFFERS) SELECT id, chat_id, sender_id, text, created_at "
|
"EXPLAIN (ANALYZE, BUFFERS) "
|
||||||
"FROM messages WHERE chat_id = (SELECT chat_id FROM messages LIMIT 1) "
|
"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;"
|
"ORDER BY created_at, id LIMIT 51;"
|
||||||
)
|
)
|
||||||
r = subprocess.run(
|
r = subprocess.run(
|
||||||
["docker", "exec", "-i", "mtusi-messenger-lab2", "python", "-c",
|
[
|
||||||
"import os,psycopg;conn=psycopg.connect(os.environ['DATABASE_URL']);"
|
"docker", "run", "--rm",
|
||||||
"cur=conn.cursor();cur.execute(%r);"
|
"--add-host=host.docker.internal:host-gateway",
|
||||||
"print('\\n'.join(row[0] for row in cur.fetchall()))" % sql],
|
"postgres:18-alpine",
|
||||||
capture_output=True, text=True, timeout=30,
|
"psql", dsn_in_container, "-c", sql,
|
||||||
|
],
|
||||||
|
capture_output=True, text=True, timeout=60,
|
||||||
)
|
)
|
||||||
out = r.stdout + r.stderr
|
out = r.stdout + r.stderr
|
||||||
check("Index" in out or "Bitmap Index" in out or "idx_messages_chat_created" in out,
|
check("Index" in out or "Bitmap Index" in out or "idx_messages_chat_created" in out,
|
||||||
"EXPLAIN не показал использование индекса:\n" + out)
|
"EXPLAIN не показал использования индекса:\n" + out)
|
||||||
print("EXPLAIN (фрагмент):")
|
print("EXPLAIN (фрагмент):")
|
||||||
for line in out.splitlines()[:8]:
|
for line in out.splitlines()[:10]:
|
||||||
print(" ", line)
|
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():
|
def main():
|
||||||
args = arguments("Lab2 level 4 checks")
|
args = arguments("Lab2 level 4 checks")
|
||||||
c = Client(args.base_url, args.ca_file)
|
c = Client(args.base_url, args.ca_file)
|
||||||
|
|
||||||
print("=== test_concurrent_registration ===")
|
print("=== test_concurrent_registration ===")
|
||||||
test_concurrent_registration(c)
|
test_concurrent_registration(c)
|
||||||
print("PASS: concurrent registration produces exactly one user")
|
print("PASS: concurrent registration produces exactly one user")
|
||||||
|
|
||||||
print("=== test_short_ttl_expiry ===")
|
print("=== test_short_ttl_expiry ===")
|
||||||
test_short_ttl_expiry(c, args.base_url)
|
test_short_ttl_expiry(c)
|
||||||
print("PASS: session expires after SESSION_TTL_SECONDS")
|
print("PASS: session expires after SESSION_TTL_SECONDS")
|
||||||
|
|
||||||
print("=== test_explain ===")
|
print("=== test_explain ===")
|
||||||
test_explain(c)
|
test_explain(c)
|
||||||
print("PASS: EXPLAIN uses idx_messages_chat_created")
|
print("PASS: EXPLAIN uses idx_messages_chat_created")
|
||||||
|
|
||||||
print("=== test_redis_unavailable ===")
|
print("=== test_redis_unavailable ===")
|
||||||
test_redis_unavailable(c, args.base_url)
|
test_redis_unavailable(c)
|
||||||
print("PASS: readiness 503 без Redis, затем восстановление")
|
print("PASS: readiness 503 без Redis, затем восстановление")
|
||||||
|
|
||||||
print("PASS: all lab2 level-4 checks passed")
|
print("PASS: all lab2 level-4 checks passed")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user