feat: функционал первой лабы перенос

This commit is contained in:
Enterxx2
2026-10-11 13:24:29 +03:00
parent 65003b6119
commit a6c74c9bb0
90 changed files with 2746 additions and 1 deletions
+63
View File
@@ -0,0 +1,63 @@
import json
import os
from collections.abc import Callable, Iterator
from pathlib import Path
import httpx
import pytest
from helpers import auth, 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]:
with httpx.Client(base_url=base_url, timeout=REQUEST_TIMEOUT_SEC) as client:
yield client
@pytest.fixture
def make_user(api: httpx.Client) -> Callable[..., dict]:
def create(label: str = "user", display_name: str | None = None) -> dict:
body = {
"username": unique_username(label),
"display_name": display_name or f"Студент {label}",
}
response = api.post("/api/v1/users", json=body)
assert response.status_code == 201, response.text
return response.json()
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=auth(user),
)
assert response.status_code == 201, response.text
return response.json()
return send
+43
View File
@@ -0,0 +1,43 @@
"""Общие проверки для собственных black-box тестов"""
import uuid
import httpx
def unique_username(label: str) -> str:
return f"st_{label}_{uuid.uuid4().hex[:12]}"
def auth(user: dict) -> dict[str, str]:
return {"X-User-Id": user["id"]}
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 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"]}
+77
View File
@@ -0,0 +1,77 @@
"""Защита состояния от гонок: 100 сообщений от 10 параллельных клиентов"""
import asyncio
import json
import time
import httpx
from helpers import 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={"X-User-Id": user["id"]}, 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}"},
)
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
+49
View File
@@ -0,0 +1,49 @@
"""Чужой чат: посторонний получает 404, существование чата не раскрывается"""
import uuid
import httpx
from helpers import assert_error, auth
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=auth(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"]]
+15
View File
@@ -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")
+94
View File
@@ -0,0 +1,94 @@
"""Неверный JSON и неверная структура тела — 400 invalid_request"""
import httpx
import pytest
from helpers import assert_error, auth
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"
)
assert_error(
api.post(f"/api/v1/chats/{chat['id']}/messages", content=raw, headers=headers),
400,
"invalid_request",
)
@pytest.mark.parametrize(
"body",
[
[],
"alice",
{"username": "valid_name"},
{"username": 123, "display_name": "x"},
{"username": "valid_name", "display_name": None},
{"username": "valid_name", "display_name": "x", "is_admin": True},
{"username": "Upper_Case", "display_name": "x"},
{"username": "ab", "display_name": "x"},
{"username": "valid_name", "display_name": " "},
{"username": "valid_name", "display_name": "я" * 101},
],
)
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=auth(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")
+59
View File
@@ -0,0 +1,59 @@
"""Пустые сообщения, границы длины и Unicode"""
import httpx
import pytest
from helpers import assert_error, auth
@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=auth(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=auth(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 = "Привет, мир 👋 — «кавычки» \u0000 и 𝔘𝔫𝔦𝔠𝔬𝔡𝔢"
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_sender_is_taken_from_x_user_id(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")
+138
View File
@@ -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")
+40
View File
@@ -0,0 +1,40 @@
"""Дубликат username и идентификация через X-User-Id"""
import uuid
import httpx
import pytest
from helpers import assert_error, unique_username
def test_duplicate_username_is_conflict(api: httpx.Client) -> None:
username = unique_username("dup")
first = api.post("/api/v1/users", json={"username": username, "display_name": "A"})
assert first.status_code == 201
second = api.post("/api/v1/users", json={"username": username, "display_name": "B"})
assert_error(second, 409, "conflict")
me = api.get("/api/v1/users/me", headers={"X-User-Id": first.json()["id"]})
assert me.json()["display_name"] == "A"
@pytest.mark.parametrize(
"headers",
[
{},
{"X-User-Id": ""},
{"X-User-Id": "not-a-uuid"},
{"X-User-Id": str(uuid.uuid4())},
],
)
def test_missing_or_unknown_user_is_unauthorized(
api: httpx.Client, headers: dict
) -> None:
assert_error(api.get("/api/v1/users/me", headers=headers), 401, "unauthorized")
assert_error(api.get("/api/v1/chats", headers=headers), 401, "unauthorized")
def test_current_user(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
me = api.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]})
assert me.status_code == 200
assert me.json() == alice