forked from mtusi2026/mtusi2026lab4
Реализация лабораторной работы 4 на 4
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
import json
|
||||
import os
|
||||
from collections.abc import Callable, Iterator
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import auth, basic, message_headers, unique_password, unique_username
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_BASE_URL = json.loads((ROOT / "lab.json").read_text())["default_base_url"]
|
||||
|
||||
REQUEST_TIMEOUT_SEC = 10
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def base_url() -> str:
|
||||
return os.environ.get("BASE_URL") or DEFAULT_BASE_URL
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def api(base_url: str) -> Iterator[httpx.Client]:
|
||||
# trust_env=False отключает перехват локального трафика системными прокси Windows/VPN
|
||||
with httpx.Client(base_url=base_url, timeout=REQUEST_TIMEOUT_SEC, trust_env=False) as client:
|
||||
yield client
|
||||
|
||||
|
||||
def register_and_login(
|
||||
client: httpx.Client, label: str, display_name: str | None = None
|
||||
) -> dict:
|
||||
"""Регистрация и вход; в словаре User плюс token и password для тестов"""
|
||||
username = unique_username(label)
|
||||
password = unique_password()
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": display_name or f"Студент {label}",
|
||||
"password": password,
|
||||
}
|
||||
response = client.post("/api/v1/users", json=body)
|
||||
assert response.status_code == 201, response.text
|
||||
user = response.json()
|
||||
session = client.post("/api/v1/auth/sessions", headers=basic(username, password))
|
||||
assert session.status_code == 201, session.text
|
||||
return {**user, "token": session.json()["token"], "password": password}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_user(api: httpx.Client) -> Callable[..., dict]:
|
||||
def create(label: str = "user", display_name: str | None = None) -> dict:
|
||||
return register_and_login(api, label, display_name)
|
||||
|
||||
return create
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_chat(api: httpx.Client) -> Callable[..., dict]:
|
||||
def create(owner: dict, members: list[dict], title: str = "Тестовый чат") -> dict:
|
||||
body = {"title": title, "member_ids": [member["id"] for member in members]}
|
||||
response = api.post("/api/v1/chats", json=body, headers=auth(owner))
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
return create
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def send_message(api: httpx.Client) -> Callable[..., dict]:
|
||||
def send(user: dict, chat: dict, text: str) -> dict:
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=message_headers(user),
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
return send
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Общие проверки для собственных black-box тестов"""
|
||||
|
||||
import base64
|
||||
import subprocess
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
USER_FIELDS = ("id", "username", "display_name", "created_at")
|
||||
|
||||
|
||||
def unique_username(label: str) -> str:
|
||||
return f"st_{label}_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
|
||||
def unique_password() -> str:
|
||||
return f"Pw-{uuid.uuid4().hex}"
|
||||
|
||||
|
||||
def basic(username: str, password: str) -> dict[str, str]:
|
||||
"""Authorization: Basic; пароль кодируется в UTF-8"""
|
||||
raw = f"{username}:{password}".encode()
|
||||
return {"Authorization": "Basic " + base64.b64encode(raw).decode()}
|
||||
|
||||
|
||||
def auth(user: dict) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {user['token']}"}
|
||||
|
||||
|
||||
def message_headers(user: dict, key: str | None = None) -> dict[str, str]:
|
||||
"""Bearer и Idempotency-Key (новый, если не задан)"""
|
||||
return {**auth(user), "Idempotency-Key": key or uuid.uuid4().hex}
|
||||
|
||||
|
||||
def public_user(user: dict) -> dict:
|
||||
"""User из ответа API без тестовых полей token/password"""
|
||||
return {field: user[field] for field in USER_FIELDS}
|
||||
|
||||
|
||||
def assert_error(response: httpx.Response, status: int, code: str) -> None:
|
||||
"""Код ответа и единый формат ошибки: request_id совпадает с заголовком"""
|
||||
assert response.status_code == status, response.text
|
||||
assert response.headers["content-type"].startswith("application/json")
|
||||
error = response.json()["error"]
|
||||
assert error["code"] == code
|
||||
assert error["message"]
|
||||
assert error["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
def assert_unauthorized(response: httpx.Response, scheme: str = "Bearer") -> None:
|
||||
"""401 с challenge нужной схемы"""
|
||||
assert_error(response, 401, "unauthorized")
|
||||
assert response.headers["WWW-Authenticate"].startswith(scheme)
|
||||
|
||||
|
||||
def read_all_messages(
|
||||
api: httpx.Client, user: dict, chat_id: str, limit: int
|
||||
) -> tuple[list[dict], int]:
|
||||
"""Обход истории по next_cursor; возвращает сообщения и число страниц"""
|
||||
items: list[dict] = []
|
||||
pages = 0
|
||||
params: dict[str, str | int] = {"limit": limit}
|
||||
while True:
|
||||
response = api.get(
|
||||
f"/api/v1/chats/{chat_id}/messages", params=params, headers=auth(user)
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
page = response.json()
|
||||
items.extend(page["items"])
|
||||
pages += 1
|
||||
if page["next_cursor"] is None:
|
||||
return items, pages
|
||||
params = {"limit": limit, "cursor": page["next_cursor"]}
|
||||
|
||||
|
||||
def compose(*args: str, stdin: str | None = None) -> str:
|
||||
"""docker compose из корня репозитория; вывод не печатается (может быть секретен)"""
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT,
|
||||
input=stdin,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
check=True,
|
||||
)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def psql(sql: str) -> str:
|
||||
"""Запрос в PostgreSQL стенда изнутри контейнера; порт БД наружу не открыт"""
|
||||
return compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
'psql -X -q -tA -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
|
||||
stdin=sql,
|
||||
).strip()
|
||||
@@ -0,0 +1,97 @@
|
||||
import os
|
||||
from uuid import uuid4
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import auth, message_headers
|
||||
|
||||
@pytest.fixture
|
||||
def sample_image_path() -> str:
|
||||
path = "test_image.png"
|
||||
# Валидный 1x1 PNG файл
|
||||
with open(path, "wb") as f:
|
||||
f.write(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDATx\x9cc\xf8\xff\xff?\x00\x05\xfe\x02\xfe\xa74\x00\x00\x00\x00IEND\xaeB`\x82')
|
||||
yield path
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
|
||||
@pytest.fixture
|
||||
def fake_txt_path() -> str:
|
||||
path = "fake.png"
|
||||
with open(path, "w") as f:
|
||||
f.write("Not a real image file!")
|
||||
yield path
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
|
||||
|
||||
def test_upload_valid_attachment(api: httpx.Client, make_user, make_chat, sample_image_path):
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
|
||||
with open(sample_image_path, "rb") as f:
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments",
|
||||
params={"filename": "photo.png"},
|
||||
content=f.read(),
|
||||
headers={**auth(alice), "Content-Type": "image/png"}
|
||||
)
|
||||
|
||||
assert response.status_code == 201, response.text
|
||||
data = response.json()
|
||||
assert data["status"] == "ready"
|
||||
assert data["filename"] == "photo.png"
|
||||
assert data["content_type"] == "image/png"
|
||||
|
||||
|
||||
def test_upload_invalid_mime(api: httpx.Client, make_user, make_chat, fake_txt_path):
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
|
||||
with open(fake_txt_path, "rb") as f:
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments",
|
||||
params={"filename": "photo.png"},
|
||||
content=f.read(),
|
||||
headers={**auth(alice), "Content-Type": "image/png"}
|
||||
)
|
||||
|
||||
assert response.status_code == 415, response.text
|
||||
|
||||
|
||||
def test_upload_invalid_filename(api: httpx.Client, make_user, make_chat, sample_image_path):
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
|
||||
with open(sample_image_path, "rb") as f:
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments",
|
||||
params={"filename": "../../../etc/passwd"},
|
||||
content=f.read(),
|
||||
headers={**auth(alice), "Content-Type": "image/png"}
|
||||
)
|
||||
|
||||
assert response.status_code == 400, response.text
|
||||
|
||||
|
||||
def test_attach_file_to_message(api: httpx.Client, make_user, make_chat, sample_image_path):
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
|
||||
with open(sample_image_path, "rb") as f:
|
||||
upload_resp = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments",
|
||||
params={"filename": "photo.png"},
|
||||
content=f.read(),
|
||||
headers={**auth(alice), "Content-Type": "image/png"}
|
||||
)
|
||||
assert upload_resp.status_code == 201, upload_resp.text
|
||||
attachment_id = upload_resp.json()["id"]
|
||||
|
||||
msg_resp = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "Смотри фото!", "attachment_ids": [attachment_id]},
|
||||
headers=message_headers(alice)
|
||||
)
|
||||
|
||||
assert msg_resp.status_code == 201, msg_resp.text
|
||||
assert attachment_id in msg_resp.json()["attachment_ids"]
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Вход по Basic, opaque Bearer-сессия, неверный пароль и logout"""
|
||||
|
||||
import base64
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import (
|
||||
assert_unauthorized,
|
||||
auth,
|
||||
basic,
|
||||
psql,
|
||||
public_user,
|
||||
unique_username,
|
||||
)
|
||||
|
||||
SESSIONS_PATH = "/api/v1/auth/sessions"
|
||||
CURRENT_SESSION_PATH = "/api/v1/auth/sessions/current"
|
||||
|
||||
|
||||
def test_login_returns_opaque_bearer_session(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
response = api.post(
|
||||
SESSIONS_PATH, headers=basic(alice["username"], alice["password"])
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
session = response.json()
|
||||
assert set(session) == {"token", "token_type", "expires_at", "user"}
|
||||
assert session["token_type"] == "Bearer"
|
||||
assert session["user"] == public_user(alice)
|
||||
assert len(session["token"]) >= 43 # 32 байта в base64url
|
||||
assert alice["id"] not in session["token"]
|
||||
assert alice["username"] not in session["token"]
|
||||
assert session["token"] != alice["token"]
|
||||
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
assert expires_at > datetime.now(UTC)
|
||||
|
||||
|
||||
def test_wrong_password_and_unknown_user_are_indistinguishable(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
wrong = api.post(SESSIONS_PATH, headers=basic(alice["username"], "Wrong-pass-123"))
|
||||
unknown = api.post(
|
||||
SESSIONS_PATH, headers=basic(unique_username("ghost"), "Wrong-pass-123")
|
||||
)
|
||||
for response in (wrong, unknown):
|
||||
assert_unauthorized(response, scheme="Basic")
|
||||
assert 'realm="messenger"' in response.headers["WWW-Authenticate"]
|
||||
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"authorization",
|
||||
[
|
||||
None,
|
||||
"",
|
||||
"Basic",
|
||||
"Basic !!!not-base64!!!",
|
||||
"Basic " + base64.b64encode(b"no-colon-here").decode(),
|
||||
"Basic " + base64.b64encode(b"\xff\xfe:password").decode(),
|
||||
"Bearer some-token",
|
||||
],
|
||||
)
|
||||
def test_malformed_basic_is_unauthorized(
|
||||
api: httpx.Client, authorization: str | None
|
||||
) -> None:
|
||||
headers = {} if authorization is None else {"Authorization": authorization}
|
||||
assert_unauthorized(api.post(SESSIONS_PATH, headers=headers), scheme="Basic")
|
||||
|
||||
|
||||
def test_utf8_password_with_colon(api: httpx.Client) -> None:
|
||||
username = unique_username("utf")
|
||||
password = "пароль:с:двоеточием 🔐"
|
||||
body = {"username": username, "display_name": "x", "password": password}
|
||||
assert api.post("/api/v1/users", json=body).status_code == 201
|
||||
assert api.post(SESSIONS_PATH, headers=basic(username, password)).status_code == 201
|
||||
assert_unauthorized(
|
||||
api.post(SESSIONS_PATH, headers=basic(username, "пароль:с:двоеточием")),
|
||||
scheme="Basic",
|
||||
)
|
||||
|
||||
|
||||
def test_basic_is_rejected_on_business_endpoints(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
headers = basic(alice["username"], alice["password"])
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=headers))
|
||||
assert_unauthorized(api.get("/api/v1/chats", headers=headers))
|
||||
|
||||
|
||||
def test_logout_revokes_only_current_session(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
second = api.post(
|
||||
SESSIONS_PATH, headers=basic(alice["username"], alice["password"])
|
||||
)
|
||||
other_session = {**alice, "token": second.json()["token"]}
|
||||
|
||||
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
|
||||
response = api.delete(CURRENT_SESSION_PATH, headers=auth(alice))
|
||||
assert response.status_code == 204
|
||||
assert response.content == b""
|
||||
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
|
||||
assert_unauthorized(api.delete(CURRENT_SESSION_PATH, headers=auth(alice)))
|
||||
assert api.get("/api/v1/users/me", headers=auth(other_session)).status_code == 200
|
||||
|
||||
|
||||
def test_logout_without_token(api: httpx.Client) -> None:
|
||||
assert_unauthorized(api.delete(CURRENT_SESSION_PATH))
|
||||
assert_unauthorized(
|
||||
api.delete(CURRENT_SESSION_PATH, headers={"Authorization": "Bearer unknown"})
|
||||
)
|
||||
|
||||
|
||||
def test_relogin_after_logout(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
api.delete(CURRENT_SESSION_PATH, headers=auth(alice))
|
||||
again = api.post(SESSIONS_PATH, headers=basic(alice["username"], alice["password"]))
|
||||
assert again.status_code == 201
|
||||
renewed = {**alice, "token": again.json()["token"]}
|
||||
assert api.get("/api/v1/users/me", headers=auth(renewed)).status_code == 200
|
||||
|
||||
|
||||
def test_password_is_not_stored_in_plaintext(make_user) -> None:
|
||||
"""Проверка в БД стенда: в users лежит PHC-строка Argon2id, а не пароль"""
|
||||
alice = make_user("alice")
|
||||
stored = psql(
|
||||
f"SELECT password_hash FROM users WHERE username = '{alice['username']}';"
|
||||
)
|
||||
assert stored.startswith("$argon2id$")
|
||||
assert alice["password"] not in stored
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
Балансировка без sticky sessions: запросы одной сессии обслуживают разные
|
||||
реплики, а состояние (сессии, сообщения, logout) общее для всех.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
import httpx
|
||||
from helpers import assert_unauthorized, auth, message_headers, public_user
|
||||
|
||||
REQUESTS = 20
|
||||
|
||||
|
||||
def test_one_session_is_served_by_several_replicas(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
"""Одно keep-alive соединение клиента к LB, без повторного входа"""
|
||||
alice = make_user("alice")
|
||||
instances: Counter[str] = Counter()
|
||||
for _ in range(REQUESTS):
|
||||
response = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == public_user(alice)
|
||||
instances[response.headers["X-Instance-Id"]] += 1
|
||||
print("\nINSTANCES FOR ONE SESSION:", dict(instances))
|
||||
assert len(instances) >= 2
|
||||
|
||||
|
||||
def test_write_is_visible_through_every_replica(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
sent = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"видно везде {uuid.uuid4().hex}"},
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert sent.status_code == 201, sent.text
|
||||
readers: set[str] = set()
|
||||
for _ in range(REQUESTS):
|
||||
page = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(bob))
|
||||
assert page.status_code == 200, page.text
|
||||
assert page.json()["items"] == [sent.json()]
|
||||
readers.add(page.headers["X-Instance-Id"])
|
||||
assert len(readers) >= 2
|
||||
|
||||
|
||||
def test_logout_applies_to_all_replicas(api: httpx.Client, make_user) -> None:
|
||||
"""Сессия попала в общий кэш через обе реплики, затем отозвана на одной"""
|
||||
alice = make_user("alice")
|
||||
for _ in range(4):
|
||||
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
|
||||
logout = api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
|
||||
assert logout.status_code == 204
|
||||
rejected_by: set[str] = set()
|
||||
for _ in range(REQUESTS):
|
||||
response = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert_unauthorized(response)
|
||||
rejected_by.add(response.headers["X-Instance-Id"])
|
||||
assert len(rejected_by) >= 2
|
||||
|
||||
|
||||
def test_every_api_response_has_instance_id(api: httpx.Client) -> None:
|
||||
for response in (
|
||||
api.get("/health/live"),
|
||||
api.get("/health/ready"),
|
||||
api.get("/api/v1/unknown"),
|
||||
api.get("/api/v1/users/me"),
|
||||
):
|
||||
assert response.headers["X-Instance-Id"]
|
||||
assert response.headers["X-Request-Id"]
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Защита состояния от гонок: 100 сообщений от 10 параллельных клиентов"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from helpers import auth, message_headers, read_all_messages
|
||||
|
||||
CLIENTS = 10
|
||||
MESSAGES_PER_CLIENT = 10
|
||||
TOTAL_MESSAGES = CLIENTS * MESSAGES_PER_CLIENT
|
||||
PAGE_LIMIT = 30
|
||||
|
||||
|
||||
async def _send_concurrently(
|
||||
base_url: str, chat_id: str, users: list[dict]
|
||||
) -> list[int]:
|
||||
"""Каждый клиент — отдельный пользователь и пул соединений; старт по сигналу"""
|
||||
start = asyncio.Event()
|
||||
|
||||
async def client_worker(user: dict) -> list[int]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=base_url, headers=auth(user), timeout=30
|
||||
) as client:
|
||||
await start.wait()
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
json={"text": f"{user['username']}#{n}"},
|
||||
headers=message_headers(user),
|
||||
)
|
||||
for n in range(MESSAGES_PER_CLIENT)
|
||||
)
|
||||
)
|
||||
return [response.status_code for response in responses]
|
||||
|
||||
workers = [asyncio.create_task(client_worker(user)) for user in users]
|
||||
await asyncio.sleep(0)
|
||||
start.set()
|
||||
results = await asyncio.gather(*workers)
|
||||
return [status for statuses in results for status in statuses]
|
||||
|
||||
|
||||
def test_parallel_messages_are_not_lost_or_duplicated(
|
||||
api: httpx.Client, base_url: str, make_user, make_chat
|
||||
) -> None:
|
||||
users = [make_user(f"c{n}") for n in range(CLIENTS)]
|
||||
chat = make_chat(users[0], users)
|
||||
|
||||
started = time.perf_counter()
|
||||
statuses = asyncio.run(_send_concurrently(base_url, chat["id"], users))
|
||||
elapsed = time.perf_counter() - started
|
||||
|
||||
items, pages = read_all_messages(api, users[-1], chat["id"], PAGE_LIMIT)
|
||||
expected_texts = {
|
||||
f"{user['username']}#{n}" for user in users for n in range(MESSAGES_PER_CLIENT)
|
||||
}
|
||||
summary = {
|
||||
"clients": CLIENTS,
|
||||
"messages_sent": len(statuses),
|
||||
"status_201": statuses.count(201),
|
||||
"messages_read": len(items),
|
||||
"unique_ids": len({item["id"] for item in items}),
|
||||
"unique_texts": len({item["text"] for item in items}),
|
||||
"pages_read": pages,
|
||||
"send_seconds": round(elapsed, 3),
|
||||
}
|
||||
print("\nCONCURRENCY RESULT:", json.dumps(summary, ensure_ascii=False))
|
||||
|
||||
assert statuses == [201] * TOTAL_MESSAGES
|
||||
assert len(items) == TOTAL_MESSAGES
|
||||
assert summary["unique_ids"] == TOTAL_MESSAGES
|
||||
assert {item["text"] for item in items} == expected_texts
|
||||
keys = [(item["created_at"], item["id"]) for item in items]
|
||||
assert keys == sorted(keys)
|
||||
assert len(set(keys)) == TOTAL_MESSAGES
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
Отказы зависимостей: Valkey и PostgreSQL останавливаются через docker compose.
|
||||
|
||||
Тесты меняют состояние стенда (stop/start контейнеров, volumes сохраняются),
|
||||
поэтому запускаются только явно: make test-failures (RUN_FAILURE_TESTS=1).
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, assert_unauthorized, auth, basic, compose
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
os.environ.get("RUN_FAILURE_TESTS") != "1",
|
||||
reason="останавливает контейнеры стенда: запускайте через make test-failures",
|
||||
)
|
||||
|
||||
READY_TIMEOUT_SEC = 60
|
||||
# Ответ при упавшей зависимости должен быть быстрым, а не висеть до таймаута клиента
|
||||
BOUNDED_RESPONSE_SEC = 3
|
||||
|
||||
|
||||
def wait_ready(api: httpx.Client) -> None:
|
||||
deadline = time.monotonic() + READY_TIMEOUT_SEC
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if api.get("/health/ready").status_code == 200:
|
||||
return
|
||||
except httpx.TransportError:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise AssertionError("API не стал готов после восстановления зависимости")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def valkey_stopped(api: httpx.Client) -> Iterator[None]:
|
||||
compose("stop", "valkey")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
compose("up", "-d", "--wait", "valkey")
|
||||
wait_ready(api)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def postgres_stopped(api: httpx.Client) -> Iterator[None]:
|
||||
compose("stop", "postgres")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
compose("start", "postgres")
|
||||
compose("up", "-d", "--wait", "postgres")
|
||||
wait_ready(api)
|
||||
|
||||
|
||||
def test_valkey_down_cache_is_bypassed(
|
||||
api: httpx.Client, make_user, make_chat, send_message, valkey_stopped
|
||||
) -> None:
|
||||
"""Без Valkey всё работает через PostgreSQL: вход, Bearer, запись, logout"""
|
||||
alice = make_user("alice")
|
||||
started = time.monotonic()
|
||||
me = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert me.status_code == 200, me.text
|
||||
assert time.monotonic() - started < BOUNDED_RESPONSE_SEC
|
||||
|
||||
chat = make_chat(alice, [alice])
|
||||
send_message(alice, chat, "без кэша")
|
||||
assert api.get("/health/ready").status_code == 200
|
||||
|
||||
assert (
|
||||
api.delete("/api/v1/auth/sessions/current", headers=auth(alice)).status_code
|
||||
== 204
|
||||
)
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
|
||||
assert_unauthorized(api.get("/api/v1/users/me"))
|
||||
|
||||
|
||||
def test_logout_during_valkey_outage_is_not_resurrected(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
"""
|
||||
Сессия попала в кэш, затем Valkey упал и пользователь вышел. После подъёма
|
||||
Valkey (без persistence — пустой) отозванный токен не принимается.
|
||||
"""
|
||||
alice = make_user("alice")
|
||||
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
|
||||
compose("stop", "valkey")
|
||||
try:
|
||||
response = api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
|
||||
assert response.status_code == 204
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
compose("up", "-d", "--wait", "valkey")
|
||||
wait_ready(api)
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
|
||||
|
||||
|
||||
def test_postgres_down_returns_bounded_503_and_no_anonymous_access(
|
||||
api: httpx.Client, make_user, postgres_stopped
|
||||
) -> None:
|
||||
alice_token_unused = {"token": "x" * 43}
|
||||
|
||||
started = time.monotonic()
|
||||
ready = api.get("/health/ready")
|
||||
assert_error(ready, 503, "unavailable")
|
||||
assert time.monotonic() - started < BOUNDED_RESPONSE_SEC
|
||||
|
||||
# Анонимный запрос остаётся 401, неизвестный токен не принимается как доверенный
|
||||
assert_unauthorized(api.get("/api/v1/users/me"))
|
||||
unknown = api.get("/api/v1/users/me", headers=auth(alice_token_unused))
|
||||
assert_error(unknown, 503, "unavailable")
|
||||
assert "asyncpg" not in unknown.text and "postgres" not in unknown.text.lower()
|
||||
|
||||
body = {"username": "st_pg_down", "display_name": "x", "password": "P" * 12}
|
||||
assert_error(api.post("/api/v1/users", json=body), 503, "unavailable")
|
||||
login = api.post("/api/v1/auth/sessions", headers=basic("st_pg_down", "P" * 12))
|
||||
assert_error(login, 503, "unavailable")
|
||||
|
||||
|
||||
def test_session_survives_postgres_restart(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
compose("restart", "postgres")
|
||||
wait_ready(api)
|
||||
chats = api.get("/api/v1/chats", headers=auth(alice))
|
||||
assert chats.status_code == 200, chats.text
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
Истечение сессии при коротком SESSION_TTL_SECONDS.
|
||||
|
||||
Нужен отдельный API с SESSION_TTL_SECONDS=2: make test-expiry поднимает
|
||||
api-short-ttl на :8081 поверх тех же PostgreSQL и Valkey.
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from conftest import register_and_login
|
||||
from helpers import assert_unauthorized, auth, basic
|
||||
|
||||
EXPIRY_BASE_URL = os.environ.get("EXPIRY_BASE_URL")
|
||||
SHORT_TTL_SEC = 2
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not EXPIRY_BASE_URL, reason="EXPIRY_BASE_URL не задан: запустите make test-expiry"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def short_api() -> httpx.Client:
|
||||
assert EXPIRY_BASE_URL is not None
|
||||
with httpx.Client(base_url=EXPIRY_BASE_URL, timeout=10) as client:
|
||||
yield client
|
||||
|
||||
|
||||
def test_session_expires_after_short_ttl(short_api: httpx.Client) -> None:
|
||||
alice = register_and_login(short_api, "ttl")
|
||||
me = short_api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert me.status_code == 200, me.text
|
||||
|
||||
time.sleep(SHORT_TTL_SEC + 1)
|
||||
|
||||
# Сессия уже лежала в кэше после первого запроса: истечь должна и там
|
||||
assert_unauthorized(short_api.get("/api/v1/users/me", headers=auth(alice)))
|
||||
assert_unauthorized(short_api.get("/api/v1/chats", headers=auth(alice)))
|
||||
assert_unauthorized(
|
||||
short_api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
|
||||
)
|
||||
|
||||
|
||||
def test_expires_at_matches_short_ttl(short_api: httpx.Client) -> None:
|
||||
before = datetime.now(UTC)
|
||||
alice = register_and_login(short_api, "ttl")
|
||||
session = short_api.post(
|
||||
"/api/v1/auth/sessions", headers=basic(alice["username"], alice["password"])
|
||||
).json()
|
||||
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
lifetime = (expires_at - before).total_seconds()
|
||||
assert 0 < lifetime <= SHORT_TTL_SEC + 1
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Чужой чат: посторонний получает 404, существование чата не раскрывается"""
|
||||
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from helpers import assert_error, auth, message_headers
|
||||
|
||||
|
||||
def test_outsider_cannot_access_chat(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
send_message(alice, chat, "секрет")
|
||||
path = f"/api/v1/chats/{chat['id']}"
|
||||
|
||||
assert_error(api.get(path, headers=auth(eve)), 404, "not_found")
|
||||
assert_error(api.get(f"{path}/messages", headers=auth(eve)), 404, "not_found")
|
||||
response = api.post(
|
||||
f"{path}/messages", json={"text": "чужое"}, headers=message_headers(eve)
|
||||
)
|
||||
assert_error(response, 404, "not_found")
|
||||
|
||||
history = api.get(f"{path}/messages", headers=auth(bob)).json()
|
||||
assert [item["text"] for item in history["items"]] == ["секрет"]
|
||||
|
||||
|
||||
def test_foreign_and_missing_chat_are_indistinguishable(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice])
|
||||
foreign = api.get(f"/api/v1/chats/{chat['id']}", headers=auth(eve)).json()
|
||||
missing = api.get(f"/api/v1/chats/{uuid.uuid4()}", headers=auth(eve)).json()
|
||||
assert foreign["error"]["code"] == missing["error"]["code"] == "not_found"
|
||||
assert foreign["error"]["message"] == missing["error"]["message"]
|
||||
|
||||
|
||||
def test_chat_list_contains_only_own_chats(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice])
|
||||
own = api.get("/api/v1/chats", headers=auth(eve)).json()
|
||||
assert own == {"items": [], "next_cursor": None}
|
||||
listed = api.get("/api/v1/chats", headers=auth(alice)).json()
|
||||
assert [item["id"] for item in listed["items"]] == [chat["id"]]
|
||||
@@ -0,0 +1,15 @@
|
||||
import httpx
|
||||
from helpers import assert_error
|
||||
|
||||
|
||||
def test_health_endpoints_have_request_id(api: httpx.Client) -> None:
|
||||
for path in ("/health/live", "/health/ready"):
|
||||
response = api.get(path)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
assert response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
def test_unknown_route_uses_error_format(api: httpx.Client) -> None:
|
||||
assert_error(api.get("/api/v1/unknown"), 404, "not_found")
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Idempotency-Key отправки сообщения: повтор, конфликт, область ключа, гонки"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth, message_headers, psql, read_all_messages
|
||||
|
||||
PARALLEL_REPLAYS = 20
|
||||
|
||||
|
||||
def post_message(
|
||||
api: httpx.Client, user: dict, chat: dict, text: str, key: str
|
||||
) -> httpx.Response:
|
||||
return api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=message_headers(user, key),
|
||||
)
|
||||
|
||||
|
||||
def history(api: httpx.Client, user: dict, chat: dict) -> list[dict]:
|
||||
items, _ = read_all_messages(api, user, chat["id"], 100)
|
||||
return items
|
||||
|
||||
|
||||
def test_replay_returns_same_message(api: httpx.Client, make_user, make_chat) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
first = post_message(api, alice, chat, "один раз", key)
|
||||
second = post_message(api, alice, chat, "один раз", key)
|
||||
|
||||
assert first.status_code == second.status_code == 201, second.text
|
||||
assert first.json() == second.json()
|
||||
assert history(api, alice, chat) == [first.json()]
|
||||
|
||||
|
||||
def test_replay_ignores_json_formatting(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
"""Пробелы и форма записи JSON не меняют смысл тела: это тот же запрос"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
headers = {**message_headers(alice), "Content-Type": "application/json"}
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
escaped = b'{"text":"\\u041f\\u0440\\u0438"}'
|
||||
compact = api.post(path, content=escaped, headers=headers)
|
||||
spaced = api.post(path, content='{ "text" : "При" }'.encode(), headers=headers)
|
||||
|
||||
assert compact.status_code == spaced.status_code == 201, spaced.text
|
||||
assert compact.json() == spaced.json()
|
||||
assert len(history(api, alice, chat)) == 1
|
||||
|
||||
|
||||
def test_same_key_with_other_body_is_conflict(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
original = post_message(api, alice, chat, "оригинал", key).json()
|
||||
|
||||
assert_error(post_message(api, alice, chat, "другой", key), 409, "conflict")
|
||||
assert history(api, alice, chat) == [original]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"headers",
|
||||
[
|
||||
{},
|
||||
{"Idempotency-Key": ""},
|
||||
{"Idempotency-Key": "with space"},
|
||||
{"Idempotency-Key": "ключ".encode()},
|
||||
{"Idempotency-Key": "a/b"},
|
||||
{"Idempotency-Key": "x" * 129},
|
||||
],
|
||||
)
|
||||
def test_missing_or_invalid_key_is_rejected(
|
||||
api: httpx.Client, make_user, make_chat, headers: dict
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "без ключа"},
|
||||
headers={**auth(alice), **headers},
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
assert history(api, alice, chat) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["x" * 128, "Az09._:-"])
|
||||
def test_key_boundaries_are_accepted(
|
||||
api: httpx.Client, make_user, make_chat, key: str
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
assert post_message(api, alice, chat, "граница", key).status_code == 201
|
||||
|
||||
|
||||
def test_key_scope_is_user_and_chat(api: httpx.Client, make_user, make_chat) -> None:
|
||||
"""Один ключ у разных пользователей и в разных чатах — независимые сообщения"""
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
other_chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
from_alice = post_message(api, alice, chat, "текст", key).json()
|
||||
from_bob = post_message(api, bob, chat, "текст", key).json()
|
||||
in_other_chat = post_message(api, alice, other_chat, "текст", key).json()
|
||||
|
||||
assert len({from_alice["id"], from_bob["id"], in_other_chat["id"]}) == 3
|
||||
assert from_bob["sender_id"] == bob["id"]
|
||||
assert len(history(api, alice, chat)) == 2
|
||||
assert len(history(api, alice, other_chat)) == 1
|
||||
|
||||
|
||||
def test_replay_rechecks_session_and_access(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
post_message(api, alice, chat, "секрет", key)
|
||||
|
||||
# Чужой с тем же ключом не получает сохранённое сообщение
|
||||
assert_error(post_message(api, eve, chat, "секрет", key), 404, "not_found")
|
||||
# Отозванная сессия не даёт повтора
|
||||
logout = api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
|
||||
assert logout.status_code == 204
|
||||
replay = post_message(api, alice, chat, "секрет", key)
|
||||
assert_error(replay, 401, "unauthorized")
|
||||
|
||||
|
||||
def test_expired_key_can_be_reused(api: httpx.Client, make_user, make_chat) -> None:
|
||||
"""После срока хранения (24 ч) ключ снова создаёт сообщение; срок сдвигается в БД"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
first = post_message(api, alice, chat, "вчера", key).json()
|
||||
psql(
|
||||
"UPDATE message_idempotency_keys "
|
||||
"SET created_at = now() - interval '2 days', "
|
||||
"expires_at = now() - interval '1 day' "
|
||||
f"WHERE chat_id = '{chat['id']}' AND idempotency_key = '{key}';"
|
||||
)
|
||||
|
||||
second = post_message(api, alice, chat, "сегодня", key)
|
||||
|
||||
assert second.status_code == 201, second.text
|
||||
assert second.json()["id"] != first["id"]
|
||||
assert [item["text"] for item in history(api, alice, chat)] == ["вчера", "сегодня"]
|
||||
stored = psql(
|
||||
"SELECT count(*) FROM message_idempotency_keys "
|
||||
f"WHERE chat_id = '{chat['id']}' AND idempotency_key = '{key}';"
|
||||
)
|
||||
assert stored == "1"
|
||||
|
||||
|
||||
async def _post_concurrently(
|
||||
base_url: str, user: dict, chat: dict, key: str, texts: list[str]
|
||||
) -> list[httpx.Response]:
|
||||
"""Все запросы стартуют по одному сигналу; отдельные соединения к LB"""
|
||||
start = asyncio.Event()
|
||||
limits = httpx.Limits(max_connections=len(texts))
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=base_url, timeout=30, limits=limits
|
||||
) as client:
|
||||
|
||||
async def post(text: str) -> httpx.Response:
|
||||
await start.wait()
|
||||
return await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=message_headers(user, key),
|
||||
)
|
||||
|
||||
tasks = [asyncio.create_task(post(text)) for text in texts]
|
||||
await asyncio.sleep(0)
|
||||
start.set()
|
||||
return list(await asyncio.gather(*tasks))
|
||||
|
||||
|
||||
def test_parallel_replays_through_replicas_create_one_message(
|
||||
api: httpx.Client, base_url: str, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
responses = asyncio.run(
|
||||
_post_concurrently(
|
||||
base_url, alice, chat, key, ["одно сообщение"] * PARALLEL_REPLAYS
|
||||
)
|
||||
)
|
||||
|
||||
statuses = Counter(response.status_code for response in responses)
|
||||
instances = Counter(response.headers["X-Instance-Id"] for response in responses)
|
||||
bodies = {json.dumps(response.json(), sort_keys=True) for response in responses}
|
||||
items = history(api, alice, chat)
|
||||
rows = psql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat['id']}';")
|
||||
print(
|
||||
"\nPARALLEL SAME KEY:",
|
||||
json.dumps(
|
||||
{
|
||||
"requests": len(responses),
|
||||
"statuses": dict(statuses),
|
||||
"instances": dict(instances),
|
||||
"distinct_bodies": len(bodies),
|
||||
"messages_in_history": len(items),
|
||||
"rows_in_db": int(rows),
|
||||
}
|
||||
),
|
||||
)
|
||||
assert statuses == {201: PARALLEL_REPLAYS}
|
||||
assert len(instances) >= 2, "запросы не распределились по репликам"
|
||||
assert len(bodies) == 1
|
||||
assert len(items) == 1 and rows == "1"
|
||||
|
||||
|
||||
def test_parallel_same_key_with_different_bodies(
|
||||
api: httpx.Client, base_url: str, make_user, make_chat
|
||||
) -> None:
|
||||
"""Победитель гонки один; совпавшие с ним тела — 201, остальные — 409"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
texts = ["вариант A", "вариант B"] * (PARALLEL_REPLAYS // 2)
|
||||
|
||||
responses = asyncio.run(_post_concurrently(base_url, alice, chat, key, texts))
|
||||
|
||||
items = history(api, alice, chat)
|
||||
assert len(items) == 1
|
||||
winner = items[0]
|
||||
for text, response in zip(texts, responses):
|
||||
if text == winner["text"]:
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.json() == winner
|
||||
else:
|
||||
assert_error(response, 409, "conflict")
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Неверный JSON и неверная структура тела — 400 invalid_request"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth, message_headers
|
||||
|
||||
PASSWORD = "Valid-password-123"
|
||||
|
||||
MALFORMED_BODIES = [
|
||||
b'{"username": "abc",',
|
||||
b"not json at all",
|
||||
b'{"text": "\xff\xfe"}',
|
||||
b"",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", MALFORMED_BODIES)
|
||||
def test_malformed_json_on_register(api: httpx.Client, raw: bytes) -> None:
|
||||
response = api.post(
|
||||
"/api/v1/users", content=raw, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", MALFORMED_BODIES)
|
||||
def test_malformed_json_on_create_chat_and_message(
|
||||
api: httpx.Client, make_user, make_chat, raw: bytes
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
headers = {**auth(alice), "Content-Type": "application/json"}
|
||||
assert_error(
|
||||
api.post("/api/v1/chats", content=raw, headers=headers), 400, "invalid_request"
|
||||
)
|
||||
message_post_headers = {
|
||||
**message_headers(alice),
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
assert_error(
|
||||
api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
content=raw,
|
||||
headers=message_post_headers,
|
||||
),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
[],
|
||||
"alice",
|
||||
{"username": "valid_name", "password": PASSWORD},
|
||||
{"username": 123, "display_name": "x", "password": PASSWORD},
|
||||
{"username": "valid_name", "display_name": None, "password": PASSWORD},
|
||||
{
|
||||
"username": "valid_name",
|
||||
"display_name": "x",
|
||||
"password": PASSWORD,
|
||||
"is_admin": True,
|
||||
},
|
||||
{"username": "Upper_Case", "display_name": "x", "password": PASSWORD},
|
||||
{"username": "ab", "display_name": "x", "password": PASSWORD},
|
||||
{"username": "valid_name", "display_name": " ", "password": PASSWORD},
|
||||
{"username": "valid_name", "display_name": "я" * 101, "password": PASSWORD},
|
||||
{"username": "valid_name", "display_name": "a\u0000b", "password": PASSWORD},
|
||||
],
|
||||
)
|
||||
def test_invalid_user_payload(api: httpx.Client, body: object) -> None:
|
||||
assert_error(api.post("/api/v1/users", json=body), 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"text": 42},
|
||||
{"text": "привет", "sender_id": "11111111-1111-4111-8111-111111111111"},
|
||||
{},
|
||||
],
|
||||
)
|
||||
def test_invalid_message_payload(
|
||||
api: httpx.Client, make_user, make_chat, body: dict
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json=body,
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_invalid_chat_payload(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
cases = [
|
||||
{"title": "t", "member_ids": [bob["id"]]},
|
||||
{"title": "t", "member_ids": [alice["id"], alice["id"]]},
|
||||
{
|
||||
"title": "t",
|
||||
"member_ids": [alice["id"], "11111111-1111-4111-8111-111111111111"],
|
||||
},
|
||||
{"title": "t", "member_ids": [alice["id"], "not-a-uuid"]},
|
||||
{"title": "t", "member_ids": []},
|
||||
{"title": " ", "member_ids": [alice["id"]]},
|
||||
]
|
||||
for body in cases:
|
||||
response = api.post("/api/v1/chats", json=body, headers=auth(alice))
|
||||
assert_error(response, 400, "invalid_request")
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Пустые сообщения, границы длины и Unicode"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth, message_headers
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", " ", " \n\t ", " "])
|
||||
def test_empty_or_blank_message_is_rejected(
|
||||
api: httpx.Client, make_user, make_chat, text: str
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
history = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(alice))
|
||||
assert history.json()["items"] == []
|
||||
|
||||
|
||||
def test_message_length_is_counted_in_code_points(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
longest = "😀" * 4000
|
||||
assert send_message(alice, chat, longest)["text"] == longest
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "😀" * 4001},
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_unicode_is_preserved(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
name = "Алиса 👩💻 é"
|
||||
alice = make_user("alice", display_name=name)
|
||||
assert alice["display_name"] == name
|
||||
chat = make_chat(alice, [alice], title="Чат 🚀 中文")
|
||||
assert chat["title"] == "Чат 🚀 中文"
|
||||
text = "Привет, мир 👋 — «кавычки» \t\n и 𝔘𝔫𝔦𝔠𝔬𝔡𝔢"
|
||||
message = send_message(alice, chat, text)
|
||||
assert message["text"] == text
|
||||
page = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(alice)).json()
|
||||
assert page["items"][0]["text"] == text
|
||||
|
||||
|
||||
def test_nul_character_is_rejected(api: httpx.Client, make_user, make_chat) -> None:
|
||||
"""PostgreSQL text не хранит U+0000: отказ 400 до записи, а не 500"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "до\u0000после"},
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
response = api.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": "a\u0000b", "member_ids": [alice["id"]]},
|
||||
headers=auth(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_sender_is_taken_from_session(make_user, make_chat, send_message) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
message = send_message(bob, chat, "от Боба")
|
||||
assert message["sender_id"] == bob["id"]
|
||||
assert message["chat_id"] == chat["id"]
|
||||
assert message["created_at"].endswith("Z")
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Обход нескольких страниц истории и списка чатов по cursor"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth, read_all_messages
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("total", "limit", "expected_pages"),
|
||||
[(7, 3, 3), (6, 3, 2), (5, 1, 5), (3, 100, 1)],
|
||||
)
|
||||
def test_walk_message_pages(
|
||||
api: httpx.Client,
|
||||
make_user,
|
||||
make_chat,
|
||||
send_message,
|
||||
total: int,
|
||||
limit: int,
|
||||
expected_pages: int,
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
sent = [send_message(alice if n % 2 else bob, chat, f"m{n}") for n in range(total)]
|
||||
|
||||
items, pages = read_all_messages(api, bob, chat["id"], limit)
|
||||
|
||||
assert pages == expected_pages
|
||||
assert items == sent
|
||||
assert len({item["id"] for item in items}) == total
|
||||
keys = [(item["created_at"], item["id"]) for item in items]
|
||||
assert keys == sorted(keys)
|
||||
|
||||
|
||||
def test_limit_can_change_between_pages(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
sent = [send_message(alice, chat, f"m{n}") for n in range(6)]
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
first = api.get(path, params={"limit": 2}, headers=auth(alice)).json()
|
||||
second = api.get(
|
||||
path, params={"limit": 4, "cursor": first["next_cursor"]}, headers=auth(alice)
|
||||
).json()
|
||||
|
||||
assert first["items"] + second["items"] == sent
|
||||
assert second["next_cursor"] is None
|
||||
|
||||
|
||||
def test_new_message_appears_after_cursor(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
send_message(alice, chat, "m0")
|
||||
send_message(alice, chat, "m1")
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
first = api.get(path, params={"limit": 1}, headers=auth(alice)).json()
|
||||
late = send_message(alice, chat, "m2")
|
||||
rest = api.get(
|
||||
path, params={"limit": 10, "cursor": first["next_cursor"]}, headers=auth(alice)
|
||||
).json()
|
||||
assert [item["text"] for item in rest["items"]] == ["m1", "m2"]
|
||||
assert rest["items"][-1] == late
|
||||
|
||||
|
||||
def test_cursor_is_bound_to_chat(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat_a = make_chat(alice, [alice], title="A")
|
||||
chat_b = make_chat(alice, [alice], title="B")
|
||||
for n in range(3):
|
||||
send_message(alice, chat_a, f"a{n}")
|
||||
cursor = api.get(
|
||||
f"/api/v1/chats/{chat_a['id']}/messages",
|
||||
params={"limit": 1},
|
||||
headers=auth(alice),
|
||||
).json()["next_cursor"]
|
||||
response = api.get(
|
||||
f"/api/v1/chats/{chat_b['id']}/messages",
|
||||
params={"cursor": cursor},
|
||||
headers=auth(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"params",
|
||||
[
|
||||
{"limit": 0},
|
||||
{"limit": 101},
|
||||
{"limit": "abc"},
|
||||
{"cursor": ""},
|
||||
{"cursor": "not-a-cursor"},
|
||||
{"cursor": "eyJzY29wZSI6IDF9"},
|
||||
],
|
||||
)
|
||||
def test_invalid_limit_or_cursor(
|
||||
api: httpx.Client, make_user, make_chat, params: dict
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages", params=params, headers=auth(alice)
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_walk_chat_list_pages(api: httpx.Client, make_user, make_chat) -> None:
|
||||
alice = make_user("alice")
|
||||
created = [make_chat(alice, [alice], title=f"chat {n}") for n in range(5)]
|
||||
listed: list[dict] = []
|
||||
params: dict[str, str | int] = {"limit": 2}
|
||||
pages = 0
|
||||
while True:
|
||||
page = api.get("/api/v1/chats", params=params, headers=auth(alice)).json()
|
||||
listed.extend(page["items"])
|
||||
pages += 1
|
||||
if page["next_cursor"] is None:
|
||||
break
|
||||
params = {"limit": 2, "cursor": page["next_cursor"]}
|
||||
assert pages == 3
|
||||
assert listed == created
|
||||
|
||||
|
||||
def test_chat_cursor_is_bound_to_user(api: httpx.Client, make_user, make_chat) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
for n in range(2):
|
||||
make_chat(alice, [alice, bob], title=f"chat {n}")
|
||||
cursor = api.get("/api/v1/chats", params={"limit": 1}, headers=auth(alice)).json()[
|
||||
"next_cursor"
|
||||
]
|
||||
response = api.get("/api/v1/chats", params={"cursor": cursor}, headers=auth(bob))
|
||||
assert_error(response, 400, "invalid_request")
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Гонка регистрации одинакового username и rollback создания чата"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from helpers import assert_error, auth, psql, unique_password, unique_username
|
||||
|
||||
PARALLEL_REGISTRATIONS = 20
|
||||
|
||||
|
||||
async def _register_concurrently(base_url: str, username: str) -> list[int]:
|
||||
"""Все запросы стартуют по одному сигналу, у каждого свой пароль"""
|
||||
start = asyncio.Event()
|
||||
|
||||
async def register(client: httpx.AsyncClient) -> int:
|
||||
await start.wait()
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": "Гонка",
|
||||
"password": unique_password(),
|
||||
}
|
||||
response = await client.post("/api/v1/users", json=body)
|
||||
return response.status_code
|
||||
|
||||
limits = httpx.Limits(max_connections=PARALLEL_REGISTRATIONS)
|
||||
async with httpx.AsyncClient(
|
||||
base_url=base_url, timeout=30, limits=limits
|
||||
) as client:
|
||||
tasks = [
|
||||
asyncio.create_task(register(client)) for _ in range(PARALLEL_REGISTRATIONS)
|
||||
]
|
||||
await asyncio.sleep(0)
|
||||
start.set()
|
||||
return list(await asyncio.gather(*tasks))
|
||||
|
||||
|
||||
def test_same_username_race_creates_exactly_one_user(base_url: str) -> None:
|
||||
username = unique_username("race")
|
||||
statuses = asyncio.run(_register_concurrently(base_url, username))
|
||||
stored = psql(f"SELECT count(*) FROM users WHERE username = '{username}';")
|
||||
print(
|
||||
"\nREGISTRATION RACE:",
|
||||
json.dumps(
|
||||
{
|
||||
"requests": len(statuses),
|
||||
"status_201": statuses.count(201),
|
||||
"status_409": statuses.count(409),
|
||||
"rows_in_db": int(stored),
|
||||
}
|
||||
),
|
||||
)
|
||||
assert statuses.count(201) == 1
|
||||
assert statuses.count(409) == PARALLEL_REGISTRATIONS - 1
|
||||
assert stored == "1"
|
||||
|
||||
|
||||
def test_failed_chat_creation_is_rolled_back(api: httpx.Client, make_user) -> None:
|
||||
"""
|
||||
Строка chats вставляется первой, затем участники нарушают FK (неизвестный
|
||||
пользователь в конце списка). После 400 в БД не должно остаться ни чата
|
||||
с этим title, ни его участников: откатилась вся транзакция.
|
||||
"""
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
title = f"rollback-{uuid.uuid4().hex}"
|
||||
body = {"title": title, "member_ids": [alice["id"], bob["id"], str(uuid.uuid4())]}
|
||||
|
||||
response = api.post("/api/v1/chats", json=body, headers=auth(alice))
|
||||
|
||||
assert_error(response, 400, "invalid_request")
|
||||
assert psql(f"SELECT count(*) FROM chats WHERE title = '{title}';") == "0"
|
||||
orphan_members = psql(
|
||||
"SELECT count(*) FROM chat_members m "
|
||||
"LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL;"
|
||||
)
|
||||
assert orphan_members == "0"
|
||||
listed = api.get("/api/v1/chats", params={"limit": 100}, headers=auth(alice))
|
||||
assert all(chat["title"] != title for chat in listed.json()["items"])
|
||||
|
||||
|
||||
def test_successful_chat_creation_commits_all_members(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
title = f"commit-{uuid.uuid4().hex}"
|
||||
body = {"title": title, "member_ids": [bob["id"], alice["id"]]}
|
||||
chat = api.post("/api/v1/chats", json=body, headers=auth(alice)).json()
|
||||
assert chat["member_ids"] == [bob["id"], alice["id"]]
|
||||
members = psql(f"SELECT count(*) FROM chat_members WHERE chat_id = '{chat['id']}';")
|
||||
assert members == "2"
|
||||
again = api.get(f"/api/v1/chats/{chat['id']}", headers=auth(bob)).json()
|
||||
assert again == chat
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Регистрация, дубликат username и идентификация только через Bearer"""
|
||||
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import (
|
||||
assert_error,
|
||||
assert_unauthorized,
|
||||
auth,
|
||||
public_user,
|
||||
unique_password,
|
||||
unique_username,
|
||||
)
|
||||
|
||||
|
||||
def test_duplicate_username_is_conflict(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("dup")
|
||||
body = {
|
||||
"username": alice["username"],
|
||||
"display_name": "B",
|
||||
"password": unique_password(),
|
||||
}
|
||||
assert_error(api.post("/api/v1/users", json=body), 409, "conflict")
|
||||
me = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert me.json()["display_name"] == alice["display_name"]
|
||||
|
||||
|
||||
def test_registration_never_returns_password(api: httpx.Client) -> None:
|
||||
password = unique_password()
|
||||
body = {
|
||||
"username": unique_username("pw"),
|
||||
"display_name": "x",
|
||||
"password": password,
|
||||
}
|
||||
response = api.post("/api/v1/users", json=body)
|
||||
assert response.status_code == 201
|
||||
assert set(response.json()) == {"id", "username", "display_name", "created_at"}
|
||||
assert password not in response.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"password",
|
||||
[None, "", "короткий", "x" * 11, "x" * 129, 123456789012],
|
||||
)
|
||||
def test_invalid_password_is_rejected(api: httpx.Client, password: object) -> None:
|
||||
body: dict[str, object] = {"username": unique_username("pw"), "display_name": "x"}
|
||||
if password is not None:
|
||||
body["password"] = password
|
||||
assert_error(api.post("/api/v1/users", json=body), 400, "invalid_request")
|
||||
|
||||
|
||||
def test_password_length_is_counted_in_code_points(api: httpx.Client) -> None:
|
||||
for password in ("😀" * 12, "😀" * 128):
|
||||
body = {
|
||||
"username": unique_username("pw"),
|
||||
"display_name": "x",
|
||||
"password": password,
|
||||
}
|
||||
assert api.post("/api/v1/users", json=body).status_code == 201
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"headers",
|
||||
[
|
||||
{},
|
||||
{"Authorization": ""},
|
||||
{"Authorization": "Bearer"},
|
||||
{"Authorization": "Bearer not-a-real-token"},
|
||||
{"Authorization": "Bearer " + "x" * 5000},
|
||||
{"Authorization": "Token abc"},
|
||||
],
|
||||
)
|
||||
def test_missing_or_unknown_token_is_unauthorized(
|
||||
api: httpx.Client, headers: dict
|
||||
) -> None:
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=headers))
|
||||
assert_unauthorized(api.get("/api/v1/chats", headers=headers))
|
||||
|
||||
|
||||
def test_x_user_id_gives_no_access(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]}))
|
||||
me = api.get("/api/v1/users/me", headers={**auth(alice), "X-User-Id": eve["id"]})
|
||||
assert me.json()["id"] == alice["id"]
|
||||
unknown = {"X-User-Id": str(uuid.uuid4())}
|
||||
assert_unauthorized(api.get("/api/v1/chats", headers=unknown))
|
||||
|
||||
|
||||
def test_current_user(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
me = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert me.status_code == 200
|
||||
assert me.json() == public_user(alice)
|
||||
Reference in New Issue
Block a user