chore: port lab 4 solution into the lab 5 skeleton

Source: mtusi2026lab4-safronov, solution/bvt2301-safronov, 2546deb.
Contracts, public tests and evidence of lab 4 are not carried over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-31 03:09:12 +03:00
co-authored by Claude Opus 5.5
parent 276dbdad8a
commit 04f859282d
479 changed files with 106103 additions and 24 deletions
+473
View File
@@ -0,0 +1,473 @@
"""HTTP-клиент набора: запросы к API и идентификация в одном месте."""
import base64
import dataclasses
import hashlib
import secrets
import time
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"
SESSIONS = f"{API}/auth/sessions"
# защита от бесконечного обхода, если next_cursor никогда не станет null
MAX_PAGES = 1000
# с лабы 3 обязателен у POST сообщения: одна отправка — один ключ, повтор
# неподтверждённой отправки — тот же ключ
IDEMPOTENCY_KEY = "Idempotency-Key"
# блок медленного скачивания: столько же отдаёт за раз поток S3 в API
DOWNLOAD_CHUNK_BYTES = 64 * 1024
class _NewKey:
"""Маркер `post_message`: сгенерировать новый ключ."""
def __repr__(self) -> str:
return "NEW_KEY"
NEW_KEY = _NewKey()
def unique_username() -> str:
"""Имя под `^[a-z0-9_]{3,32}$`, уникальное для каждого вызова."""
return f"t_{uuid.uuid4().hex[:12]}"
def unique_password() -> str:
"""Синтетический пароль из 12–128 символов, свой у каждого вызова."""
return f"pw-{uuid.uuid4().hex}"
def new_key() -> str:
"""Новый `Idempotency-Key`: 32 символа из допустимого алфавита."""
return uuid.uuid4().hex
def key_headers(key: str | None = None) -> dict[str, str]:
"""Заголовок ключа для запросов в обход `post_message`."""
return {IDEMPOTENCY_KEY: new_key() if key is None else key}
def registration(
username: str,
display_name: Any = "Test user",
password: Any = None,
) -> dict[str, Any]:
"""Тело `POST /users`; пароль по умолчанию — новый синтетический."""
return {
"username": username,
"display_name": display_name,
"password": unique_password() if password is None else password,
}
def basic_auth(username: str, password: str) -> dict[str, str]:
"""`Authorization: Basic` из username и пароля в UTF-8."""
raw = f"{username}:{password}".encode()
return {"Authorization": "Basic " + base64.b64encode(raw).decode("ascii")}
def bearer_auth(token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {token}"}
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]
password: str
token: str
@classmethod
def unregistered(cls) -> "Actor":
"""Пользователь, которого нет на сервере, с невыданным токеном."""
return cls(
user={"id": str(uuid.uuid4()), "username": unique_username()},
password=unique_password(),
token=secrets.token_urlsafe(32),
)
@property
def id(self) -> str:
return self.user["id"]
@property
def username(self) -> str:
return self.user["username"]
def with_token(self, token: str) -> "Actor":
"""Тот же пользователь с другой сессией."""
return dataclasses.replace(self, token=token)
def headers(self) -> dict[str, str]:
"""Идентификация: с лабы 2 — Bearer-токен сессии."""
return bearer_auth(self.token)
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",
password: str | None = None,
) -> Actor:
"""Регистрация и сразу вход: у пользователя есть токен."""
password = password or unique_password()
resp = self.request(
"POST",
f"{API}/users",
json=registration(
username or unique_username(),
display_name,
password,
),
)
user = assert_ok(resp, 201, "User")
return self.login(user, password)
def login_response(self, username: str, password: str) -> httpx.Response:
return self.request(
"POST",
SESSIONS,
headers=basic_auth(username, password),
)
def login(self, user: dict[str, Any], password: str) -> Actor:
"""Новая сессия пользователя; ответ проверяется по схеме `Session`."""
resp = self.login_response(user["username"], password)
session = assert_ok(resp, 201, "Session")
assert session["user"] == user, "session user differs from user"
return Actor(user=user, password=password, token=session["token"])
def logout(self, actor: Actor) -> httpx.Response:
return self.request("DELETE", f"{SESSIONS}/current", actor=actor)
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 post_message(
self,
actor: Actor | None,
chat_id: str,
*,
key: str | None | _NewKey = NEW_KEY,
headers: dict[str, str] | None = None,
**kwargs: Any,
) -> httpx.Response:
"""`POST` сообщения как есть; тело — `json=` или `content=`.
`key`: по умолчанию — новый ключ, `None` — без заголовка, строка —
этот ключ (в том числе пустой или неверный).
"""
merged = dict(headers or {})
if isinstance(key, _NewKey):
merged[IDEMPOTENCY_KEY] = new_key()
elif key is not None:
merged[IDEMPOTENCY_KEY] = key
return self.request(
"POST",
f"{API}/chats/{chat_id}/messages",
actor=actor,
headers=merged,
**kwargs,
)
def send_message(
self,
actor: Actor,
chat_id: str,
text: str,
*,
key: str | None = None,
attachment_ids: Sequence[str] | None = None,
) -> dict[str, Any]:
"""Успешная отправка: 201 и `Message`; без `key` — новый ключ.
`attachment_ids=None` — поля в теле нет.
"""
body: dict[str, Any] = {"text": text}
if attachment_ids is not None:
body["attachment_ids"] = list(attachment_ids)
resp = self.post_message(
actor,
chat_id,
key=new_key() if key is None else key,
json=body,
)
message = assert_ok(resp, 201, "Message")
if attachment_ids is not None:
assert message["attachment_ids"] == [
item.lower() for item in attachment_ids
], "attachment_ids differ from sent"
return message
def post_attachment(
self,
actor: Actor | None,
chat_id: str,
data: Any,
*,
content_type: str | None = "image/png",
filename: str | None = "image.png",
headers: dict[str, str] | None = None,
) -> httpx.Response:
"""Загрузка как есть: сырые байты (или итератор — частями, без
`Content-Length`); `None` — без заголовка или параметра."""
merged = dict(headers or {})
if content_type is not None:
merged["Content-Type"] = content_type
params = {} if filename is None else {"filename": filename}
return self.request(
"POST",
f"{API}/chats/{chat_id}/attachments",
actor=actor,
headers=merged,
params=params,
content=data,
)
def upload(
self,
actor: Actor,
chat_id: str,
data: bytes,
*,
content_type: str = "image/png",
filename: str = "image.png",
) -> dict[str, Any]:
"""Успешная загрузка: 201 и `Attachment` с размером и SHA-256."""
resp = self.post_attachment(
actor,
chat_id,
data,
content_type=content_type,
filename=filename,
)
attachment = assert_ok(resp, 201, "Attachment")
assert attachment["size_bytes"] == len(data), "size_bytes differs"
assert attachment["sha256"] == hashlib.sha256(data).hexdigest(), (
"sha256 differs"
)
assert attachment["chat_id"] == chat_id.lower(), "chat_id differs"
assert attachment["owner_id"] == actor.id, "owner_id differs"
assert attachment["filename"] == filename, "filename changed"
return attachment
def attachment_meta(
self,
actor: Actor | None,
attachment_id: str,
) -> httpx.Response:
return self.request(
"GET",
f"{API}/attachments/{attachment_id}",
actor=actor,
)
def attachment_content(
self,
actor: Actor | None,
attachment_id: str,
*,
variant: str | None = None,
) -> httpx.Response:
params = {} if variant is None else {"variant": variant}
return self.request(
"GET",
f"{API}/attachments/{attachment_id}/content",
actor=actor,
params=params,
)
def attachment_content_slowly(
self,
actor: Actor | None,
attachment_id: str,
*,
pause_s: float,
chunk_bytes: int = DOWNLOAD_CHUNK_BYTES,
) -> httpx.Response:
"""Байты оригинала потоком: пауза `pause_s` после каждого блока
`chunk_bytes` — клиент читает медленнее сети.
Отдаёт ответ со статусом, заголовками и прочитанными байтами в
`content`, как `attachment_content`: его проверяет тот же
`assert_content`.
"""
with self.client.stream(
"GET",
f"{API}/attachments/{attachment_id}/content",
headers=actor.headers() if actor is not None else {},
) as streamed:
chunks = []
for chunk in streamed.iter_bytes(chunk_bytes):
chunks.append(chunk)
time.sleep(pause_s)
return httpx.Response(
streamed.status_code,
headers=streamed.headers,
content=b"".join(chunks),
request=streamed.request,
)
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
+201
View File
@@ -0,0 +1,201 @@
"""Настройка набора: адрес стенда, проверка доступности, фикстуры."""
import os
import subprocess
from collections.abc import Callable, 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("/")
# сколько реплик API за BASE_URL: стенд с LB — API_REPLICAS (make
# student_test), один процесс — 1 (make test_isolated, драйвер в консоли).
# Режим задаётся явно, а не угадывается по ответам: иначе сломанный LB
# давал бы пропуск вместо падения
EXPECT_REPLICAS = int(os.environ.get("EXPECT_REPLICAS", "2"))
# hook стенда отказов и «тесный» API задаёт make failure_checks
FAULT_HOOK = os.environ.get("FAULT_HOOK", "")
FAULT_TIGHT_BASE_URL = os.environ.get("FAULT_TIGHT_BASE_URL", "").rstrip("/")
# «узкий по загрузкам» API стенда отказов (change upload-memory)
FAULT_UPLOADS_BASE_URL = os.environ.get("FAULT_UPLOADS_BASE_URL", "").rstrip(
"/",
)
# API стенда отказов с коротким сроком вызова S3 (change fix-upload-put-flake)
FAULT_S3_BASE_URL = os.environ.get("FAULT_S3_BASE_URL", "").rstrip("/")
FAULT_HOOK_TIMEOUT_S = 120
# срок клиента «узкого» API: больше ожидания места, срока тела и шагов
UPLOADS_CLIENT_TIMEOUT_S = 30
# срок клиента API с коротким сроком S3: медленное скачивание оригинала
# в несколько MiB длится дольше 5 с по умолчанию у `Api`
S3_CLIENT_TIMEOUT_S = 30
@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)
is_fault = item.get_closest_marker("fault") is not None
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)
if is_fault:
collected.fault.add(mark.args)
config.stash[COLLECTED] = collected
@pytest.hookimpl(trylast=True)
def pytest_collection_finish(session: pytest.Session) -> None:
"""Проверки отказов без стенда make failure_checks не запускаются.
Выход до первого теста: без hook ни одно хранилище не трогается.
"""
selected = [
item for item in session.items if item.get_closest_marker("fault")
]
if selected and not (
FAULT_HOOK
and FAULT_TIGHT_BASE_URL
and FAULT_UPLOADS_BASE_URL
and FAULT_S3_BASE_URL
):
pytest.exit(
"fault checks need the failure stand and its hook: "
"run make failure_checks",
returncode=2,
)
@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 expect_replicas() -> int:
return EXPECT_REPLICAS
@pytest.fixture
def replicas() -> int:
"""Тест реплик: нужны ≥ 2 реплики за балансировщиком.
Против одного процесса тест пропускается с причиной, а не считается
пройденным.
"""
if EXPECT_REPLICAS < 2:
pytest.skip(
f"one API process (EXPECT_REPLICAS={EXPECT_REPLICAS}): "
"replica checks need the stand with the load balancer",
)
return EXPECT_REPLICAS
@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="Алиса и Боб")
@pytest.fixture(scope="session")
def stand() -> Callable[..., str]:
"""Действие над стендом отказов через hook; возвращает его stdout.
`stand("stop", "postgres")` — «стенд, останови postgres». Hook —
исполняемый файл, вызов без shell, как `ACTION_SCRIPT` в
`tests/resilience.py`. Сам тест docker не трогает. Не путать с
маркером `fault`: он только выбирает тесты (`-m fault`).
"""
def call(*args: str, stdin: bytes = b"") -> str:
# stdin — байты: тело объекта, который hook пишет мимо API
# (`put-object`, design change track2-reconciler, решение 11)
result = subprocess.run(
[FAULT_HOOK, *args],
input=stdin,
capture_output=True,
timeout=FAULT_HOOK_TIMEOUT_S,
check=False,
)
stderr = result.stderr.decode(errors="replace").strip()
assert result.returncode == 0, f"fault hook {' '.join(args)}: {stderr}"
return result.stdout.decode().strip()
return call
@pytest.fixture(scope="session")
def tight_api() -> Iterator[Api]:
"""API стенда отказов со сроками сессии и ключа идемпотентности 2 с и
пулом из одного соединения."""
with Api(FAULT_TIGHT_BASE_URL) as client:
yield client
@pytest.fixture(scope="session")
def uploads_api() -> Iterator[Api]:
"""API стенда отказов с одним местом загрузки, одной загрузкой в
очереди, ожиданием места 1 с и сроком тела 3 с (`FAULT_UPLOADS_ENV`)."""
with Api(
FAULT_UPLOADS_BASE_URL,
timeout=UPLOADS_CLIENT_TIMEOUT_S,
) as client:
yield client
@pytest.fixture(scope="session")
def s3_api() -> Iterator[Api]:
"""API стенда отказов со сроком вызова S3 1 с (`FAULT_S3_ENV`)."""
with Api(FAULT_S3_BASE_URL, timeout=S3_CLIENT_TIMEOUT_S) as client:
yield client
+274
View File
@@ -0,0 +1,274 @@
"""Проверка ответов по `contracts/openapi.json` и форматам контракта."""
import json
import re
from collections.abc import Iterable, Mapping
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", "owner_id"})
# списки UUID в ответах: участники чата и с лабы 4 вложения сообщения
ID_LIST_KEYS = frozenset({"member_ids", "attachment_ids"})
TIME_KEYS = frozenset({"created_at", "expires_at", "updated_at"})
# WWW-Authenticate у 401 (contracts/README.md): вход и остальные запросы
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
# признаки внутренностей сервиса в error.message
LEAK_RE = re.compile(r"Traceback|File \"|\.py\b|/app/|/src/|Error\(")
# X-Instance-Id (спек api-conventions): допустим в заголовке и журнале
INSTANCE_ID_RE = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
# статус -> code ошибки (спек api-conventions)
ERROR_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
405: "invalid_request",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
# с change upload-memory: все места загрузки процесса заняты
429: "rate_limited",
500: "internal_error",
503: "unavailable",
}
# Retry-After у 429 — положительное целое число секунд (спек
# api-conventions, «Соответствие статусов и кодов ошибок»)
RETRY_AFTER_RE = re.compile(r"^[1-9][0-9]*$")
@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 in ID_LIST_KEYS:
for number, member in enumerate(item):
assert_uuid(member, f"{where}/{number}")
elif key in TIME_KEYS:
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`, `X-Instance-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",
)
if status == 429:
retry_after = resp.headers.get("Retry-After", "")
assert RETRY_AFTER_RE.fullmatch(retry_after), describe(
resp,
f"Retry-After {retry_after!r} is not a positive integer",
)
return error
def assert_errors(
responses: Mapping[str, httpx.Response],
status: int,
) -> None:
"""Каждый вариант запроса — ошибка `status` в формате контракта.
Статусы сверяются все разом: при падении видно, что ответил каждый
вариант, а не только первый.
"""
statuses = {name: resp.status_code for name, resp in responses.items()}
assert set(statuses.values()) == {status}, (
f"expected {status} for every variant, got {statuses}"
)
for resp in responses.values():
assert_error(resp, status)
def assert_unauthorized(
resp: httpx.Response,
challenge: str,
) -> dict[str, Any]:
"""401 в формате контракта с заданным `WWW-Authenticate`."""
error = assert_error(resp, 401)
assert resp.headers.get("WWW-Authenticate") == challenge, describe(
resp,
f"expected WWW-Authenticate {challenge}",
)
return error
def assert_no_storage_traces(resp: httpx.Response) -> None:
"""Ни перенаправления, ни заголовков S3 в ответе API."""
assert "location" not in resp.headers, describe(resp, "has Location")
amz = [name for name in resp.headers if name.lower().startswith("x-amz-")]
assert not amz, describe(resp, f"S3 headers {amz}")
def assert_content(
resp: httpx.Response,
data: bytes,
content_type: str,
) -> None:
"""Байты оригинала: 200, тип без параметров, длина, `nosniff`, те же
байты, без перенаправления и следов S3."""
assert resp.status_code == 200, describe(resp, "expected 200")
assert resp.headers.get("X-Request-Id", "").strip(), describe(
resp,
"no X-Request-Id",
)
assert_instance_id(resp)
assert resp.headers.get("Content-Type") == content_type, describe(
resp,
f"Content-Type is not {content_type}",
)
assert resp.headers.get("Content-Length") == str(len(data)), describe(
resp,
f"Content-Length is not {len(data)}",
)
assert resp.headers.get("X-Content-Type-Options") == "nosniff", describe(
resp,
"no X-Content-Type-Options: nosniff",
)
assert_no_storage_traces(resp)
assert resp.content == data, (
f"downloaded {len(resp.content)} bytes differ from {len(data)} sent"
)
def assert_instance_id(resp: httpx.Response) -> str:
"""Непустой `X-Instance-Id` допустимого формата; возвращает значение."""
instance_id = resp.headers.get("X-Instance-Id", "")
assert INSTANCE_ID_RE.fullmatch(instance_id), describe(
resp,
f"bad X-Instance-Id {instance_id!r}",
)
return instance_id
def assert_replicas(values: Iterable[str], expected: int) -> set[str]:
"""Ответы дали не меньше двух разных `X-Instance-Id`; возвращает их.
`expected` — `EXPECT_REPLICAS`: сколько реплик ждали за `BASE_URL`.
"""
seen = set(values)
assert len(seen) >= 2, (
f"saw {len(seen)} X-Instance-Id {sorted(seen)} behind BASE_URL, "
f"EXPECT_REPLICAS={expected}: no load balancing across replicas; "
"against one API process run with EXPECT_REPLICAS=1"
)
return seen
def json_body(resp: httpx.Response) -> Any:
"""JSON-тело в UTF-8, непустые `X-Request-Id` и `X-Instance-Id`."""
request_id = resp.headers.get("X-Request-Id", "")
assert request_id.strip(), describe(resp, "no X-Request-Id")
assert_instance_id(resp)
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]}"
)
+55
View File
@@ -0,0 +1,55 @@
# Override стенда отказов make failure_checks (student-tests/run_failures.py):
# тот же docker-compose.yml под проектом <рабочий>-failures (имя рабочего
# проекта — из name в docker-compose.yml, сейчас mtusi-lab5), со своим
# volume и сетью. Порты Postgres, Valkey и S3 не публикуются: к ним ходит
# только fault_hook.py через docker compose exec. Сервисы api и haproxy не
# запускаются: контейнеры API создаёт оркестратор (docker compose run
# -p 127.0.0.1:...), у реплик api своих портов нет. Порт LB сброшен, чтобы
# случайный up не занял APP_OUT_PORT рабочего стенда.
#
# Healthcheck PostgreSQL проверяет служебную базу postgres, а не базу
# приложения: с 127.0.0.1 образ пускает без пароля (trust), и каждая
# проверка — сессия в pg_stat_database базы. Иначе раз в 5 с она попадала
# бы в счётчик теста «Соединения пула не переоткрываются» (действие hook
# db-sessions).
#
# У PostgreSQL — init (tini) с PID 1, postmaster — его потомок. fault_hook.py
# fill-connections отвязывает psql в фоне sh, запущенного docker compose exec;
# после clear-connections они становятся сиротами пространства PID. С init их
# молча подбирает он, а не postmaster: тот считал их «untracked child process»
# и выход с кодом 2 — аварией (все процессы завершены, recovery, сброс
# статистики). Только на стенде отказов: на рабочем стенде и в bench/ фоновых
# процессов в контейнере PostgreSQL нет (design change fix-known-issues,
# решение 11). Правило docker.md «сервер — PID 1» касается образа API.
services:
postgres:
init: true
ports: !reset []
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U \"$$POSTGRES_USER\" -d postgres"]
valkey:
ports: !reset []
# свой S3 со своим volume, порт API S3 не публикуется. Срок остановки
# короткий намеренно: здесь проверяется отказ, а не плавная остановка, и
# stop не тянет 15 с (design change s3-storage, решение 9)
s3:
ports: !reset []
stop_grace_period: 2s
haproxy:
ports: !reset []
# уборщик с grace и интервалом, сравнимыми со временем теста (design
# change upload-consistency, решение 10). Grace 20 с больше границы живой
# загрузки при сроках по умолчанию (2 × 6 + 5 = 17 с): занижать сроки ради
# меньшего grace значило бы обойти проверку. Без перезапуска: падение не
# прячется. Значения run_failures.py передаёт тестам
# (FAULT_CLEANER_GRACE_S, FAULT_CLEANER_INTERVAL_S). Плановая сверка
# выключена: иначе она исправляла бы расхождения, которые тест внёс и ещё
# проверяет. Сверку запускают сами тесты (hook reconcile), плановую —
# отдельный уборщик hook run-cleaner (design change track2-reconciler,
# решения 9 и 11)
cleaner:
restart: "no"
environment:
CLEANER__PENDING_GRACE_SECONDS: "20"
CLEANER__INTERVAL_SECONDS: "1"
RECONCILER__INTERVAL_SECONDS: "0"
+1063
View File
File diff suppressed because it is too large Load Diff
+316
View File
@@ -0,0 +1,316 @@
"""Изображения для тестов вложений: настоящие, повреждённые, огромные.
PNG собираются на stdlib — любые IHDR и IDAT, Adam7, точный размер файла
чанком-заполнителем `tEXt`, «бомба», порча CRC. JPEG — через Pillow
(dev-группа): прогрессивный, серый, CMYK, с EXIF, с подменой размеров в
SOF, без таблиц, с изменённым заголовком скана и без данных скана.
Большие файлы и «бомбы» живут только в памяти теста и в git не попадают
(`tests/fixtures/README.md`).
"""
import functools
import io
import random
import struct
import zlib
from pathlib import Path
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
# маркеры JPEG: таблицы квантования и Хаффмана, начало скана, конец
JPEG_DQT = 0xDB
JPEG_DHT = 0xC4
JPEG_SOS = 0xDA
JPEG_EOI = b"\xff\xd9"
# 27 байт из замечания к PR: SOI, SOF0 1 × 1, SOS без данных и EOI — ни
# таблицы квантования, ни таблиц Хаффмана
JPEG_WITHOUT_TABLES = bytes.fromhex(
"ffd8ffc0000b080001000101011100ffda0008010100003f00ffd9",
)
SAMPLE_PNG_PATH = (
Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sample.png"
)
# лимиты контракта лабы 4
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
_CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
_ADAM7 = (
(0, 0, 8, 8),
(4, 0, 8, 8),
(0, 4, 4, 8),
(2, 0, 4, 4),
(0, 2, 2, 4),
(1, 0, 2, 2),
(0, 1, 1, 2),
)
@functools.cache
def sample_png() -> bytes:
"""Публичный fixture `tests/fixtures/sample.png` (320 × 200)."""
return SAMPLE_PNG_PATH.read_bytes()
def chunk(kind: bytes, body: bytes) -> bytes:
"""Чанк PNG с верной CRC."""
crc = zlib.crc32(kind + body)
return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", crc)
def _rows(
width: int,
height: int,
*,
bits_per_pixel: int,
interlace: bool,
) -> bytes:
"""Распакованные данные: строки с фильтром 0 и узором в пикселях."""
passes = _ADAM7 if interlace else ((0, 0, 1, 1),)
out = bytearray()
for x0, y0, dx, dy in passes:
pass_width = (width - x0 + dx - 1) // dx if width > x0 else 0
pass_height = (height - y0 + dy - 1) // dy if height > y0 else 0
if not pass_width or not pass_height:
continue
row_bytes = (pass_width * bits_per_pixel + 7) // 8
row = bytes((i * 7) % 256 for i in range(row_bytes))
out += (b"\x00" + row) * pass_height
return bytes(out)
def png(
width: int = 64,
height: int = 48,
*,
color: int = 2,
depth: int = 8,
interlace: bool = False,
idat: bytes | None = None,
) -> bytes:
"""Настоящий PNG: IHDR, PLTE для палитры, IDAT, IEND.
`idat` — готовый сжатый поток вместо строк по размерам (огромные
размеры в маленьком файле, «бомба»).
"""
ihdr = struct.pack(
">IIBBBBB",
width,
height,
depth,
color,
0,
0,
1 if interlace else 0,
)
if idat is None:
idat = zlib.compress(
_rows(
width,
height,
bits_per_pixel=depth * _CHANNELS[color],
interlace=interlace,
),
9,
)
palette = chunk(b"PLTE", bytes(range(48))) if color == 3 else b""
return (
PNG_SIGNATURE
+ chunk(b"IHDR", ihdr)
+ palette
+ chunk(b"IDAT", idat)
+ chunk(b"IEND", b"")
)
def png_of_size(size: int) -> bytes:
"""Настоящий PNG 64 × 48 ровно `size` байт: добор чанком `tEXt`."""
base = png()
filler = size - len(base) - 12
assert filler >= 2, f"size {size} is too small"
text = chunk(b"tEXt", b"k\x00" + b"x" * (filler - 2))
# tEXt — после IHDR (8 + 25 байт), до IDAT
data = base[:33] + text + base[33:]
assert len(data) == size
return data
def png_noise(width: int = 1024, height: int = 341, *, seed: int = 0) -> bytes:
"""Настоящий RGB PNG из шума: сжимается плохо, поэтому размер файла —
около `width × height × 3` байт (по умолчанию ~1 MiB). Разные `seed` —
разные байты; один `seed` — одни и те же."""
noise = random.Random(seed)
row_bytes = width * 3
rows = b"".join(
b"\x00" + noise.randbytes(row_bytes) for _ in range(height)
)
return png(width, height, color=2, idat=zlib.compress(rows, 1))
def png_huge(width: int, height: int) -> bytes:
"""Несколько килобайт с огромными размерами в IHDR."""
return png(
width,
height,
color=0,
depth=1,
idat=zlib.compress(bytes(4096)),
)
def png_bomb(unpacked_mib: int = 200) -> bytes:
"""PNG 100 × 100, IDAT которого распаковывается в `unpacked_mib` MiB."""
compressor = zlib.compressobj(9)
block = bytes(1024 * 1024)
stream = b"".join(compressor.compress(block) for _ in range(unpacked_mib))
return png(100, 100, idat=stream + compressor.flush())
def flip_byte(data: bytes, offset: int) -> bytes:
damaged = bytearray(data)
damaged[offset] ^= 0x55
return bytes(damaged)
def png_idat_byte_changed(data: bytes | None = None) -> bytes:
"""Изменённый байт внутри первого IDAT (CRC чанка не сходится)."""
data = data or sample_png()
return flip_byte(data, data.index(b"IDAT") + 40)
def truncated(data: bytes, keep: float = 0.5) -> bytes:
return data[: int(len(data) * keep)]
def with_tail(data: bytes, tail: bytes = b"TAIL" * 64) -> bytes:
"""Байты после IEND или EOI."""
return data + tail
def _pillow_image(mode: str, size: tuple[int, int]) -> object:
from PIL import Image # noqa: PLC0415 — Pillow только для JPEG
width, height = size
image = Image.new("RGB", size)
image.putdata(
[
((x * 7) % 256, (y * 13) % 256, (x * y) % 256)
for y in range(height)
for x in range(width)
],
)
return image.convert(mode)
def jpeg(
mode: str = "RGB",
size: tuple[int, int] = (64, 48),
**save: object,
) -> bytes:
"""Настоящий JPEG через Pillow; `save` — параметры `Image.save`."""
from PIL import Image # noqa: PLC0415
buffer = io.BytesIO()
image = _pillow_image(mode, size)
if "exif" in save and save["exif"] is True:
exif = Image.Exif()
exif[0x010F] = "student-tests"
exif[0x0112] = 1
save["exif"] = exif
image.save(buffer, "JPEG", **save)
return buffer.getvalue()
def jpeg_huge(width: int, height: int) -> bytes:
"""Маленький JPEG с подменёнными размерами в SOF0."""
data = bytearray(jpeg())
sof = data.index(b"\xff\xc0")
data[sof + 5 : sof + 9] = struct.pack(">HH", height, width)
return bytes(data)
def _jpeg_header(data: bytes) -> list[tuple[int, int, int]]:
"""Сегменты до первого скана включительно: маркер, начало, конец."""
segments = []
pos = 2
while True:
marker = data[pos + 1]
(length,) = struct.unpack_from(">H", data, pos + 2)
segments.append((marker, pos, pos + 2 + length))
pos += 2 + length
if marker == JPEG_SOS:
return segments
def jpeg_without(marker: int, data: bytes | None = None) -> bytes:
"""JPEG без сегментов `marker` (`JPEG_DQT`, `JPEG_DHT`) до первого
скана."""
data = data or jpeg()
out = bytearray(data)
for found, start, end in reversed(_jpeg_header(data)):
if found == marker:
del out[start:end]
return bytes(out)
def jpeg_scan_byte(data: bytes, index: int, value: int) -> bytes:
"""Байт `index` тела первого SOS заменён на `value`: 1 — id первой
компоненты, -3, -2, -1 — Ss, Se и Ah/Al."""
_, start, end = _jpeg_header(data)[-1]
out = bytearray(data)
out[start + 4 + index if index >= 0 else end + index] = value
return bytes(out)
def jpeg_empty_scan(data: bytes | None = None) -> bytes:
"""JPEG, у которого за заголовком первого скана сразу EOI."""
data = data or jpeg()
return data[: _jpeg_header(data)[-1][2]] + JPEG_EOI
def png_variants() -> dict[str, bytes]:
"""Разновидности PNG спека: палитра, альфа, серый с альфой, 16 и 1
бит, Adam7."""
return {
"palette": png(color=3, depth=8),
"rgba": png(color=6),
"gray-alpha": png(color=4),
"rgb-16-bit": png(color=2, depth=16),
"gray-1-bit": png(color=0, depth=1),
"adam7": png(37, 29, interlace=True),
}
def jpeg_variants() -> dict[str, bytes]:
"""Разновидности JPEG спека: прогрессивный, серый, CMYK, с EXIF,
baseline без таблиц Хаффмана (кадр Motion JPEG: декодер берёт
стандартные)."""
return {
"progressive": jpeg(progressive=True),
"gray": jpeg("L"),
"cmyk": jpeg("CMYK"),
"exif": jpeg(exif=True),
"no-huffman-tables": jpeg_without(JPEG_DHT),
}
def jpeg_undecodable() -> dict[str, bytes]:
"""JPEG, которые проходят разбор маркеров, но не декодируются или
заведомо оборваны (спек `attachments`, «Недекодируемый JPEG»)."""
progressive = jpeg(progressive=True)
return {
"27 bytes without tables": JPEG_WITHOUT_TABLES,
"no quantization tables": jpeg_without(JPEG_DQT),
"progressive without huffman tables": jpeg_without(
JPEG_DHT,
progressive,
),
"scan of unknown component": jpeg_scan_byte(jpeg(), 1, 9),
# первый скан Pillow — DC трёх компонент; полоса 1–63 делает его
# AC-сканом, а у AC-скана компонента одна
"progressive ac band of 3 components": jpeg_scan_byte(
jpeg_scan_byte(progressive, -3, 1),
-2,
63,
),
"empty scan data": jpeg_empty_scan(),
}
+449
View File
@@ -0,0 +1,449 @@
"""`make failure_checks`: проверки отказов на отдельном стенде.
Поднимает тот же `docker-compose.yml` под проектом `<рабочий>-failures`
с override `student-tests/failures.compose.yml`: свои PostgreSQL, Valkey и
S3 со своими volumes, порты хранилищ не публикуются. Затем:
- собирает образ из рабочего дерева, применяет миграции и bootstrap S3;
- запускает уборщика незавершённых загрузок с grace 20 с и интервалом
1 с (`failures.compose.yml`; design change `upload-consistency`,
решение 10) без плановой сверки (design change `track2-reconciler`,
решение 9) и передаёт значения тестам; уборщика с плановой сверкой
`<проект>-cleaner-scheduled` запускает hook и убирает этот скрипт;
- запускает четыре контейнера API: обычный (с `MAX_UPLOAD_BYTES=1` и
`MAX_IMAGE_PIXELS=1` в окружении — лимиты вложений от них не зависят),
«тесный» (сроки сессии и ключа идемпотентности 2 с, пул из одного
соединения), «узкий по загрузкам» (одно место загрузки, одна в
очереди, ожидание места 1 с, срок тела 3 с; change `upload-memory`) и
«с коротким сроком S3» (срок вызова S3 1 с; change
`fix-upload-put-flake`);
- прогоняет тесты с маркером `fault` (`pytest -m fault`), передав им hook
`student-tests/fault_hook.py`; при падении печатает журналы API и
уборщика;
- после тестов читает журнал PostgreSQL стенда: печатает сводку и падает
на признаках аварийного перезапуска (решение 12 design change
`fix-known-issues`);
- удаляет стенд вместе с volume при любом исходе, в том числе по Ctrl+C.
Рабочий стенд, его база, кэш и хранилище объектов не затрагиваются. Только stdlib. Решения
1, 2, 5 design change `failure-checks`. Запускается `$(PYTHON)`, а не
`uv run`, по той же причине, что `run_isolated.py`.
"""
from __future__ import annotations
import json
import os
import signal
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ENV_FILE = ROOT / ".env"
COMPOSE_FILES = (
ROOT / "docker-compose.yml",
ROOT / "student-tests" / "failures.compose.yml",
)
FAULT_HOOK = ROOT / "student-tests" / "fault_hook.py"
PROJECT_SUFFIX = "-failures"
READY_TIMEOUT_S = 60
LOG_TAIL_LINES = 50
# признаки аварийного перезапуска PostgreSQL: postmaster счёл аварией выход
# неизвестного потомка, завершил все процессы и восстанавливается. Штатные
# stop / start дают «database system was shut down», обрыв backend — FATAL
CRASH_MARKERS = (
"untracked child process",
"terminating any other active server processes",
"reinitializing",
"automatic recovery in progress",
)
CRASH_LINES_MAX = 20
# «тесный» API: короткие сроки сессии и ключа идемпотентности, пул из
# одного соединения
TIGHT_ENV = {
"AUTH__SESSION_TTL_SECONDS": "2",
"IDEMPOTENCY__TTL_SECONDS": "2",
"DATABASE__POOL_SIZE": "1",
"DATABASE__MAX_OVERFLOW": "0",
"DATABASE__POOL_TIMEOUT_SECONDS": "1",
"DATABASE__REQUEST_TIMEOUT_SECONDS": "2",
}
# обычный API: имена лимитов skeleton с заведомо малыми значениями. Лимиты
# вложений — константы контракта, и окружение их не меняет (спек
# `service-configuration`, «Окружение не меняет лимит»): тест грузит
# `sample.png` и ждёт 201. Те же пары тест получает в
# `FAULT_LIMITS_ENV` и сверяет, что стенд запущен с ними
LIMITS_ENV = {
"MAX_UPLOAD_BYTES": "1",
"MAX_IMAGE_PIXELS": "1",
}
# «узкий по загрузкам» API (change upload-memory, design, решение 11): одно
# место загрузки, одна загрузка в очереди, ожидание места 1 с, срок тела
# 3 с: держатель места в test_upload_slots_busy отпускается через ~1,3–1,5 с
# после того, как занял место (ожидавшая получает 429 через 1 с), и срок
# тела должен оставить запас (с 2 с он был ~0,5 с; verify, S5). Те же пары
# тест получает в `FAULT_UPLOADS_ENV` и сверяет, что стенд запущен с ними
UPLOADS_ENV = {
"UPLOADS__MAX_CONCURRENT": "1",
"UPLOADS__MAX_WAITING": "1",
"UPLOADS__WAIT_TIMEOUT_SECONDS": "1",
"UPLOADS__BODY_TIMEOUT_SECONDS": "3",
}
# API «с коротким сроком S3» (change fix-upload-put-flake, design, решение
# 3): срок вызова S3 1 с, и простой дольше срока в test_upload_after_idle_s3
# — 1,5 с, а не 6. Других тестов на нём нет: пул S3 процесса — только от
# этого теста. Те же пары тест получает в `FAULT_S3_ENV` и сверяет стенд
S3_ENV = {
"S3__TIMEOUT_SECONDS": "1",
}
def say(message: str) -> None:
print(f"[failure_checks] {message}", flush=True)
def run(
*args: str,
check: bool = True,
quiet: bool = False,
env: dict[str, str] | None = None,
) -> subprocess.CompletedProcess[str]:
"""Команда из корня репозитория; вывод — в терминал, если не quiet."""
return subprocess.run(
args,
cwd=ROOT,
check=check,
text=True,
capture_output=quiet,
env=env,
)
def dc(
project: str,
*args: str,
check: bool = True,
quiet: bool = False,
) -> subprocess.CompletedProcess[str]:
"""docker compose проекта отказов; без `-p` не вызывается никогда."""
files = [arg for path in COMPOSE_FILES for arg in ("-f", str(path))]
return run(
"docker",
"compose",
"-p",
project,
*files,
*args,
check=check,
quiet=quiet,
)
def working_project() -> str:
config = run("docker", "compose", "config", "--format", "json", quiet=True)
return json.loads(config.stdout)["name"]
def app_port() -> str:
"""`APP__PORT` из `.env`: на нём слушает API внутри контейнера."""
if ENV_FILE.exists():
for line in ENV_FILE.read_text(encoding="utf-8").splitlines():
if line.strip().startswith("APP__PORT="):
return line.split("=", 1)[1].strip()
return "8080"
def storage_names(project: str) -> dict[str, str]:
"""Bucket и имя базы стенда — из окружения сервиса `api` в его
конфигурации compose: по ним hook считает объекты вложений."""
config = dc(project, "config", "--format", "json", quiet=True)
environment = json.loads(config.stdout)["services"]["api"]["environment"]
return {
"FAULT_S3_BUCKET": environment["S3__BUCKET"],
"FAULT_DATABASE": environment["DATABASE__NAME"],
}
def cleaner_timings(project: str) -> dict[str, str]:
"""Grace и интервал уборщика стенда — из окружения сервиса `cleaner`
в конфигурации compose (`failures.compose.yml`): тесты ждут по ним."""
config = dc(project, "config", "--format", "json", quiet=True)
environment = json.loads(config.stdout)["services"]["cleaner"][
"environment"
]
return {
"FAULT_CLEANER_GRACE_S": environment["CLEANER__PENDING_GRACE_SECONDS"],
"FAULT_CLEANER_INTERVAL_S": environment["CLEANER__INTERVAL_SECONDS"],
"FAULT_RECONCILER_INTERVAL_S": environment[
"RECONCILER__INTERVAL_SECONDS"
],
}
def env_pairs(env: dict[str, str]) -> str:
"""`KEY=value` через пробел: так окружение API получают тесты."""
return " ".join(f"{key}={value}" for key, value in env.items())
def free_port() -> int:
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def wait_ready(url: str, container: str) -> None:
deadline = time.monotonic() + READY_TIMEOUT_S
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(url, timeout=2) as response:
if response.status == 200:
return
except (urllib.error.URLError, OSError):
pass
state = run(
"docker",
"inspect",
"-f",
"{{.State.Running}}",
container,
check=False,
quiet=True,
)
if state.stdout.strip() != "true":
raise RuntimeError(f"container {container} is not running")
time.sleep(1)
raise RuntimeError(f"{url} not ready in {READY_TIMEOUT_S}s")
def leftovers(project: str, kind: str) -> str:
"""Контейнеры (`ps -a`) или volume проекта, которые ещё остались."""
command = ("ps", "-aq") if kind == "container" else ("volume", "ls", "-q")
return run(
"docker",
*command,
"--filter",
f"label=com.docker.compose.project={project}",
quiet=True,
check=False,
).stdout.strip()
def cleanup(project: str, containers: list[str]) -> bool:
"""Контейнеры API, сервисы и volume проекта отказов; True — чисто."""
for name in containers:
run("docker", "rm", "-f", name, check=False, quiet=True)
down = dc(project, "down", "-v", "--remove-orphans", check=False)
return (
down.returncode == 0
and not leftovers(project, "container")
and not leftovers(project, "volume")
)
def postgres_log_check(project: str) -> int:
"""Журнал PostgreSQL стенда отказов: сводка всегда, признаки аварии —
строками; 1 — признаки есть или журнал не прочитан. Два счётчика
FATAL показывают, что заполнение и освобождение слотов правда были."""
log = dc(
project,
"logs",
"--no-log-prefix",
"postgres",
check=False,
quiet=True,
)
if log.returncode != 0:
# сбой чтения журнала — не сбой подготовки стенда
tail = log.stderr.strip().splitlines()[-1:] or ["no stderr"]
say(
f"postgres log unavailable: docker compose logs exited "
f"{log.returncode}: {tail[0]}",
)
return 1
lines = (log.stdout + log.stderr).splitlines()
crashes = [line for line in lines if any(m in line for m in CRASH_MARKERS)]
too_many = sum("too many clients" in line for line in lines)
admin = sum("administrator command" in line for line in lines)
say(
f"postgres log: {len(lines)} lines, crash markers {len(crashes)}; "
f'"too many clients" {too_many}, "administrator command" {admin}',
)
if not crashes:
return 0
say("crash markers in the postgres log:")
for line in crashes[:CRASH_LINES_MAX]:
print(line, flush=True)
return 1
def start_api(
project: str,
name: str,
port: int,
env: dict[str, str],
) -> str:
env_args = [
arg for key, value in env.items() for arg in ("-e", f"{key}={value}")
]
dc(
project,
"run",
"-d",
"--no-deps",
"--name",
name,
*env_args,
"-p",
f"127.0.0.1:{port}:{app_port()}",
"api",
quiet=True,
)
base_url = f"http://127.0.0.1:{port}"
wait_ready(f"{base_url}/health/ready", name)
return base_url
def main() -> int:
pytest_args = sys.argv[1:]
working = working_project()
project = f"{working}{PROJECT_SUFFIX}"
if project == working or not project.endswith(PROJECT_SUFFIX):
say(f"refusing to use project {project!r}")
return 2
default_name = f"{project}-api"
tight_name = f"{project}-api-tight"
uploads_name = f"{project}-api-uploads"
s3_name = f"{project}-api-s3"
# уборщик с плановой сверкой — его запускает hook run-cleaner (design
# change track2-reconciler, решение 11); убирается вместе с API
scheduled_name = f"{project}-cleaner-scheduled"
containers = [
default_name,
tight_name,
uploads_name,
s3_name,
scheduled_name,
]
say(f"project={project} (working stand: {working})")
if not cleanup(project, containers):
say("leftovers of a previous run could not be removed")
return 1
results: dict[str, int] = {}
failed = True
try:
say("build image")
dc(project, "build", "api")
say("start postgres, valkey and s3")
dc(project, "up", "-d", "--wait", "postgres", "valkey", "s3")
say("migrations")
dc(project, "run", "--rm", "migrate")
# --wait одноразовый сервис считает готовым уже запущенным: код
# выхода bootstrap — отдельным up, как make start_s3
say("s3 bootstrap")
dc(
project,
"up",
"--no-deps",
"--exit-code-from",
"s3-bootstrap",
"s3-bootstrap",
)
timings = cleaner_timings(project)
say(
f"start cleaner: grace {timings['FAULT_CLEANER_GRACE_S']} s, "
f"interval {timings['FAULT_CLEANER_INTERVAL_S']} s, "
"reconcile interval "
f"{timings['FAULT_RECONCILER_INTERVAL_S']} s (0 — off)",
)
dc(project, "up", "-d", "--no-deps", "cleaner")
say("start api containers")
base_url = start_api(project, default_name, free_port(), LIMITS_ENV)
tight_url = start_api(project, tight_name, free_port(), TIGHT_ENV)
uploads_url = start_api(
project,
uploads_name,
free_port(),
UPLOADS_ENV,
)
s3_url = start_api(project, s3_name, free_port(), S3_ENV)
say(
f"ready: api={base_url} tight={tight_url} uploads={uploads_url} "
f"s3={s3_url}",
)
env = (
os.environ
| {
"BASE_URL": base_url,
"FAULT_TIGHT_BASE_URL": tight_url,
"FAULT_UPLOADS_BASE_URL": uploads_url,
"FAULT_S3_BASE_URL": s3_url,
"FAULT_HOOK": str(FAULT_HOOK),
"FAULT_PROJECT": project,
"FAULT_LIMITS_ENV": env_pairs(LIMITS_ENV),
"FAULT_UPLOADS_ENV": env_pairs(UPLOADS_ENV),
"FAULT_S3_ENV": env_pairs(S3_ENV),
}
| storage_names(project)
| timings
)
say("pytest -m fault")
results["fault"] = run(
"uv",
"run",
"pytest",
"-m",
"fault",
*pytest_args,
check=False,
env=env,
).returncode
failed = bool(results["fault"])
# стенд ещё жив: журнал PostgreSQL до уборки
results["postgres"] = postgres_log_check(project)
except KeyboardInterrupt:
say("interrupted")
results["interrupted"] = 130
except (subprocess.CalledProcessError, RuntimeError) as e:
say(f"setup failed: {e}")
results["setup"] = 1
finally:
# повторный Ctrl+C не должен оборвать уборку на полпути
signal.signal(signal.SIGINT, signal.SIG_IGN)
if failed:
for name in containers:
say(f"last {LOG_TAIL_LINES} lines of {name}")
run(
"docker",
"logs",
"--tail",
str(LOG_TAIL_LINES),
name,
check=False,
)
say(f"last {LOG_TAIL_LINES} lines of cleaner")
dc(
project,
"logs",
"--no-log-prefix",
"--tail",
str(LOG_TAIL_LINES),
"cleaner",
check=False,
)
say("cleanup")
if not cleanup(project, containers):
say("cleanup failed")
results["cleanup"] = 1
say(f"results: {results}")
return next((code for code in results.values() if code), 0)
if __name__ == "__main__":
sys.exit(main())
+315
View File
@@ -0,0 +1,315 @@
"""`make test_isolated`: образ на временной базе `test_<db>`.
Создаёт базу в Postgres стенда, накатывает на неё миграции сервисом
`migrate`, поднимает отдельный контейнер `api` из определения compose с
подменой только `DATABASE__NAME`, прогоняет `make test` и
`make student_test` (`EXPECT_REPLICAS=1`: один процесс без
балансировщика, тесты реплик пропускаются), затем удаляет контейнер и
базу — при любом исходе, в том числе по Ctrl+C. Рабочая база и рабочие
контейнеры стенда не трогаются. Valkey стенда общий: ключи кэша включают имя базы, и
карточки тестового прогона не смешиваются с рабочими. S3 стенда тоже
общий: ключи объектов начинаются с имени базы, и префикс `test_<db>/`
bucket удаляется в начале (хвост прошлого прогона) и в уборке через
`weed shell` в контейнере `s3` (design change `s3-storage`, решение 9).
Только stdlib: всё через docker compose и make. Решение 12 design change
`postgres-storage`.
Запускается напрямую `$(PYTHON)`, как проверки skeleton, а не через
`uv run`: uv пересылает SIGINT дочернему процессу, хотя тот уже получил
его от группы процессов, и второй `KeyboardInterrupt` обрывал уборку.
"""
from __future__ import annotations
import argparse
import json
import re
import signal
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ENV_FILE = ROOT / ".env"
DB_NAME_RE = re.compile(r"^[a-z0-9_]+$")
# префикс объектов S3 собирается только из такого имени временной базы:
# ошибка в имени не может удалить рабочий префикс
TEST_DB_NAME_RE = re.compile(r"^test_[a-z0-9_]+$")
# как S3_BUCKET_NAME_PATTERN в src/utils/constants.py
BUCKET_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$")
DEFAULT_BUCKET = "messenger"
# fs.rm отсутствующего пути: «rm: <путь>: filer: no entry is found in filer
# store» — не ошибка уборки
WEED_NO_ENTRY = "no entry is found"
READY_TIMEOUT_S = 60
LOG_TAIL_LINES = 50
def say(message: str) -> None:
print(f"[test_isolated] {message}", flush=True)
def run(
*args: str,
check: bool = True,
stdin: str | None = None,
quiet: bool = False,
) -> subprocess.CompletedProcess[str]:
"""Команда из корня репозитория; вывод — в терминал, если не quiet."""
return subprocess.run(
args,
cwd=ROOT,
check=check,
input=stdin,
text=True,
capture_output=quiet,
)
def read_env() -> dict[str, str]:
"""`KEY=VALUE` из `.env`; подстановок `${...}` нужные ключи не имеют."""
values: dict[str, str] = {}
for line in ENV_FILE.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
values[key.strip()] = value.strip()
return values
def compose_project() -> str:
config = run(
"docker",
"compose",
"config",
"--format",
"json",
quiet=True,
)
return json.loads(config.stdout)["name"]
def psql(sql: str) -> None:
"""SQL в служебной базе `postgres` под `POSTGRES_USER` контейнера."""
run(
"docker",
"compose",
"exec",
"-T",
"postgres",
"sh",
"-c",
'exec psql -U "$POSTGRES_USER" -d postgres -v ON_ERROR_STOP=1 -X -q',
stdin=sql,
)
def drop_database(name: str) -> None:
# WITH (FORCE) рвёт оставшиеся соединения, если контейнер не ушёл
psql(f'DROP DATABASE IF EXISTS "{name}" WITH (FORCE);\n')
def object_prefix(bucket: str, test_db: str) -> str:
"""Путь filer префикса `test_<db>/` в bucket; другое имя — отказ."""
if not TEST_DB_NAME_RE.fullmatch(test_db):
raise ValueError(f"not a test database name: {test_db}")
if not BUCKET_NAME_RE.fullmatch(bucket):
raise ValueError(f"invalid bucket name: {bucket}")
return f"/buckets/{bucket}/{test_db}"
def weed_shell(command: str) -> str:
"""Одна команда `weed shell` в контейнере `s3`: ключ подписи — в его
окружении, master и filer — на его loopback. Вывод — stdout и stderr
вместе."""
result = run(
"docker",
"compose",
"exec",
"-T",
"s3",
"sh",
"-c",
"exec weed shell -master=127.0.0.1:9333 2>&1",
stdin=f"{command}\n",
quiet=True,
)
return result.stdout
def remove_objects(prefix: str) -> None:
"""Удалить объекты под префиксом временной базы; его отсутствие — не
ошибка. `weed shell` выходит с кодом 0 и при ошибке команды, поэтому
успех проверяется отдельно: строк `rm:` с ошибкой нет, и `fs.ls`
префикса пуст. Иначе — `RuntimeError` с первой строкой ошибки."""
removed = weed_shell(f"fs.rm -r {prefix}")
# отсутствие префикса fs.rm печатает так же строкой rm: — это не ошибка
errors = [
line
for line in removed.splitlines()
if line.startswith("rm:") and WEED_NO_ENTRY not in line
]
left = [
line for line in weed_shell(f"fs.ls {prefix}").splitlines() if line
]
if errors or left:
detail = errors[0] if errors else f"{len(left)} entries left"
raise RuntimeError(f"objects {prefix}/ not removed: {detail}")
def remove_container(name: str) -> None:
run("docker", "rm", "-f", name, check=False, quiet=True)
def wait_ready(url: str, container: str) -> None:
deadline = time.monotonic() + READY_TIMEOUT_S
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(url, timeout=2) as response:
if response.status == 200:
return
except (urllib.error.URLError, OSError):
pass
state = run(
"docker",
"inspect",
"-f",
"{{.State.Running}}",
container,
check=False,
quiet=True,
)
if state.stdout.strip() != "true":
raise RuntimeError(f"container {container} is not running")
time.sleep(1)
raise RuntimeError(f"{url} not ready in {READY_TIMEOUT_S}s")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"--keep-db",
action="store_true",
help="не удалять базу после прогона (KEEP_TEST_DB=1)",
)
args = parser.parse_args()
env = read_env()
test_db = f"test_{env['POSTGRES_DB']}"
if not DB_NAME_RE.fullmatch(test_db):
say(f"unsupported database name: {test_db}")
return 2
try:
prefix = object_prefix(env.get("S3__BUCKET", DEFAULT_BUCKET), test_db)
except ValueError as e:
say(str(e))
return 2
port = env["TEST_APP_PORT"]
app_port = env.get("APP__PORT", "8080")
container = f"{compose_project()}-test-api"
base_url = f"http://127.0.0.1:{port}"
say(
f"database={test_db} objects={prefix}/ container={container} "
f"base_url={base_url}",
)
remove_container(container)
drop_database(test_db)
say(f"remove objects {prefix}/")
try:
remove_objects(prefix)
except (subprocess.CalledProcessError, RuntimeError) as e:
say(f"setup failed: {e}")
return 1
results: dict[str, int] = {}
failed = True
try:
say("build image")
run("docker", "compose", "build", "api")
say(f"create database {test_db}")
psql(f'CREATE DATABASE "{test_db}";\n')
say("migrations")
run(
"docker",
"compose",
"run",
"--rm",
"--no-deps",
"-e",
f"DATABASE__NAME={test_db}",
"migrate",
)
say("start api container")
run(
"docker",
"compose",
"run",
"-d",
"--no-deps",
"--name",
container,
"-e",
f"DATABASE__NAME={test_db}",
"-p",
f"127.0.0.1:{port}:{app_port}",
"api",
quiet=True,
)
wait_ready(f"{base_url}/health/ready", container)
say("ready")
for target in ("test", "student_test"):
say(f"make {target}")
results[target] = run(
"make",
target,
f"BASE_URL={base_url}",
# один контейнер API без балансировщика: тесты реплик
# пропускаются с причиной
"EXPECT_REPLICAS=1",
check=False,
).returncode
failed = any(results.values())
except KeyboardInterrupt:
say("interrupted")
results["interrupted"] = 130
except (subprocess.CalledProcessError, RuntimeError) as e:
say(f"setup failed: {e}")
results["setup"] = 1
finally:
# повторный Ctrl+C не должен оборвать уборку на полпути
signal.signal(signal.SIGINT, signal.SIG_IGN)
if failed:
say(f"last {LOG_TAIL_LINES} lines of {container}")
run(
"docker",
"logs",
"--tail",
str(LOG_TAIL_LINES),
container,
check=False,
)
say("cleanup")
run("docker", "stop", container, check=False, quiet=True)
remove_container(container)
try:
if args.keep_db:
say(f"kept database {test_db} and objects {prefix}/")
else:
drop_database(test_db)
say(f"remove objects {prefix}/")
remove_objects(prefix)
except (subprocess.CalledProcessError, RuntimeError) as e:
say(f"cleanup failed: {e}")
results["cleanup"] = 1
say(f"results: {results}")
return next((code for code in results.values() if code), 0)
if __name__ == "__main__":
sys.exit(main())
+232
View File
@@ -0,0 +1,232 @@
"""Сверка тестов со сценариями основных спеков `openspec/specs/`."""
import re
from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
SPECS_DIR = ROOT / "openspec" / "specs"
# основные спеки поведения API; спеки контейнера, логов и конфига
# проверяются evidence, а не HTTP-тестами
CAPABILITIES = (
"api-conventions",
"identification",
"sessions",
"users",
"chats",
"messages",
"pagination",
"data-storage",
"chat-cache",
"health",
"idempotency",
"attachments",
# уборщик: все сценарии — проверки отказов (design change
# upload-consistency, решение 10)
"storage-consistency",
)
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",
),
("api-conventions", "Instance id в ответе 500"): Exclusion(
reason="нужен сбой внутри сервиса, как для «Ответ 500»",
check="тот же ручной сбой: у ответа 500 есть X-Instance-Id "
"процесса; обработчик Exception — src/api/errors.py",
),
("idempotency", "Повтор после рестарта API"): Exclusion(
reason="нужен новый процесс API, тесты сервер не трогают",
check="отправка с ключом, docker compose up -d --force-recreate "
"api, повтор: другой X-Instance-Id, тот же Message — "
"evidence/idempotency/replay-after-restart.md",
),
("chat-cache", "Чтение из кэша"): Exclusion(
reason="по HTTP ответ из кэша не отличить от ответа из PostgreSQL",
check="driver.py --port <LB> cache-check скилла "
"run-mtusi-messenger: чтения таблицы chats (seq_scan + idx_scan) "
"и keyspace_hits Valkey за 50 чтений через LB — "
"evidence/cache/hits.md",
),
("chat-cache", "Срок записи"): Exclusion(
reason="срок ключа виден только в Valkey",
check="driver.py --port <LB> cache-check: TTL ключа карточки не "
"больше настроенного и чтениями не продлевается — "
"evidence/cache/hits.md",
),
("chat-cache", "Временная база"): Exclusion(
reason="ключи видны только в Valkey, а набор не знает, на какой "
"базе работает",
check="make test_isolated, затем driver.py --port <LB> "
"cache-check --require-test-keys (без ключей тестовой базы — код "
"1): число ключей с префиксами рабочей и тестовой базы — "
"evidence/cache/hits.md",
),
("data-storage", "Прежний пользователь после рестарта"): Exclusion(
reason="нужен рестарт стенда, тесты сервер не трогают",
check="make test-persistence ACTION_SCRIPT=scripts/restart.sh: "
"прежний токен читает те же данные — "
"evidence/replicas/test-persistence.md",
),
("identification", "Кнопка Authorize в Swagger"): Exclusion(
reason="это интерфейс /docs в браузере",
check="схемы bearerAuth и basicAuth, из которых строится кнопка, "
"проверяет тест сценария «Схема в openapi.json»; кнопку — вручную "
"(REPORT.md, таблица доказательств)",
),
("sessions", "Токена нет в хранилище"): Exclusion(
reason="нужен доступ к таблицам PostgreSQL, а тесты ходят по HTTP",
check="driver.py --port <LB> auth-storage скилла "
"run-mtusi-messenger: token_hash — SHA-256 токена, самого токена "
"нет в pg_dump базы — evidence/auth/passwords-and-tokens.md",
),
("sessions", "Прежний токен после рестарта"): Exclusion(
reason="нужен рестарт стенда, тесты сервер не трогают",
check="make test-persistence ACTION_SCRIPT=scripts/restart.sh — "
"evidence/replicas/test-persistence.md",
),
("attachments", "Принявшая реплика остановлена"): Exclusion(
reason="нужно остановить реплику API, тесты стенд не трогают",
check="driver.py --port <LB> attachment-failover [--mode stop|kill] "
"скилла run-mtusi-messenger: загрузка через LB, scripts/stop-one.sh "
"реплики ответа, скачивание через другую с тем же SHA-256, 404 "
"постороннему — evidence/attachments/failover.md",
),
("attachments", "Байты не в БД и не на диске API"): Exclusion(
reason="нужен взгляд в схему PostgreSQL, bucket S3 и файловые "
"системы контейнеров, а тесты ходят по HTTP",
check="driver.py --port <LB> attachment-storage: колонки таблиц "
"вложений, вид object_key, объект в bucket, анонимный GET — 403, "
"docker diff реплик — evidence/attachments/storage.md",
),
("attachments", "Рестарт стенда"): Exclusion(
reason="нужен рестарт стенда, тесты сервер не трогают",
check="make test-persistence ACTION_SCRIPT=scripts/restart.sh: с "
"LAB=4 проверка скачивает тот же оригинал прежним токеном — "
"evidence/replicas/test-persistence.md",
),
("attachments", "Одна копия тела при записи в S3"): Exclusion(
reason="нужен пик памяти cgroup реплики под одновременными "
"загрузками и образ кода до change upload-memory, а тесты ходят "
"по HTTP",
check="make bench_uploads (профиль uploads стенда bench/): "
"варианты «до» и «без лимита» при 10 клиентах по 10 MiB, пик окна "
"над памятью до загрузок в телах на загрузку — "
"evidence/uploads/baseline/summary.md",
),
("attachments", "Память не растёт с числом загрузок"): Exclusion(
reason="нужен пик памяти cgroup реплики, реплика без swap и "
"завершение ядром из-за памяти, а тесты ходят по HTTP",
check="make bench_uploads: вариант «с лимитом» при 10, 20 и 40 "
"клиентах по 10 MiB — пик окна, oom, ответы по кодам — "
"evidence/uploads/baseline/summary.md",
),
("users", "Хэш в БД"): Exclusion(
reason="нужен доступ к таблице users, а тесты ходят по HTTP",
check="driver.py --port <LB> auth-storage: префикс $argon2id$ и "
"разные хэши одинаковых паролей, пароля нет в pg_dump базы — "
"evidence/auth/passwords-and-tokens.md",
),
}
# ссылка исключения на доказательство в репозитории лабы
EVIDENCE_RE = re.compile(r"evidence/[\w./-]+\.md")
@dataclass
class Collected:
"""Что собрал pytest: маркеры `spec`, модули тестов и сценарии,
которые проверяют тесты `fault` (их выполняет только
`make failure_checks`)."""
marks: dict[Scenario, list[str]] = field(default_factory=dict)
modules: set[str] = field(default_factory=set)
fault: set[Scenario] = 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
def missing_evidence(
excluded: Mapping[Scenario, Exclusion],
root: Path = ROOT,
) -> list[str]:
"""Ссылки исключений на файлы `evidence/`, которых нет в репозитории.
`evidence/` в следующую лабу не переносится: доказательство снимается
заново на её стенде, иначе ссылка повисла бы молча (design change
`fix-known-issues`, решение 2)."""
return [
f"exclusion refers to missing {path}: {capability} / {scenario}"
for (capability, scenario), exclusion in sorted(excluded.items())
for path in EVIDENCE_RE.findall(exclusion.check)
if not (root / path).is_file()
]
+460
View File
@@ -0,0 +1,460 @@
"""Спек `api-conventions`: JSON, ошибки, X-Request-Id, X-Instance-Id,
форматы."""
import json
import urllib.parse
import uuid
from collections import Counter
from typing import Any
import httpx
import pytest
import images
from api_client import (
API,
Actor,
Api,
new_key,
registration,
unique_username,
)
from contract import (
assert_content,
assert_created_at,
assert_error,
assert_errors,
assert_instance_id,
assert_ok,
assert_uuid,
json_body,
)
UNICODE_TEXT = "Привет, мир 👋"
# не UUID в пути: типы JSON, записанные строкой URL
NOT_UUID_PATHS = ("123", "false", "[]", "{}")
# не UUID в элементе member_ids: значения других типов JSON
NOT_UUID_VALUES: tuple[Any, ...] = ([], {}, 123, False)
@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.post_message(alice, chat["id"], 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
def business_responses(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> list[tuple[httpx.Response, int]]:
"""Успехи 200 и 201 и ошибки 400, 401, 404 и 409 — с ожидаемым
статусом."""
key = new_key()
sent = api.post_message(alice, chat["id"], key=key, json={"text": "a"})
return [
(api.request("GET", f"{API}/users/me", actor=alice), 200),
(sent, 201),
(api.request("GET", f"{API}/chats/nope", actor=alice), 400),
(api.request("GET", f"{API}/users/me"), 401),
(api.request("GET", f"{API}/chats/{chat['id']}", actor=eve), 404),
(
api.post_message(alice, chat["id"], key=key, json={"text": "b"}),
409,
),
]
def service_responses(api: Api) -> list[tuple[httpx.Response, int]]:
"""Health, неизвестный путь и неподдерживаемый метод."""
return [
(api.request("GET", "/health/live"), 200),
(api.request("GET", "/health/ready"), 200),
(api.request("GET", f"{API}/unknown"), 404),
(api.request("DELETE", f"{API}/users"), 405),
]
@pytest.mark.spec("api-conventions", "Instance id в успешном ответе и ошибке")
def test_instance_id_on_success_and_error(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
for resp, status in business_responses(api, alice, eve, chat):
assert resp.status_code == status, resp.text
assert_instance_id(resp)
@pytest.mark.spec(
"api-conventions",
"Instance id в health и служебных ответах",
)
def test_instance_id_on_service_responses(api: Api) -> None:
for resp, status in service_responses(api):
assert resp.status_code == status, resp.text
assert_instance_id(resp)
@pytest.mark.spec("api-conventions", "Одно значение на процесс")
def test_one_instance_id_per_process(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
expect_replicas: int,
) -> None:
"""Две одинаковые серии по 18 разных запросов. Против одного процесса
— одно значение на всё. Через балансировщик (round-robin, до 8
реплик) каждая реплика отвечает в серии хотя бы дважды: значение,
новое на каждый запрос, не прошло бы ни одну проверку."""
def series() -> list[str]:
responses = business_responses(api, alice, eve, chat)
for _ in range(3):
responses += service_responses(api)
return [assert_instance_id(resp) for resp, _ in responses]
first, second = series(), series()
counts = Counter(first + second)
print(f"two series of {len(first)} requests: {dict(counts)}")
if expect_replicas < 2:
assert len(counts) == 1, f"one process answered with {set(counts)}"
return
assert all(served > 1 for served in counts.values()), counts
assert set(second) <= set(first), (
f"new X-Instance-Id in the second series: {set(second) - set(first)}"
)
@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=registration(alice.username, "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=registration("ab", "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={**registration(unique_username(), "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=registration(username, 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"])
def other_uuid_forms(value: str) -> dict[str, str]:
"""Тот же UUID в записях, которых нет в `format: uuid` контракта."""
return {
"no hyphens": value.replace("-", ""),
"urn": f"urn:uuid:{value}",
"braces": f"{{{value}}}",
}
def chat_id_requests(
api: Api,
actor: Actor,
chat_id: str,
) -> dict[str, httpx.Response]:
"""Три ручки с `chat_id` в пути; значение кодируется для URL явно."""
quoted = urllib.parse.quote(chat_id, safe="")
return {
"GET chat": api.request("GET", f"{API}/chats/{quoted}", actor=actor),
"GET history": api.messages_page(actor, quoted),
"POST message": api.post_message(
actor,
quoted,
json={"text": "path"},
),
}
def post_chat(
api: Api,
actor: Actor,
title: str,
member_ids: list[Any],
) -> httpx.Response:
return api.request(
"POST",
f"{API}/chats",
actor=actor,
json={"title": title, "member_ids": member_ids},
)
def chat_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("api-conventions", "UUID другого типа в теле")
def test_uuid_of_other_type_in_body(api: Api, alice: Actor) -> None:
title = f"rejected-{uuid.uuid4().hex}"
# рядом с id Алисы: иначе 400 дала бы и проверка «вызывающий в списке»
assert_errors(
{
repr(value): post_chat(api, alice, title, [alice.id, value])
for value in NOT_UUID_VALUES
},
400,
)
assert title not in chat_titles(api, alice)
@pytest.mark.spec("api-conventions", "Не UUID в пути")
def test_not_uuid_in_path(api: Api, alice: Actor) -> None:
assert_errors(
{
f"{name} {value}": resp
for value in NOT_UUID_PATHS
for name, resp in chat_id_requests(api, alice, value).items()
},
400,
)
@pytest.mark.spec("api-conventions", "Другая запись UUID")
def test_other_uuid_forms(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
history = api.all_messages(alice, chat["id"])
title = f"rejected-{uuid.uuid4().hex}"
responses = {
f"{name} / {form}": resp
for form, value in other_uuid_forms(chat["id"]).items()
for name, resp in chat_id_requests(api, alice, value).items()
}
responses |= {
f"member_ids / {form}": post_chat(api, alice, title, [alice.id, value])
for form, value in other_uuid_forms(bob.id).items()
}
assert_errors(responses, 400)
assert api.all_messages(alice, chat["id"]) == history
assert title not in chat_titles(api, alice)
@pytest.mark.spec("api-conventions", "UUID в верхнем регистре в пути")
def test_upper_case_uuid_in_path(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
upper = chat["id"].upper()
got = api.request("GET", f"{API}/chats/{upper}", actor=alice)
# assert_ok проверяет и формат: id и chat_id в ответах — нижний регистр
assert assert_ok(got, 200, "Chat") == chat
sent = assert_ok(
api.post_message(alice, upper, json={"text": "upper"}),
201,
"Message",
)
assert sent["chat_id"] == chat["id"]
upper_page = assert_ok(api.messages_page(alice, upper), 200, "MessagePage")
lower_page = assert_ok(
api.messages_page(alice, chat["id"]),
200,
"MessagePage",
)
assert upper_page == lower_page == {"items": [sent], "next_cursor": None}
@pytest.mark.spec("api-conventions", "Лимит и тип вложения")
def test_attachment_limit_and_type_codes(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
over = images.png_of_size(images.MAX_BYTES + 1)
assert_error(api.post_attachment(alice, chat["id"], over), 413)
text = "не картинка".encode()
assert_error(api.post_attachment(alice, chat["id"], text), 415)
def attachment_requests(
api: Api,
actor: Actor,
attachment_id: str,
) -> dict[str, httpx.Response]:
quoted = urllib.parse.quote(attachment_id, safe="")
return {
"meta": api.attachment_meta(actor, quoted),
"content": api.attachment_content(actor, quoted),
}
@pytest.mark.spec("api-conventions", "Идентификаторы вложений в другой записи")
def test_attachment_ids_in_other_forms(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment = api.upload(alice, chat["id"], images.sample_png())
responses = {
f"{name} / {form}": resp
for form, value in other_uuid_forms(attachment["id"]).items()
for name, resp in attachment_requests(api, alice, value).items()
}
responses |= {
f"attachment_ids / {form}": api.post_message(
alice,
chat["id"],
json={"text": "x", "attachment_ids": [value]},
)
for form, value in other_uuid_forms(attachment["id"]).items()
}
assert_errors(responses, 400)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec(
"api-conventions",
"Идентификаторы вложений в верхнем регистре",
)
def test_attachment_ids_in_upper_case(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data)
upper = attachment["id"].upper()
meta = assert_ok(api.attachment_meta(alice, upper), 200, "Attachment")
assert meta == attachment
assert_content(api.attachment_content(alice, upper), data, "image/png")
message = api.send_message(alice, chat["id"], "x", attachment_ids=[upper])
assert message["attachment_ids"] == [attachment["id"]]
+768
View File
@@ -0,0 +1,768 @@
"""Спек `attachments`: загрузка, лимиты, тип и целостность, имя файла,
доступ, метаданные, скачивание, повтор, реплики.
Проверки отказов S3 — `test_failures.py`; сценарии, которым нужен стенд
(остановка реплики, рестарт, взгляд в БД и bucket), — исключения сверки
покрытия (`spec_coverage.py`).
"""
import hashlib
import threading
import time
import urllib.parse
import uuid
from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor
from typing import Any
import pytest
import images
from api_client import API, Actor, Api
from contract import (
BEARER_CHALLENGE,
assert_content,
assert_error,
assert_errors,
assert_instance_id,
assert_no_storage_traces,
assert_ok,
assert_replicas,
assert_unauthorized,
)
# больше лимита в 3 раза: 30 MiB
BIG_BYTES = 30 * 1024 * 1024
# сколько скачиваний ждать ответа другой реплики (round-robin LB)
REPLICA_ATTEMPTS = 20
# одновременные загрузки сценария «Загрузки в пределах лимита»
CONCURRENT_UPLOADS = 10
# срок клиента загрузки: больше ожидания места (5 с) и сроков шагов
CONCURRENT_CLIENT_TIMEOUT_S = 30
def chunks(data: bytes, size: int = 1024 * 1024) -> Iterator[bytes]:
"""Тело частями: httpx шлёт его без `Content-Length`."""
for offset in range(0, len(data), size):
yield data[offset : offset + size]
def big_body() -> bytes:
"""30 MiB, которые начинаются как PNG."""
return images.PNG_SIGNATURE + bytes(BIG_BYTES - len(images.PNG_SIGNATURE))
@pytest.mark.spec("attachments", "Загрузка PNG")
def test_upload_png(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data, filename="sample.png")
assert attachment["status"] == "ready"
assert attachment["variants"] == []
assert attachment["error_code"] is None
assert attachment["content_type"] == "image/png"
assert attachment["size_bytes"] == 111817
assert attachment["sha256"] == (
"99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75"
)
@pytest.mark.spec("attachments", "Загрузка JPEG")
def test_upload_jpeg(api: Api, bob: Actor, chat: dict[str, Any]) -> None:
data = images.jpeg(size=(320, 200))
attachment = api.upload(
bob,
chat["id"],
data,
content_type="image/jpeg",
filename="photo.jpg",
)
assert attachment["content_type"] == "image/jpeg"
@pytest.mark.spec("attachments", "Разновидности PNG и JPEG")
def test_image_kinds(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
kinds = [
("image/png", name, data)
for name, data in images.png_variants().items()
] + [
("image/jpeg", name, data)
for name, data in images.jpeg_variants().items()
]
for content_type, name, data in kinds:
attachment = api.upload(
alice,
chat["id"],
data,
content_type=content_type,
filename=f"{name}.img",
)
assert attachment["content_type"] == content_type, name
@pytest.mark.spec("attachments", "Граница размера")
def test_size_boundary(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
exact = images.png_of_size(images.MAX_BYTES)
api.upload(alice, chat["id"], exact)
over = images.png_of_size(images.MAX_BYTES + 1)
assert_error(api.post_attachment(alice, chat["id"], over), 413)
@pytest.mark.spec("attachments", "Заявленный размер больше лимита")
def test_declared_size_over_limit(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
resp = api.post_attachment(alice, chat["id"], big_body())
assert resp.request.headers["Content-Length"] == str(BIG_BYTES)
assert_error(resp, 413)
@pytest.mark.spec("attachments", "Большое тело без Content-Length")
def test_chunked_body_over_limit(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
resp = api.post_attachment(alice, chat["id"], chunks(big_body()))
assert "Content-Length" not in resp.request.headers
assert_error(resp, 413)
@pytest.mark.spec("attachments", "Огромные размеры в маленьком файле")
def test_huge_dimensions(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
assert_errors(
{
"png 8000x5001": api.post_attachment(
alice,
chat["id"],
images.png_huge(8000, 5001),
),
"png 1x40000001": api.post_attachment(
alice,
chat["id"],
images.png_huge(1, 40_000_001),
),
"jpeg 10000x4001": api.post_attachment(
alice,
chat["id"],
images.jpeg_huge(10000, 4001),
content_type="image/jpeg",
),
"jpeg 65535x65535": api.post_attachment(
alice,
chat["id"],
images.jpeg_huge(65535, 65535),
content_type="image/jpeg",
),
},
413,
)
@pytest.mark.spec("attachments", "Ровно 40 млн пикселей")
def test_exactly_max_pixels(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.png(8000, 5000, color=0, depth=1)
api.upload(alice, chat["id"], data)
@pytest.mark.spec("attachments", "Данные длиннее размеров")
def test_decompression_bomb(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
assert_error(
api.post_attachment(alice, chat["id"], images.png_bomb()),
415,
)
@pytest.mark.spec("attachments", "Не изображение")
def test_not_an_image(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
assert_errors(
{
name: api.post_attachment(alice, chat["id"], data)
for name, data in (
("text", "просто текст".encode()),
("gif", b"GIF89a" + bytes(64)),
("empty", b""),
)
},
415,
)
@pytest.mark.spec("attachments", "Подмена MIME")
def test_mime_spoofing(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
assert_errors(
{
"jpeg as png": api.post_attachment(
alice,
chat["id"],
images.jpeg(),
content_type="image/png",
),
"png as jpeg": api.post_attachment(
alice,
chat["id"],
images.sample_png(),
content_type="image/jpeg",
),
},
415,
)
@pytest.mark.spec("attachments", "Неподходящий Content-Type")
def test_unsuitable_content_type(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
assert_errors(
{
str(content_type): api.post_attachment(
alice,
chat["id"],
data,
content_type=content_type,
)
for content_type in (
"application/octet-stream",
"text/plain",
None,
)
},
415,
)
resp = api.post_attachment(
alice,
chat["id"],
data,
content_type="IMAGE/PNG; charset=binary",
)
assert assert_ok(resp, 201, "Attachment")["content_type"] == "image/png"
@pytest.mark.spec("attachments", "Обрезанный файл")
def test_truncated_files(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
png, jpeg = images.sample_png(), images.jpeg(size=(320, 200))
assert_errors(
{
"png half": api.post_attachment(
alice,
chat["id"],
images.truncated(png),
),
"png -1 byte": api.post_attachment(alice, chat["id"], png[:-1]),
"jpeg half": api.post_attachment(
alice,
chat["id"],
images.truncated(jpeg),
content_type="image/jpeg",
),
"jpeg -2 bytes": api.post_attachment(
alice,
chat["id"],
jpeg[:-2],
content_type="image/jpeg",
),
},
415,
)
@pytest.mark.spec("attachments", "Испорченные данные PNG")
def test_damaged_png_data(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
garbage = images.PNG_SIGNATURE + uuid.uuid4().bytes * 256
assert_errors(
{
"idat byte": api.post_attachment(
alice,
chat["id"],
images.png_idat_byte_changed(),
),
"garbage": api.post_attachment(alice, chat["id"], garbage),
},
415,
)
@pytest.mark.spec("attachments", "Недекодируемый JPEG")
def test_undecodable_jpeg(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
assert_errors(
{
name: api.post_attachment(
alice,
chat["id"],
data,
content_type="image/jpeg",
)
for name, data in images.jpeg_undecodable().items()
},
415,
)
@pytest.mark.spec("attachments", "Хвост после конца изображения")
def test_tail_after_end(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
for content_type, data in (
("image/png", images.with_tail(images.sample_png())),
("image/jpeg", images.with_tail(images.jpeg())),
):
attachment = api.upload(
alice,
chat["id"],
data,
content_type=content_type,
)
assert_content(
api.attachment_content(bob, attachment["id"]),
data,
content_type,
)
@pytest.mark.spec("attachments", "Опасное имя")
def test_dangerous_filename(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
names = {
"dot-dot": "../x.png",
"slash": "a/b.png",
"backslash": "a\\b.png",
"nul": "a\x00b.png",
"newline": "a\nb.png",
"del": "a\x7fb.png",
"c1 nel": "a\x85b.png",
"empty": "",
"spaces": " ",
"256": "я" * 256,
}
assert_errors(
{
name: api.post_attachment(alice, chat["id"], data, filename=value)
for name, value in names.items()
}
| {
"missing": api.post_attachment(
alice,
chat["id"],
data,
filename=None,
),
},
400,
)
@pytest.mark.spec("attachments", "Имя не в UTF-8")
def test_filename_not_utf8(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Процент-коды `filename` идут в строке запроса как есть: httpx их
не перекодирует. Без строгого разбора `a%FFb.png` давал 201 с U+FFFD
в имени вместо байта."""
data = images.sample_png()
path = f"{API}/chats/{chat['id']}/attachments"
def upload(query: str) -> Any:
return api.request(
"POST",
f"{path}?{query}",
actor=alice,
headers={"Content-Type": "image/png"},
content=data,
)
assert_errors(
{
"invalid byte": upload("filename=a%FFb.png"),
"truncated sequence": upload("filename=a%C3.png"),
"encoded surrogate": upload("filename=a%ED%A0%80b.png"),
},
400,
)
# верный UTF-8 в процент-кодах — то же имя, что прислано
attachment = assert_ok(
upload("filename=%C3%A9t%C3%A9.png"),
201,
"Attachment",
)
assert attachment["filename"] == "été.png"
def assert_name_kept(
api: Api,
actor: Actor,
chat_id: str,
filename: str,
) -> None:
attachment = api.upload(
actor,
chat_id,
images.sample_png(),
filename=filename,
)
meta = assert_ok(
api.attachment_meta(actor, attachment["id"]),
200,
"Attachment",
)
assert meta["filename"] == attachment["filename"] == filename
@pytest.mark.spec("attachments", "Имя в Unicode")
def test_unicode_filename(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
family = "👨‍👩‍👧"
core = f"фото {family} отпуска"
name = " " + core + "ё" * (253 - len(core)) + " "
assert len(name) == 255
assert_name_kept(api, alice, chat["id"], name)
@pytest.mark.spec("attachments", "Символы форматирования в имени")
def test_format_characters_in_filename(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
for name in (
"‮gnp.exe",
"⁦שלום⁩.png",
"строка
вторая.png",
"пере­нос.png",
):
assert_name_kept(api, alice, chat["id"], name)
@pytest.mark.spec("attachments", "Посторонний с большим файлом")
def test_outsider_with_big_file(
api: Api,
eve: Actor,
chat: dict[str, Any],
) -> None:
assert_error(api.post_attachment(eve, chat["id"], big_body()), 404)
@pytest.mark.spec("attachments", "Без сессии с опасным именем")
def test_no_session_with_dangerous_name(
api: Api,
chat: dict[str, Any],
) -> None:
for filename in ("a/b.png", "ok.png"):
resp = api.post_attachment(
None,
chat["id"],
images.sample_png(),
filename=filename,
)
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("attachments", "Неверный тип и большой размер")
def test_wrong_type_and_big_size(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
resp = api.post_attachment(
alice,
chat["id"],
big_body(),
content_type="text/plain",
)
assert_error(resp, 415)
@pytest.mark.spec("attachments", "Другой участник")
def test_other_member_reads(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data)
assert_ok(api.attachment_meta(bob, attachment["id"]), 200, "Attachment")
assert_content(
api.attachment_content(bob, attachment["id"]),
data,
"image/png",
)
@pytest.mark.spec("attachments", "Посторонний и неизвестный id")
def test_outsider_and_unknown_id(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
attachment = api.upload(alice, chat["id"], images.sample_png())
unknown = str(uuid.uuid4())
responses = {
"eve meta": api.attachment_meta(eve, attachment["id"]),
"eve content": api.attachment_content(eve, attachment["id"]),
"unknown meta": api.attachment_meta(alice, unknown),
"unknown content": api.attachment_content(alice, unknown),
}
assert_errors(responses, 404)
messages = {resp.json()["error"]["message"] for resp in responses.values()}
assert len(messages) == 1, messages
@pytest.mark.spec("attachments", "Неверный id вложения")
def test_bad_attachment_id(api: Api, alice: Actor) -> None:
assert_errors(
{
f"{kind} {value}": call(alice, value)
for value in ("123", "abc")
for kind, call in (
("meta", api.attachment_meta),
("content", api.attachment_content),
)
},
400,
)
@pytest.mark.spec("attachments", "Чтение без сессии")
def test_read_without_session(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment = api.upload(alice, chat["id"], images.sample_png())
for resp in (
api.attachment_meta(None, attachment["id"]),
api.attachment_content(None, attachment["id"]),
):
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("attachments", "Метаданные равны ответу загрузки")
def test_meta_equals_upload(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
attachment = api.upload(alice, chat["id"], images.sample_png())
meta = assert_ok(
api.attachment_meta(bob, attachment["id"]),
200,
"Attachment",
)
assert meta == attachment
@pytest.mark.spec("attachments", "Побайтный оригинал")
def test_original_bytes(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
for content_type, data in (
("image/png", images.sample_png()),
("image/jpeg", images.jpeg(size=(320, 200))),
):
attachment = api.upload(
alice,
chat["id"],
data,
content_type=content_type,
)
resp = api.attachment_content(bob, attachment["id"])
assert not resp.is_redirect
assert_content(resp, data, content_type)
assert hashlib.sha256(resp.content).hexdigest() == attachment["sha256"]
@pytest.mark.spec("attachments", "Вариант original")
def test_variant_original(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data)
assert_content(
api.attachment_content(alice, attachment["id"], variant="original"),
data,
"image/png",
)
assert_errors(
{
variant or "empty": api.attachment_content(
alice,
attachment["id"],
variant=variant,
)
for variant in ("thumbnail", "")
},
400,
)
@pytest.mark.spec("attachments", "Без следов хранилища в ответе")
def test_no_storage_traces(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
upload = api.post_attachment(alice, chat["id"], data)
# assert_ok сверяет тело со схемой контракта: лишних полей нет
attachment = assert_ok(upload, 201, "Attachment")
meta = api.attachment_meta(alice, attachment["id"])
assert_ok(meta, 200, "Attachment")
content = api.attachment_content(alice, attachment["id"])
assert_content(content, data, "image/png")
for resp in (upload, meta, content):
assert_no_storage_traces(resp)
@pytest.mark.spec("attachments", "Повторная загрузка")
def test_repeated_upload(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
first = api.upload(alice, chat["id"], data)
second = api.upload(alice, chat["id"], data)
assert first["id"] != second["id"]
assert first["sha256"] == second["sha256"]
for attachment in (first, second):
assert_content(
api.attachment_content(bob, attachment["id"]),
data,
"image/png",
)
@pytest.mark.spec("attachments", "Загрузки в пределах лимита")
def test_concurrent_uploads(api: Api, base_url: str) -> None:
"""10 участников одного чата загружают по PNG ~1 MiB одновременно: при
параметрах загрузок по умолчанию (4 места и 16 в очереди на процесс)
все помещаются даже в один процесс (design change `upload-memory`,
решение 11)."""
actors = [
api.register(display_name=f"Uploader {number}")
for number in range(CONCURRENT_UPLOADS)
]
chat = api.create_chat(actors[0], *actors[1:], title="Uploads")
bodies = [
images.png_noise(seed=number) for number in range(CONCURRENT_UPLOADS)
]
barrier = threading.Barrier(CONCURRENT_UPLOADS)
def upload(number: int) -> tuple[dict[str, Any], float, float]:
with Api(base_url, timeout=CONCURRENT_CLIENT_TIMEOUT_S) as own:
# соединение открыто до барьера: после него сразу загрузка
own.request("GET", "/health/live")
barrier.wait()
started = time.monotonic()
attachment = own.upload(
actors[number],
chat["id"],
bodies[number],
filename=f"noise-{number}.png",
)
return attachment, started, time.monotonic()
with ThreadPoolExecutor(max_workers=CONCURRENT_UPLOADS) as pool:
results = list(pool.map(upload, range(CONCURRENT_UPLOADS)))
attachments = [attachment for attachment, _, _ in results]
assert len({item["id"] for item in attachments}) == CONCURRENT_UPLOADS
# загрузки правда шли одновременно, а не по очереди клиента
spans = sorted((started, ended) for _, started, ended in results)
overlapping = sum(started < spans[0][1] for started, _ in spans)
assert overlapping >= 2, f"uploads did not overlap: {spans}"
for number, attachment in enumerate(attachments):
assert_content(
api.attachment_content(actors[0], attachment["id"]),
bodies[number],
"image/png",
)
@pytest.mark.spec("attachments", "Скачивание через другую реплику")
def test_download_through_other_replica(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
replicas: int,
) -> None:
data = images.sample_png()
upload = api.post_attachment(alice, chat["id"], data)
attachment = assert_ok(upload, 201, "Attachment")
uploaded_via = assert_instance_id(upload)
seen = {uploaded_via}
for _ in range(REPLICA_ATTEMPTS):
resp = api.attachment_content(bob, attachment["id"])
assert_content(resp, data, "image/png")
seen.add(assert_instance_id(resp))
if assert_instance_id(resp) != uploaded_via:
break
assert_replicas(seen, replicas)
print(f"uploaded via {uploaded_via}, downloaded via {sorted(seen)}")
def test_upload_path_with_quoted_chat_id(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `api-conventions`, «UUID на входе»: `chat_id` загрузки в
другой записи — 400, как у остальных ручек чата."""
data = images.sample_png()
value = chat["id"]
assert_errors(
{
form: api.post_attachment(
alice,
urllib.parse.quote(raw, safe=""),
data,
)
for form, raw in (
("no hyphens", value.replace("-", "")),
("urn", f"urn:uuid:{value}"),
("braces", f"{{{value}}}"),
("number", "123"),
)
},
400,
)
+78
View File
@@ -0,0 +1,78 @@
"""Спек `chat-cache`: что видно по HTTP при кэше карточки чата.
Попадание в кэш, срок записи и отказ Valkey по HTTP не различить: это
исключения в `spec_coverage.py` с evidence.
"""
from typing import Any
import pytest
from api_client import API, Actor, Api
from contract import assert_error, assert_ok
@pytest.mark.spec("chat-cache", "Повторное чтение чата")
def test_repeated_reads_match_creation(
api: Api,
alice: Actor,
bob: Actor,
eve: Actor,
) -> None:
# порядок участников не совпадает ни с сортировкой, ни с порядком
# регистрации: кэш обязан сохранить его как есть
created = api.create_chat(bob, eve, alice, title="Кэш «карточки»")
path = f"{API}/chats/{created['id']}"
first = assert_ok(api.request("GET", path, actor=alice), 200, "Chat")
second = assert_ok(api.request("GET", path, actor=eve), 200, "Chat")
assert first == second == created
assert first["member_ids"] == [bob.id, eve.id, alice.id]
@pytest.mark.spec("chat-cache", "Проверка членства по карточке")
def test_membership_from_new_chat(
api: Api,
alice: Actor,
bob: Actor,
eve: Actor,
) -> None:
chat = api.create_chat(alice, bob)
api.send_message(bob, chat["id"], "сразу после создания")
path = f"{API}/chats/{chat['id']}"
assert_error(api.request("GET", path, actor=eve), 404)
assert_error(
api.post_message(eve, chat["id"], json={"text": "посторонний"}),
404,
)
@pytest.mark.spec("chat-cache", "Сообщение видно сразу")
def test_message_visible_at_once(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
# история уже прочитана: если бы она кэшировалась, второе чтение
# отдало бы старую страницу
assert api.all_messages(bob, chat["id"]) == []
message = api.send_message(alice, chat["id"], "видно сразу")
assert api.all_messages(bob, chat["id"]) == [message]
@pytest.mark.spec("chat-cache", "Новый чат в списке")
def test_new_chat_listed_at_once(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
listed = [
item["id"] for page in api.chat_pages(bob) for item in page["items"]
]
assert listed == [chat["id"]]
second = api.create_chat(alice, bob, title="Второй")
listed = [
item["id"] for page in api.chat_pages(bob) for item in page["items"]
]
assert listed == [chat["id"], second["id"]]
+155
View File
@@ -0,0 +1,155 @@
"""Спек `chats`: создание, чтение, список, неизменный состав."""
import uuid
from typing import Any
import httpx
import pytest
from api_client import API, Actor, Api
from contract import assert_error, assert_errors, assert_ok
def create_raw(
api: Api,
actor: Actor,
title: str,
member_ids: Any,
) -> 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_in_upper_case(api: Api, alice: Actor, bob: Actor) -> None:
resp = create_raw(api, alice, "Upper", [alice.id, bob.id.upper()])
chat = assert_ok(resp, 201, "Chat")
assert chat["member_ids"] == [alice.id, bob.id]
assert chat["id"] in listed_ids(api, bob)
@pytest.mark.spec("chats", "Повтор участника в другом регистре")
def test_duplicate_member_other_case(api: Api, alice: Actor) -> None:
title = f"rejected-{uuid.uuid4().hex}"
member_ids = [alice.id, alice.id.upper()]
assert_error(create_raw(api, alice, title, member_ids), 400)
assert title not in listed_titles(api, alice)
@pytest.mark.spec("chats", "member_ids не массив")
def test_member_ids_not_array(api: Api, alice: Actor) -> None:
title = f"rejected-{uuid.uuid4().hex}"
assert_errors(
{
repr(member_ids): create_raw(api, alice, title, member_ids)
for member_ids in ({}, 123, False, alice.id)
},
400,
)
assert title not in listed_titles(api, alice)
@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"]
+138
View File
@@ -0,0 +1,138 @@
"""Самопроверка `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",
instance_id: str | None = "api-1",
) -> httpx.Response:
"""Ответ API лабы 3; `instance_id=None` — без `X-Instance-Id`."""
headers = {"X-Request-Id": request_id}
if instance_id is not None:
headers["X-Instance-Id"] = instance_id
return httpx.Response(
status,
json=body,
headers=headers,
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("instance_id", [None, "", "api 1", "a" * 65])
def test_bad_instance_id_fails(instance_id: str | None) -> None:
body = {
"error": {
"code": "not_found",
"message": "Not found",
"request_id": "rid-1",
},
}
with pytest.raises(AssertionError, match="X-Instance-Id"):
assert_error(fake_response(404, body, instance_id=instance_id), 404)
@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}")
+125
View File
@@ -0,0 +1,125 @@
"""У каждого сценария основных спеков есть тест или исключение."""
from pathlib import Path
import pytest
from spec_coverage import (
CAPABILITIES,
COLLECTED,
EXCLUDED,
Exclusion,
Scenario,
all_scenarios,
coverage_problems,
missing_evidence,
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())
# тесты fault выполняет только make failure_checks
by_fault = len(scenarios & collected.fault)
print(
f"coverage: {len(scenarios)} scenarios in "
f"{len(CAPABILITIES)} specs, {tested} tested "
f"({by_fault} by make failure_checks), {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_exclusion_evidence_exists() -> None:
"""Файл evidence, на который ссылается исключение, есть в репозитории
(спек student-tests, «Доказательства исключений сверки в
репозитории»)."""
problems = missing_evidence(EXCLUDED)
assert not problems, "\n".join(problems)
def test_missing_evidence_fails(tmp_path: Path) -> None:
excluded = {
("health", "Сценарий"): Exclusion(
reason="r",
check="команда — evidence/demo/file.md",
),
}
assert missing_evidence(excluded, tmp_path) == [
"exclusion refers to missing evidence/demo/file.md: health / Сценарий",
]
(tmp_path / "evidence" / "demo").mkdir(parents=True)
(tmp_path / "evidence" / "demo" / "file.md").write_text(
"x",
encoding="utf-8",
)
assert missing_evidence(excluded, tmp_path) == []
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 / Удалённый сценарий",
]
+71
View File
@@ -0,0 +1,71 @@
"""Спек `data-storage`.
Гонки — в `test_race.py`; рестарт, отказы БД и пул — исключения в
`spec_coverage.py`.
"""
from typing import Any
import pytest
import images
from api_client import API, Actor, Api, new_key
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
@pytest.mark.spec("data-storage", "Порядок участников")
def test_member_order_kept(api: Api, alice: Actor, bob: Actor) -> None:
# порядок [bob, alice] из запроса не совпадает с порядком регистрации;
# «в том числе после рестарта» — evidence/storage/restart.md
created = api.create_chat(bob, alice, title="Порядок участников")
expected = [bob.id, alice.id]
assert created["member_ids"] == expected
resp = api.request("GET", f"{API}/chats/{created['id']}", actor=alice)
assert assert_ok(resp, 200, "Chat")["member_ids"] == expected
listed = {
chat["id"]: chat["member_ids"]
for page in api.chat_pages(alice)
for chat in page["items"]
}
assert listed[created["id"]] == expected
@pytest.mark.spec("data-storage", "Порядок вложений")
def test_attachment_order_kept(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
a, b, c = (
api.upload(alice, chat["id"], images.sample_png())["id"]
for _ in range(3)
)
key = new_key()
order = [c, a, b]
sent = api.send_message(
alice,
chat["id"],
"порядок",
key=key,
attachment_ids=order,
)
assert sent["attachment_ids"] == order
assert api.all_messages(alice, chat["id"]) == [sent]
replay = api.send_message(
alice,
chat["id"],
"порядок",
key=key,
attachment_ids=order,
)
assert replay["attachment_ids"] == order
File diff suppressed because it is too large Load Diff
+36
View File
@@ -0,0 +1,36 @@
"""Спек `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_id_is_ignored(api: Api) -> None:
ghost = Actor.unregistered()
for path in HEALTH:
resp = api.request("GET", path, headers={"X-User-Id": ghost.id})
assert assert_ok(resp, 200, "Health") == {"status": "ok"}
@pytest.mark.spec("health", "Неизвестный токен")
def test_unknown_token_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"}
+405
View File
@@ -0,0 +1,405 @@
"""Спек `idempotency`: повторная отправка сообщения с `Idempotency-Key`.
Сценарии, которым нужен особый стенд (сбой записи, остановка БД, короткий
срок ключа), — в `test_failures.py`; гонка одного ключа — в
`test_race.py`; повтор после рестарта API — исключение с evidence.
Повтору через другую реплику нужны ≥ 2 реплики за `BASE_URL` (фикстура
`replicas`), против одного процесса он пропускается.
"""
from typing import Any
import pytest
import images
from api_client import (
API,
IDEMPOTENCY_KEY,
Actor,
Api,
key_headers,
new_key,
)
from contract import (
BEARER_CHALLENGE,
assert_error,
assert_instance_id,
assert_ok,
assert_replicas,
assert_unauthorized,
)
# 128 символов, в том числе все допустимые знаки, кроме букв и цифр
LONGEST_KEY = "a1.B_:-Z" * 16
def texts(api: Api, actor: Actor, chat_id: str) -> list[str]:
return [item["text"] for item in api.all_messages(actor, chat_id)]
@pytest.mark.spec("idempotency", "Нет ключа")
def test_no_key(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
resp = api.post_message(alice, chat["id"], key=None, json={"text": "x"})
assert_error(resp, 400)
assert texts(api, alice, chat["id"]) == []
@pytest.mark.spec("idempotency", "Неверный ключ")
def test_bad_key(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
for key in ("", "a" * 129, "a b", "a/b", "ключ"):
# не-ASCII заголовок httpx шлёт только байтами
resp = api.post_message(
alice,
chat["id"],
key=None,
headers={IDEMPOTENCY_KEY: key.encode()},
json={"text": "x"},
)
assert_error(resp, 400)
if key:
assert key not in resp.text, f"key {key!r} echoed in response"
assert texts(api, alice, chat["id"]) == []
@pytest.mark.spec("idempotency", "Граница длины ключа")
def test_longest_key(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
assert len(LONGEST_KEY) == 128
message = api.send_message(
alice,
chat["id"],
"длинный ключ",
key=LONGEST_KEY,
)
assert texts(api, alice, chat["id"]) == [message["text"]]
@pytest.mark.spec("idempotency", "Ключ у других запросов")
def test_key_on_other_requests(api: Api, alice: Actor, bob: Actor) -> None:
headers = key_headers()
created = [
assert_ok(
api.request(
"POST",
f"{API}/chats",
actor=alice,
headers=headers,
json={
"title": "Тот же ключ",
"member_ids": [alice.id, bob.id],
},
),
201,
"Chat",
)
for _ in range(2)
]
assert created[0]["id"] != created[1]["id"]
@pytest.mark.spec("idempotency", "Повтор того же тела")
def test_replay_same_body(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
key = new_key()
first = api.send_message(alice, chat["id"], "Привет, мир 👋", key=key)
again = api.send_message(alice, chat["id"], "Привет, мир 👋", key=key)
assert again == first
assert texts(api, alice, chat["id"]) == ["Привет, мир 👋"]
@pytest.mark.spec("idempotency", "Тот же JSON в другой записи")
def test_replay_other_json_spelling(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
key = new_key()
first = api.send_message(alice, chat["id"], "Привет", key=key)
# те же поле и текст: пробелы и \u-экранирование вместо UTF-8
raw = b'{ "text" :\n "\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442" }'
resp = api.post_message(
alice,
chat["id"],
key=key,
headers={"Content-Type": "application/json"},
content=raw,
)
assert assert_ok(resp, 201, "Message") == first
assert texts(api, alice, chat["id"]) == ["Привет"]
@pytest.mark.spec("idempotency", "Другой текст")
def test_other_body_conflict(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
key = new_key()
first = api.send_message(alice, chat["id"], "первое", key=key)
resp = api.post_message(
alice,
chat["id"],
key=key,
json={"text": "второе"},
)
assert_error(resp, 409)
assert texts(api, alice, chat["id"]) == ["первое"]
assert api.send_message(alice, chat["id"], "первое", key=key) == first
def two_attachments(api: Api, actor: Actor, chat_id: str) -> list[str]:
return [
api.upload(actor, chat_id, images.sample_png())["id"] for _ in range(2)
]
@pytest.mark.spec("idempotency", "Вложения по умолчанию")
def test_replay_with_default_attachments(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
key = new_key()
first = api.send_message(alice, chat["id"], "без файлов", key=key)
again = api.send_message(
alice,
chat["id"],
"без файлов",
key=key,
attachment_ids=[],
)
assert again == first
assert texts(api, alice, chat["id"]) == ["без файлов"]
@pytest.mark.spec("idempotency", "Повтор сообщения с вложениями")
def test_replay_with_attachments(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
first_id, second_id = two_attachments(api, alice, chat["id"])
key = new_key()
ids = [first_id, second_id]
first = api.send_message(
alice,
chat["id"],
"файлы",
key=key,
attachment_ids=ids,
)
again = api.send_message(
alice,
chat["id"],
"файлы",
key=key,
attachment_ids=ids,
)
upper = api.send_message(
alice,
chat["id"],
"файлы",
key=key,
attachment_ids=[item.upper() for item in ids],
)
assert first == again == upper
assert first["attachment_ids"] == ids
history = api.all_messages(alice, chat["id"])
assert [item["id"] for item in history] == [first["id"]]
@pytest.mark.spec("idempotency", "Другие вложения")
def test_other_attachments_conflict(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
first_id, second_id = two_attachments(api, alice, chat["id"])
key = new_key()
first = api.send_message(
alice,
chat["id"],
"файлы",
key=key,
attachment_ids=[first_id, second_id],
)
for body in (
{"text": "файлы", "attachment_ids": [second_id, first_id]},
{"text": "файлы"},
):
assert_error(
api.post_message(alice, chat["id"], key=key, json=body),
409,
)
history = api.all_messages(alice, chat["id"])
assert history == [first]
assert history[0]["attachment_ids"] == [first_id, second_id]
@pytest.mark.spec("idempotency", "Другой пользователь")
def test_same_key_other_user(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
key = new_key()
from_alice = api.send_message(alice, chat["id"], "от Алисы", key=key)
from_bob = api.send_message(bob, chat["id"], "от Боба", key=key)
assert from_alice["id"] != from_bob["id"]
assert sorted(texts(api, alice, chat["id"])) == ["от Алисы", "от Боба"]
@pytest.mark.spec("idempotency", "Другой чат")
def test_same_key_other_chat(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
other = api.create_chat(alice, bob, title="Второй чат")
key = new_key()
first = api.send_message(alice, chat["id"], "одно и то же", key=key)
second = api.send_message(alice, other["id"], "одно и то же", key=key)
assert first["id"] != second["id"]
assert second["chat_id"] == other["id"]
for chat_id in (chat["id"], other["id"]):
assert texts(api, alice, chat_id) == ["одно и то же"]
@pytest.mark.spec("idempotency", "Отозванный токен")
def test_replay_with_revoked_token(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
key = new_key()
api.send_message(alice, chat["id"], "до выхода", key=key)
assert api.logout(alice).status_code == 204
resp = api.post_message(
alice,
chat["id"],
key=key,
json={"text": "до выхода"},
)
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("idempotency", "Новая сессия того же пользователя")
def test_replay_with_new_session(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
key = new_key()
first = api.send_message(alice, chat["id"], "одна сессия", key=key)
again = api.login(alice.user, alice.password)
assert again.token != alice.token
assert api.send_message(again, chat["id"], "одна сессия", key=key) == first
@pytest.mark.spec("idempotency", "Посторонний с чужим ключом")
def test_outsider_with_members_key(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
key = new_key()
first = api.send_message(alice, chat["id"], "только участникам", key=key)
resp = api.post_message(
eve,
chat["id"],
key=key,
json={"text": "только участникам"},
)
assert_error(resp, 404)
assert (
api.send_message(
alice,
chat["id"],
"только участникам",
key=key,
)
== first
)
assert texts(api, alice, chat["id"]) == ["только участникам"]
@pytest.mark.spec("idempotency", "Без сессии и без ключа")
def test_no_session_and_no_key(api: Api, chat: dict[str, Any]) -> None:
resp = api.post_message(None, chat["id"], key=None, json={"text": "x"})
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("idempotency", "Посторонний без ключа")
def test_outsider_without_key(
api: Api,
eve: Actor,
chat: dict[str, Any],
) -> None:
resp = api.post_message(eve, chat["id"], key=None, json={"text": "x"})
assert_error(resp, 400)
@pytest.mark.spec("idempotency", "Невалидное тело с занятым ключом")
def test_invalid_body_with_used_key(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
key = new_key()
api.send_message(alice, chat["id"], "первое", key=key)
resp = api.post_message(alice, chat["id"], key=key, json={"text": ""})
assert_error(resp, 400)
@pytest.mark.spec("idempotency", "Невалидный запрос не занимает ключ")
def test_invalid_request_keeps_key_free(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
key = new_key()
resp = api.post_message(alice, chat["id"], key=key, json={"text": ""})
assert_error(resp, 400)
message = api.send_message(alice, chat["id"], "теперь валидно", key=key)
assert texts(api, alice, chat["id"]) == [message["text"]]
@pytest.mark.spec("idempotency", "Повтор через другую реплику")
def test_replay_on_other_replica(
api: Api,
alice: Actor,
chat: dict[str, Any],
replicas: int,
) -> None:
"""Повтор с тем же ключом, который обслужила другая реплика, — тот же
`Message`; другое тело с этим ключом — 409 от разных реплик."""
key = new_key()
body = {"text": "повтор через реплики"}
resp = api.post_message(alice, chat["id"], key=key, json=body)
first = assert_ok(resp, 201, "Message")
origin = assert_instance_id(resp)
replays: dict[str, Any] = {}
for _ in range(2 * replicas):
resp = api.post_message(alice, chat["id"], key=key, json=body)
replays[assert_instance_id(resp)] = assert_ok(resp, 201, "Message")
if replays.keys() - {origin}:
break
print(f"sent via {origin}, replayed via {sorted(replays)}")
# повтор через другую реплику: среди отправки и повторов ≥ 2 значения
assert_replicas({origin, *replays}, replicas)
assert all(message == first for message in replays.values())
conflicts = set()
for _ in range(2 * replicas):
resp = api.post_message(alice, chat["id"], key=key, json={"text": "?"})
assert_error(resp, 409)
conflicts.add(assert_instance_id(resp))
print(f"409 via {sorted(conflicts)}")
assert_replicas(conflicts, replicas)
assert texts(api, alice, chat["id"]) == [body["text"]]
+120
View File
@@ -0,0 +1,120 @@
"""Спек `identification`: Bearer на защищённых эндпоинтах с лабы 2.
Единственный модуль, который собирает `Authorization` и `X-User-Id`
сам, а не через `Actor.headers()`: проверяются именно заголовки.
"""
import secrets
from typing import Any
import pytest
from api_client import API, Actor, Api, basic_auth, bearer_auth
from contract import (
BEARER_CHALLENGE,
assert_error,
assert_ok,
assert_unauthorized,
contract,
)
ME = f"{API}/users/me"
@pytest.mark.spec("identification", "Действующий токен")
def test_valid_token(api: Api, alice: Actor) -> None:
resp = api.request("GET", ME, headers=bearer_auth(alice.token))
assert assert_ok(resp, 200, "User") == alice.user
@pytest.mark.spec("identification", "Нет заголовка")
def test_no_header(api: Api) -> None:
assert_unauthorized(api.request("GET", ME), BEARER_CHALLENGE)
@pytest.mark.spec("identification", "Неизвестный токен")
def test_unknown_token(api: Api) -> None:
for token in (secrets.token_urlsafe(32), "x"):
resp = api.request("GET", ME, headers=bearer_auth(token))
assert_unauthorized(resp, BEARER_CHALLENGE)
# схема без токена — тот же ответ
resp = api.request("GET", ME, headers={"Authorization": "Bearer"})
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("identification", "Basic на бизнес-эндпоинте")
def test_basic_on_business_endpoint(api: Api, alice: Actor) -> None:
resp = api.request(
"GET",
ME,
headers=basic_auth(alice.username, alice.password),
)
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("identification", "Только X-User-Id")
def test_only_user_id_header(api: Api, alice: Actor) -> None:
resp = api.request("GET", ME, headers={"X-User-Id": alice.id})
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("identification", "X-User-Id не меняет владельца")
def test_user_id_header_ignored(api: Api, alice: Actor, eve: Actor) -> None:
resp = api.request(
"GET",
ME,
headers={**bearer_auth(alice.token), "X-User-Id": eve.id},
)
assert assert_ok(resp, 200, "User") == alice.user
@pytest.mark.spec("identification", "Чужой чат без заголовка")
def test_chat_without_token(api: Api, chat: dict[str, Any]) -> None:
resp = api.request("GET", f"{API}/chats/{chat['id']}")
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("identification", "Невалидное поле без заголовка")
def test_invalid_field_without_token(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
# с ключом: кроме токена в запросе неверно только поле
resp = api.post_message(None, chat["id"], json={"text": ""})
assert_unauthorized(resp, BEARER_CHALLENGE)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("identification", "Битый JSON без заголовка")
def test_malformed_json_without_token(
api: Api,
chat: dict[str, Any],
) -> None:
# согласованное расхождение: битый JSON отклоняется до аутентификации
resp = api.post_message(
None,
chat["id"],
headers={"Content-Type": "application/json"},
content=b"{bad",
)
assert_error(resp, 400)
@pytest.mark.spec("identification", "Схема в openapi.json")
def test_security_schemes_in_openapi(api: Api) -> None:
resp = api.request("GET", "/openapi.json")
assert resp.status_code == 200
served = resp.json()
schemes = served["components"]["securitySchemes"]
expected = contract()["components"]["securitySchemes"]
assert schemes["bearerAuth"] == expected["bearerAuth"]
assert schemes["basicAuth"] == expected["basicAuth"]
assert "devUser" not in schemes
paths = served["paths"]
assert paths[ME]["get"]["security"] == [{"bearerAuth": []}]
assert paths[f"{API}/auth/sessions"]["post"]["security"] == [
{"basicAuth": []},
]
assert not paths[f"{API}/users"]["post"].get("security")
+57
View File
@@ -0,0 +1,57 @@
"""Спек `load-balancing`: запросы одной сессии и запись через реплики.
Capability `load-balancing` вне сверки покрытия (`spec_coverage.py`):
почти все её сценарии требуют действий над контейнерами и доказываются
evidence. Сценарии, которые проверяются по HTTP, названы в докстрингах.
Тесты нужны ≥ 2 реплики за `BASE_URL` (фикстура `replicas`).
"""
from collections import Counter
from typing import Any
from api_client import API, Actor, Api
from contract import assert_instance_id, assert_ok, assert_replicas
SESSION_REQUESTS = 20
def test_one_session_on_several_replicas(
api: Api,
alice: Actor,
replicas: int,
) -> None:
"""Сценарий «Одна сессия на разных репликах»: один вход, 20 запросов
с одним токеном — все 200 с этим пользователем, ≥ 2 реплики."""
served: Counter[str] = Counter()
for _ in range(SESSION_REQUESTS):
resp = api.request("GET", f"{API}/users/me", actor=alice)
assert assert_ok(resp, 200, "User") == alice.user
served[assert_instance_id(resp)] += 1
print(f"one session, {SESSION_REQUESTS} requests: {dict(served)}")
assert_replicas(served, replicas)
def test_write_visible_through_other_replica(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
replicas: int,
) -> None:
"""Сценарий «Запись видна через другую реплику»: сообщение,
отправленное через одну реплику, есть в каждом следующем чтении
истории, в том числе через другие реплики."""
resp = api.post_message(alice, chat["id"], json={"text": "через LB"})
message = assert_ok(resp, 201, "Message")
writer = assert_instance_id(resp)
readers: Counter[str] = Counter()
for _ in range(2 * replicas + 2):
page = api.messages_page(bob, chat["id"])
assert message in assert_ok(page, 200, "MessagePage")["items"]
readers[assert_instance_id(page)] += 1
print(f"written via {writer}, read via {dict(readers)}")
assert_replicas(readers, replicas)
assert readers.keys() - {writer}, (
f"every read was served by the writer {writer}"
)
+319
View File
@@ -0,0 +1,319 @@
"""Спек `messages`: отправка, валидация текста, история, вложения."""
import uuid
from typing import Any
import httpx
import pytest
import images
from api_client import Actor, Api, order_key
from contract import assert_error, assert_errors, assert_ok
def send_raw(
api: Api,
actor: Actor,
chat_id: str,
body: dict[str, Any],
) -> httpx.Response:
"""Отправка с новым ключом; ответ проверяет тест."""
return api.post_message(actor, chat_id, 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"] == "Привет, мир 👋"
assert message["attachment_ids"] == []
def upload(api: Api, actor: Actor, chat_id: str) -> str:
"""Готовое вложение чата; id."""
return api.upload(actor, chat_id, images.sample_png())["id"]
@pytest.mark.spec("messages", "Сообщение с вложениями")
def test_message_with_attachments(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
first, second = (
upload(api, alice, chat["id"]),
upload(api, alice, chat["id"]),
)
message = api.send_message(
alice,
chat["id"],
"два файла",
attachment_ids=[second, first],
)
assert message["attachment_ids"] == [second, first]
@pytest.mark.spec("messages", "Пустой текст с вложением")
def test_empty_text_with_attachment(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment_id = upload(api, alice, chat["id"])
message = api.send_message(
alice,
chat["id"],
"",
attachment_ids=[attachment_id],
)
assert message["text"] == ""
assert message["attachment_ids"] == [attachment_id]
@pytest.mark.spec("messages", "Пробелы с вложением")
def test_blank_text_with_attachment(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Согласовано с преподавателем 2026-10-20: пустой текст — и `""`, и
из одних пробелов; с вложением допустим и не нормализуется."""
attachment_id = upload(api, alice, chat["id"])
message = api.send_message(
alice,
chat["id"],
" ",
attachment_ids=[attachment_id],
)
assert message["text"] == " "
assert message["attachment_ids"] == [attachment_id]
assert_error(send_raw(api, alice, chat["id"], {"text": " "}), 400)
assert [item["id"] for item in api.all_messages(alice, chat["id"])] == [
message["id"],
]
@pytest.mark.spec("messages", "Вложения в истории")
def test_attachments_in_history(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
first, second = (
upload(api, alice, chat["id"]),
upload(api, alice, chat["id"]),
)
with_files = api.send_message(
alice,
chat["id"],
"с файлами",
attachment_ids=[second, first],
)
plain = api.send_message(bob, chat["id"], "без файлов")
history = api.all_messages(bob, chat["id"])
assert history == sorted([with_files, plain], key=order_key)
by_id = {item["id"]: item["attachment_ids"] for item in history}
assert by_id == {with_files["id"]: [second, first], plain["id"]: []}
@pytest.mark.spec("messages", "Вложение другого участника")
def test_attachment_of_other_member(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
attachment_id = upload(api, alice, chat["id"])
api.send_message(bob, chat["id"], "ответ", attachment_ids=[attachment_id])
@pytest.mark.spec("messages", "Вложение другого чата")
def test_attachment_of_other_chat(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
other = api.create_chat(alice, bob, title="Y")
attachment_id = upload(api, alice, other["id"])
resp = send_raw(
api,
alice,
chat["id"],
{"text": "чужой чат", "attachment_ids": [attachment_id]},
)
assert_error(resp, 404)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Чужое вложение")
def test_foreign_attachment(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
eve_chat = api.create_chat(eve, title="Ева")
attachment_id = upload(api, eve, eve_chat["id"])
resp = send_raw(
api,
alice,
chat["id"],
{"text": "", "attachment_ids": [attachment_id]},
)
assert_error(resp, 404)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Неизвестное вложение")
def test_unknown_attachment(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
resp = send_raw(
api,
alice,
chat["id"],
{"text": "x", "attachment_ids": [str(uuid.uuid4())]},
)
assert_error(resp, 404)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Неверный список вложений")
def test_bad_attachment_list(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment_id = upload(api, alice, chat["id"])
bodies = {
"repeat": [attachment_id, attachment_id],
"repeat upper": [attachment_id, attachment_id.upper()],
"eleven": [str(uuid.uuid4()) for _ in range(11)],
"string": attachment_id,
"number item": [123],
"123 item": ["123"],
}
assert_errors(
{
name: send_raw(
api,
alice,
chat["id"],
{"text": "x", "attachment_ids": value},
)
for name, value in bodies.items()
},
400,
)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Одно вложение в двух сообщениях")
def test_one_attachment_in_two_messages(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment_id = upload(api, alice, chat["id"])
first = api.send_message(
alice,
chat["id"],
"раз",
attachment_ids=[attachment_id],
)
second = api.send_message(
alice,
chat["id"],
"два",
attachment_ids=[attachment_id],
)
assert first["id"] != second["id"]
history = api.all_messages(alice, chat["id"])
assert [item["attachment_ids"] for item in history] == [
[attachment_id],
[attachment_id],
]
@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
+262
View File
@@ -0,0 +1,262 @@
"""Спек `pagination`: `limit`, `next_cursor`, курсоры обоих списков."""
import base64
import json
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_errors, assert_ok
# подмена в содержимом курсора: какие поля заменить
type Change = Callable[[dict[str, Any]], dict[str, Any]]
# подмены выданного курсора, которые дают 400 (сценарий «Изменённый
# курсор»): ключ элемента не строка, тот же id в другой записи, версия
# не ровно целое 1
CURSOR_CHANGES: dict[str, Change] = {
"i=[]": lambda _: {"i": []},
"i={}": lambda _: {"i": {}},
"i=123": lambda _: {"i": 123},
"i=false": lambda _: {"i": False},
"i without hyphens": lambda payload: {"i": payload["i"].replace("-", "")},
"i upper case": lambda payload: {"i": payload["i"].upper()},
"v=true": lambda _: {"v": True},
"v=1.0": lambda _: {"v": 1.0},
}
# и которые принимаются: незнакомое поле игнорируется, иначе новое
# необязательное поле ломало бы курсоры при поочерёдной замене реплик
CURSOR_KEPT: dict[str, Change] = {
"unchanged": lambda _: {},
"extra field": lambda _: {"x": 1},
}
@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)
def cursor_payload(cursor: str) -> dict[str, Any]:
"""Содержимое курсора сервиса: base64url без `=` от JSON."""
padded = cursor + "=" * (-len(cursor) % 4)
return json.loads(base64.urlsafe_b64decode(padded))
def encode_payload(payload: dict[str, Any]) -> str:
"""Курсор из содержимого — так же, как его кодирует сервис."""
raw = json.dumps(payload, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
def tamper(cursor: str, change: Change) -> str:
"""Выданный курсор с одной подменой в содержимом.
Без подмены перекодирование обязано вернуть ту же строку: иначе формат
курсора изменился, и 400 на подмену ничего бы не доказывал.
"""
payload = cursor_payload(cursor)
assert encode_payload(payload) == cursor, (
f"cursor format changed, re-encoded payload differs: {payload}"
)
return encode_payload(payload | change(payload))
@dataclass(frozen=True)
class IssuedCursor:
"""Список и курсор его второй страницы, выданный сервером."""
listing: Listing
cursor: str
@pytest.fixture
def issued(
listing: Listing,
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> IssuedCursor:
"""В истории два сообщения, у Алисы два чата: у обоих списков есть
вторая страница при `limit=1`."""
fill(api, alice, chat["id"], 2)
api.create_chat(alice, bob, title="second")
first = assert_ok(listing.page(limit=1), 200, listing.schema)
assert first["next_cursor"], "no second page"
return IssuedCursor(listing=listing, cursor=first["next_cursor"])
@pytest.mark.spec("pagination", "Изменённый курсор")
def test_tampered_cursor(issued: IssuedCursor) -> None:
"""Курсор не собирается с нуля: с чужими `v` или `s` его отсекла бы
проверка версии или области раньше разбора ключа."""
page = issued.listing.page
schema = issued.listing.schema
# контроль: без подмены и с незнакомым полем — та же вторая страница
second = assert_ok(page(cursor=issued.cursor), 200, schema)
for name, change in CURSOR_KEPT.items():
kept = assert_ok(
page(cursor=tamper(issued.cursor, change)),
200,
schema,
)
assert kept == second, f"{name}: another page"
assert_errors(
{
name: page(cursor=tamper(issued.cursor, change))
for name, change in CURSOR_CHANGES.items()
},
400,
)
+234
View File
@@ -0,0 +1,234 @@
"""Гонки: одновременные запросы по отдельным соединениям."""
import threading
import time
from collections import Counter
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from typing import Any
import httpx
import pytest
from api_client import (
API,
Actor,
Api,
new_key,
order_key,
registration,
unique_username,
)
from contract import (
assert_error,
assert_instance_id,
assert_ok,
assert_replicas,
)
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")
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()
# у каждой отправки свой ключ: это 100 разных сообщений
resp = own.post_message(
actors[number],
chat["id"],
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=registration(username, 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
@pytest.mark.spec("idempotency", "Гонка одного ключа")
def test_same_key_at_once(
api: Api,
alice: Actor,
chat: dict[str, Any],
base_url: str,
) -> None:
"""Спек `student-tests`, сценарий «Гонка одного ключа»: одно тело с
одним ключом от `CLIENTS` клиентов сразу — ровно одно сообщение.
На любом стенде: против одного процесса API гонку решает PostgreSQL
так же, как между репликами. Ответы разных реплик требует
`test_same_key_through_replicas`.
"""
results = race_one_key(api, alice, chat, base_url)
peak = max_in_flight([(start, end) for _, start, end in results])
assert peak >= 2, "requests did not overlap: race is not proven"
@pytest.mark.spec("idempotency", "Гонка одного ключа через реплики")
def test_same_key_through_replicas(
api: Api,
alice: Actor,
chat: dict[str, Any],
base_url: str,
replicas: int,
) -> None:
"""Та же гонка через балансировщик: среди ответов есть пара
пересекающихся по времени запросов, которые обслужили разные реплики.
Это и есть «одновременно через разные реплики», а не просто «разные
реплики за весь прогон». Против одного процесса — пропуск."""
results = race_one_key(api, alice, chat, base_url)
spans = [
(assert_instance_id(resp), start, end) for resp, start, end in results
]
served = Counter(instance for instance, _, _ in spans)
print(f"key race through replicas: {dict(served)}")
assert_replicas(served, replicas)
assert overlap_on_different_replicas(spans), (
f"no overlapping requests on different replicas: {dict(served)}"
)
def race_one_key(
api: Api,
alice: Actor,
chat: dict[str, Any],
base_url: str,
) -> list[tuple[httpx.Response, float, float]]:
"""`CLIENTS` клиентов сразу шлют одно тело с одним ключом: все 201 с
одним `Message`, в истории ровно одно сообщение. Возвращает ответы со
временем начала и конца."""
key = new_key()
body = {"text": "один раз"}
def send(own: Api, _number: int) -> tuple[httpx.Response, float, float]:
start = time.monotonic()
resp = own.post_message(alice, chat["id"], key=key, json=body)
return resp, start, time.monotonic()
results = run_together(send, base_url)
statuses = Counter(resp.status_code for resp, _, _ in results)
peak = max_in_flight([(start, end) for _, start, end in results])
history = api.all_messages(alice, chat["id"])
print(
f"key race: {CLIENTS} clients, statuses {dict(statuses)}, "
f"max in flight {peak}; history: {len(history)} messages",
)
assert statuses == {201: CLIENTS}, statuses
messages = [assert_ok(resp, 201, "Message") for resp, _, _ in results]
assert all(message == messages[0] for message in messages)
assert history == [messages[0]]
return results
def overlap_on_different_replicas(
spans: list[tuple[str, float, float]],
) -> bool:
"""Есть два запроса разных реплик, которые были в полёте одновременно."""
return any(
first[0] != second[0] and first[1] < second[2] and second[1] < first[2]
for number, first in enumerate(spans)
for second in spans[number + 1 :]
)
+283
View File
@@ -0,0 +1,283 @@
"""Обязательные сценарии уровня «4» (README.md, рубрика)."""
import uuid
from collections.abc import Iterator
from typing import Any
import pytest
import images
from api_client import API, Actor, Api, key_headers, order_key, registration
from contract import (
BASIC_CHALLENGE,
BEARER_CHALLENGE,
assert_error,
assert_errors,
assert_unauthorized,
)
@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, extra in (
(f"{API}/users", None, {}),
(f"{API}/chats", alice, {}),
# с ключом: 400 из-за JSON, а не из-за отсутствия ключа
(f"{API}/chats/{chat['id']}/messages", alice, key_headers()),
):
resp = api.request(
"POST",
path,
actor=actor,
headers=headers | extra,
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:
# POST сообщения без ключа получил бы 400 раньше проверки доступа
headers = key_headers() if method == "POST" else None
foreign = assert_error(
api.request(
method,
path + suffix,
actor=eve,
headers=headers,
json=body,
),
404,
)
absent = assert_error(
api.request(
method,
missing + suffix,
actor=eve,
headers=headers,
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:
for text in ("", " ", "\t\n "):
resp = api.post_message(alice, chat["id"], 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=registration(alice.username, "Другая Алиса"),
)
assert_error(resp, 409)
@pytest.mark.spec("sessions", "Неверный пароль")
def test_wrong_password(api: Api, alice: Actor) -> None:
resp = api.login_response(alice.username, alice.password + "-wrong")
assert_unauthorized(resp, BASIC_CHALLENGE)
assert "token" not in resp.json()
@pytest.mark.spec("sessions", "Выход")
def test_logout(api: Api, alice: Actor) -> None:
resp = api.logout(alice)
assert resp.status_code == 204, resp.text
assert resp.content == b""
after = api.request("GET", f"{API}/users/me", actor=alice)
assert_unauthorized(after, BEARER_CHALLENGE)
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)
# --- лаба 4: негативные тесты вложений (спек student-tests) -------------
def _chunks(data: bytes, size: int = 1024 * 1024) -> Iterator[bytes]:
for offset in range(0, len(data), size):
yield data[offset : offset + size]
@pytest.mark.spec("attachments", "Заявленный размер больше лимита")
@pytest.mark.spec("attachments", "Большое тело без Content-Length")
def test_rubric_too_big_file(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Слишком большой файл в рубрике»: больше
10 MiB с `Content-Length` и частями — 413 в формате контракта."""
data = images.png_of_size(images.MAX_BYTES + 1024 * 1024)
assert_errors(
{
"content-length": api.post_attachment(alice, chat["id"], data),
"chunked": api.post_attachment(alice, chat["id"], _chunks(data)),
},
413,
)
@pytest.mark.spec("attachments", "Обрезанный файл")
@pytest.mark.spec("attachments", "Испорченные данные PNG")
def test_rubric_damaged_image(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Повреждённое изображение в рубрике»:
обрезанные PNG и JPEG и PNG с изменённым байтом данных — 415."""
assert_errors(
{
"png cut": api.post_attachment(
alice,
chat["id"],
images.truncated(images.sample_png()),
),
"jpeg cut": api.post_attachment(
alice,
chat["id"],
images.truncated(images.jpeg()),
content_type="image/jpeg",
),
"png byte": api.post_attachment(
alice,
chat["id"],
images.png_idat_byte_changed(),
),
},
415,
)
@pytest.mark.spec("attachments", "Подмена MIME")
@pytest.mark.spec("attachments", "Не изображение")
def test_rubric_mime_spoofing(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Подмена MIME в рубрике»: JPEG как PNG и
текст как JPEG — 415."""
assert_errors(
{
"jpeg as png": api.post_attachment(
alice,
chat["id"],
images.jpeg(),
content_type="image/png",
),
"text as jpeg": api.post_attachment(
alice,
chat["id"],
b"plain text, not an image",
content_type="image/jpeg",
),
},
415,
)
@pytest.mark.spec("messages", "Чужое вложение")
@pytest.mark.spec("messages", "Неизвестное вложение")
@pytest.mark.spec("attachments", "Посторонний и неизвестный id")
def test_rubric_foreign_attachment_id(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Чужое attachment_id в рубрике»: сообщение с
вложением чужого чата и с неизвестным id, чтение постороннего — 404."""
eve_chat = api.create_chat(eve, title="Ева")
eve_attachment = api.upload(eve, eve_chat["id"], images.sample_png())
alice_attachment = api.upload(alice, chat["id"], images.sample_png())
assert_errors(
{
"foreign in message": api.post_message(
alice,
chat["id"],
json={"text": "x", "attachment_ids": [eve_attachment["id"]]},
),
"unknown in message": api.post_message(
alice,
chat["id"],
json={"text": "x", "attachment_ids": [str(uuid.uuid4())]},
),
"outsider meta": api.attachment_meta(eve, alice_attachment["id"]),
"outsider content": api.attachment_content(
eve,
alice_attachment["id"],
),
},
404,
)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Вложение другого чата")
def test_rubric_attachment_of_other_chat(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
"""Спек `student-tests`, «Вложение другого чата в рубрике»: участник
двух чатов шлёт в один вложение другого — 404, в истории пусто."""
other = api.create_chat(alice, bob, title="Второй чат")
attachment = api.upload(alice, other["id"], images.sample_png())
resp = api.post_message(
alice,
chat["id"],
json={"text": "", "attachment_ids": [attachment["id"]]},
)
assert_error(resp, 404)
assert api.all_messages(alice, chat["id"]) == []
+157
View File
@@ -0,0 +1,157 @@
"""Спек `sessions`: вход по Basic, токен, отказ во входе, отзыв.
Истечение, рестарт и недоступность БД требуют особого стенда — это
исключения в `spec_coverage.py`. Неверный пароль и выход — в
`test_rubric.py` (обязательные сценарии уровня «4»).
"""
import base64
from datetime import UTC, datetime
import pytest
from api_client import (
API,
SESSIONS,
Actor,
Api,
bearer_auth,
unique_username,
)
from contract import (
BASIC_CHALLENGE,
BEARER_CHALLENGE,
assert_ok,
assert_unauthorized,
)
ME = f"{API}/users/me"
def basic_header(raw: bytes) -> dict[str, str]:
"""`Authorization: Basic` из произвольных байтов, в том числе битых."""
return {"Authorization": "Basic " + base64.b64encode(raw).decode("ascii")}
@pytest.mark.spec("sessions", "Успешный вход")
def test_login(api: Api, alice: Actor) -> None:
resp = api.login_response(alice.username, alice.password)
session = assert_ok(resp, 201, "Session")
assert session["token_type"] == "Bearer"
assert session["user"] == alice.user
expires_at = datetime.fromisoformat(session["expires_at"])
assert expires_at > datetime.now(UTC)
me = api.request("GET", ME, headers=bearer_auth(session["token"]))
assert assert_ok(me, 200, "User") == alice.user
@pytest.mark.spec("sessions", "Успешный вход")
def test_login_ignores_body(api: Api, alice: Actor, eve: Actor) -> None:
# тело не читается: вход определяет только Basic
resp = api.request(
"POST",
SESSIONS,
headers=basic_header(f"{alice.username}:{alice.password}".encode()),
json={"username": eve.username, "password": eve.password},
)
assert assert_ok(resp, 201, "Session")["user"] == alice.user
@pytest.mark.spec("sessions", "Двоеточие и не-ASCII в пароле")
def test_password_with_colon_and_cyrillic(api: Api) -> None:
password = "Пароль:с:двоеточиями-1"
actor = api.register(password=password)
resp = api.request("GET", ME, actor=actor)
assert assert_ok(resp, 200, "User") == actor.user
@pytest.mark.spec("sessions", "Несколько сессий")
def test_two_sessions(api: Api, alice: Actor) -> None:
second = api.login(alice.user, alice.password)
assert second.token != alice.token
for actor in (alice, second):
resp = api.request("GET", ME, actor=actor)
assert assert_ok(resp, 200, "User") == alice.user
@pytest.mark.spec("sessions", "Токен не выводится из данных пользователя")
def test_token_is_opaque(api: Api, alice: Actor) -> None:
second = api.login(alice.user, alice.password)
for token in (alice.token, second.token):
assert len(token) >= 32
for value in (alice.username, alice.id, alice.id.replace("-", "")):
assert value not in token
assert alice.token != second.token
@pytest.mark.spec("sessions", "Неизвестный пользователь")
def test_unknown_user_same_as_wrong_password(api: Api, alice: Actor) -> None:
wrong = assert_unauthorized(
api.login_response(alice.username, "Wrong-password-1"),
BASIC_CHALLENGE,
)
unknown = assert_unauthorized(
api.login_response(unique_username(), "Wrong-password-1"),
BASIC_CHALLENGE,
)
assert (unknown["code"], unknown["message"]) == (
wrong["code"],
wrong["message"],
)
@pytest.mark.spec("sessions", "Битый Basic")
def test_broken_basic(api: Api, alice: Actor) -> None:
headers = (
{"Authorization": "Basic !!!"},
basic_header(b"no-colon-here"),
basic_header(b"\xff\xfe:not-utf-8-password"),
{"Authorization": "Basic"},
bearer_auth(alice.token),
{},
)
for header in headers:
resp = api.request("POST", SESSIONS, headers=header)
assert_unauthorized(resp, BASIC_CHALLENGE)
@pytest.mark.spec("sessions", "Повторный выход")
def test_logout_twice(api: Api, alice: Actor) -> None:
assert api.logout(alice).status_code == 204
assert_unauthorized(api.logout(alice), BEARER_CHALLENGE)
# без токена выход тоже 401 с вызовом Bearer
resp = api.request("DELETE", f"{SESSIONS}/current")
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("sessions", "Другая сессия остаётся")
def test_other_session_survives_logout(api: Api, alice: Actor) -> None:
second = api.login(alice.user, alice.password)
assert api.logout(alice).status_code == 204
assert_unauthorized(api.request("GET", ME, actor=alice), BEARER_CHALLENGE)
resp = api.request("GET", ME, actor=second)
assert assert_ok(resp, 200, "User") == alice.user
def test_revoked_token_rejected_everywhere(
api: Api,
alice: Actor,
bob: Actor,
) -> None:
"""Отозванный токен не проходит ни на одном защищённом эндпоинте."""
chat = api.create_chat(alice, bob)
assert api.logout(alice).status_code == 204
for method, path in (
("GET", ME),
("GET", f"{API}/chats"),
("GET", f"{API}/chats/{chat['id']}"),
("GET", f"{API}/chats/{chat['id']}/messages"),
):
resp = api.request(method, path, actor=alice)
assert_unauthorized(resp, BEARER_CHALLENGE)
resp = api.post_message(alice, chat["id"], json={"text": "после выхода"})
assert_unauthorized(resp, BEARER_CHALLENGE)
assert api.all_messages(bob, chat["id"]) == []
+116
View File
@@ -0,0 +1,116 @@
"""Спек `users`: регистрация и текущий пользователь."""
import httpx
import pytest
from api_client import API, Actor, Api, registration, unique_username
from contract import (
BASIC_CHALLENGE,
assert_error,
assert_ok,
assert_unauthorized,
)
def register_raw(
api: Api,
username: str,
display_name: str = "User",
password: str | None = None,
) -> httpx.Response:
return api.request(
"POST",
f"{API}/users",
json=registration(username, display_name, password),
)
@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
@pytest.mark.spec("users", "Нет пароля")
def test_password_missing(api: Api) -> None:
resp = api.request(
"POST",
f"{API}/users",
json={"username": unique_username(), "display_name": "User"},
)
assert_error(resp, 400)
@pytest.mark.spec("users", "Граница длины пароля")
def test_password_length(api: Api) -> None:
# длина — в code points: «ж» занимает два байта UTF-8
for length, status in ((11, 400), (12, 201), (128, 201), (129, 400)):
resp = register_raw(api, unique_username(), password="ж" * length)
if status == 201:
assert_ok(resp, 201, "User")
else:
assert_error(resp, status)
@pytest.mark.spec("users", "Пароль из пробелов")
def test_password_blank(api: Api) -> None:
assert_error(register_raw(api, unique_username(), password=" " * 12), 400)
# значимые пробелы по краям допустимы и не обрезаются
actor = api.register(password=" spaced-pass ")
assert api.login(actor.user, " spaced-pass ").user == actor.user
@pytest.mark.spec("users", "Длинный пароль в UTF-8 целиком")
def test_long_password_compared_whole(api: Api) -> None:
password = "ж" * 128
actor = api.register(password=password)
changed = password[:-1] + "з"
resp = api.login_response(actor.username, changed)
assert_unauthorized(resp, BASIC_CHALLENGE)
assert api.login(actor.user, password).user == actor.user