forked from mtusi2026/mtusi2026lab2
219 lines
8.0 KiB
Python
219 lines
8.0 KiB
Python
import os
|
|
import subprocess
|
|
import time
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
BASE = os.getenv("BASE_URL", "http://localhost:8080")
|
|
API = BASE + "/api/v1"
|
|
PW = "correct horse battery"
|
|
|
|
|
|
def dc(*a):
|
|
return subprocess.run(["docker", "compose", *a], check=True, capture_output=True, text=True)
|
|
|
|
|
|
def psql(sql):
|
|
return dc("exec", "-T", "db", "psql", "-U", "postgres", "-d", "messenger_db",
|
|
"-v", "ON_ERROR_STOP=1", "-c", sql)
|
|
|
|
|
|
def client():
|
|
return httpx.Client(timeout=10)
|
|
|
|
|
|
def register(c, username=None, password=PW):
|
|
username = username or "u" + uuid.uuid4().hex[:12]
|
|
r = c.post(f"{API}/users", json={"username": username, "display_name": "T", "password": password})
|
|
assert r.status_code == 201, r.text
|
|
return r.json()
|
|
|
|
|
|
def login(c, username, password=PW):
|
|
return c.post(f"{API}/auth/sessions", auth=(username, password))
|
|
|
|
|
|
def auth(tok):
|
|
return {"Authorization": f"Bearer {tok}"}
|
|
|
|
|
|
def user_with_token(c):
|
|
u = register(c)
|
|
return u, login(c, u["username"]).json()["token"]
|
|
|
|
|
|
def make_chat(c, tok, member_ids):
|
|
r = c.post(f"{API}/chats", json={"title": "t", "member_ids": member_ids}, headers=auth(tok))
|
|
assert r.status_code == 201, r.text
|
|
return r.json()
|
|
|
|
|
|
def wait_ready(timeout=30):
|
|
end = time.time() + timeout
|
|
while time.time() < end:
|
|
try:
|
|
if httpx.get(BASE + "/health/ready", timeout=3).status_code == 200:
|
|
return
|
|
except httpx.HTTPError:
|
|
pass
|
|
time.sleep(1)
|
|
raise AssertionError("API not ready")
|
|
|
|
|
|
# ---------- аутентификация ----------
|
|
def test_wrong_password_401():
|
|
with client() as c:
|
|
u = register(c)
|
|
r = login(c, u["username"], "wrong password!!")
|
|
assert r.status_code == 401
|
|
assert r.headers["www-authenticate"].startswith("Basic")
|
|
|
|
|
|
def test_long_passwords_not_truncated():
|
|
with client() as c:
|
|
pw = "a" * 72 + "X" * 12
|
|
u = register(c, password=pw)
|
|
assert login(c, u["username"], "a" * 72 + "Y" * 12).status_code == 401
|
|
assert login(c, u["username"], pw).status_code == 201
|
|
|
|
|
|
def test_logout_revokes_only_current_session():
|
|
with client() as c:
|
|
u = register(c)
|
|
t1 = login(c, u["username"]).json()["token"]
|
|
t2 = login(c, u["username"]).json()["token"]
|
|
assert c.delete(f"{API}/auth/sessions/current", headers=auth(t1)).status_code == 204
|
|
assert c.get(f"{API}/users/me", headers=auth(t1)).status_code == 401
|
|
assert c.get(f"{API}/users/me", headers=auth(t2)).status_code == 200
|
|
assert c.delete(f"{API}/auth/sessions/current", headers=auth(t1)).status_code == 401
|
|
|
|
|
|
def test_logout_invalidates_cache_immediately():
|
|
with client() as c:
|
|
_, tok = user_with_token(c)
|
|
assert c.get(f"{API}/users/me", headers=auth(tok)).status_code == 200 # прогрели кэш
|
|
c.delete(f"{API}/auth/sessions/current", headers=auth(tok))
|
|
assert c.get(f"{API}/users/me", headers=auth(tok)).status_code == 401
|
|
|
|
|
|
@pytest.mark.ttl
|
|
def test_session_expires():
|
|
with client() as c:
|
|
_, tok = user_with_token(c)
|
|
assert c.get(f"{API}/users/me", headers=auth(tok)).status_code == 200
|
|
time.sleep(3.5)
|
|
assert c.get(f"{API}/users/me", headers=auth(tok)).status_code == 401
|
|
|
|
|
|
# ---------- гонки и откат ----------
|
|
def test_register_race_one_winner():
|
|
name = "race" + uuid.uuid4().hex[:10]
|
|
|
|
def go(_):
|
|
with client() as c:
|
|
return c.post(f"{API}/users", json={"username": name, "display_name": "T",
|
|
"password": PW}).status_code
|
|
|
|
with ThreadPoolExecutor(10) as ex:
|
|
codes = list(ex.map(go, range(10)))
|
|
assert codes.count(201) == 1 and codes.count(409) == 9, codes
|
|
|
|
|
|
def test_chat_validation_and_rollback():
|
|
with client() as c:
|
|
u, tok = user_with_token(c)
|
|
before = c.get(f"{API}/chats", headers=auth(tok)).json()["items"]
|
|
for ids in ([u["id"], u["id"]], # дубликат
|
|
[u["id"], str(uuid.uuid4())], # неизвестный участник
|
|
[str(uuid.uuid4())]): # нет вызывающего
|
|
r = c.post(f"{API}/chats", json={"title": "t", "member_ids": ids}, headers=auth(tok))
|
|
assert r.status_code == 400, (ids, r.text)
|
|
assert c.get(f"{API}/chats", headers=auth(tok)).json()["items"] == before
|
|
|
|
|
|
# ---------- пагинация ----------
|
|
def test_cursor_garbage_and_foreign_cursor_400():
|
|
with client() as c:
|
|
u, tok = user_with_token(c)
|
|
c1, c2 = make_chat(c, tok, [u["id"]]), make_chat(c, tok, [u["id"]])
|
|
for i in range(2):
|
|
c.post(f"{API}/chats/{c1['id']}/messages", json={"text": f"m{i}"}, headers=auth(tok))
|
|
assert c.get(f"{API}/chats/{c1['id']}/messages?cursor=garbage", headers=auth(tok)).status_code == 400
|
|
assert c.get(f"{API}/chats?cursor=garbage", headers=auth(tok)).status_code == 400
|
|
nxt = c.get(f"{API}/chats/{c1['id']}/messages?limit=1", headers=auth(tok)).json()["next_cursor"]
|
|
assert nxt
|
|
assert c.get(f"{API}/chats/{c2['id']}/messages?cursor={nxt}", headers=auth(tok)).status_code == 400
|
|
|
|
|
|
def test_pagination_with_equal_timestamps():
|
|
with client() as c:
|
|
u, tok = user_with_token(c)
|
|
chat = make_chat(c, tok, [u["id"]])
|
|
vals = ",".join(f"(gen_random_uuid(),'{chat['id']}','{u['id']}','m{i}','2026-01-01T00:00:00Z')"
|
|
for i in range(3))
|
|
psql(f"INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES {vals}")
|
|
seen, cursor = [], None
|
|
for _ in range(5):
|
|
url = f"{API}/chats/{chat['id']}/messages?limit=1" + (f"&cursor={cursor}" if cursor else "")
|
|
page = c.get(url, headers=auth(tok)).json()
|
|
seen += [m["id"] for m in page["items"]]
|
|
cursor = page["next_cursor"]
|
|
if not cursor:
|
|
break
|
|
assert len(seen) == 3 and len(set(seen)) == 3
|
|
|
|
|
|
def test_pagination_full_walk_in_order():
|
|
with client() as c:
|
|
u, tok = user_with_token(c)
|
|
chat = make_chat(c, tok, [u["id"]])
|
|
sent = [c.post(f"{API}/chats/{chat['id']}/messages", json={"text": f"m{i}"},
|
|
headers=auth(tok)).json()["id"] for i in range(5)]
|
|
got, cursor = [], None
|
|
while True:
|
|
url = f"{API}/chats/{chat['id']}/messages?limit=2" + (f"&cursor={cursor}" if cursor else "")
|
|
page = c.get(url, headers=auth(tok)).json()
|
|
got += [m["id"] for m in page["items"]]
|
|
cursor = page["next_cursor"]
|
|
if not cursor:
|
|
break
|
|
assert got == sent
|
|
|
|
|
|
# ---------- отказы зависимостей ----------
|
|
@pytest.mark.chaos
|
|
def test_valkey_down_falls_back_to_db():
|
|
with client() as c:
|
|
_, tok = user_with_token(c)
|
|
dc("stop", "valkey")
|
|
try:
|
|
assert c.get(f"{API}/users/me", headers=auth(tok)).status_code == 200 # обход кэша
|
|
assert c.get(f"{API}/users/me").status_code == 401 # аноним не доверенный
|
|
assert c.get(f"{API}/users/me", headers={"Authorization": "Bearer nope"}).status_code == 401
|
|
finally:
|
|
dc("start", "valkey")
|
|
time.sleep(2)
|
|
assert c.get(f"{API}/users/me", headers=auth(tok)).status_code == 200
|
|
|
|
|
|
@pytest.mark.chaos
|
|
def test_db_paused_returns_503_and_recovers():
|
|
with client() as c:
|
|
_, tok = user_with_token(c)
|
|
dc("pause", "db")
|
|
try:
|
|
t0 = time.time()
|
|
r = httpx.get(BASE + "/health/ready", timeout=8)
|
|
assert r.status_code == 503
|
|
assert time.time() - t0 < 5
|
|
assert c.get(f"{API}/users/me").status_code == 401
|
|
r = httpx.get(f"{API}/chats", headers=auth(tok), timeout=20)
|
|
assert r.status_code == 503 and r.json()["error"]["code"] == "unavailable"
|
|
finally:
|
|
dc("unpause", "db")
|
|
wait_ready()
|
|
assert c.get(f"{API}/chats", headers=auth(tok)).status_code == 200
|