118 lines
4.9 KiB
Python
118 lines
4.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Уровень 4 lab2: конкурентная регистрация, expiry TTL, недоступность Redis, EXPLAIN."""
|
|
import base64
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
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
|
|
|
|
|
|
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 = __import__("threading").Lock()
|
|
|
|
def one(_):
|
|
local = Client(c.base, timeout=10)
|
|
try:
|
|
local.call("POST", "/api/v1/users", 201, body=body)
|
|
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)
|
|
|
|
|
|
def test_short_ttl_expiry(c, base_url):
|
|
"""Регистрация + сессия с TTL=2с; через 4с токен недействителен."""
|
|
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})
|
|
cred = base64.b64encode((username + ":" + password).encode()).decode()
|
|
session = c.call("POST", "/api/v1/auth/sessions", 201,
|
|
headers={"Authorization": "Basic " + cred})["json"]
|
|
# Работает сразу
|
|
c.call("GET", "/api/v1/users/me", 200,
|
|
headers={"Authorization": "Bearer " + session["token"]})
|
|
# Ждём больше TTL
|
|
time.sleep(4)
|
|
c.call("GET", "/api/v1/users/me", 401,
|
|
headers={"Authorization": "Bearer " + session["token"]})
|
|
|
|
|
|
def test_redis_unavailable(c, base_url):
|
|
"""Останавливаем 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):
|
|
"""EXPLAIN (ANALYZE, BUFFERS) по запросу истории — индекс используется."""
|
|
# Просим psql через docker exec выполнить EXPLAIN.
|
|
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", "exec", "-i", "mtusi-messenger-lab2", "python", "-c",
|
|
"import os,psycopg;conn=psycopg.connect(os.environ['DATABASE_URL']);"
|
|
"cur=conn.cursor();cur.execute(%r);"
|
|
"print('\\n'.join(row[0] for row in cur.fetchall()))" % sql],
|
|
capture_output=True, text=True, timeout=30,
|
|
)
|
|
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()[:8]:
|
|
print(" ", line)
|
|
|
|
|
|
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, args.base_url)
|
|
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, args.base_url)
|
|
print("PASS: readiness 503 без Redis, затем восстановление")
|
|
print("PASS: all lab2 level-4 checks passed")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main) |