chore: carry lab 3 over
- carry the lab 3 solution over from mtusi2026lab3-safronov (solution/bvt2301-safronov, ce89eba): src, migrations, student-tests, bench, openspec, .claude, infra/haproxy and infra/valkey, own scripts, Dockerfile, compose, pyproject and uv lock - merge Makefile, .gitignore and .dockerignore (the lab 3 versions only add lines to the skeleton, which is the same in lab 4) and .env.example (lab 4 skeleton names listed in the header) - rename the compose project to mtusi-lab4 and the image to :lab4 so the stand does not reuse the lab 3 containers and volumes - update AGENTS.md for lab 4: current lab, origin commit, contract and test files of the new skeleton Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,348 @@
|
||||
"""HTTP-клиент набора: запросы к API и идентификация в одном месте."""
|
||||
|
||||
import base64
|
||||
import dataclasses
|
||||
import secrets
|
||||
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"
|
||||
|
||||
|
||||
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,
|
||||
) -> dict[str, Any]:
|
||||
"""Успешная отправка: 201 и `Message`; без `key` — новый ключ."""
|
||||
resp = self.post_message(
|
||||
actor,
|
||||
chat_id,
|
||||
key=new_key() if key is None else key,
|
||||
json={"text": text},
|
||||
)
|
||||
return assert_ok(resp, 201, "Message")
|
||||
|
||||
def messages_page(
|
||||
self,
|
||||
actor: Actor,
|
||||
chat_id: str,
|
||||
*,
|
||||
limit: int | str | None = None,
|
||||
cursor: str | None = None,
|
||||
) -> httpx.Response:
|
||||
return self.request(
|
||||
"GET",
|
||||
f"{API}/chats/{chat_id}/messages",
|
||||
actor=actor,
|
||||
params=_page_params(limit, cursor),
|
||||
)
|
||||
|
||||
def chats_page(
|
||||
self,
|
||||
actor: Actor,
|
||||
*,
|
||||
limit: int | str | None = None,
|
||||
cursor: str | None = None,
|
||||
) -> httpx.Response:
|
||||
return self.request(
|
||||
"GET",
|
||||
f"{API}/chats",
|
||||
actor=actor,
|
||||
params=_page_params(limit, cursor),
|
||||
)
|
||||
|
||||
def message_pages(
|
||||
self,
|
||||
actor: Actor,
|
||||
chat_id: str,
|
||||
*,
|
||||
limits: Sequence[int] = (100,),
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Все страницы истории по `next_cursor`.
|
||||
|
||||
Страница `i` берётся с `limits[i]`, дальше — с последним `limit`.
|
||||
"""
|
||||
|
||||
def fetch(limit: int, cursor: str | None) -> httpx.Response:
|
||||
return self.messages_page(
|
||||
actor,
|
||||
chat_id,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
)
|
||||
|
||||
return walk_pages(fetch, limits=limits, schema="MessagePage")
|
||||
|
||||
def chat_pages(
|
||||
self,
|
||||
actor: Actor,
|
||||
*,
|
||||
limits: Sequence[int] = (100,),
|
||||
) -> list[dict[str, Any]]:
|
||||
def fetch(limit: int, cursor: str | None) -> httpx.Response:
|
||||
return self.chats_page(actor, limit=limit, cursor=cursor)
|
||||
|
||||
return walk_pages(fetch, limits=limits, schema="ChatPage")
|
||||
|
||||
def all_messages(
|
||||
self,
|
||||
actor: Actor,
|
||||
chat_id: str,
|
||||
*,
|
||||
limits: Sequence[int] = (100,),
|
||||
) -> list[dict[str, Any]]:
|
||||
pages = self.message_pages(actor, chat_id, limits=limits)
|
||||
return [item for page in pages for item in page["items"]]
|
||||
|
||||
|
||||
def walk_pages(
|
||||
fetch: Callable[[int, str | None], httpx.Response],
|
||||
*,
|
||||
limits: Sequence[int],
|
||||
schema: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Обход списка по курсору до `next_cursor` null."""
|
||||
pages: list[dict[str, Any]] = []
|
||||
cursor: str | None = None
|
||||
for number in range(MAX_PAGES):
|
||||
limit = limits[min(number, len(limits) - 1)]
|
||||
page = assert_ok(fetch(limit, cursor), 200, schema)
|
||||
assert len(page["items"]) <= limit, (
|
||||
f"page {number} has {len(page['items'])} items, limit {limit}"
|
||||
)
|
||||
pages.append(page)
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return pages
|
||||
raise AssertionError(f"next_cursor is not null after {MAX_PAGES} pages")
|
||||
|
||||
|
||||
def _page_params(
|
||||
limit: int | str | None,
|
||||
cursor: str | None,
|
||||
) -> dict[str, str]:
|
||||
params: dict[str, str] = {}
|
||||
if limit is not None:
|
||||
params["limit"] = str(limit)
|
||||
if cursor is not None:
|
||||
params["cursor"] = cursor
|
||||
return params
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Настройка набора: адрес стенда, проверка доступности, фикстуры."""
|
||||
|
||||
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("/")
|
||||
FAULT_HOOK_TIMEOUT_S = 120
|
||||
|
||||
|
||||
@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):
|
||||
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) -> str:
|
||||
result = subprocess.run(
|
||||
[FAULT_HOOK, *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=FAULT_HOOK_TIMEOUT_S,
|
||||
check=False,
|
||||
)
|
||||
assert result.returncode == 0, (
|
||||
f"fault hook {' '.join(args)}: {result.stderr.strip()}"
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
return call
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def tight_api() -> Iterator[Api]:
|
||||
"""API стенда отказов со сроками сессии и ключа идемпотентности 2 с и
|
||||
пулом из одного соединения."""
|
||||
with Api(FAULT_TIGHT_BASE_URL) as client:
|
||||
yield client
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Проверка ответов по `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"})
|
||||
TIME_KEYS = frozenset({"created_at", "expires_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",
|
||||
500: "internal_error",
|
||||
503: "unavailable",
|
||||
}
|
||||
|
||||
|
||||
@cache
|
||||
def contract() -> dict[str, Any]:
|
||||
return json.loads(CONTRACT_PATH.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@cache
|
||||
def validator(schema: str) -> Draft202012Validator:
|
||||
"""Валидатор `#/components/schemas/<schema>` внутри контракта."""
|
||||
document = contract()
|
||||
if schema not in document["components"]["schemas"]:
|
||||
raise KeyError(f"no schema {schema!r} in {CONTRACT_PATH.name}")
|
||||
resource = Resource.from_contents(
|
||||
document,
|
||||
default_specification=DRAFT202012,
|
||||
)
|
||||
registry = Registry().with_resource(_CONTRACT_URI, resource)
|
||||
return Draft202012Validator(
|
||||
{"$ref": f"{_CONTRACT_URI}#/components/schemas/{schema}"},
|
||||
registry=registry,
|
||||
)
|
||||
|
||||
|
||||
def check_body(body: Any, schema: str) -> None:
|
||||
"""Тело совпадает со схемой контракта, `id` и время — в его формате."""
|
||||
errors = sorted(
|
||||
validator(schema).iter_errors(body),
|
||||
key=lambda error: list(map(str, error.path)),
|
||||
)
|
||||
assert not errors, f"{schema} schema: " + "; ".join(
|
||||
f"/{'/'.join(map(str, error.path))}: {error.message}"
|
||||
for error in errors
|
||||
)
|
||||
check_formats(body)
|
||||
|
||||
|
||||
def check_formats(value: Any, path: str = "") -> None:
|
||||
if isinstance(value, dict):
|
||||
for key, item in value.items():
|
||||
where = f"{path}/{key}"
|
||||
if key in ID_KEYS:
|
||||
assert_uuid(item, where)
|
||||
elif key == "member_ids":
|
||||
for number, member in enumerate(item):
|
||||
assert_uuid(member, f"{where}/{number}")
|
||||
elif key 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",
|
||||
)
|
||||
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_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]}"
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
# Override стенда отказов make failure_checks (student-tests/run_failures.py):
|
||||
# тот же docker-compose.yml под проектом <рабочий>-failures (имя рабочего
|
||||
# проекта — из name в docker-compose.yml, сейчас mtusi-lab4), со своим
|
||||
# volume и сетью. Порты Postgres и Valkey не публикуются: к ним ходит только
|
||||
# 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 []
|
||||
haproxy:
|
||||
ports: !reset []
|
||||
Executable
+429
@@ -0,0 +1,429 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Hook стенда отказов для проверок `fault` (`make failure_checks`).
|
||||
|
||||
Тесты вызывают его как `[FAULT_HOOK, действие, аргументы…]` без shell —
|
||||
так же `tests/resilience.py` вызывает `ACTION_SCRIPT`. Сами тесты docker
|
||||
не трогают. Hook работает только с проектом compose из `FAULT_PROJECT`,
|
||||
его задаёт `student-tests/run_failures.py`. Проект рабочего стенда hook
|
||||
не трогает. Решение 3 design change `failure-checks`.
|
||||
|
||||
Действия:
|
||||
stop|start|pause|unpause postgres|valkey
|
||||
flush-cache FLUSHALL
|
||||
cache-hits keyspace_hits из INFO stats
|
||||
cache-has-chat <chat_id> EXISTS ключа карточки: 0 или 1
|
||||
fail-members <title> вставка участников чата с этим названием
|
||||
падает (триггер в базе стенда отказов)
|
||||
clear-fail-members убрать триггер
|
||||
fail-messages <text> вставка сообщения с этим текстом падает
|
||||
(триггер; ключ идемпотентности к этому
|
||||
моменту уже вставлен в той же транзакции)
|
||||
clear-fail-messages убрать триггер
|
||||
count-chats <title> число чатов с этим названием
|
||||
fill-connections <секунд> занять все слоты max_connections сессиями
|
||||
psql (`SELECT pg_sleep`) и оборвать
|
||||
соединения API: их пулы переподключаются
|
||||
и получают «too many clients» (53300)
|
||||
clear-connections освободить слоты и дождаться подключения
|
||||
db-sessions pg_stat_database.sessions базы стенда:
|
||||
сколько сессий PostgreSQL приняла за всё
|
||||
время (учитывает и сессию самого вызова)
|
||||
|
||||
Пароли не печатает: valkey-cli берёт пароль из VALKEYCLI_AUTH
|
||||
контейнера, psql работает от POSTGRES_USER контейнера. Только stdlib.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COMPOSE_FILES = (
|
||||
ROOT / "docker-compose.yml",
|
||||
ROOT / "student-tests" / "failures.compose.yml",
|
||||
)
|
||||
PROJECT_SUFFIX = "-failures"
|
||||
SERVICES = ("postgres", "valkey")
|
||||
# та же проверка, что в healthcheck сервиса в docker-compose.yml. У
|
||||
# PostgreSQL стенда отказов healthcheck переопределён на базу postgres
|
||||
# (failures.compose.yml), а проба после start / unpause ходит в базу
|
||||
# приложения и добавляет в её pg_stat_database одну сессию: тест «Соединения
|
||||
# пула не переоткрываются» start в своём окне не вызывает
|
||||
PROBES = {
|
||||
"postgres": 'pg_isready -q -h 127.0.0.1 -U "$POSTGRES_USER" '
|
||||
'-d "$POSTGRES_DB"',
|
||||
"valkey": 'test "$(valkey-cli -p "$VALKEY_PORT" ping)" = PONG',
|
||||
}
|
||||
PROBE_TIMEOUT_S = 30
|
||||
# начало ключа карточки — копия CACHE_KEY_PREFIX из src/utils/constants.py:
|
||||
# hook на stdlib и код приложения не импортирует. Меняется формат ключа —
|
||||
# менять и здесь, иначе упадут test_flush_cache и test_valkey_back
|
||||
CACHE_KEY_PREFIX = "messenger:v1"
|
||||
|
||||
FAIL_MEMBERS_SQL = """\
|
||||
CREATE OR REPLACE FUNCTION fault_fail_members() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF (SELECT title FROM chats WHERE id = NEW.chat_id) = TG_ARGV[0] THEN
|
||||
RAISE EXCEPTION 'fault injected: chat members insert';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END
|
||||
$$;
|
||||
DROP TRIGGER IF EXISTS fault_fail_members ON chat_members;
|
||||
CREATE TRIGGER fault_fail_members BEFORE INSERT ON chat_members
|
||||
FOR EACH ROW EXECUTE FUNCTION fault_fail_members(:'title');
|
||||
"""
|
||||
CLEAR_FAIL_MEMBERS_SQL = """\
|
||||
DROP TRIGGER IF EXISTS fault_fail_members ON chat_members;
|
||||
DROP FUNCTION IF EXISTS fault_fail_members();
|
||||
"""
|
||||
FAIL_MESSAGES_SQL = """\
|
||||
CREATE OR REPLACE FUNCTION fault_fail_messages() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.text = TG_ARGV[0] THEN
|
||||
RAISE EXCEPTION 'fault injected: message insert';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END
|
||||
$$;
|
||||
DROP TRIGGER IF EXISTS fault_fail_messages ON messages;
|
||||
CREATE TRIGGER fault_fail_messages BEFORE INSERT ON messages
|
||||
FOR EACH ROW EXECUTE FUNCTION fault_fail_messages(:'title');
|
||||
"""
|
||||
CLEAR_FAIL_MESSAGES_SQL = """\
|
||||
DROP TRIGGER IF EXISTS fault_fail_messages ON messages;
|
||||
DROP FUNCTION IF EXISTS fault_fail_messages();
|
||||
"""
|
||||
COUNT_CHATS_SQL = "SELECT count(*) FROM chats WHERE title = :'title';\n"
|
||||
# Сессия psql учитывает себя в sessions, только когда сбросит свои
|
||||
# счётчики: обычно на первом простое до запроса, но без ожидания
|
||||
# блокировки, и при занятой — позже. Принудительный сброс в отдельной
|
||||
# транзакции делает это детерминированным: значение всегда включает
|
||||
# сессию самого вызова
|
||||
DB_SESSIONS_SQL = """\
|
||||
SELECT pg_stat_force_next_flush();
|
||||
SELECT sessions FROM pg_stat_database WHERE datname = current_database();
|
||||
"""
|
||||
|
||||
# Заполнение слотов: отвязанный sh в контейнере Postgres. Сначала столько
|
||||
# попыток, сколько слотов, затем новая попытка раз в 0,05 с до конца
|
||||
# срока: слот, освободившийся после обрыва соединения API, сразу занимает
|
||||
# снова psql, а не переподключение пула. Лишние попытки получают отказ и
|
||||
# выходят. Сессии — через сокет ([local]), пользователь контейнера.
|
||||
# После CLEAR_FILL_SH фоновые psql — сироты пространства PID: их подбирает
|
||||
# init стенда отказов (init: true у postgres в failures.compose.yml), а не
|
||||
# postmaster, для которого выход чужого потомка с кодом 2 — авария
|
||||
FILL_PID = "/tmp/fault-fill.pid"
|
||||
FILL_SH = f"""\
|
||||
echo $$ > {FILL_PID}
|
||||
hold() {{
|
||||
PGAPPNAME=fault_fill psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -XAtq \\
|
||||
-c "SELECT pg_sleep($1)" >/dev/null 2>&1 &
|
||||
}}
|
||||
end=$(( $(date +%s) + $1 ))
|
||||
slots=$(psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -XAtq \\
|
||||
-c 'SHOW max_connections')
|
||||
i=0
|
||||
while [ "$i" -lt "$slots" ]; do hold "$1"; i=$((i + 1)); done
|
||||
while [ "$(date +%s)" -lt "$end" ]; do hold "$1"; sleep 0.05; done
|
||||
"""
|
||||
# Обрыв соединений по TCP (это пулы API) сигналом SIGTERM — то же, что
|
||||
# pg_terminate_backend, но без своего слота. Заголовок процесса backend —
|
||||
# «postgres: <user> <db> <адрес>(<порт>) <состояние>»; сокет ([local]) и
|
||||
# проверку готовности с 127.0.0.1 не трогаем. Печатает число оборванных.
|
||||
KILL_TCP_SH = """\
|
||||
n=0
|
||||
for d in /proc/[0-9]*; do
|
||||
t=$(tr '\\0' ' ' < "$d/cmdline" 2>/dev/null) || continue
|
||||
case "$t" in
|
||||
"postgres: "*" 127.0.0.1("*) ;;
|
||||
"postgres: "*"("*")"*) kill -TERM "${d#/proc/}" 2>/dev/null \\
|
||||
&& n=$((n + 1)) ;;
|
||||
esac
|
||||
done
|
||||
echo "$n"
|
||||
"""
|
||||
CLEAR_FILL_SH = f"""\
|
||||
[ -f {FILL_PID} ] && kill "$(cat {FILL_PID})" 2>/dev/null
|
||||
rm -f {FILL_PID}
|
||||
for d in /proc/[0-9]*; do
|
||||
t=$(tr '\\0' ' ' < "$d/cmdline" 2>/dev/null) || continue
|
||||
case "$t" in
|
||||
"postgres: "*" [local] "*) kill -TERM "${{d#/proc/}}" 2>/dev/null ;;
|
||||
esac
|
||||
done
|
||||
"""
|
||||
PROBE_SQL_SH = (
|
||||
'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -XAtq -c "SELECT 1"'
|
||||
)
|
||||
TOO_MANY = "too many clients"
|
||||
FILL_TIMEOUT_S = 20
|
||||
|
||||
|
||||
class HookError(Exception):
|
||||
"""Неверный вызов или проект: код 2 и сообщение в stderr."""
|
||||
|
||||
|
||||
def working_project() -> str:
|
||||
"""Имя проекта рабочего стенда — из docker-compose.yml без `-p`."""
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "config", "--format", "json"],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
return json.loads(result.stdout)["name"]
|
||||
|
||||
|
||||
def fault_project() -> str:
|
||||
project = os.environ.get("FAULT_PROJECT", "")
|
||||
if not project.endswith(PROJECT_SUFFIX):
|
||||
raise HookError(
|
||||
f"FAULT_PROJECT must end with {PROJECT_SUFFIX!r}: "
|
||||
"run make failure_checks",
|
||||
)
|
||||
if project == working_project():
|
||||
raise HookError("FAULT_PROJECT is the working stand, refusing")
|
||||
return project
|
||||
|
||||
|
||||
def compose_run(
|
||||
project: str,
|
||||
*args: str,
|
||||
stdin: str | None = None,
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
files = [arg for path in COMPOSE_FILES for arg in ("-f", str(path))]
|
||||
return subprocess.run(
|
||||
["docker", "compose", "-p", project, *files, *args],
|
||||
cwd=ROOT,
|
||||
input=stdin,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
def compose(project: str, *args: str, stdin: str | None = None) -> str:
|
||||
result = compose_run(project, *args, stdin=stdin)
|
||||
if result.returncode != 0:
|
||||
sys.stderr.write(result.stderr)
|
||||
raise SystemExit(result.returncode)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def wait_answers(project: str, name: str) -> str:
|
||||
"""Ждать, пока сервис ответит своей проверкой из healthcheck.
|
||||
|
||||
После `unpause` Docker до следующего запуска healthcheck (до 5 с)
|
||||
показывает `unhealthy`, и `up --wait` сразу выходит с ошибкой, хотя
|
||||
сервис уже отвечает. Поэтому проверка — напрямую.
|
||||
"""
|
||||
deadline = time.monotonic() + PROBE_TIMEOUT_S
|
||||
while time.monotonic() < deadline:
|
||||
probe = compose_run(
|
||||
project,
|
||||
"exec",
|
||||
"-T",
|
||||
name,
|
||||
"sh",
|
||||
"-c",
|
||||
PROBES[name],
|
||||
)
|
||||
if probe.returncode == 0:
|
||||
return ""
|
||||
time.sleep(0.2)
|
||||
raise HookError(f"{name} does not answer in {PROBE_TIMEOUT_S}s")
|
||||
|
||||
|
||||
def valkey(project: str, *args: str) -> str:
|
||||
# аргументы — позиционные параметры sh, без подстановки в строку
|
||||
return compose(
|
||||
project,
|
||||
"exec",
|
||||
"-T",
|
||||
"valkey",
|
||||
"sh",
|
||||
"-c",
|
||||
'exec valkey-cli -p "$VALKEY_PORT" "$@"',
|
||||
"sh",
|
||||
*args,
|
||||
)
|
||||
|
||||
|
||||
def psql(project: str, sql: str, *, title: str = "") -> str:
|
||||
return compose(
|
||||
project,
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -XAtq '
|
||||
'-v ON_ERROR_STOP=1 -v title="$1"',
|
||||
"sh",
|
||||
title,
|
||||
stdin=sql,
|
||||
)
|
||||
|
||||
|
||||
def service(name: str) -> str:
|
||||
if name not in SERVICES:
|
||||
raise HookError(f"service must be one of {SERVICES}")
|
||||
return name
|
||||
|
||||
|
||||
def wait_healthy(project: str, name: str) -> str:
|
||||
# тот же контейнер, без пересоздания; --wait ждёт его healthcheck
|
||||
return compose(project, "up", "-d", "--wait", "--no-recreate", name)
|
||||
|
||||
|
||||
def cache_hits(project: str) -> str:
|
||||
for line in valkey(project, "INFO", "stats").splitlines():
|
||||
if line.startswith("keyspace_hits:"):
|
||||
return line.split(":", 1)[1].strip()
|
||||
raise HookError("keyspace_hits not found in INFO stats")
|
||||
|
||||
|
||||
def cache_has_chat(project: str, chat_id: str) -> str:
|
||||
database = compose(
|
||||
project,
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"printenv",
|
||||
"POSTGRES_DB",
|
||||
)
|
||||
key = f"{CACHE_KEY_PREFIX}:{database}:chat:{uuid.UUID(chat_id)}"
|
||||
return valkey(project, "EXISTS", key)
|
||||
|
||||
|
||||
def postgres_sh(project: str, script: str, *args: str) -> str:
|
||||
return compose(
|
||||
project,
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
script,
|
||||
"sh",
|
||||
*args,
|
||||
)
|
||||
|
||||
|
||||
def probe_connect(project: str) -> subprocess.CompletedProcess[str]:
|
||||
"""Новое подключение psql и `SELECT 1`."""
|
||||
return compose_run(
|
||||
project,
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
PROBE_SQL_SH,
|
||||
)
|
||||
|
||||
|
||||
def slots_full(project: str) -> bool:
|
||||
"""Новое подключение получает «too many clients»."""
|
||||
probe = probe_connect(project)
|
||||
return probe.returncode != 0 and TOO_MANY in probe.stderr
|
||||
|
||||
|
||||
def fill_connections(project: str, seconds: str) -> str:
|
||||
"""Все слоты заняты psql, соединений API не осталось.
|
||||
|
||||
Готово, когда новое подключение получает отказ, а обрывать уже
|
||||
некого: пул API, переподключаясь, получит 53300.
|
||||
"""
|
||||
if int(seconds) <= 0:
|
||||
raise HookError("seconds must be positive")
|
||||
compose(
|
||||
project,
|
||||
"exec",
|
||||
"-d",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
FILL_SH,
|
||||
"sh",
|
||||
str(int(seconds)),
|
||||
)
|
||||
deadline = time.monotonic() + FILL_TIMEOUT_S
|
||||
while time.monotonic() < deadline:
|
||||
if slots_full(project) and postgres_sh(project, KILL_TCP_SH) == "0":
|
||||
return ""
|
||||
time.sleep(0.1)
|
||||
raise HookError(f"connections are not filled in {FILL_TIMEOUT_S}s")
|
||||
|
||||
|
||||
def clear_connections(project: str) -> str:
|
||||
deadline = time.monotonic() + FILL_TIMEOUT_S
|
||||
while time.monotonic() < deadline:
|
||||
postgres_sh(project, CLEAR_FILL_SH)
|
||||
if probe_connect(project).returncode == 0:
|
||||
return ""
|
||||
time.sleep(0.2)
|
||||
raise HookError(f"connections are not freed in {FILL_TIMEOUT_S}s")
|
||||
|
||||
|
||||
def run(project: str, action: str, args: list[str]) -> str:
|
||||
"""Выполнить действие; синтаксис без match: hook запускают и 3.9."""
|
||||
if action in ("stop", "pause") and len(args) == 1:
|
||||
return compose(project, action, service(args[0]))
|
||||
if action == "start" and len(args) == 1:
|
||||
return wait_healthy(project, service(args[0]))
|
||||
if action == "unpause" and len(args) == 1:
|
||||
compose(project, "unpause", service(args[0]))
|
||||
return wait_answers(project, args[0])
|
||||
if action == "flush-cache" and not args:
|
||||
return valkey(project, "FLUSHALL")
|
||||
if action == "cache-hits" and not args:
|
||||
return cache_hits(project)
|
||||
if action == "cache-has-chat" and len(args) == 1:
|
||||
return cache_has_chat(project, args[0])
|
||||
if action == "fail-members" and len(args) == 1:
|
||||
return psql(project, FAIL_MEMBERS_SQL, title=args[0])
|
||||
if action == "clear-fail-members" and not args:
|
||||
return psql(project, CLEAR_FAIL_MEMBERS_SQL)
|
||||
if action == "fail-messages" and len(args) == 1:
|
||||
# аргумент триггера передаётся той же переменной psql, что title
|
||||
return psql(project, FAIL_MESSAGES_SQL, title=args[0])
|
||||
if action == "clear-fail-messages" and not args:
|
||||
return psql(project, CLEAR_FAIL_MESSAGES_SQL)
|
||||
if action == "count-chats" and len(args) == 1:
|
||||
return psql(project, COUNT_CHATS_SQL, title=args[0])
|
||||
if action == "fill-connections" and len(args) == 1:
|
||||
return fill_connections(project, args[0])
|
||||
if action == "clear-connections" and not args:
|
||||
return clear_connections(project)
|
||||
if action == "db-sessions" and not args:
|
||||
return psql(project, DB_SESSIONS_SQL)
|
||||
raise HookError(f"unknown action or arguments: {action} {args}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__, file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
output = run(fault_project(), sys.argv[1], sys.argv[2:])
|
||||
except (HookError, ValueError) as e:
|
||||
print(f"fault_hook: {e}", file=sys.stderr)
|
||||
return 2
|
||||
if output:
|
||||
print(output)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,318 @@
|
||||
"""`make failure_checks`: проверки отказов на отдельном стенде.
|
||||
|
||||
Поднимает тот же `docker-compose.yml` под проектом `<рабочий>-failures`
|
||||
с override `student-tests/failures.compose.yml`: свои PostgreSQL и Valkey
|
||||
со своим volume, порты хранилищ не публикуются. Затем:
|
||||
- собирает образ из рабочего дерева и применяет миграции;
|
||||
- запускает два контейнера API: обычный и «тесный» (сроки сессии и ключа
|
||||
идемпотентности 2 с, пул из одного соединения);
|
||||
- прогоняет тесты с маркером `fault` (`pytest -m fault`), передав им hook
|
||||
`student-tests/fault_hook.py`;
|
||||
- после тестов читает журнал 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",
|
||||
}
|
||||
|
||||
|
||||
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 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"
|
||||
containers = [default_name, tight_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 and valkey")
|
||||
dc(project, "up", "-d", "--wait", "postgres", "valkey")
|
||||
say("migrations")
|
||||
dc(project, "run", "--rm", "migrate")
|
||||
say("start api containers")
|
||||
base_url = start_api(project, default_name, free_port(), {})
|
||||
tight_url = start_api(project, tight_name, free_port(), TIGHT_ENV)
|
||||
say(f"ready: api={base_url} tight={tight_url}")
|
||||
env = os.environ | {
|
||||
"BASE_URL": base_url,
|
||||
"FAULT_TIGHT_BASE_URL": tight_url,
|
||||
"FAULT_HOOK": str(FAULT_HOOK),
|
||||
"FAULT_PROJECT": project,
|
||||
}
|
||||
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("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())
|
||||
@@ -0,0 +1,239 @@
|
||||
"""`make test_isolated`: образ на временной базе `test_<db>`.
|
||||
|
||||
Создаёт базу в Postgres стенда, накатывает на неё миграции сервисом
|
||||
`migrate`, поднимает отдельный контейнер `api` из определения compose с
|
||||
подменой только `DATABASE__NAME`, прогоняет `make test` и
|
||||
`make student_test` (`EXPECT_REPLICAS=1`: один процесс без
|
||||
балансировщика, тесты реплик пропускаются), затем удаляет контейнер и
|
||||
базу — при любом исходе, в том числе по Ctrl+C. Рабочая база и рабочие
|
||||
контейнеры стенда не трогаются. Valkey стенда общий: ключи кэша включают имя базы, и
|
||||
карточки тестового прогона не смешиваются с рабочими. Только 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_]+$")
|
||||
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 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
|
||||
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} container={container} base_url={base_url}")
|
||||
remove_container(container)
|
||||
drop_database(test_db)
|
||||
|
||||
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}")
|
||||
else:
|
||||
drop_database(test_db)
|
||||
except subprocess.CalledProcessError 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())
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Сверка тестов со сценариями основных спеков `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",
|
||||
)
|
||||
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",
|
||||
),
|
||||
("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()
|
||||
]
|
||||
@@ -0,0 +1,391 @@
|
||||
"""Спек `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
|
||||
|
||||
from api_client import (
|
||||
API,
|
||||
Actor,
|
||||
Api,
|
||||
new_key,
|
||||
registration,
|
||||
unique_username,
|
||||
)
|
||||
from contract import (
|
||||
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}
|
||||
@@ -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"]]
|
||||
@@ -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"]
|
||||
@@ -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}")
|
||||
@@ -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 / Удалённый сценарий",
|
||||
]
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Спек `data-storage`.
|
||||
|
||||
Гонки — в `test_race.py`; рестарт, отказы БД и пул — исключения в
|
||||
`spec_coverage.py`.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from api_client import API, Actor, Api
|
||||
from contract import assert_ok
|
||||
|
||||
|
||||
@pytest.mark.spec("data-storage", "Созданное видно сразу")
|
||||
def test_created_user_visible_at_once(api: Api) -> None:
|
||||
for _ in range(5):
|
||||
actor = api.register()
|
||||
resp = api.request("GET", f"{API}/users/me", actor=actor)
|
||||
assert assert_ok(resp, 200, "User") == actor.user
|
||||
|
||||
|
||||
@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
|
||||
@@ -0,0 +1,509 @@
|
||||
"""Проверки отказов: выполняет только `make failure_checks` (маркер `fault`).
|
||||
|
||||
Стенд и hook готовит `student-tests/run_failures.py`: свои Postgres и
|
||||
Valkey, обычный API (`BASE_URL`) и «тесный» (сроки сессии и ключа
|
||||
идемпотентности 2 с, пул из одного соединения). На хранилища тесты действуют только через фикстуру
|
||||
`stand` (hook `student-tests/fault_hook.py`) и всегда возвращают их в
|
||||
рабочее состояние. Решение 4 design change `failure-checks`.
|
||||
"""
|
||||
|
||||
import statistics
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from api_client import API, Actor, Api, new_key
|
||||
from contract import (
|
||||
BEARER_CHALLENGE,
|
||||
assert_error,
|
||||
assert_ok,
|
||||
assert_unauthorized,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.fault
|
||||
|
||||
type Stand = Callable[..., str]
|
||||
|
||||
RESTORE = {"stop": "start", "pause": "unpause"}
|
||||
# запас к границам времени: планировщик Docker Desktop
|
||||
SLACK_S = 0.3
|
||||
# [cache] timeout_seconds и retry_after_seconds по умолчанию
|
||||
CACHE_TIMEOUT_S = 0.2
|
||||
CACHE_RETRY_AFTER_S = 5
|
||||
# окружение «тесного» API (TIGHT_ENV в run_failures.py)
|
||||
SESSION_TTL_S = 2
|
||||
IDEMPOTENCY_TTL_S = 2
|
||||
POOL_TIMEOUT_S = 1
|
||||
# срок проверки Postgres в /health/ready
|
||||
READINESS_TIMEOUT_S = 2
|
||||
# сколько секунд hook держит слоты max_connections; clear-connections
|
||||
# освобождает их раньше
|
||||
FILL_HOLD_S = 30
|
||||
ME = f"{API}/users/me"
|
||||
|
||||
|
||||
@contextmanager
|
||||
def outage(stand: Stand, action: str, service: str) -> Iterator[None]:
|
||||
"""`stop` или `pause` хранилища; в `finally` — обратно."""
|
||||
stand(action, service)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
stand(RESTORE[action], service)
|
||||
|
||||
|
||||
def timed(
|
||||
call: Callable[[], httpx.Response],
|
||||
) -> tuple[httpx.Response, float]:
|
||||
started = time.monotonic()
|
||||
resp = call()
|
||||
return resp, time.monotonic() - started
|
||||
|
||||
|
||||
def read_chat(api: Api, actor: Actor, chat: dict[str, Any]) -> httpx.Response:
|
||||
return api.request("GET", f"{API}/chats/{chat['id']}", actor=actor)
|
||||
|
||||
|
||||
def wait_cache_ready(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
actor: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
"""Дождаться, пока чтение снова пишет карточку в кэш.
|
||||
|
||||
После отказа в прошлом тесте API пропускает кэш ещё до 5 с.
|
||||
"""
|
||||
deadline = time.monotonic() + CACHE_RETRY_AFTER_S + 2
|
||||
stand("flush-cache")
|
||||
while time.monotonic() < deadline:
|
||||
assert_ok(read_chat(api, actor, chat), 200, "Chat")
|
||||
if stand("cache-has-chat", chat["id"]) == "1":
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise AssertionError("cache did not come back")
|
||||
|
||||
|
||||
def chat_titles(api: Api, actor: Actor) -> set[str]:
|
||||
return {
|
||||
chat["title"]
|
||||
for page in api.chat_pages(actor)
|
||||
for chat in page["items"]
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Сессии: срок 2 с на «тесном» API, БД остановлена — на обычном
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.spec("sessions", "Истёкший токен")
|
||||
def test_expired_token(tight_api: Api) -> None:
|
||||
actor = tight_api.register()
|
||||
assert_ok(tight_api.request("GET", ME, actor=actor), 200, "User")
|
||||
time.sleep(SESSION_TTL_S + 1)
|
||||
assert_unauthorized(
|
||||
tight_api.request("GET", ME, actor=actor),
|
||||
BEARER_CHALLENGE,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.spec("sessions", "Срок не продлевается")
|
||||
def test_use_does_not_extend_session(tight_api: Api) -> None:
|
||||
actor = tight_api.register()
|
||||
logged_in = time.monotonic()
|
||||
successes = 0
|
||||
while time.monotonic() - logged_in < SESSION_TTL_S - SLACK_S:
|
||||
assert_ok(tight_api.request("GET", ME, actor=actor), 200, "User")
|
||||
successes += 1
|
||||
time.sleep(0.5)
|
||||
assert successes >= 3, "too few requests before expiry"
|
||||
time.sleep(max(0.0, logged_in + SESSION_TTL_S + 1 - time.monotonic()))
|
||||
assert_unauthorized(
|
||||
tight_api.request("GET", ME, actor=actor),
|
||||
BEARER_CHALLENGE,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.spec("sessions", "БД остановлена при запросе с токеном")
|
||||
def test_token_while_database_stopped(api: Api, stand: Stand) -> None:
|
||||
actor = api.register()
|
||||
with outage(stand, "stop", "postgres"):
|
||||
resp = api.request("GET", ME, actor=actor)
|
||||
assert_error(resp, 503)
|
||||
# недоступность хранилища — не отказ в аутентификации
|
||||
assert "WWW-Authenticate" not in resp.headers
|
||||
assert_ok(api.request("GET", ME, actor=actor), 200, "User")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Хранение: откат, остановленная БД, исчерпанный пул
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.spec("data-storage", "Сбой при добавлении участников")
|
||||
def test_members_failure_rolls_back_chat(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
bob: Actor,
|
||||
) -> None:
|
||||
title = f"fault-{uuid.uuid4().hex}"
|
||||
stand("fail-members", title)
|
||||
try:
|
||||
resp = api.request(
|
||||
"POST",
|
||||
f"{API}/chats",
|
||||
actor=alice,
|
||||
json={"title": title, "member_ids": [alice.id, bob.id]},
|
||||
)
|
||||
assert_error(resp, 500)
|
||||
finally:
|
||||
stand("clear-fail-members")
|
||||
for actor in (alice, bob):
|
||||
assert title not in chat_titles(api, actor)
|
||||
assert stand("count-chats", title) == "0"
|
||||
|
||||
|
||||
@pytest.mark.spec("data-storage", "БД остановлена")
|
||||
@pytest.mark.spec("data-storage", "БД вернулась")
|
||||
def test_database_stopped_and_back(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
with outage(stand, "stop", "postgres"):
|
||||
resp, took = timed(
|
||||
lambda: api.post_message(
|
||||
alice,
|
||||
chat["id"],
|
||||
json={"text": "во время отказа"},
|
||||
),
|
||||
)
|
||||
error = assert_error(resp, 503)
|
||||
assert took < 2, f"503 took {took:.2f}s"
|
||||
for word in ("postgres", "sql", "connect"):
|
||||
assert word not in error["message"].lower()
|
||||
message = api.send_message(alice, chat["id"], "после возврата")
|
||||
# запись во время отказа не зафиксирована, новая — видна
|
||||
assert api.all_messages(alice, chat["id"]) == [message]
|
||||
|
||||
|
||||
@pytest.mark.spec("data-storage", "Соединения исчерпаны")
|
||||
def test_pool_exhausted(tight_api: Api, stand: Stand) -> None:
|
||||
actor = tight_api.register()
|
||||
holder = Api(str(tight_api.client.base_url), timeout=15)
|
||||
first: list[int] = []
|
||||
|
||||
def hold_connection() -> None:
|
||||
first.append(holder.request("GET", ME, actor=actor).status_code)
|
||||
|
||||
with outage(stand, "pause", "postgres"):
|
||||
thread = threading.Thread(target=hold_connection)
|
||||
thread.start()
|
||||
time.sleep(SLACK_S)
|
||||
resp, took = timed(lambda: tight_api.request("GET", ME, actor=actor))
|
||||
assert_error(resp, 503)
|
||||
assert took < POOL_TIMEOUT_S + 0.5, f"503 took {took:.2f}s"
|
||||
thread.join()
|
||||
holder.close()
|
||||
assert first == [503]
|
||||
# срок сессии 2 с мог истечь за время паузы: проверяем пул новым входом
|
||||
fresh = tight_api.register()
|
||||
assert_ok(tight_api.request("GET", ME, actor=fresh), 200, "User")
|
||||
|
||||
|
||||
@pytest.mark.spec("data-storage", "Предел соединений PostgreSQL исчерпан")
|
||||
def test_connection_limit_reached(tight_api: Api, stand: Stand) -> None:
|
||||
actor = tight_api.register()
|
||||
# hook оборвал соединение пула: при выдаче pool_pre_ping
|
||||
# переподключается и получает «too many clients» (SQLSTATE 53300)
|
||||
stand("fill-connections", str(FILL_HOLD_S))
|
||||
try:
|
||||
resp, took = timed(lambda: tight_api.request("GET", ME, actor=actor))
|
||||
error = assert_error(resp, 503)
|
||||
# отказ PostgreSQL мгновенный: ответ не ждёт срока пула
|
||||
assert took < POOL_TIMEOUT_S + 0.5, f"503 took {took:.2f}s"
|
||||
# недоступность хранилища — не отказ в аутентификации
|
||||
assert "WWW-Authenticate" not in resp.headers
|
||||
for word in ("postgres", "sql", "client", "connect"):
|
||||
assert word not in error["message"].lower()
|
||||
finally:
|
||||
stand("clear-connections")
|
||||
# слоты свободны: сервис снова обслуживает запросы без рестарта; срок
|
||||
# сессии 2 с за время заполнения истёк — новый вход
|
||||
fresh = tight_api.register()
|
||||
assert_ok(tight_api.request("GET", ME, actor=fresh), 200, "User")
|
||||
|
||||
|
||||
# пачка одновременных запросов больше пула обычного API (10)
|
||||
BURST_THREADS = 48
|
||||
BURST_AFTER_BARRIER = 4
|
||||
# PGSTAT_IDLE_INTERVAL PostgreSQL (10 с) и запас
|
||||
STATS_FLUSH_S = 11
|
||||
|
||||
|
||||
def burst(api: Api, actor: Actor) -> None:
|
||||
"""Пачка: у каждого потока свой клиент (keep-alive), один запрос до
|
||||
барьера и BURST_AFTER_BARRIER после — около BURST_THREADS
|
||||
одновременно. Все ответы — 200."""
|
||||
barrier = threading.Barrier(BURST_THREADS)
|
||||
clients = [
|
||||
Api(str(api.client.base_url), timeout=15) for _ in range(BURST_THREADS)
|
||||
]
|
||||
responses: list[httpx.Response] = []
|
||||
errors: list[BaseException] = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def worker(client: Api) -> None:
|
||||
try:
|
||||
got = [client.request("GET", ME, actor=actor)]
|
||||
barrier.wait()
|
||||
got += [
|
||||
client.request("GET", ME, actor=actor)
|
||||
for _ in range(BURST_AFTER_BARRIER)
|
||||
]
|
||||
except BaseException as e: # noqa: BLE001 — поднимется в тесте
|
||||
barrier.abort()
|
||||
with lock:
|
||||
errors.append(e)
|
||||
return
|
||||
with lock:
|
||||
responses.extend(got)
|
||||
|
||||
threads = [
|
||||
threading.Thread(target=worker, args=(client,)) for client in clients
|
||||
]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
for client in clients:
|
||||
client.close()
|
||||
assert not errors, f"burst failed: {errors[0]!r}"
|
||||
assert len(responses) == BURST_THREADS * (1 + BURST_AFTER_BARRIER)
|
||||
for resp in responses:
|
||||
assert_ok(resp, 200, "User")
|
||||
|
||||
|
||||
@pytest.mark.spec("data-storage", "Соединения пула не переоткрываются")
|
||||
def test_pool_keeps_connections(
|
||||
api: Api,
|
||||
tight_api: Api,
|
||||
stand: Stand,
|
||||
) -> None:
|
||||
actor = api.register()
|
||||
# соединение «тесного» API могли оборвать прежние тесты
|
||||
# (fill-connections): его переподключение не должно попасть в окно
|
||||
tight = tight_api.register()
|
||||
assert_ok(tight_api.request("GET", ME, actor=tight), 200, "User")
|
||||
# прогрев: пул обычного API набирает свой размер
|
||||
for _ in range(2):
|
||||
burst(api, actor)
|
||||
# новый backend учитывает себя в sessions не сразу: его счётчики уходят
|
||||
# в общую статистику без ожидания блокировки и при занятой блокировке
|
||||
# откладываются. Простаивающий backend сбрасывает их принудительно по
|
||||
# таймеру PGSTAT_IDLE_INTERVAL (10 с): без паузы соединения прогрева
|
||||
# попадали в окно по одному
|
||||
time.sleep(STATS_FLUSH_S)
|
||||
# калибровка: второй вызов видит сессию первого вызова hook, и только её
|
||||
s1 = int(stand("db-sessions"))
|
||||
s2 = int(stand("db-sessions"))
|
||||
assert s2 - s1 == 1, f"stand is noisy: {s2 - s1} sessions between calls"
|
||||
for _ in range(3):
|
||||
burst(api, actor)
|
||||
s3 = int(stand("db-sessions"))
|
||||
opened = s3 - s2 - 1
|
||||
assert opened == 0, (
|
||||
f"PostgreSQL accepted {opened} new sessions during "
|
||||
f"{3 * BURST_THREADS * (1 + BURST_AFTER_BARRIER)} requests"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Readiness
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.spec("health", "Хранилище не готово")
|
||||
def test_readiness_without_database(api: Api, stand: Stand) -> None:
|
||||
with outage(stand, "stop", "postgres"):
|
||||
resp, took = timed(lambda: api.request("GET", "/health/ready"))
|
||||
assert_error(resp, 503)
|
||||
assert took < READINESS_TIMEOUT_S + 0.5, f"ready took {took:.2f}s"
|
||||
live = api.request("GET", "/health/live")
|
||||
assert live.status_code == 200
|
||||
assert api.request("GET", "/health/ready").status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.spec("health", "Кэш недоступен")
|
||||
def test_readiness_without_cache(api: Api, stand: Stand) -> None:
|
||||
with outage(stand, "stop", "valkey"):
|
||||
assert api.request("GET", "/health/ready").status_code == 200
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Кэш карточки чата
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.spec("chat-cache", "Очистка кэша")
|
||||
def test_flush_cache(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
bob: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
wait_cache_ready(api, stand, bob, chat)
|
||||
stand("flush-cache")
|
||||
assert stand("cache-has-chat", chat["id"]) == "0"
|
||||
assert assert_ok(read_chat(api, bob, chat), 200, "Chat") == chat
|
||||
assert stand("cache-has-chat", chat["id"]) == "1"
|
||||
|
||||
|
||||
@pytest.mark.spec("chat-cache", "Valkey остановлен")
|
||||
def test_valkey_stopped(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
bob: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
sent = [api.send_message(alice, chat["id"], "до отказа")]
|
||||
with outage(stand, "stop", "valkey"):
|
||||
resp, took = timed(lambda: read_chat(api, bob, chat))
|
||||
assert assert_ok(resp, 200, "Chat") == chat
|
||||
assert took < CACHE_TIMEOUT_S + SLACK_S, f"read took {took:.2f}s"
|
||||
resp, took = timed(
|
||||
lambda: api.post_message(
|
||||
alice,
|
||||
chat["id"],
|
||||
json={"text": "во время отказа"},
|
||||
),
|
||||
)
|
||||
sent.append(assert_ok(resp, 201, "Message"))
|
||||
assert took < CACHE_TIMEOUT_S + SLACK_S, f"send took {took:.2f}s"
|
||||
assert api.all_messages(bob, chat["id"]) == sent
|
||||
|
||||
|
||||
@pytest.mark.spec("chat-cache", "Valkey завис")
|
||||
def test_valkey_paused(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
bob: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
wait_cache_ready(api, stand, bob, chat)
|
||||
baseline = statistics.median(
|
||||
timed(lambda: read_chat(api, bob, chat))[1] for _ in range(5)
|
||||
)
|
||||
with outage(stand, "pause", "valkey"):
|
||||
resp, took = timed(lambda: read_chat(api, bob, chat))
|
||||
assert assert_ok(resp, 200, "Chat") == chat
|
||||
assert took < baseline + CACHE_TIMEOUT_S + SLACK_S, (
|
||||
f"read took {took:.2f}s, baseline {baseline:.3f}s"
|
||||
)
|
||||
# окно пропуска: следующий запрос таймаута не ждёт
|
||||
resp, took = timed(lambda: read_chat(api, bob, chat))
|
||||
assert assert_ok(resp, 200, "Chat") == chat
|
||||
assert took < CACHE_TIMEOUT_S, f"second read took {took:.2f}s"
|
||||
|
||||
|
||||
@pytest.mark.spec("chat-cache", "Valkey вернулся")
|
||||
def test_valkey_back(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
bob: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
with outage(stand, "stop", "valkey"):
|
||||
assert_ok(read_chat(api, bob, chat), 200, "Chat")
|
||||
# API не перезапускался; кэш снова в работе после окна пропуска
|
||||
time.sleep(CACHE_RETRY_AFTER_S + 0.5)
|
||||
assert_ok(read_chat(api, bob, chat), 200, "Chat")
|
||||
assert stand("cache-has-chat", chat["id"]) == "1"
|
||||
hits = int(stand("cache-hits"))
|
||||
assert assert_ok(read_chat(api, bob, chat), 200, "Chat") == chat
|
||||
assert int(stand("cache-hits")) > hits
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Идемпотентность: ключ только вместе с сообщением, срок 2 с на «тесном» API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.spec("idempotency", "Сбой при записи сообщения")
|
||||
def test_message_failure_keeps_key_free(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
# ключ вставляется первым: триггер роняет транзакцию уже после него
|
||||
text = f"fault-{uuid.uuid4().hex}"
|
||||
key = new_key()
|
||||
stand("fail-messages", text)
|
||||
try:
|
||||
resp = api.post_message(
|
||||
alice,
|
||||
chat["id"],
|
||||
key=key,
|
||||
json={"text": text},
|
||||
)
|
||||
assert_error(resp, 500)
|
||||
finally:
|
||||
stand("clear-fail-messages")
|
||||
# ключ не занят: повтор выполняется заново, а не 500 и не 409
|
||||
message = api.send_message(alice, chat["id"], text, key=key)
|
||||
assert api.all_messages(alice, chat["id"]) == [message]
|
||||
|
||||
|
||||
@pytest.mark.spec("idempotency", "Отказ БД при отправке")
|
||||
def test_database_outage_keeps_key_free(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
text = "при отказе БД"
|
||||
key = new_key()
|
||||
with outage(stand, "stop", "postgres"):
|
||||
resp = api.post_message(
|
||||
alice,
|
||||
chat["id"],
|
||||
key=key,
|
||||
json={"text": text},
|
||||
)
|
||||
assert_error(resp, 503)
|
||||
message = api.send_message(alice, chat["id"], text, key=key)
|
||||
assert api.all_messages(alice, chat["id"]) == [message]
|
||||
|
||||
|
||||
@pytest.mark.spec("idempotency", "Ключ после срока")
|
||||
def test_key_free_after_ttl(tight_api: Api) -> None:
|
||||
alice = tight_api.register()
|
||||
chat = tight_api.create_chat(alice)
|
||||
key = new_key()
|
||||
first = tight_api.send_message(alice, chat["id"], "до срока", key=key)
|
||||
# в пределах срока ключ занят: другое тело — 409
|
||||
resp = tight_api.post_message(
|
||||
alice,
|
||||
chat["id"],
|
||||
key=key,
|
||||
json={"text": "после срока"},
|
||||
)
|
||||
assert_error(resp, 409)
|
||||
time.sleep(IDEMPOTENCY_TTL_S + SLACK_S)
|
||||
# сессия «тесного» API тоже истекла: новый вход, ключ тот же
|
||||
alice = tight_api.login(alice.user, alice.password)
|
||||
second = tight_api.send_message(alice, chat["id"], "после срока", key=key)
|
||||
assert second["id"] != first["id"]
|
||||
history = tight_api.all_messages(alice, chat["id"])
|
||||
assert [item["id"] for item in history] == [first["id"], second["id"]]
|
||||
@@ -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"}
|
||||
@@ -0,0 +1,315 @@
|
||||
"""Спек `idempotency`: повторная отправка сообщения с `Idempotency-Key`.
|
||||
|
||||
Сценарии, которым нужен особый стенд (сбой записи, остановка БД, короткий
|
||||
срок ключа), — в `test_failures.py`; гонка одного ключа — в
|
||||
`test_race.py`; повтор после рестарта API — исключение с evidence.
|
||||
Повтору через другую реплику нужны ≥ 2 реплики за `BASE_URL` (фикстура
|
||||
`replicas`), против одного процесса он пропускается.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
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
|
||||
|
||||
|
||||
@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"]]
|
||||
@@ -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")
|
||||
@@ -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}"
|
||||
)
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Спек `messages`: отправка, валидация текста, история."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from api_client import Actor, Api, order_key
|
||||
from contract import assert_error, assert_ok
|
||||
|
||||
|
||||
def send_raw(
|
||||
api: Api,
|
||||
actor: Actor,
|
||||
chat_id: str,
|
||||
body: dict[str, Any],
|
||||
) -> httpx.Response:
|
||||
"""Отправка с новым ключом; ответ проверяет тест."""
|
||||
return api.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"] == "Привет, мир 👋"
|
||||
|
||||
|
||||
@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
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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 :]
|
||||
)
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Обязательные сценарии уровня «4» (README.md, рубрика)."""
|
||||
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from api_client import API, Actor, Api, key_headers, order_key, registration
|
||||
from contract import (
|
||||
BASIC_CHALLENGE,
|
||||
BEARER_CHALLENGE,
|
||||
assert_error,
|
||||
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)
|
||||
@@ -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"]) == []
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user