chore: carry over lab 1 solution into lab 2 skeleton

Copy the committed lab 1 sources as-is: src/, student-tests/, bench/,
Dockerfile, docker-compose.yml, pyproject.toml, uv.lock,
.python-version, config_example.toml, AGENTS.md, CLAUDE.md, .claude/,
openspec/, .graphifyignore and KNOWN_ISSUES.md. Lab 1 evidence stays
in the lab 1 repository.

Merge the new skeleton files with own sections: Makefile (lab 2
targets plus own run, docker, bench and common targets), .gitignore,
.dockerignore and .env.example. Rename the image to
mtusi-messenger:lab2 and point AGENTS.md at lab 2.

The application is still the in-memory lab 1 implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-30 22:11:46 +03:00
co-authored by Claude Opus 5.5
parent 65003b6119
commit 7b775a29a9
174 changed files with 19023 additions and 11 deletions
+227
View File
@@ -0,0 +1,227 @@
"""HTTP-клиент набора: запросы к API и идентификация в одном месте."""
import uuid
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from datetime import datetime
from typing import Any
import httpx
from contract import assert_ok
API = "/api/v1"
# защита от бесконечного обхода, если next_cursor никогда не станет null
MAX_PAGES = 1000
def unique_username() -> str:
"""Имя под `^[a-z0-9_]{3,32}$`, уникальное для каждого вызова."""
return f"t_{uuid.uuid4().hex[:12]}"
def order_key(item: dict[str, Any]) -> tuple[datetime, int]:
"""Порядок списков API: `(created_at, id)`, id сравнивается как UUID."""
created_at = datetime.fromisoformat(item["created_at"])
return created_at, uuid.UUID(item["id"]).int
@dataclass(frozen=True)
class Actor:
"""Зарегистрированный пользователь и то, как он себя называет."""
user: dict[str, Any]
@classmethod
def unregistered(cls) -> "Actor":
"""Пользователь, которого нет на сервере."""
return cls(user={"id": str(uuid.uuid4())})
@property
def id(self) -> str:
return self.user["id"]
def headers(self) -> dict[str, str]:
"""Идентификация: лаба 1 — `X-User-Id`, с лабы 2 — Bearer."""
return {"X-User-Id": self.id}
class Api:
"""Тонкая обёртка над `httpx.Client` с методами API мессенджера."""
def __init__(self, base_url: str, *, timeout: float = 5) -> None:
self.client = httpx.Client(base_url=base_url, timeout=timeout)
def close(self) -> None:
self.client.close()
def __enter__(self) -> "Api":
return self
def __exit__(self, *_: object) -> None:
self.close()
def request(
self,
method: str,
path: str,
*,
actor: Actor | None = None,
headers: dict[str, str] | None = None,
**kwargs: Any,
) -> httpx.Response:
merged = actor.headers() if actor is not None else {}
merged.update(headers or {})
return self.client.request(method, path, headers=merged, **kwargs)
def register(
self,
*,
username: str | None = None,
display_name: str = "Test user",
) -> Actor:
resp = self.request(
"POST",
f"{API}/users",
json={
"username": username or unique_username(),
"display_name": display_name,
},
)
return Actor(assert_ok(resp, 201, "User"))
def create_chat(
self,
actor: Actor,
*members: Actor,
title: str = "Test chat",
) -> dict[str, Any]:
"""Чат, где `actor` — первый участник, за ним `members`."""
member_ids = [actor.id, *(member.id for member in members)]
resp = self.request(
"POST",
f"{API}/chats",
actor=actor,
json={"title": title, "member_ids": member_ids},
)
return assert_ok(resp, 201, "Chat")
def send_message(
self,
actor: Actor,
chat_id: str,
text: str,
) -> dict[str, Any]:
resp = self.request(
"POST",
f"{API}/chats/{chat_id}/messages",
actor=actor,
json={"text": text},
)
return assert_ok(resp, 201, "Message")
def messages_page(
self,
actor: Actor,
chat_id: str,
*,
limit: int | str | None = None,
cursor: str | None = None,
) -> httpx.Response:
return self.request(
"GET",
f"{API}/chats/{chat_id}/messages",
actor=actor,
params=_page_params(limit, cursor),
)
def chats_page(
self,
actor: Actor,
*,
limit: int | str | None = None,
cursor: str | None = None,
) -> httpx.Response:
return self.request(
"GET",
f"{API}/chats",
actor=actor,
params=_page_params(limit, cursor),
)
def message_pages(
self,
actor: Actor,
chat_id: str,
*,
limits: Sequence[int] = (100,),
) -> list[dict[str, Any]]:
"""Все страницы истории по `next_cursor`.
Страница `i` берётся с `limits[i]`, дальше — с последним `limit`.
"""
def fetch(limit: int, cursor: str | None) -> httpx.Response:
return self.messages_page(
actor,
chat_id,
limit=limit,
cursor=cursor,
)
return walk_pages(fetch, limits=limits, schema="MessagePage")
def chat_pages(
self,
actor: Actor,
*,
limits: Sequence[int] = (100,),
) -> list[dict[str, Any]]:
def fetch(limit: int, cursor: str | None) -> httpx.Response:
return self.chats_page(actor, limit=limit, cursor=cursor)
return walk_pages(fetch, limits=limits, schema="ChatPage")
def all_messages(
self,
actor: Actor,
chat_id: str,
*,
limits: Sequence[int] = (100,),
) -> list[dict[str, Any]]:
pages = self.message_pages(actor, chat_id, limits=limits)
return [item for page in pages for item in page["items"]]
def walk_pages(
fetch: Callable[[int, str | None], httpx.Response],
*,
limits: Sequence[int],
schema: str,
) -> list[dict[str, Any]]:
"""Обход списка по курсору до `next_cursor` null."""
pages: list[dict[str, Any]] = []
cursor: str | None = None
for number in range(MAX_PAGES):
limit = limits[min(number, len(limits) - 1)]
page = assert_ok(fetch(limit, cursor), 200, schema)
assert len(page["items"]) <= limit, (
f"page {number} has {len(page['items'])} items, limit {limit}"
)
pages.append(page)
cursor = page["next_cursor"]
if cursor is None:
return pages
raise AssertionError(f"next_cursor is not null after {MAX_PAGES} pages")
def _page_params(
limit: int | str | None,
cursor: str | None,
) -> dict[str, str]:
params: dict[str, str] = {}
if limit is not None:
params["limit"] = str(limit)
if cursor is not None:
params["cursor"] = cursor
return params
+82
View File
@@ -0,0 +1,82 @@
"""Настройка набора: адрес стенда, проверка доступности, фикстуры."""
import os
from collections.abc import Iterator
from typing import Any
import httpx
import pytest
from api_client import Actor, Api
from spec_coverage import COLLECTED, Collected
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
@pytest.hookimpl(tryfirst=True)
def pytest_collection_modifyitems(
config: pytest.Config,
items: list[pytest.Item],
) -> None:
"""Маркеры `spec` всех собранных тестов, до отбора по `-k` / `-m`."""
collected = Collected()
for item in items:
collected.modules.add(item.path.name)
for mark in item.iter_markers("spec"):
if len(mark.args) != 2 or mark.kwargs:
raise pytest.UsageError(
f"{item.nodeid}: spec marker takes (capability, scenario)",
)
collected.marks.setdefault(mark.args, []).append(item.nodeid)
config.stash[COLLECTED] = collected
@pytest.fixture(scope="session", autouse=True)
def _server_reachable() -> None:
"""Без сервера прогон останавливается одной строкой, а не 100 ошибками."""
try:
resp = httpx.get(f"{BASE_URL}/health/live", timeout=2)
except httpx.HTTPError as exc:
pytest.exit(
f"server is not reachable at {BASE_URL}: {exc!r}",
returncode=2,
)
if resp.status_code != 200:
pytest.exit(
f"{BASE_URL}/health/live answered {resp.status_code}: "
"another service on this port?",
returncode=2,
)
@pytest.fixture(scope="session")
def base_url() -> str:
return BASE_URL
@pytest.fixture(scope="session")
def api() -> Iterator[Api]:
with Api(BASE_URL) as client:
yield client
@pytest.fixture
def alice(api: Api) -> Actor:
return api.register(display_name="Алиса")
@pytest.fixture
def bob(api: Api) -> Actor:
return api.register(display_name="Боб")
@pytest.fixture
def eve(api: Api) -> Actor:
"""Посторонний: ни в одном чате фикстур не состоит."""
return api.register(display_name="Ева")
@pytest.fixture
def chat(api: Api, alice: Actor, bob: Actor) -> dict[str, Any]:
"""Чат Алисы и Боба."""
return api.create_chat(alice, bob, title="Алиса и Боб")
+158
View File
@@ -0,0 +1,158 @@
"""Проверка ответов по `contracts/openapi.json` и форматам контракта."""
import json
import re
from datetime import datetime, timedelta
from functools import cache
from pathlib import Path
from typing import Any
import httpx
from jsonschema import Draft202012Validator
from referencing import Registry, Resource
from referencing.jsonschema import DRAFT202012
CONTRACT_PATH = (
Path(__file__).resolve().parents[1] / "contracts" / "openapi.json"
)
_CONTRACT_URI = "urn:mtusi:contract"
UUID_RE = re.compile(
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
)
# RFC 3339 в UTC: шесть знаков долей секунды и суффикс Z
CREATED_AT_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$")
ID_KEYS = frozenset({"id", "chat_id", "sender_id"})
# признаки внутренностей сервиса в error.message
LEAK_RE = re.compile(r"Traceback|File \"|\.py\b|/app/|/src/|Error\(")
# статус -> code ошибки (спек api-conventions)
ERROR_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
405: "invalid_request",
409: "conflict",
500: "internal_error",
503: "unavailable",
}
@cache
def contract() -> dict[str, Any]:
return json.loads(CONTRACT_PATH.read_text(encoding="utf-8"))
@cache
def validator(schema: str) -> Draft202012Validator:
"""Валидатор `#/components/schemas/<schema>` внутри контракта."""
document = contract()
if schema not in document["components"]["schemas"]:
raise KeyError(f"no schema {schema!r} in {CONTRACT_PATH.name}")
resource = Resource.from_contents(
document,
default_specification=DRAFT202012,
)
registry = Registry().with_resource(_CONTRACT_URI, resource)
return Draft202012Validator(
{"$ref": f"{_CONTRACT_URI}#/components/schemas/{schema}"},
registry=registry,
)
def check_body(body: Any, schema: str) -> None:
"""Тело совпадает со схемой контракта, `id` и время — в его формате."""
errors = sorted(
validator(schema).iter_errors(body),
key=lambda error: list(map(str, error.path)),
)
assert not errors, f"{schema} schema: " + "; ".join(
f"/{'/'.join(map(str, error.path))}: {error.message}"
for error in errors
)
check_formats(body)
def check_formats(value: Any, path: str = "") -> None:
if isinstance(value, dict):
for key, item in value.items():
where = f"{path}/{key}"
if key in ID_KEYS:
assert_uuid(item, where)
elif key == "member_ids":
for number, member in enumerate(item):
assert_uuid(member, f"{where}/{number}")
elif key == "created_at":
assert_created_at(item, where)
else:
check_formats(item, where)
elif isinstance(value, list):
for number, item in enumerate(value):
check_formats(item, f"{path}/{number}")
def assert_uuid(value: Any, where: str = "id") -> None:
assert isinstance(value, str) and UUID_RE.fullmatch(value), (
f"{where}: {value!r} is not a lowercase UUID"
)
def assert_created_at(value: Any, where: str = "created_at") -> None:
assert isinstance(value, str) and CREATED_AT_RE.fullmatch(value), (
f"{where}: {value!r} is not RFC 3339 UTC with microseconds and Z"
)
parsed = datetime.fromisoformat(value)
assert parsed.utcoffset() == timedelta(0), f"{where}: {value!r} not UTC"
def assert_ok(resp: httpx.Response, status: int, schema: str) -> Any:
"""Успешный ответ: статус, JSON, `X-Request-Id`, тело по схеме."""
assert resp.status_code == status, describe(resp, f"expected {status}")
body = json_body(resp)
check_body(body, schema)
return body
def assert_error(resp: httpx.Response, status: int) -> dict[str, Any]:
"""Ошибка в формате контракта; `code` соответствует статусу."""
assert resp.status_code == status, describe(resp, f"expected {status}")
body = json_body(resp)
check_body(body, "Error")
error = body["error"]
assert error["code"] == ERROR_CODES[status], describe(
resp,
f"expected code {ERROR_CODES[status]}",
)
assert error["message"].strip(), describe(resp, "empty message")
assert not LEAK_RE.search(error["message"]), describe(
resp,
"message reveals internals",
)
assert error["request_id"] == resp.headers["X-Request-Id"], describe(
resp,
"request_id differs from X-Request-Id",
)
return error
def json_body(resp: httpx.Response) -> Any:
"""JSON-тело в UTF-8 и непустой `X-Request-Id`."""
request_id = resp.headers.get("X-Request-Id", "")
assert request_id.strip(), describe(resp, "no X-Request-Id")
media_type, _, params = resp.headers.get("Content-Type", "").partition(
";",
)
assert media_type.strip() == "application/json", describe(
resp,
"Content-Type is not application/json",
)
charset = params.strip().lower().removeprefix("charset=")
assert charset in ("", "utf-8"), describe(resp, f"charset {charset}")
return json.loads(resp.content.decode("utf-8"))
def describe(resp: httpx.Response, problem: str) -> str:
return (
f"{resp.request.method} {resp.request.url.path}: {problem}; "
f"got {resp.status_code} {resp.text[:300]}"
)
+120
View File
@@ -0,0 +1,120 @@
"""Сверка тестов со сценариями основных спеков `openspec/specs/`."""
import re
from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from pathlib import Path
import pytest
SPECS_DIR = Path(__file__).resolve().parents[1] / "openspec" / "specs"
# основные спеки поведения API; спеки контейнера, логов и конфига
# проверяются evidence, а не HTTP-тестами
CAPABILITIES = (
"api-conventions",
"identification",
"users",
"chats",
"messages",
"pagination",
"data-storage",
"health",
)
SCENARIO_RE = re.compile(r"^#### Scenario: (.+?)\s*$", re.MULTILINE)
type Scenario = tuple[str, str]
@dataclass(frozen=True)
class Exclusion:
"""Сценарий, который не воспроизвести по HTTP против сервера."""
reason: str
check: str
EXCLUDED: dict[Scenario, Exclusion] = {
("api-conventions", "Ответ 500"): Exclusion(
reason="500 возникает только при сбое внутри сервиса, "
"штатным запросом его не вызвать",
check="временно бросить исключение в ручке и запросить её; "
"обработчик Exception — src/api/errors.py",
),
("api-conventions", "Исключение внутри обработки"): Exclusion(
reason="нужен сбой внутри сервиса, как для «Ответ 500»; "
"traceback виден только в логе процесса",
check="тот же ручной сбой, затем make logs: запись error с "
"traceback и тем же request_id",
),
("data-storage", "Прежний пользователь после рестарта"): Exclusion(
reason="нужен рестарт процесса, тесты сервер не трогают",
check="evidence/container/lifecycle.txt: после рестарта "
"прежний X-User-Id получает 401",
),
("health", "Хранилище не готово"): Exclusion(
reason="хранилище создаётся при старте, у запущенного сервера "
"оно готово всегда",
check="ветка 503 в src/api/routers/health.py, проверка чтением кода",
),
("identification", "Кнопка Authorize в Swagger"): Exclusion(
reason="это интерфейс /docs в браузере",
check="схему devUser, из которой строится кнопка, проверяет "
"тест сценария «Схема в openapi.json»; кнопку — вручную",
),
}
@dataclass
class Collected:
"""Что собрал pytest: маркеры `spec` и модули тестов."""
marks: dict[Scenario, list[str]] = field(default_factory=dict)
modules: set[str] = field(default_factory=set)
COLLECTED = pytest.StashKey[Collected]()
def spec_scenarios(capability: str, specs_dir: Path = SPECS_DIR) -> list[str]:
text = (specs_dir / capability / "spec.md").read_text(encoding="utf-8")
return SCENARIO_RE.findall(text)
def all_scenarios(
capabilities: Iterable[str] = CAPABILITIES,
specs_dir: Path = SPECS_DIR,
) -> set[Scenario]:
return {
(capability, scenario)
for capability in capabilities
for scenario in spec_scenarios(capability, specs_dir)
}
def coverage_problems(
scenarios: set[Scenario],
marks: Mapping[Scenario, list[str]],
excluded: Mapping[Scenario, Exclusion],
) -> list[str]:
"""Расхождения между спеками, маркерами и исключениями."""
problems = [
f"no test and no exclusion: {capability} / {scenario}"
for capability, scenario in sorted(
scenarios - marks.keys() - excluded.keys(),
)
]
problems += [
f"marker points to unknown scenario {capability} / {scenario}: "
+ ", ".join(nodeids)
for (capability, scenario), nodeids in sorted(marks.items())
if (capability, scenario) not in scenarios
]
problems += [
f"exclusion points to unknown scenario: {capability} / {scenario}"
for capability, scenario in sorted(excluded.keys() - scenarios)
]
problems += [
f"scenario is both tested and excluded: {capability} / {scenario}"
for capability, scenario in sorted(marks.keys() & excluded.keys())
]
return problems
+173
View File
@@ -0,0 +1,173 @@
"""Спек `api-conventions`: JSON, ошибки, X-Request-Id, форматы."""
import json
from typing import Any
import pytest
from api_client import API, Actor, Api, unique_username
from contract import (
assert_created_at,
assert_error,
assert_ok,
assert_uuid,
json_body,
)
UNICODE_TEXT = "Привет, мир 👋"
@pytest.mark.spec("api-conventions", "Unicode сохраняется")
def test_unicode_round_trip(api: Api, bob: Actor) -> None:
alice = api.register(display_name=UNICODE_TEXT)
chat = api.create_chat(alice, bob, title=UNICODE_TEXT)
resp = api.request(
"POST",
f"{API}/chats/{chat['id']}/messages",
actor=alice,
json={"text": UNICODE_TEXT},
)
message = assert_ok(resp, 201, "Message")
# тело разбирается из байтов как UTF-8, без догадок httpx о кодировке
assert json.loads(resp.content.decode("utf-8"))["text"] == UNICODE_TEXT
me = assert_ok(
api.request("GET", f"{API}/users/me", actor=alice),
200,
"User",
)
stored_chat = assert_ok(
api.request("GET", f"{API}/chats/{chat['id']}", actor=bob),
200,
"Chat",
)
history = api.all_messages(bob, chat["id"])
assert alice.user["display_name"] == me["display_name"] == UNICODE_TEXT
assert chat["title"] == stored_chat["title"] == UNICODE_TEXT
assert [item["text"] for item in history] == [message["text"]]
assert message["text"] == UNICODE_TEXT
@pytest.mark.spec("api-conventions", "Длина в code points")
def test_length_in_code_points(api: Api, alice: Actor) -> None:
title = "👋" * 100
assert len(title.encode("utf-8")) > 100
chat = api.create_chat(alice, title=title)
assert chat["title"] == title
@pytest.mark.spec("api-conventions", "Успешный ответ")
def test_request_id_on_success(api: Api, alice: Actor) -> None:
responses = [
api.request("GET", "/health/live"),
api.request("GET", f"{API}/users/me", actor=alice),
api.request("GET", f"{API}/chats", actor=alice),
]
for resp in responses:
assert resp.status_code == 200
assert resp.headers.get("X-Request-Id", "").strip()
@pytest.mark.spec("api-conventions", "Разные запросы")
def test_request_ids_differ(api: Api) -> None:
first = api.request("GET", "/health/live").headers["X-Request-Id"]
second = api.request("GET", "/health/live").headers["X-Request-Id"]
assert first != second
@pytest.mark.spec("api-conventions", "Ошибка содержит request_id заголовка")
def test_error_request_id_matches_header(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
# assert_error сверяет error.request_id с заголовком у каждой ошибки
assert_error(api.request("GET", f"{API}/chats/nope", actor=alice), 400)
assert_error(api.request("GET", f"{API}/users/me"), 401)
assert_error(
api.request("GET", f"{API}/chats/{chat['id']}", actor=eve),
404,
)
assert_error(api.request("DELETE", f"{API}/users"), 405)
resp = api.request(
"POST",
f"{API}/users",
json={"username": alice.user["username"], "display_name": "Alice"},
)
assert_error(resp, 409)
@pytest.mark.spec("api-conventions", "Нет тела FastAPI по умолчанию")
def test_no_fastapi_detail(api: Api, alice: Actor) -> None:
validation = api.request(
"POST",
f"{API}/users",
json={"username": "ab", "display_name": "x"},
)
not_found = api.request("GET", f"{API}/unknown", actor=alice)
for resp, status in ((validation, 400), (not_found, 404)):
assert_error(resp, status)
assert list(json_body(resp)) == ["error"]
@pytest.mark.spec("api-conventions", "Неизвестный путь")
def test_unknown_path(api: Api) -> None:
assert_error(api.request("GET", f"{API}/unknown"), 404)
@pytest.mark.spec("api-conventions", "Неподдерживаемый метод")
def test_method_not_allowed(api: Api) -> None:
assert_error(api.request("DELETE", f"{API}/users"), 405)
@pytest.mark.spec("api-conventions", "Лишнее поле")
def test_extra_field(api: Api, alice: Actor) -> None:
resp = api.request(
"POST",
f"{API}/users",
json={
"username": unique_username(),
"display_name": "Extra",
"is_admin": True,
},
)
assert_error(resp, 400)
resp = api.request(
"POST",
f"{API}/chats",
actor=alice,
json={"title": "Extra", "member_ids": [alice.id], "topic": "x"},
)
assert_error(resp, 400)
@pytest.mark.spec("api-conventions", "Неверный тип без приведения")
def test_wrong_type_is_not_coerced(api: Api) -> None:
username = unique_username()
resp = api.request(
"POST",
f"{API}/users",
json={"username": username, "display_name": 123},
)
assert_error(resp, 400)
# пользователь не создан: то же имя свободно
user = api.register(username=username, display_name="123").user
assert user["display_name"] == "123"
@pytest.mark.spec("api-conventions", "Формат created_at")
@pytest.mark.spec("api-conventions", "Формат id")
def test_id_and_created_at_format(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
message = api.send_message(alice, chat["id"], "format")
for obj in (alice.user, chat, message):
assert_uuid(obj["id"])
assert_created_at(obj["created_at"])
for member_id in chat["member_ids"]:
assert_uuid(member_id)
assert_uuid(message["chat_id"])
assert_uuid(message["sender_id"])
+126
View File
@@ -0,0 +1,126 @@
"""Спек `chats`: создание, чтение, список, неизменный состав."""
import uuid
from typing import Any
import httpx
import pytest
from api_client import API, Actor, Api
from contract import assert_error, assert_ok
def create_raw(
api: Api,
actor: Actor,
title: str,
member_ids: list[str],
) -> httpx.Response:
return api.request(
"POST",
f"{API}/chats",
actor=actor,
json={"title": title, "member_ids": member_ids},
)
def listed_ids(api: Api, actor: Actor) -> set[str]:
return {
chat["id"] for page in api.chat_pages(actor) for chat in page["items"]
}
def listed_titles(api: Api, actor: Actor) -> set[str]:
return {
chat["title"]
for page in api.chat_pages(actor)
for chat in page["items"]
}
@pytest.mark.spec("chats", "Успешное создание")
def test_create_chat(api: Api, alice: Actor, bob: Actor) -> None:
resp = create_raw(api, alice, "Проект", [alice.id, bob.id])
chat = assert_ok(resp, 201, "Chat")
assert chat["member_ids"] == [alice.id, bob.id]
assert chat["title"] == "Проект"
# порядок участников сохраняется, даже если создатель не первый
resp = create_raw(api, alice, "Проект 2", [bob.id, alice.id])
reversed_chat = assert_ok(resp, 201, "Chat")
assert reversed_chat["member_ids"] == [bob.id, alice.id]
assert reversed_chat["id"] != chat["id"]
@pytest.mark.spec("chats", "Вызывающего нет в списке")
def test_caller_not_in_members(api: Api, alice: Actor, bob: Actor) -> None:
title = f"rejected-{uuid.uuid4().hex}"
assert_error(create_raw(api, alice, title, [bob.id]), 400)
# отклонённый чат не появился ни в одном списке
assert title not in listed_titles(api, alice)
assert title not in listed_titles(api, bob)
@pytest.mark.spec("chats", "Повтор участника")
def test_duplicate_member(api: Api, alice: Actor) -> None:
assert_error(create_raw(api, alice, "Dup", [alice.id, alice.id]), 400)
@pytest.mark.spec("chats", "Неизвестный участник")
def test_unknown_member(api: Api, alice: Actor) -> None:
title = f"rejected-{uuid.uuid4().hex}"
member_ids = [alice.id, str(uuid.uuid4())]
assert_error(create_raw(api, alice, title, member_ids), 400)
assert title not in listed_titles(api, alice)
@pytest.mark.spec("chats", "Пустой список")
def test_empty_members(api: Api, alice: Actor) -> None:
assert_error(create_raw(api, alice, "Empty", []), 400)
@pytest.mark.spec("chats", "Участник")
def test_member_reads_chat(
api: Api,
bob: Actor,
chat: dict[str, Any],
) -> None:
resp = api.request("GET", f"{API}/chats/{chat['id']}", actor=bob)
assert assert_ok(resp, 200, "Chat") == chat
@pytest.mark.spec("chats", "Неверный chat_id")
def test_invalid_chat_id(api: Api, alice: Actor) -> None:
assert_error(api.request("GET", f"{API}/chats/nope", actor=alice), 400)
@pytest.mark.spec("chats", "Участник видит чат")
def test_member_lists_chat(
api: Api,
bob: Actor,
chat: dict[str, Any],
) -> None:
assert chat["id"] in listed_ids(api, bob)
@pytest.mark.spec("chats", "Посторонний не видит чат")
def test_outsider_does_not_list_chat(
api: Api,
eve: Actor,
chat: dict[str, Any],
) -> None:
assert chat["id"] not in listed_ids(api, eve)
@pytest.mark.spec("chats", "Повторное чтение")
def test_members_do_not_change(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
path = f"{API}/chats/{chat['id']}"
first = assert_ok(api.request("GET", path, actor=alice), 200, "Chat")
api.send_message(bob, chat["id"], "между чтениями")
api.create_chat(alice, bob)
second = assert_ok(api.request("GET", path, actor=bob), 200, "Chat")
assert first["member_ids"] == second["member_ids"] == chat["member_ids"]
+120
View File
@@ -0,0 +1,120 @@
"""Самопроверка `contract.py`: неверная форма ответа роняет тест.
Спек `student-tests`, сценарий «Ошибка не в формате контракта».
"""
import httpx
import pytest
from api_client import Actor
from contract import assert_error, check_body
def fake_response(
status: int,
body: object,
request_id: str = "rid-1",
) -> httpx.Response:
return httpx.Response(
status,
json=body,
headers={"X-Request-Id": request_id},
request=httpx.Request("GET", "http://stand/api/v1/chats/x"),
)
def test_contract_error_passes() -> None:
body = {
"error": {
"code": "not_found",
"message": "Not found",
"request_id": "rid-1",
},
}
assert assert_error(fake_response(404, body), 404)["code"] == "not_found"
@pytest.mark.parametrize(
("status", "body"),
[
(404, {"detail": "Not Found"}),
(400, {"detail": [{"loc": ["body"], "msg": "bad"}]}),
(
404,
{
"error": {
"code": "not_found",
"message": "Not found",
"request_id": "other",
},
},
),
(
404,
{
"error": {
"code": "invalid_request",
"message": "Not found",
"request_id": "rid-1",
},
},
),
(
404,
{
"error": {
"code": "not_found",
"message": "Not found",
"request_id": "rid-1",
"detail": "x",
},
},
),
(
500,
{
"error": {
"code": "internal_error",
"message": 'File "/app/src/main.py", line 1',
"request_id": "rid-1",
},
},
),
],
ids=[
"fastapi-404",
"fastapi-validation",
"request-id-mismatch",
"code-not-matching-status",
"extra-field",
"leaks-internals",
],
)
def test_wrong_error_body_fails(status: int, body: object) -> None:
# статус верный: падать должна проверка тела
with pytest.raises(AssertionError):
assert_error(fake_response(status, body), status)
def test_success_body_checks(alice: Actor) -> None:
user = alice.user
check_body(user, "User")
broken = {
"extra field": {**user, "extra": 1},
"missing field": {k: v for k, v in user.items() if k != "username"},
"uppercase id": {**user, "id": user["id"].upper()},
"created_at without Z": {
**user,
"created_at": user["created_at"][:-1],
},
"created_at without microseconds": {
**user,
"created_at": user["created_at"][:19] + "Z",
},
}
for name, body in broken.items():
try:
check_body(body, "User")
except AssertionError:
continue
pytest.fail(f"accepted: {name}")
+96
View File
@@ -0,0 +1,96 @@
"""У каждого сценария основных спеков есть тест или исключение."""
from pathlib import Path
import pytest
from spec_coverage import (
CAPABILITIES,
COLLECTED,
EXCLUDED,
Exclusion,
Scenario,
all_scenarios,
coverage_problems,
spec_scenarios,
)
TESTS_DIR = Path(__file__).parent
def complete_marks(scenarios: set[Scenario]) -> dict[Scenario, list[str]]:
"""Маркеры, при которых покрыто всё, кроме исключений."""
return {scenario: ["test_x"] for scenario in scenarios - EXCLUDED.keys()}
def test_every_scenario_is_covered(request: pytest.FixtureRequest) -> None:
collected = request.config.stash[COLLECTED]
modules = {path.name for path in TESTS_DIR.glob("test_*.py")}
if not modules <= collected.modules:
pytest.skip(
"coverage is checked only when the whole suite is collected: "
"make student_test",
)
scenarios = all_scenarios()
problems = coverage_problems(scenarios, collected.marks, EXCLUDED)
tested = len(scenarios & collected.marks.keys())
print(
f"coverage: {len(scenarios)} scenarios in "
f"{len(CAPABILITIES)} specs, {tested} tested, "
f"{len(EXCLUDED)} excluded",
)
assert not problems, "\n".join(problems)
def test_every_spec_has_scenarios() -> None:
for capability in CAPABILITIES:
assert spec_scenarios(capability), f"no scenarios in {capability}"
def test_exclusions_explain_reason_and_check() -> None:
for (capability, scenario), exclusion in EXCLUDED.items():
assert exclusion.reason.strip(), f"{capability} / {scenario}"
assert exclusion.check.strip(), f"{capability} / {scenario}"
def test_scenario_parser(tmp_path: Path) -> None:
spec = tmp_path / "demo" / "spec.md"
spec.parent.mkdir()
spec.write_text(
"### Requirement: R\n\n#### Scenario: Первый\n\n- **WHEN** x\n\n"
"#### Scenario: Второй \n",
encoding="utf-8",
)
assert spec_scenarios("demo", tmp_path) == ["Первый", "Второй"]
def test_new_scenario_without_test_fails() -> None:
scenarios = all_scenarios()
marks = complete_marks(scenarios)
assert coverage_problems(scenarios, marks, EXCLUDED) == []
grown = scenarios | {("users", "Новый сценарий")}
assert coverage_problems(grown, marks, EXCLUDED) == [
"no test and no exclusion: users / Новый сценарий",
]
def test_marker_typo_fails() -> None:
scenarios = all_scenarios()
marks = complete_marks(scenarios)
marks[("users", "Повтор usernme")] = ["test_typo"]
assert coverage_problems(scenarios, marks, EXCLUDED) == [
"marker points to unknown scenario users / Повтор usernme: test_typo",
]
def test_stale_exclusion_fails() -> None:
scenarios = all_scenarios()
marks = complete_marks(scenarios)
excluded = {
**EXCLUDED,
("health", "Удалённый сценарий"): Exclusion(reason="r", check="c"),
}
assert coverage_problems(scenarios, marks, excluded) == [
"exclusion points to unknown scenario: health / Удалённый сценарий",
]
+17
View File
@@ -0,0 +1,17 @@
"""Спек `data-storage`.
Гонки — в `test_race.py`, рестарт — исключение в `spec_coverage.py`.
"""
import pytest
from api_client import API, Api
from contract import assert_ok
@pytest.mark.spec("data-storage", "Созданное видно сразу")
def test_created_user_visible_at_once(api: Api) -> None:
for _ in range(5):
actor = api.register()
resp = api.request("GET", f"{API}/users/me", actor=actor)
assert assert_ok(resp, 200, "User") == actor.user
+28
View File
@@ -0,0 +1,28 @@
"""Спек `health`: live и ready без идентификации, вне `/api/v1`."""
import pytest
from api_client import Actor, Api
from contract import assert_ok
HEALTH = ("/health/live", "/health/ready")
@pytest.mark.spec("health", "Процесс жив")
def test_live(api: Api) -> None:
resp = api.request("GET", "/health/live")
assert assert_ok(resp, 200, "Health") == {"status": "ok"}
@pytest.mark.spec("health", "Сервис запущен")
def test_ready(api: Api) -> None:
resp = api.request("GET", "/health/ready")
assert assert_ok(resp, 200, "Health") == {"status": "ok"}
@pytest.mark.spec("health", "Неизвестный X-User-Id")
def test_unknown_user_is_ignored(api: Api) -> None:
ghost = Actor.unregistered()
for path in HEALTH:
resp = api.request("GET", path, actor=ghost)
assert assert_ok(resp, 200, "Health") == {"status": "ok"}
+86
View File
@@ -0,0 +1,86 @@
"""Спек `identification`: заголовок `X-User-Id` лабы 1.
Единственный модуль, который собирает заголовок сам, а не через
`Actor.headers()`: проверяется именно заголовок. На лабе 2 модуль
переписывается вместе со спеком.
"""
import uuid
from typing import Any
import pytest
from api_client import API, Actor, Api
from contract import assert_error, assert_ok, contract
ME = f"{API}/users/me"
@pytest.mark.spec("identification", "Корректный заголовок")
def test_valid_header(api: Api, alice: Actor) -> None:
resp = api.request("GET", ME, headers={"X-User-Id": alice.id})
assert assert_ok(resp, 200, "User") == alice.user
@pytest.mark.spec("identification", "Нет заголовка")
def test_no_header(api: Api) -> None:
assert_error(api.request("GET", ME), 401)
@pytest.mark.spec("identification", "Не UUID")
def test_not_uuid(api: Api) -> None:
resp = api.request("GET", ME, headers={"X-User-Id": "not-a-uuid"})
assert_error(resp, 401)
@pytest.mark.spec("identification", "Неизвестный пользователь")
def test_unknown_user(api: Api) -> None:
resp = api.request("GET", ME, headers={"X-User-Id": str(uuid.uuid4())})
assert_error(resp, 401)
@pytest.mark.spec("identification", "Чужой чат без заголовка")
def test_chat_without_header(api: Api, chat: dict[str, Any]) -> None:
assert_error(api.request("GET", f"{API}/chats/{chat['id']}"), 401)
@pytest.mark.spec("identification", "Невалидное поле без заголовка")
def test_invalid_field_without_header(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
resp = api.request(
"POST",
f"{API}/chats/{chat['id']}/messages",
json={"text": ""},
)
assert_error(resp, 401)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("identification", "Битый JSON без заголовка")
def test_malformed_json_without_header(
api: Api,
chat: dict[str, Any],
) -> None:
# согласованное расхождение: битый JSON отклоняется до идентификации
resp = api.request(
"POST",
f"{API}/chats/{chat['id']}/messages",
headers={"Content-Type": "application/json"},
content=b"{bad",
)
assert_error(resp, 400)
@pytest.mark.spec("identification", "Схема в openapi.json")
def test_security_scheme_in_openapi(api: Api) -> None:
resp = api.request("GET", "/openapi.json")
assert resp.status_code == 200
served = resp.json()
expected = contract()["components"]["securitySchemes"]["devUser"]
assert served["components"]["securitySchemes"]["devUser"] == expected
assert served["paths"][ME]["get"]["security"] == [{"devUser": []}]
assert not served["paths"][f"{API}/users"]["post"].get("security")
+110
View File
@@ -0,0 +1,110 @@
"""Спек `messages`: отправка, валидация текста, история."""
from typing import Any
import httpx
import pytest
from api_client import API, Actor, Api, order_key
from contract import assert_error, assert_ok
def send_raw(
api: Api,
actor: Actor,
chat_id: str,
body: dict[str, Any],
) -> httpx.Response:
return api.request(
"POST",
f"{API}/chats/{chat_id}/messages",
actor=actor,
json=body,
)
@pytest.mark.spec("messages", "Участник отправляет сообщение")
def test_member_sends(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
resp = send_raw(api, alice, chat["id"], {"text": "Привет, мир 👋"})
message = assert_ok(resp, 201, "Message")
assert message["sender_id"] == alice.id
assert message["chat_id"] == chat["id"]
assert message["text"] == "Привет, мир 👋"
@pytest.mark.spec("messages", "Граница длины")
def test_text_length(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
# кириллица: 2 байта на символ, считаются code points
text = "я" * 4000
message = assert_ok(
send_raw(api, alice, chat["id"], {"text": text}),
201,
"Message",
)
assert message["text"] == text
assert_error(send_raw(api, alice, chat["id"], {"text": text + "я"}), 400)
assert [item["id"] for item in api.all_messages(alice, chat["id"])] == [
message["id"],
]
@pytest.mark.spec("messages", "Попытка подменить отправителя")
def test_sender_id_in_body(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
body = {"text": "от Боба", "sender_id": bob.id}
assert_error(send_raw(api, alice, chat["id"], body), 400)
assert api.all_messages(bob, chat["id"]) == []
@pytest.mark.spec("messages", "Два участника, две страницы")
def test_two_members_two_pages(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
sent = [
api.send_message(alice, chat["id"], "от Алисы"),
api.send_message(bob, chat["id"], "от Боба"),
]
first = assert_ok(
api.messages_page(bob, chat["id"], limit=1),
200,
"MessagePage",
)
assert len(first["items"]) == 1
assert first["next_cursor"]
second = assert_ok(
api.messages_page(
bob,
chat["id"],
limit=1,
cursor=first["next_cursor"],
),
200,
"MessagePage",
)
assert len(second["items"]) == 1
assert second["next_cursor"] is None
assert first["items"] + second["items"] == sorted(sent, key=order_key)
@pytest.mark.spec("messages", "Чтение после записи")
def test_read_after_write(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
for number in range(5):
message = api.send_message(alice, chat["id"], f"сразу {number}")
history = api.all_messages(bob, chat["id"])
assert message in history
+163
View File
@@ -0,0 +1,163 @@
"""Спек `pagination`: `limit`, `next_cursor`, курсоры обоих списков."""
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
import httpx
import pytest
from api_client import Actor, Api, order_key
from contract import assert_error, assert_ok
@dataclass(frozen=True)
class Listing:
"""Постраничный список: запрос страницы и схема ответа."""
page: Callable[..., httpx.Response]
schema: str
@pytest.fixture(params=["messages", "chats"])
def listing(
request: pytest.FixtureRequest,
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> Listing:
"""История чата или список чатов Алисы: правила `limit` общие."""
if request.param == "messages":
return Listing(
page=lambda **params: api.messages_page(
alice,
chat["id"],
**params,
),
schema="MessagePage",
)
return Listing(
page=lambda **params: api.chats_page(alice, **params),
schema="ChatPage",
)
def fill(api: Api, actor: Actor, chat_id: str, count: int) -> list[dict]:
return [
api.send_message(actor, chat_id, f"page-{number}")
for number in range(count)
]
@pytest.mark.spec("pagination", "Ноль")
def test_limit_zero(listing: Listing) -> None:
assert_error(listing.page(limit=0), 400)
@pytest.mark.spec("pagination", "Больше максимума и не число")
def test_limit_out_of_range(listing: Listing) -> None:
for limit in (101, -1, "abc", "1.5"):
assert_error(listing.page(limit=limit), 400)
# границы диапазона допустимы
for limit in (1, 100):
assert_ok(listing.page(limit=limit), 200, listing.schema)
@pytest.mark.spec("pagination", "По умолчанию")
def test_default_limit(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
fill(api, alice, chat["id"], 60)
page = assert_ok(
api.messages_page(alice, chat["id"]),
200,
"MessagePage",
)
assert len(page["items"]) == 50
assert page["next_cursor"]
@pytest.mark.spec("pagination", "Последняя полная страница")
def test_last_full_page(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
sent = fill(api, alice, chat["id"], 2)
page = assert_ok(
api.messages_page(alice, chat["id"], limit=2),
200,
"MessagePage",
)
assert page["items"] == sorted(sent, key=order_key)
assert page["next_cursor"] is None
@pytest.mark.spec("pagination", "Полный обход")
def test_full_walk(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
sent = fill(api, alice, chat["id"], 7)
pages = api.message_pages(alice, chat["id"], limits=(3, 2))
assert [len(page["items"]) for page in pages] == [3, 2, 2]
items = [item for page in pages for item in page["items"]]
assert items == sorted(sent, key=order_key)
def test_chat_list_walk(api: Api, alice: Actor, bob: Actor) -> None:
"""Список чатов обходится так же, как история."""
created = [api.create_chat(alice, bob, title=f"c{n}") for n in range(5)]
pages = api.chat_pages(bob, limits=(2,))
items = [item for page in pages for item in page["items"]]
assert items == sorted(created, key=order_key)
@pytest.mark.spec("pagination", "Курсор другого чата")
def test_cursor_of_other_chat(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
other = api.create_chat(alice, bob, title="B")
fill(api, alice, chat["id"], 2)
fill(api, alice, other["id"], 2)
first = assert_ok(
api.messages_page(alice, chat["id"], limit=1),
200,
"MessagePage",
)
resp = api.messages_page(
alice,
other["id"],
limit=1,
cursor=first["next_cursor"],
)
assert_error(resp, 400)
def test_cursor_of_other_list(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
"""Курсор списка чатов не подходит истории, и наоборот."""
api.create_chat(alice, bob)
fill(api, alice, chat["id"], 2)
chats_cursor = assert_ok(
api.chats_page(alice, limit=1),
200,
"ChatPage",
)["next_cursor"]
history_cursor = assert_ok(
api.messages_page(alice, chat["id"], limit=1),
200,
"MessagePage",
)["next_cursor"]
assert chats_cursor
assert history_cursor
assert_error(
api.messages_page(alice, chat["id"], cursor=chats_cursor),
400,
)
assert_error(api.chats_page(alice, cursor=history_cursor), 400)
@pytest.mark.spec("pagination", "Повреждённый курсор")
def test_garbage_cursor(listing: Listing) -> None:
# eyJ4IjoxfQ — корректный base64 от {"x":1}, но не курсор сервиса
for cursor in ("garbage", "eyJ4IjoxfQ", "!!!"):
assert_error(listing.page(cursor=cursor), 400)
+134
View File
@@ -0,0 +1,134 @@
"""Гонки: одновременные запросы по отдельным соединениям."""
import threading
import time
from collections import Counter
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
import httpx
import pytest
from api_client import API, Api, order_key, unique_username
from contract import assert_error, assert_ok
CLIENTS = 10
MESSAGES_PER_CLIENT = 10
HISTORY_PAGE = 30
def run_together[T](work: Callable[[Api, int], T], base_url: str) -> list[T]:
"""`CLIENTS` потоков со своим соединением стартуют за барьером."""
barrier = threading.Barrier(CLIENTS)
def client(number: int) -> T:
with Api(base_url) as own:
# соединение открыто до барьера: после него сразу запросы
own.request("GET", "/health/live")
barrier.wait()
return work(own, number)
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
return list(pool.map(client, range(CLIENTS)))
def max_in_flight(spans: list[tuple[float, float]]) -> int:
"""Сколько запросов максимум было в полёте одновременно."""
# при равенстве времени конец считается раньше начала
events = sorted(
[(start, 1) for start, _ in spans] + [(end, -1) for _, end in spans],
)
current = peak = 0
for _, delta in events:
current += delta
peak = max(peak, current)
return peak
@pytest.mark.spec("data-storage", "100 сообщений от 10 клиентов")
def test_hundred_messages_from_ten_clients(api: Api, base_url: str) -> None:
actors = [
api.register(display_name=f"Racer {number}")
for number in range(CLIENTS)
]
chat = api.create_chat(actors[0], *actors[1:], title="Race")
path = f"{API}/chats/{chat['id']}/messages"
def send_all(
own: Api,
number: int,
) -> list[tuple[str, httpx.Response, float, float]]:
results = []
for index in range(MESSAGES_PER_CLIENT):
text = f"race-{number}-{index}"
start = time.monotonic()
resp = own.request(
"POST",
path,
actor=actors[number],
json={"text": text},
)
results.append((text, resp, start, time.monotonic()))
return results
results = [
row for rows in run_together(send_all, base_url) for row in rows
]
statuses = Counter(resp.status_code for _, resp, _, _ in results)
peak = max_in_flight([(start, end) for _, _, start, end in results])
assert statuses == {201: CLIENTS * MESSAGES_PER_CLIENT}, statuses
created = {}
for text, resp, _, _ in results:
message = assert_ok(resp, 201, "Message")
assert message["text"] == text
created[message["id"]] = message
pages = api.message_pages(actors[0], chat["id"], limits=(HISTORY_PAGE,))
items = [item for page in pages for item in page["items"]]
ids = [item["id"] for item in items]
print(
f"race: {CLIENTS} clients x {MESSAGES_PER_CLIENT} messages, "
f"statuses {dict(statuses)}, max in flight {peak}; "
f"history: {len(items)} messages, {len(set(ids))} unique ids, "
f"{len(pages)} pages by {HISTORY_PAGE}",
)
assert peak >= 2, "requests did not overlap: race is not proven"
assert len(items) == CLIENTS * MESSAGES_PER_CLIENT
assert len(set(ids)) == len(ids)
assert set(ids) == created.keys()
assert items == sorted(created.values(), key=order_key)
senders = {actor.id for actor in actors}
assert {item["sender_id"] for item in items} == senders
@pytest.mark.spec("users", "Одновременная регистрация")
@pytest.mark.spec("data-storage", "Гонка за username")
def test_same_username_at_once(base_url: str) -> None:
username = unique_username()
def register(own: Api, number: int) -> tuple[httpx.Response, float, float]:
start = time.monotonic()
resp = own.request(
"POST",
f"{API}/users",
json={"username": username, "display_name": f"Racer {number}"},
)
return resp, start, time.monotonic()
results = run_together(register, base_url)
statuses = Counter(resp.status_code for resp, _, _ in results)
peak = max_in_flight([(start, end) for _, start, end in results])
print(
f"username race: {CLIENTS} clients, statuses {dict(statuses)}, "
f"max in flight {peak}",
)
assert peak >= 2, "requests did not overlap: race is not proven"
assert statuses == {201: 1, 409: CLIENTS - 1}, statuses
for resp, _, _ in results:
if resp.status_code == 409:
assert_error(resp, 409)
else:
assert assert_ok(resp, 201, "User")["username"] == username
+104
View File
@@ -0,0 +1,104 @@
"""Обязательные сценарии уровня «4» (README.md, рубрика)."""
import uuid
from typing import Any
import pytest
from api_client import API, Actor, Api, order_key
from contract import assert_error
@pytest.mark.spec("api-conventions", "Битый JSON")
def test_malformed_json(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
headers = {"Content-Type": "application/json"}
for path, actor in (
(f"{API}/users", None),
(f"{API}/chats", alice),
(f"{API}/chats/{chat['id']}/messages", alice),
):
resp = api.request(
"POST",
path,
actor=actor,
headers=headers,
content=b"{bad",
)
assert_error(resp, 400)
@pytest.mark.spec("chats", "Посторонний")
@pytest.mark.spec("messages", "Посторонний пишет")
@pytest.mark.spec("messages", "Посторонний читает")
def test_foreign_chat(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
path = f"{API}/chats/{chat['id']}"
missing = f"{API}/chats/{uuid.uuid4()}"
requests = (
("GET", "", None),
("GET", "/messages", None),
("POST", "/messages", {"text": "чужое"}),
)
for method, suffix, body in requests:
foreign = assert_error(
api.request(method, path + suffix, actor=eve, json=body),
404,
)
absent = assert_error(
api.request(method, missing + suffix, actor=eve, json=body),
404,
)
# чужой чат неотличим от несуществующего
assert (foreign["code"], foreign["message"]) == (
absent["code"],
absent["message"],
)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Пустой текст")
@pytest.mark.spec("api-conventions", "Строка из пробелов")
def test_empty_message(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
path = f"{API}/chats/{chat['id']}/messages"
for text in ("", " ", "\t\n "):
resp = api.request("POST", path, actor=alice, json={"text": text})
assert_error(resp, 400)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("users", "Повтор username")
def test_duplicate_username(api: Api, alice: Actor) -> None:
resp = api.request(
"POST",
f"{API}/users",
json={
"username": alice.user["username"],
"display_name": "Другая Алиса",
},
)
assert_error(resp, 409)
def test_history_walk_across_pages(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
"""12 сообщений, страницы по 5, 3, 4: `limit` меняется между ними."""
sent = [
api.send_message(sender, chat["id"], f"walk-{number}")
for number, sender in enumerate([alice, bob] * 6)
]
pages = api.message_pages(bob, chat["id"], limits=(5, 3, 4))
assert [len(page["items"]) for page in pages] == [5, 3, 4]
assert all(page["next_cursor"] for page in pages[:-1])
assert pages[-1]["next_cursor"] is None
items = [item for page in pages for item in page["items"]]
assert len({item["id"] for item in items}) == len(sent)
assert items == sorted(sent, key=order_key)
+71
View File
@@ -0,0 +1,71 @@
"""Спек `users`: регистрация и текущий пользователь."""
import httpx
import pytest
from api_client import API, Actor, Api, unique_username
from contract import assert_error, assert_ok
def register_raw(
api: Api,
username: str,
display_name: str = "User",
) -> httpx.Response:
return api.request(
"POST",
f"{API}/users",
json={"username": username, "display_name": display_name},
)
@pytest.mark.spec("users", "Успешная регистрация")
def test_register(api: Api, bob: Actor) -> None:
username = unique_username()
resp = register_raw(api, username, "Алиса")
user = assert_ok(resp, 201, "User")
assert (user["username"], user["display_name"]) == (username, "Алиса")
assert user["id"] != bob.id
@pytest.mark.spec("users", "Заглавные буквы")
def test_username_uppercase(api: Api) -> None:
username = unique_username()
assert_error(register_raw(api, username.upper()), 400)
# то же имя строчными свободно: отказ был только из-за регистра
api.register(username=username)
@pytest.mark.spec("users", "Слишком короткий")
def test_username_too_short(api: Api) -> None:
assert_error(register_raw(api, "ab"), 400)
@pytest.mark.spec("users", "Перевод строки в конце")
def test_username_trailing_newline(api: Api) -> None:
assert_error(register_raw(api, unique_username() + "\n"), 400)
@pytest.mark.spec("users", "Граница длины")
def test_display_name_length(api: Api) -> None:
user = assert_ok(
register_raw(api, unique_username(), "👋" * 100),
201,
"User",
)
assert user["display_name"] == "👋" * 100
assert_error(register_raw(api, unique_username(), "👋" * 101), 400)
@pytest.mark.spec("users", "Только пробелы")
def test_display_name_blank(api: Api) -> None:
assert_error(register_raw(api, unique_username(), " "), 400)
# значимые пробелы по краям не обрезаются
user = api.register(display_name=" Алиса ").user
assert user["display_name"] == " Алиса "
@pytest.mark.spec("users", "Совпадает с регистрацией")
def test_me_equals_registration(api: Api, alice: Actor) -> None:
resp = api.request("GET", f"{API}/users/me", actor=alice)
assert assert_ok(resp, 200, "User") == alice.user