feat: establish PostgreSQL lab2 baseline with benchmark tooling
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
# student-tests/ — собственные тесты
|
||||
|
||||
Нужны для оценки «4» (`README.md`). Лаба 1 (сохраняется): неверный
|
||||
JSON, чужой чат, пустое сообщение, дубликат username, обход нескольких
|
||||
страниц, гонка «100 сообщений от 10 клиентов → ровно 100 уникальных».
|
||||
Лаба 2: автоматические проверки истечения сессии при коротком
|
||||
`SESSION_TTL_SECONDS`, logout, неверного пароля, недоступности
|
||||
PostgreSQL и Valkey; гонка регистрации одного username; откат составной
|
||||
операции (создание чата).
|
||||
|
||||
Объём намеренно минимальный: обязательные сценарии рубрики и то, на чём
|
||||
держится архитектура. Не раздувать набор тестами «на всякий случай»;
|
||||
новый тест — когда появилось новое поведение или найден дефект.
|
||||
|
||||
## Как запускаются
|
||||
|
||||
Все тесты — по HTTP против запущенного стенда, `src` не импортируют.
|
||||
In-process режима лабы 1 больше нет: с PostgreSQL и асинхронным пулом
|
||||
несколько `TestClient` (у каждого свой event loop) не делят одно
|
||||
приложение.
|
||||
|
||||
| Команда | Против чего | Что идёт |
|
||||
|---|---|---|
|
||||
| `make test-isolated` | отдельный проект compose `<рабочий>-isolated`: свои PostgreSQL, Valkey и volume, свои пароли, образ `:lab2-test`; удаляется после прогона | `make test` + все тесты, кроме `fault` — **обычный прогон** |
|
||||
| `make failure-checks [FAULT_ARGS=-rP]` | проект `<рабочий>-failures`: обычный API и «тесный» (срок сессии 2 с, пул 1, ожидание пула 1 с, срок операции 2 с) | только `pytest -m fault` |
|
||||
| `make student-test [BASE_URL=...]` | любой запущенный стенд (по умолчанию `http://localhost:8080`) | все, кроме `fault`; оставляет данные в его базе |
|
||||
|
||||
Оба отдельных стенда поднимает `stand.py` (stdlib, Python 3.9+): тот же
|
||||
`compose.yaml` с override `stand.compose.yml` (порты хранилищ не
|
||||
публикуются) и подстановками `stand.env` вместо `.env` рабочего стенда;
|
||||
API — `docker compose run` на свободных портах `127.0.0.1`; уборка
|
||||
`down -v` в `finally` и по Ctrl+C. Два прогона одного вида
|
||||
одновременно не запускать: уборка в начале второго удалит стенд первого.
|
||||
|
||||
Отсюда правила:
|
||||
|
||||
- тест не рассчитывает на пустой сервер: пользователи — с уникальным
|
||||
`username` (`helpers.register` → `unique_username`), свои чаты;
|
||||
- тест не лезет во внутреннее состояние: только HTTP. Исключение —
|
||||
проверки отказов: на хранилища они действуют через фикстуру `stand`
|
||||
(hook `fault_hook.py`), сами docker не трогают;
|
||||
- клиент — фикстура `client`; ещё независимые клиенты (своё соединение)
|
||||
— фабрика `new_client()`; «тесный» API — `tight_client`.
|
||||
|
||||
## Как писать
|
||||
|
||||
- Файлы: `test_rubric.py` — обязательные сценарии рубрики, `test_race.py`
|
||||
— гонки, `test_auth.py` — пароль, Basic, Bearer, выход, схемы в
|
||||
OpenAPI, `test_cache.py` — что кэш не меняет ответы, `test_request_id.py`
|
||||
— поведение слоя `X-Request-Id`, `test_failures.py` — проверки отказов
|
||||
(маркер `fault` на весь модуль). Имя теста говорит, что проверяется.
|
||||
- Хелперы — `helpers.py`: `register` (регистрация с паролем и вход —
|
||||
«актёр» = поля `User` + `password` + `token`), `login`, `logout`,
|
||||
`create_chat`, `send`, `read_history`, `chat_ids`, `public`,
|
||||
`assert_error`, `assert_unauthorized`. Идентификация собирается только
|
||||
в `headers()` (Bearer); заголовки руками — только в `test_auth.py`.
|
||||
- Ошибку проверять через `assert_error(resp, status, code)` (статус,
|
||||
`code`, форма, `request_id` = `X-Request-Id`), 401 — через
|
||||
`assert_unauthorized(resp, BASIC_CHALLENGE | BEARER_CHALLENGE)`.
|
||||
- Успешный ответ — статус и поля; обход истории — порядок
|
||||
`(created_at, id)`, отсутствие повторов и потерь.
|
||||
- Варианты одного сценария — `@pytest.mark.parametrize` с `ids=`.
|
||||
- Тест гонок — настоящая параллельность: потоки за
|
||||
`threading.Barrier`, у каждого свой клиент, соединение открыто до
|
||||
барьера. Тест требует ≥ 2 запросов в полёте одновременно. Не
|
||||
заменять потоки циклом.
|
||||
- `sleep` — только там, где ждут срок (истечение сессии, окно пропуска
|
||||
кэша), с запасом 0,3–1 с. Синхронизировать потоки сном нельзя.
|
||||
- Проверка отказа, которая останавливает или замораживает хранилище, —
|
||||
в `with outage(stand, ...)`: в `finally` хранилище возвращается.
|
||||
Длительности печатаются (`print`), чтобы `FAULT_ARGS=-rP` дал числа
|
||||
для `evidence/`.
|
||||
- Hook `fault_hook.py` работает только с проектом из `FAULT_PROJECT`
|
||||
(оканчивается на `-failures`); формат ключа кэша в нём — копия
|
||||
`CACHE_KEY_PREFIX`: поменяли формат — поменять и там.
|
||||
- Пароли и токены тестов синтетические, не печатаются и не попадают в
|
||||
`evidence/`.
|
||||
|
||||
## Нельзя
|
||||
|
||||
- Править `tests/` (публичные проверки skeleton) или класть туда свои
|
||||
тесты.
|
||||
- Ослаблять проверки, ставить `skip`/`xfail`, удалять тест, чтобы
|
||||
прогон стал зелёным (корневой `AGENTS.md`, разделы 2 и 9).
|
||||
- Мокать хранилище или сервисы: тесты проверяют систему целиком.
|
||||
- Запускать `pytest -m fault` против рабочего стенда: conftest
|
||||
остановит прогон с кодом 2 без hook, а hook откажется работать с
|
||||
рабочим проектом.
|
||||
|
||||
## После изменения тестов
|
||||
|
||||
1. `make fmt && make lint`.
|
||||
2. `make test-isolated`; изменились проверки отказов — `make failure-checks`.
|
||||
3. Изменился состав или вывод гонок и отказов — обновить
|
||||
`evidence/tests/` реальным выводом и строку в `REPORT.md`.
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Фикстуры собственных тестов. Все тесты — по HTTP против запущенного стенда.
|
||||
|
||||
`BASE_URL` (по умолчанию `http://localhost:8080`): compose-стенд
|
||||
(`make up`), сервис на хосте (`make run`) или отдельный стенд
|
||||
`make test-isolated`. Состояние общее и растёт от прогона к прогону:
|
||||
тесты не рассчитывают на пустой сервер.
|
||||
|
||||
Проверки отказов (маркер `fault`) идут только на стенде
|
||||
`make failure-checks`: он передаёт hook (`FAULT_HOOK`) и адрес «тесного»
|
||||
API (`FAULT_TIGHT_BASE_URL`). Без них такие тесты не запускаются.
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from collections.abc import Callable, Iterator
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from helpers import ClientFactory
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
||||
FAULT_HOOK = os.environ.get("FAULT_HOOK", "")
|
||||
FAULT_TIGHT_BASE_URL = os.environ.get("FAULT_TIGHT_BASE_URL", "").rstrip("/")
|
||||
FAULT_HOOK_TIMEOUT = 120
|
||||
|
||||
|
||||
@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 their stand and hook: run make failure-checks",
|
||||
returncode=2,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _server_reachable() -> None:
|
||||
"""Без сервера — одна понятная строка, а не десяток ошибок."""
|
||||
try:
|
||||
response = 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 response.status_code != 200:
|
||||
pytest.exit(
|
||||
f"{BASE_URL}/health/live answered {response.status_code}: "
|
||||
"another service on this port?",
|
||||
returncode=2,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def new_client() -> Iterator[ClientFactory]:
|
||||
"""Фабрика независимых клиентов: у каждого своё keep-alive соединение."""
|
||||
clients: list[httpx.Client] = []
|
||||
|
||||
def factory() -> httpx.Client:
|
||||
client = httpx.Client(base_url=BASE_URL, timeout=15)
|
||||
clients.append(client)
|
||||
return client
|
||||
|
||||
yield factory
|
||||
for client in clients:
|
||||
client.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(new_client: ClientFactory) -> httpx.Client:
|
||||
return new_client()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tight_client() -> Iterator[httpx.Client]:
|
||||
"""API стенда отказов со сроком сессии 2 с и пулом из одного соединения."""
|
||||
with httpx.Client(base_url=FAULT_TIGHT_BASE_URL, timeout=15) as client:
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def stand() -> Callable[..., str]:
|
||||
"""Действие над стендом отказов через hook; возвращает его stdout.
|
||||
|
||||
`stand("stop", "postgres")` — «стенд, останови postgres». Hook —
|
||||
исполняемый файл, вызов без shell, как `ACTION_SCRIPT` в
|
||||
`tests/resilience.py`. Сам тест docker не трогает.
|
||||
"""
|
||||
|
||||
def call(*args: str) -> str:
|
||||
result = subprocess.run(
|
||||
[FAULT_HOOK, *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=FAULT_HOOK_TIMEOUT,
|
||||
check=False,
|
||||
)
|
||||
assert result.returncode == 0, f"fault hook {' '.join(args)}: {result.stderr}"
|
||||
return result.stdout.strip()
|
||||
|
||||
return call
|
||||
Executable
+219
@@ -0,0 +1,219 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Hook стенда отказов для проверок `fault` (`make failure-checks`).
|
||||
|
||||
Тесты вызывают его как `[FAULT_HOOK, действие, аргументы…]` без shell —
|
||||
так же `tests/resilience.py` вызывает `ACTION_SCRIPT`. Сами тесты docker
|
||||
не трогают. Hook работает только с проектом compose из `FAULT_PROJECT`
|
||||
(его и пароли стенда передаёт `student-tests/stand.py` через окружение) и
|
||||
отказывается работать с проектом рабочего стенда.
|
||||
|
||||
Действия:
|
||||
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 убрать триггер
|
||||
count-chats <title> число чатов с этим названием
|
||||
|
||||
Пароли не печатает: valkey-cli берёт пароль из VALKEYCLI_AUTH
|
||||
контейнера, psql работает от POSTGRES_USER контейнера. Только stdlib,
|
||||
Python 3.9+.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COMPOSE_FILES = (ROOT / "compose.yaml", ROOT / "student-tests" / "stand.compose.yml")
|
||||
ENV_FILE = ROOT / "student-tests" / "stand.env"
|
||||
PROJECT_SUFFIX = "-failures"
|
||||
SERVICES = ("postgres", "valkey")
|
||||
# та же проверка, что healthcheck сервиса в compose.yaml
|
||||
PROBES = {
|
||||
"postgres": 'pg_isready -q -h 127.0.0.1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
|
||||
"valkey": 'test "$(valkey-cli ping)" = PONG',
|
||||
}
|
||||
PROBE_TIMEOUT = 30
|
||||
# начало ключа карточки — копия CACHE_KEY_PREFIX из src/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();
|
||||
"""
|
||||
COUNT_CHATS_SQL = "SELECT count(*) FROM chats WHERE title = :'title';\n"
|
||||
|
||||
|
||||
class HookError(Exception):
|
||||
"""Неверный вызов или проект: код 2 и сообщение в stderr."""
|
||||
|
||||
|
||||
def fault_project() -> str:
|
||||
project = os.environ.get("FAULT_PROJECT", "")
|
||||
if not project.endswith(PROJECT_SUFFIX) or project == PROJECT_SUFFIX:
|
||||
raise HookError(
|
||||
f"FAULT_PROJECT must end with {PROJECT_SUFFIX!r}: run make failure-checks",
|
||||
)
|
||||
return project
|
||||
|
||||
|
||||
def compose_run(project: str, *args: str, stdin: str | None = None):
|
||||
files = [arg for path in COMPOSE_FILES for arg in ("-f", str(path))]
|
||||
return subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"-p",
|
||||
project,
|
||||
"--env-file",
|
||||
str(ENV_FILE),
|
||||
*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 service(name: str) -> str:
|
||||
if name not in SERVICES:
|
||||
raise HookError(f"service must be one of {SERVICES}")
|
||||
return name
|
||||
|
||||
|
||||
def wait_answers(project: str, name: str) -> str:
|
||||
"""Ждать, пока сервис ответит проверкой из своего healthcheck.
|
||||
|
||||
После `unpause` Docker до следующего запуска healthcheck показывает
|
||||
старое состояние, и `up --wait` выходит с ошибкой, хотя сервис уже
|
||||
отвечает. Поэтому проверка — напрямую.
|
||||
"""
|
||||
deadline = time.monotonic() + PROBE_TIMEOUT
|
||||
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")
|
||||
|
||||
|
||||
def valkey(project: str, *args: str) -> str:
|
||||
# аргументы — позиционные параметры sh, без подстановки в строку
|
||||
return compose(
|
||||
project,
|
||||
"exec",
|
||||
"-T",
|
||||
"valkey",
|
||||
"sh",
|
||||
"-c",
|
||||
'exec valkey-cli "$@"',
|
||||
"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 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 run(project: str, action: str, args: list[str]) -> str:
|
||||
"""Выполнить действие; без match: hook запускается и на Python 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:
|
||||
# тот же контейнер, без пересоздания; --wait ждёт его healthcheck
|
||||
return compose(project, "up", "-d", "--wait", "--no-recreate", 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 == "count-chats" and len(args) == 1:
|
||||
return psql(project, COUNT_CHATS_SQL, title=args[0])
|
||||
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 exc:
|
||||
print(f"fault_hook: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
if output:
|
||||
print(output)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Короткие обёртки над API. Проверка формы ответа — здесь, а не в каждом тесте.
|
||||
|
||||
Пользователь теста — «актёр»: словарь `User` из ответа API плюс его
|
||||
синтетический пароль (`password`) и токен текущей сессии (`token`).
|
||||
Для сравнения с ответами API — `public(actor)`. Пароли и токены
|
||||
синтетические и никуда не печатаются.
|
||||
"""
|
||||
|
||||
import base64
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
|
||||
USERS = "/api/v1/users"
|
||||
ME = f"{USERS}/me"
|
||||
CHATS = "/api/v1/chats"
|
||||
SESSIONS = "/api/v1/auth/sessions"
|
||||
CURRENT_SESSION = f"{SESSIONS}/current"
|
||||
# WWW-Authenticate у 401 (contracts/README.md): вход и остальные запросы
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
USER_FIELDS = frozenset({"id", "username", "display_name", "created_at"})
|
||||
|
||||
# фикстура new_client: каждый вызов — новый клиент со своим соединением
|
||||
type ClientFactory = Callable[[], httpx.Client]
|
||||
|
||||
|
||||
def headers(actor: dict[str, Any]) -> dict[str, str]:
|
||||
"""Идентификация с лабы 2: Bearer-токен сессии. Собирается только здесь."""
|
||||
return bearer_header(actor["token"])
|
||||
|
||||
|
||||
def bearer_header(token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def basic_header(username: str, password: str) -> dict[str, str]:
|
||||
"""`Authorization: Basic` из username и пароля в UTF-8."""
|
||||
return basic_raw(f"{username}:{password}".encode())
|
||||
|
||||
|
||||
def basic_raw(raw: bytes) -> dict[str, str]:
|
||||
"""`Authorization: Basic` из произвольных байтов, в том числе битых."""
|
||||
return {"Authorization": "Basic " + base64.b64encode(raw).decode("ascii")}
|
||||
|
||||
|
||||
def unique_username(label: str) -> str:
|
||||
# состояние стенда общее: username не должен повторяться
|
||||
return f"{label}_{uuid4().hex[:12]}"
|
||||
|
||||
|
||||
def unique_password() -> str:
|
||||
"""Синтетический пароль 12–128 символов, свой у каждого вызова."""
|
||||
return f"pw-{uuid4().hex}"
|
||||
|
||||
|
||||
def public(actor: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Поля `User` из контракта: без пароля и токена теста."""
|
||||
return {key: actor[key] for key in USER_FIELDS}
|
||||
|
||||
|
||||
def login_response(
|
||||
client: httpx.Client, username: str, password: str
|
||||
) -> httpx.Response:
|
||||
return client.post(SESSIONS, headers=basic_header(username, password))
|
||||
|
||||
|
||||
def login(client: httpx.Client, actor: dict[str, Any]) -> str:
|
||||
"""Новая сессия пользователя; ответ проверяется по форме `Session`."""
|
||||
response = login_response(client, actor["username"], actor["password"])
|
||||
assert response.status_code == 201, response.text
|
||||
session = response.json()
|
||||
assert set(session) == {"token", "token_type", "expires_at", "user"}
|
||||
assert session["token_type"] == "Bearer"
|
||||
assert session["expires_at"].endswith("Z")
|
||||
assert session["user"] == public(actor)
|
||||
assert len(session["token"]) >= 32
|
||||
return session["token"]
|
||||
|
||||
|
||||
def logout(client: httpx.Client, actor: dict[str, Any]) -> httpx.Response:
|
||||
return client.delete(CURRENT_SESSION, headers=headers(actor))
|
||||
|
||||
|
||||
def register(
|
||||
client: httpx.Client,
|
||||
label: str = "user",
|
||||
*,
|
||||
password: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Регистрация с паролем и сразу вход: у актёра есть токен."""
|
||||
password = password or unique_password()
|
||||
body = {
|
||||
"username": unique_username(label),
|
||||
"display_name": f"Тест {label}",
|
||||
"password": password,
|
||||
}
|
||||
response = client.post(USERS, json=body)
|
||||
assert response.status_code == 201, response.text
|
||||
user = response.json()
|
||||
# пароля и его хэша в ответе нет: только поля User
|
||||
assert set(user) == USER_FIELDS
|
||||
assert user["username"] == body["username"]
|
||||
actor = {**user, "password": password}
|
||||
actor["token"] = login(client, actor)
|
||||
return actor
|
||||
|
||||
|
||||
def create_chat(
|
||||
client: httpx.Client,
|
||||
owner: dict[str, Any],
|
||||
*others: dict[str, Any],
|
||||
title: str = "Тестовый чат",
|
||||
) -> dict[str, Any]:
|
||||
member_ids = [owner["id"], *(user["id"] for user in others)]
|
||||
response = client.post(
|
||||
CHATS,
|
||||
json={"title": title, "member_ids": member_ids},
|
||||
headers=headers(owner),
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def messages_path(chat: dict[str, Any]) -> str:
|
||||
return f"{CHATS}/{chat['id']}/messages"
|
||||
|
||||
|
||||
def send(
|
||||
client: httpx.Client,
|
||||
user: dict[str, Any],
|
||||
chat: dict[str, Any],
|
||||
text: str,
|
||||
) -> httpx.Response:
|
||||
return client.post(messages_path(chat), json={"text": text}, headers=headers(user))
|
||||
|
||||
|
||||
def read_history(
|
||||
client: httpx.Client,
|
||||
user: dict[str, Any],
|
||||
chat: dict[str, Any],
|
||||
*,
|
||||
limit: int,
|
||||
) -> tuple[list[dict[str, Any]], list[int]]:
|
||||
"""Вся история обходом по курсору: сообщения и размеры страниц."""
|
||||
items: list[dict[str, Any]] = []
|
||||
sizes: list[int] = []
|
||||
params: dict[str, Any] = {"limit": limit}
|
||||
while True:
|
||||
response = client.get(messages_path(chat), params=params, headers=headers(user))
|
||||
assert response.status_code == 200, response.text
|
||||
page = response.json()
|
||||
assert set(page) == {"items", "next_cursor"}
|
||||
items.extend(page["items"])
|
||||
sizes.append(len(page["items"]))
|
||||
if page["next_cursor"] is None:
|
||||
return items, sizes
|
||||
params = {"limit": limit, "cursor": page["next_cursor"]}
|
||||
|
||||
|
||||
def chat_ids(client: httpx.Client, user: dict[str, Any]) -> list[str]:
|
||||
"""Id всех чатов пользователя обходом списка по курсору."""
|
||||
ids: list[str] = []
|
||||
params: dict[str, Any] = {"limit": 100}
|
||||
while True:
|
||||
response = client.get(CHATS, params=params, headers=headers(user))
|
||||
assert response.status_code == 200, response.text
|
||||
page = response.json()
|
||||
ids.extend(item["id"] for item in page["items"])
|
||||
if page["next_cursor"] is None:
|
||||
return ids
|
||||
params = {"limit": 100, "cursor": page["next_cursor"]}
|
||||
|
||||
|
||||
def assert_error(response: httpx.Response, status: int, code: str) -> dict[str, Any]:
|
||||
"""Ошибка в формате контракта; request_id совпадает с заголовком."""
|
||||
assert response.status_code == status, response.text
|
||||
assert response.headers["content-type"].startswith("application/json")
|
||||
body = response.json()
|
||||
assert set(body) == {"error"}
|
||||
error = body["error"]
|
||||
assert set(error) == {"code", "message", "request_id"}
|
||||
assert error["code"] == code
|
||||
assert error["message"]
|
||||
assert error["request_id"] == response.headers["X-Request-Id"]
|
||||
return error
|
||||
|
||||
|
||||
def assert_unauthorized(response: httpx.Response, challenge: str) -> dict[str, Any]:
|
||||
"""401 в формате контракта с нужным вызовом в `WWW-Authenticate`."""
|
||||
error = assert_error(response, 401, "unauthorized")
|
||||
assert response.headers.get("WWW-Authenticate") == challenge
|
||||
return error
|
||||
@@ -0,0 +1,16 @@
|
||||
# Override отдельных стендов тестов (student-tests/stand.py): тот же
|
||||
# compose.yaml под проектом <рабочий>-isolated или <рабочий>-failures, со
|
||||
# своим volume и сетью. Порты хранилищ не публикуются: к ним ходит только
|
||||
# fault_hook.py через docker compose exec. Контейнеры API создаёт stand.py
|
||||
# (docker compose run -p 127.0.0.1:...), у них свой тег образа: рабочий
|
||||
# образ стенда не пересобирается.
|
||||
services:
|
||||
postgres:
|
||||
ports: !reset []
|
||||
valkey:
|
||||
ports: !reset []
|
||||
migrate:
|
||||
image: mtusi-messenger-vladimirceva:lab2-test
|
||||
api:
|
||||
image: mtusi-messenger-vladimirceva:lab2-test
|
||||
ports: !reset []
|
||||
@@ -0,0 +1,7 @@
|
||||
# Подстановки compose для отдельных стендов тестов (student-tests/stand.py)
|
||||
# вместо .env рабочего стенда: docker compose --env-file student-tests/stand.env.
|
||||
# Только несекретные имена: пароли stand.py генерирует на каждый прогон.
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_DB=messenger
|
||||
LOG_LEVEL=INFO
|
||||
SESSION_TTL_SECONDS=3600
|
||||
@@ -0,0 +1,311 @@
|
||||
"""Отдельные стенды собственных тестов: `make test-isolated`, `make failure-checks`.
|
||||
|
||||
python3 student-tests/stand.py isolated
|
||||
python3 student-tests/stand.py failures [аргументы pytest]
|
||||
|
||||
Оба поднимают тот же `compose.yaml` под своим проектом
|
||||
(`<рабочий>-isolated`, `<рабочий>-failures`) с override
|
||||
`student-tests/stand.compose.yml`: свои PostgreSQL и Valkey со своим
|
||||
volume, порты хранилищ не публикуются, образ API — свой тег. Подстановки
|
||||
— `student-tests/stand.env`, а не `.env` рабочего стенда; пароли
|
||||
хранилищ генерируются на прогон и никуда не пишутся. Затем:
|
||||
|
||||
- собрать образ из рабочего каталога, поднять хранилища, миграции;
|
||||
- контейнеры API (`docker compose run`) на свободных портах 127.0.0.1;
|
||||
- isolated: `make test` и `pytest` (без проверок отказов) против API;
|
||||
- failures: ещё «тесный» API (срок сессии 2 с, пул из одного
|
||||
соединения, короткие сроки) и `pytest -m fault` с hook
|
||||
`student-tests/fault_hook.py`;
|
||||
- удалить стенд вместе с volume при любом исходе, в том числе по Ctrl+C.
|
||||
|
||||
Рабочий стенд, его база и кэш не затрагиваются: каждый вызов compose —
|
||||
только с `-p <проект стенда>`. Два прогона одного вида одновременно не
|
||||
запускать: уборка в начале второго удалит стенд первого. Только stdlib и
|
||||
Python 3.9+: скрипт запускается `python3`, как проверки skeleton.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
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]
|
||||
COMPOSE_FILES = (ROOT / "compose.yaml", ROOT / "student-tests" / "stand.compose.yml")
|
||||
ENV_FILE = ROOT / "student-tests" / "stand.env"
|
||||
FAULT_HOOK = ROOT / "student-tests" / "fault_hook.py"
|
||||
# что из окружения хоста нужно самому docker compose и uv; остальное
|
||||
# (в том числе POSTGRES_* из shell) в стенд не попадает
|
||||
HOST_ENV = ("PATH", "HOME", "USER", "TMPDIR", "LANG", "DOCKER_HOST", "DOCKER_CONFIG")
|
||||
READY_TIMEOUT = 60
|
||||
LOG_TAIL_LINES = 50
|
||||
# «тесный» API стенда отказов: срок сессии 2 с, пул из одного соединения,
|
||||
# короткие сроки ожидания пула и операции
|
||||
TIGHT_ENV = {
|
||||
"SESSION_TTL_SECONDS": "2",
|
||||
"DB_POOL_SIZE": "1",
|
||||
"DB_POOL_OVERFLOW": "0",
|
||||
"DB_POOL_TIMEOUT": "1",
|
||||
"DB_OPERATION_TIMEOUT": "2",
|
||||
}
|
||||
KINDS = ("isolated", "failures")
|
||||
|
||||
|
||||
def say(kind: str, message: str) -> None:
|
||||
print(f"[{kind}] {message}", flush=True)
|
||||
|
||||
|
||||
def working_project() -> str:
|
||||
"""Имя проекта рабочего стенда — из compose.yaml (`name:`)."""
|
||||
config = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"--env-file",
|
||||
str(ENV_FILE),
|
||||
"-f",
|
||||
str(COMPOSE_FILES[0]),
|
||||
"config",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
# подстановки не важны: нужно только имя проекта
|
||||
env={**stand_env(), "POSTGRES_PASSWORD": "x", "VALKEY_PASSWORD": "x"},
|
||||
)
|
||||
return json.loads(config.stdout)["name"]
|
||||
|
||||
|
||||
def stand_env() -> dict[str, str]:
|
||||
"""Окружение docker compose стенда, собранное с нуля.
|
||||
|
||||
Пароли хранилищ новые на каждый прогон: живут только здесь, в
|
||||
контейнерах стенда и у дочерних процессов (hook вызывает compose с ними
|
||||
же). В вывод и файлы не попадают.
|
||||
"""
|
||||
env = {key: os.environ[key] for key in HOST_ENV if key in os.environ}
|
||||
return {
|
||||
**env,
|
||||
"POSTGRES_PASSWORD": secrets.token_hex(16),
|
||||
"VALKEY_PASSWORD": secrets.token_hex(16),
|
||||
}
|
||||
|
||||
|
||||
def free_port() -> int:
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return sock.getsockname()[1]
|
||||
|
||||
|
||||
class Stand:
|
||||
def __init__(self, kind: str) -> None:
|
||||
self.kind = kind
|
||||
self.env = stand_env()
|
||||
working = working_project()
|
||||
self.project = f"{working}-{kind}"
|
||||
if self.project == working:
|
||||
raise SystemExit(f"refusing to use the working project {working!r}")
|
||||
self.containers: list[str] = []
|
||||
|
||||
def run(self, *args: str, check: bool = True, quiet: bool = False, env=None):
|
||||
return subprocess.run(
|
||||
args,
|
||||
cwd=ROOT,
|
||||
check=check,
|
||||
text=True,
|
||||
capture_output=quiet,
|
||||
env=env or self.env,
|
||||
)
|
||||
|
||||
def compose(self, *args: str, check: bool = True, quiet: bool = False):
|
||||
"""docker compose стенда; без `-p <проект>` не вызывается никогда."""
|
||||
files = [arg for path in COMPOSE_FILES for arg in ("-f", str(path))]
|
||||
return self.run(
|
||||
"docker",
|
||||
"compose",
|
||||
"-p",
|
||||
self.project,
|
||||
"--env-file",
|
||||
str(ENV_FILE),
|
||||
*files,
|
||||
*args,
|
||||
check=check,
|
||||
quiet=quiet,
|
||||
)
|
||||
|
||||
def leftovers(self) -> list[str]:
|
||||
"""Контейнеры и volume проекта стенда, которые ещё остались."""
|
||||
label = f"label=com.docker.compose.project={self.project}"
|
||||
found = []
|
||||
for command in (("ps", "-aq"), ("volume", "ls", "-q")):
|
||||
out = self.run(
|
||||
"docker", *command, "--filter", label, check=False, quiet=True
|
||||
)
|
||||
found += out.stdout.split()
|
||||
return found
|
||||
|
||||
def cleanup(self) -> bool:
|
||||
for name in self.containers:
|
||||
self.run("docker", "rm", "-f", name, check=False, quiet=True)
|
||||
down = self.compose("down", "-v", "--remove-orphans", check=False, quiet=True)
|
||||
return down.returncode == 0 and not self.leftovers()
|
||||
|
||||
def wait_ready(self, base_url: str, container: str) -> None:
|
||||
deadline = time.monotonic() + READY_TIMEOUT
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
f"{base_url}/health/ready", timeout=2
|
||||
) as resp:
|
||||
if resp.status == 200:
|
||||
return
|
||||
except (urllib.error.URLError, OSError):
|
||||
pass
|
||||
state = self.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(0.5)
|
||||
raise RuntimeError(f"{base_url} not ready in {READY_TIMEOUT}s")
|
||||
|
||||
def start_api(self, suffix: str, extra_env: dict[str, str]) -> str:
|
||||
name = f"{self.project}-{suffix}"
|
||||
self.containers.append(name)
|
||||
port = free_port()
|
||||
env_args = [
|
||||
arg for key, value in extra_env.items() for arg in ("-e", f"{key}={value}")
|
||||
]
|
||||
self.compose(
|
||||
"run",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--name",
|
||||
name,
|
||||
*env_args,
|
||||
"-p",
|
||||
f"127.0.0.1:{port}:8080",
|
||||
"api",
|
||||
quiet=True,
|
||||
)
|
||||
base_url = f"http://127.0.0.1:{port}"
|
||||
self.wait_ready(base_url, name)
|
||||
return base_url
|
||||
|
||||
def prepare(self) -> None:
|
||||
say(self.kind, "build image")
|
||||
self.compose("build", "api")
|
||||
say(self.kind, "start postgres and valkey")
|
||||
self.compose("up", "-d", "--wait", "postgres", "valkey")
|
||||
say(self.kind, "migrations")
|
||||
self.compose("run", "--rm", "migrate")
|
||||
|
||||
def tests_env(self, base_url: str) -> dict[str, str]:
|
||||
# пароли стенда нужны hook-у: compose проверяет подстановки на
|
||||
# каждой команде. Тесты сами их не читают и не печатают
|
||||
return {**os.environ, **self.env, "BASE_URL": base_url}
|
||||
|
||||
def isolated(self, pytest_args: list[str]) -> dict[str, int]:
|
||||
self.prepare()
|
||||
base_url = self.start_api("api", {})
|
||||
say(self.kind, f"ready: api={base_url}")
|
||||
results = {}
|
||||
say(self.kind, "make test")
|
||||
results["test"] = self.run(
|
||||
"make", "test", f"BASE_URL={base_url}", check=False, env=os.environ.copy()
|
||||
).returncode
|
||||
say(self.kind, "pytest")
|
||||
results["student-test"] = self.run(
|
||||
"uv",
|
||||
"run",
|
||||
"pytest",
|
||||
*pytest_args,
|
||||
check=False,
|
||||
env={**os.environ, "BASE_URL": base_url},
|
||||
).returncode
|
||||
return results
|
||||
|
||||
def failures(self, pytest_args: list[str]) -> dict[str, int]:
|
||||
self.prepare()
|
||||
base_url = self.start_api("api", {})
|
||||
tight_url = self.start_api("api-tight", TIGHT_ENV)
|
||||
say(self.kind, f"ready: api={base_url} tight={tight_url}")
|
||||
env = {
|
||||
**self.tests_env(base_url),
|
||||
"FAULT_TIGHT_BASE_URL": tight_url,
|
||||
"FAULT_HOOK": str(FAULT_HOOK),
|
||||
"FAULT_PROJECT": self.project,
|
||||
}
|
||||
say(self.kind, "pytest -m fault")
|
||||
code = self.run(
|
||||
"uv",
|
||||
"run",
|
||||
"pytest",
|
||||
"-m",
|
||||
"fault",
|
||||
*pytest_args,
|
||||
check=False,
|
||||
env=env,
|
||||
).returncode
|
||||
return {"fault": code}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) < 2 or sys.argv[1] not in KINDS:
|
||||
print(__doc__, file=sys.stderr)
|
||||
return 2
|
||||
kind, pytest_args = sys.argv[1], sys.argv[2:]
|
||||
stand = Stand(kind)
|
||||
say(kind, f"project={stand.project}")
|
||||
if not stand.cleanup():
|
||||
say(kind, "leftovers of a previous run could not be removed")
|
||||
return 1
|
||||
|
||||
results: dict[str, int] = {}
|
||||
failed = True
|
||||
try:
|
||||
results = getattr(stand, kind)(pytest_args)
|
||||
failed = any(results.values())
|
||||
except KeyboardInterrupt:
|
||||
say(kind, "interrupted")
|
||||
results["interrupted"] = 130
|
||||
except (subprocess.CalledProcessError, RuntimeError) as exc:
|
||||
say(kind, f"setup failed: {exc}")
|
||||
results["setup"] = 1
|
||||
finally:
|
||||
# повторный Ctrl+C не должен оборвать уборку на полпути
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
if failed:
|
||||
for name in stand.containers:
|
||||
say(kind, f"last {LOG_TAIL_LINES} lines of {name}")
|
||||
stand.run(
|
||||
"docker", "logs", "--tail", str(LOG_TAIL_LINES), name, check=False
|
||||
)
|
||||
say(kind, "cleanup")
|
||||
if not stand.cleanup():
|
||||
say(kind, "cleanup failed")
|
||||
results["cleanup"] = 1
|
||||
|
||||
say(kind, f"results: {results}")
|
||||
return next((code for code in results.values() if code), 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Переход 1 → 2: пароль, вход по Basic, Bearer-сессия, выход.
|
||||
|
||||
Единственный модуль, который собирает `Authorization` и `X-User-Id` сам,
|
||||
а не через `helpers.headers()`: здесь проверяются именно заголовки.
|
||||
Неверный пароль и logout — в `test_rubric.py` (рубрика уровня «4»),
|
||||
срок сессии и отказ БД — в `test_failures.py`.
|
||||
"""
|
||||
|
||||
import secrets
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from helpers import (
|
||||
BASIC_CHALLENGE,
|
||||
BEARER_CHALLENGE,
|
||||
CHATS,
|
||||
ME,
|
||||
SESSIONS,
|
||||
USERS,
|
||||
assert_error,
|
||||
assert_unauthorized,
|
||||
basic_header,
|
||||
basic_raw,
|
||||
bearer_header,
|
||||
create_chat,
|
||||
headers,
|
||||
login,
|
||||
logout,
|
||||
messages_path,
|
||||
public,
|
||||
read_history,
|
||||
register,
|
||||
unique_password,
|
||||
unique_username,
|
||||
)
|
||||
|
||||
|
||||
def test_login_returns_opaque_session(client: httpx.Client) -> None:
|
||||
alice = register(client, "alice")
|
||||
response = client.post(
|
||||
SESSIONS, headers=basic_header(alice["username"], alice["password"])
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
session = response.json()
|
||||
assert session["user"] == public(alice)
|
||||
expires_at = datetime.fromisoformat(session["expires_at"])
|
||||
assert expires_at > datetime.now(UTC)
|
||||
# токен ничего не кодирует: ни username, ни id
|
||||
token = session["token"]
|
||||
for value in (alice["username"], alice["id"], alice["id"].replace("-", "")):
|
||||
assert value not in token
|
||||
me = client.get(ME, headers=bearer_header(token))
|
||||
assert me.json() == public(alice)
|
||||
|
||||
|
||||
def test_login_ignores_json_body(client: httpx.Client) -> None:
|
||||
alice, eve = register(client, "alice"), register(client, "eve")
|
||||
response = client.post(
|
||||
SESSIONS,
|
||||
headers=basic_header(alice["username"], alice["password"]),
|
||||
json={"username": eve["username"], "password": eve["password"]},
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.json()["user"] == public(alice)
|
||||
|
||||
|
||||
def test_password_with_colon_and_cyrillic(client: httpx.Client) -> None:
|
||||
"""Пароль — UTF-8, разделитель Basic — первое двоеточие."""
|
||||
actor = register(client, "utf", password="Пароль:с:двоеточиями-1")
|
||||
assert client.get(ME, headers=headers(actor)).json() == public(actor)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
["short", " " * 12, "x" * 129],
|
||||
ids=["too-short", "blank", "too-long"],
|
||||
)
|
||||
def test_bad_password_on_registration_is_400(client: httpx.Client, value: str) -> None:
|
||||
body = {
|
||||
"username": unique_username("pw"),
|
||||
"display_name": "Тест",
|
||||
"password": value,
|
||||
}
|
||||
assert_error(client.post(USERS, json=body), 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"header",
|
||||
[
|
||||
{"Authorization": "Basic !!!"},
|
||||
basic_raw(b"no-colon-here"),
|
||||
basic_raw(b"\xff\xfe:not-utf-8-password"),
|
||||
{"Authorization": "Basic"},
|
||||
bearer_header(secrets.token_urlsafe(32)),
|
||||
{},
|
||||
],
|
||||
ids=["not-base64", "no-colon", "not-utf8", "empty", "bearer", "none"],
|
||||
)
|
||||
def test_broken_basic_is_401(client: httpx.Client, header: dict[str, str]) -> None:
|
||||
assert_unauthorized(client.post(SESSIONS, headers=header), BASIC_CHALLENGE)
|
||||
|
||||
|
||||
def test_basic_on_business_endpoint_is_401(client: httpx.Client) -> None:
|
||||
alice = register(client, "alice")
|
||||
response = client.get(
|
||||
ME, headers=basic_header(alice["username"], alice["password"])
|
||||
)
|
||||
assert_unauthorized(response, BEARER_CHALLENGE)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"header",
|
||||
[
|
||||
{},
|
||||
{"Authorization": "Bearer"},
|
||||
bearer_header("x"),
|
||||
bearer_header(secrets.token_urlsafe(32)),
|
||||
],
|
||||
ids=["none", "empty", "short", "unknown"],
|
||||
)
|
||||
def test_missing_or_unknown_token_is_401(
|
||||
client: httpx.Client, header: dict[str, str]
|
||||
) -> None:
|
||||
assert_unauthorized(client.get(ME, headers=header), BEARER_CHALLENGE)
|
||||
|
||||
|
||||
def test_x_user_id_gives_no_access(client: httpx.Client) -> None:
|
||||
alice, eve = register(client, "alice"), register(client, "eve")
|
||||
# только X-User-Id — 401; вместе с Bearer alice — по-прежнему alice
|
||||
assert_unauthorized(
|
||||
client.get(ME, headers={"X-User-Id": alice["id"]}), BEARER_CHALLENGE
|
||||
)
|
||||
response = client.get(ME, headers={**headers(alice), "X-User-Id": eve["id"]})
|
||||
assert response.json() == public(alice)
|
||||
|
||||
|
||||
def test_two_sessions_and_logout_of_one(client: httpx.Client) -> None:
|
||||
alice = register(client, "alice")
|
||||
second = {**alice, "token": login(client, alice)}
|
||||
assert second["token"] != alice["token"]
|
||||
|
||||
assert logout(client, alice).status_code == 204
|
||||
assert_unauthorized(client.get(ME, headers=headers(alice)), BEARER_CHALLENGE)
|
||||
# другая сессия того же пользователя продолжает работать
|
||||
assert client.get(ME, headers=headers(second)).json() == public(alice)
|
||||
|
||||
|
||||
def test_revoked_token_is_rejected_everywhere(client: httpx.Client) -> None:
|
||||
alice, bob = register(client, "alice"), register(client, "bob")
|
||||
chat = create_chat(client, alice, bob)
|
||||
assert logout(client, alice).status_code == 204
|
||||
for method, path in (
|
||||
("GET", ME),
|
||||
("GET", CHATS),
|
||||
("GET", f"{CHATS}/{chat['id']}"),
|
||||
("GET", messages_path(chat)),
|
||||
):
|
||||
response = client.request(method, path, headers=headers(alice))
|
||||
assert_unauthorized(response, BEARER_CHALLENGE)
|
||||
response = client.post(
|
||||
messages_path(chat),
|
||||
json={"text": "после выхода"},
|
||||
headers=headers(alice),
|
||||
)
|
||||
assert_unauthorized(response, BEARER_CHALLENGE)
|
||||
items, _ = read_history(client, bob, chat, limit=50)
|
||||
assert items == []
|
||||
|
||||
|
||||
def test_user_never_contains_password(client: httpx.Client) -> None:
|
||||
password = unique_password()
|
||||
actor = register(client, "secret", password=password)
|
||||
for response in (
|
||||
client.get(ME, headers=headers(actor)),
|
||||
client.post(SESSIONS, headers=basic_header(actor["username"], password)),
|
||||
):
|
||||
assert password not in response.text
|
||||
assert "password" not in response.text
|
||||
|
||||
|
||||
def test_security_schemes_in_openapi(client: httpx.Client) -> None:
|
||||
"""Схемы bearerAuth и basicAuth как в контракте: кнопка Authorize в /docs."""
|
||||
served = client.get("/openapi.json").json()
|
||||
schemes = served["components"]["securitySchemes"]
|
||||
assert schemes["bearerAuth"] == {
|
||||
"type": "http",
|
||||
"scheme": "bearer",
|
||||
"bearerFormat": "opaque session token",
|
||||
}
|
||||
assert schemes["basicAuth"] == {"type": "http", "scheme": "basic"}
|
||||
paths = served["paths"]
|
||||
assert paths[ME]["get"]["security"] == [{"bearerAuth": []}]
|
||||
assert paths[SESSIONS]["post"]["security"] == [{"basicAuth": []}]
|
||||
assert not paths[USERS]["post"].get("security")
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Кэш карточек чатов в Valkey: что видно по HTTP.
|
||||
|
||||
Попадание в кэш по HTTP не отличить от чтения из PostgreSQL, поэтому
|
||||
здесь проверяется только то, что кэш не меняет ответы: карточка с тем же
|
||||
порядком участников, членство нового чата сразу, история и список чатов
|
||||
без устаревших данных после записи (read-after-write из контракта).
|
||||
Отказ Valkey, очистка и возврат кэша — `test_failures.py`.
|
||||
"""
|
||||
|
||||
import httpx
|
||||
|
||||
from helpers import (
|
||||
CHATS,
|
||||
assert_error,
|
||||
chat_ids,
|
||||
create_chat,
|
||||
headers,
|
||||
read_history,
|
||||
register,
|
||||
send,
|
||||
)
|
||||
|
||||
|
||||
def test_repeated_reads_return_the_created_card(client: httpx.Client) -> None:
|
||||
alice, bob, eve = (register(client, name) for name in ("alice", "bob", "eve"))
|
||||
# порядок участников не совпадает ни с сортировкой, ни с порядком
|
||||
# регистрации: кэш обязан сохранить его как есть
|
||||
created = create_chat(client, bob, eve, alice, title="Кэш «карточки»")
|
||||
path = f"{CHATS}/{created['id']}"
|
||||
first = client.get(path, headers=headers(alice)).json()
|
||||
second = client.get(path, headers=headers(eve)).json()
|
||||
assert first == second == created
|
||||
assert first["member_ids"] == [bob["id"], eve["id"], alice["id"]]
|
||||
|
||||
|
||||
def test_new_chat_membership_works_at_once(client: httpx.Client) -> None:
|
||||
alice, bob, eve = (register(client, name) for name in ("alice", "bob", "eve"))
|
||||
chat = create_chat(client, alice, bob)
|
||||
assert send(client, bob, chat, "сразу после создания").status_code == 201
|
||||
assert_error(
|
||||
client.get(f"{CHATS}/{chat['id']}", headers=headers(eve)), 404, "not_found"
|
||||
)
|
||||
assert_error(send(client, eve, chat, "посторонний"), 404, "not_found")
|
||||
|
||||
|
||||
def test_message_is_visible_to_the_next_read(client: httpx.Client) -> None:
|
||||
alice, bob = register(client, "alice"), register(client, "bob")
|
||||
chat = create_chat(client, alice, bob)
|
||||
# история уже прочитана: если бы она кэшировалась, второе чтение
|
||||
# отдало бы старую страницу
|
||||
assert read_history(client, bob, chat, limit=50)[0] == []
|
||||
message = send(client, alice, chat, "видно сразу").json()
|
||||
assert read_history(client, bob, chat, limit=50)[0] == [message]
|
||||
|
||||
|
||||
def test_new_chat_is_listed_at_once(client: httpx.Client) -> None:
|
||||
alice, bob = register(client, "alice"), register(client, "bob")
|
||||
first = create_chat(client, alice, bob)
|
||||
assert chat_ids(client, bob) == [first["id"]]
|
||||
second = create_chat(client, alice, bob, title="Второй")
|
||||
assert chat_ids(client, bob) == [first["id"], second["id"]]
|
||||
@@ -0,0 +1,296 @@
|
||||
"""Проверки отказов (уровень «4»): выполняет только `make failure-checks`.
|
||||
|
||||
Стенд и hook готовит `student-tests/stand.py failures`: свои PostgreSQL и
|
||||
Valkey, обычный API (`BASE_URL`) и «тесный» (срок сессии 2 с, пул из
|
||||
одного соединения, срок ожидания пула 1 с, срок операции 2 с). На
|
||||
хранилища тесты действуют только через фикстуру `stand` (hook
|
||||
`student-tests/fault_hook.py`) и всегда возвращают их в рабочее состояние
|
||||
(`outage`): упавшая проверка не ломает следующие.
|
||||
|
||||
Что проверяется: истечение сессии и то, что запросы её не продлевают;
|
||||
недоступная БД — 503 без деталей и без вызова аутентификации, а не 401 и
|
||||
не анонимный доступ; ограниченное ожидание при замёрзшей БД и
|
||||
исчерпанном пуле; откат создания чата; readiness; обход кэша при отказе
|
||||
Valkey и его возврат без рестарта API. Границы времени — с запасом
|
||||
0,3–1 с, но на порядок ниже «плохого» поведения (секунды повторов
|
||||
redis-py, зависший до разморозки запрос).
|
||||
"""
|
||||
|
||||
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 helpers import (
|
||||
BEARER_CHALLENGE,
|
||||
CHATS,
|
||||
ME,
|
||||
assert_error,
|
||||
assert_unauthorized,
|
||||
chat_ids,
|
||||
create_chat,
|
||||
headers,
|
||||
public,
|
||||
read_history,
|
||||
register,
|
||||
send,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.fault
|
||||
|
||||
type Stand = Callable[..., str]
|
||||
|
||||
RESTORE = {"stop": "start", "pause": "unpause"}
|
||||
# запас к границам времени: планировщик Docker Desktop
|
||||
SLACK = 0.3
|
||||
# значения по умолчанию CACHE_TIMEOUT и CACHE_RETRY_AFTER
|
||||
CACHE_TIMEOUT = 0.2
|
||||
CACHE_RETRY_AFTER = 5.0
|
||||
# окружение «тесного» API (TIGHT_ENV в stand.py)
|
||||
SESSION_TTL = 2
|
||||
POOL_TIMEOUT = 1.0
|
||||
OPERATION_TIMEOUT = 2.0
|
||||
# ограниченное закрытие соединения (DB_CLOSE_TIMEOUT) и срок readiness
|
||||
CLOSE_TIMEOUT = 2.0
|
||||
READINESS_TIMEOUT = 2.0
|
||||
|
||||
|
||||
@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()
|
||||
response = call()
|
||||
return response, time.monotonic() - started
|
||||
|
||||
|
||||
def read_chat(client: httpx.Client, actor: dict[str, Any], chat: dict[str, Any]):
|
||||
return client.get(f"{CHATS}/{chat['id']}", headers=headers(actor))
|
||||
|
||||
|
||||
def wait_cache_ready(
|
||||
client: httpx.Client,
|
||||
stand: Stand,
|
||||
actor: dict[str, Any],
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
"""Дождаться, пока чтение снова пишет карточку в кэш.
|
||||
|
||||
После отказа в прошлом тесте API пропускает кэш ещё до 5 с.
|
||||
"""
|
||||
deadline = time.monotonic() + CACHE_RETRY_AFTER + 2
|
||||
stand("flush-cache")
|
||||
while time.monotonic() < deadline:
|
||||
assert read_chat(client, actor, chat).status_code == 200
|
||||
if stand("cache-has-chat", chat["id"]) == "1":
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise AssertionError("cache did not come back")
|
||||
|
||||
|
||||
# --- сессии: срок 2 с на «тесном» API, БД остановлена — на обычном -----------
|
||||
|
||||
|
||||
def test_expired_token_is_401(tight_client: httpx.Client) -> None:
|
||||
actor = register(tight_client, "ttl")
|
||||
assert tight_client.get(ME, headers=headers(actor)).status_code == 200
|
||||
time.sleep(SESSION_TTL + 1)
|
||||
assert_unauthorized(tight_client.get(ME, headers=headers(actor)), BEARER_CHALLENGE)
|
||||
|
||||
|
||||
def test_requests_do_not_extend_session(tight_client: httpx.Client) -> None:
|
||||
actor = register(tight_client, "ttl")
|
||||
logged_in = time.monotonic()
|
||||
successes = 0
|
||||
while time.monotonic() - logged_in < SESSION_TTL - SLACK:
|
||||
assert tight_client.get(ME, headers=headers(actor)).status_code == 200
|
||||
successes += 1
|
||||
time.sleep(0.5)
|
||||
assert successes >= 3, "too few requests before expiry"
|
||||
time.sleep(max(0.0, logged_in + SESSION_TTL + 1 - time.monotonic()))
|
||||
assert_unauthorized(tight_client.get(ME, headers=headers(actor)), BEARER_CHALLENGE)
|
||||
|
||||
|
||||
def test_token_while_database_stopped_is_503(
|
||||
client: httpx.Client, stand: Stand
|
||||
) -> None:
|
||||
actor = register(client, "db")
|
||||
with outage(stand, "stop", "postgres"):
|
||||
response = client.get(ME, headers=headers(actor))
|
||||
assert_error(response, 503, "unavailable")
|
||||
# недоступность хранилища — не отказ в аутентификации
|
||||
assert "WWW-Authenticate" not in response.headers
|
||||
# тот же токен после возврата БД
|
||||
assert client.get(ME, headers=headers(actor)).json() == public(actor)
|
||||
|
||||
|
||||
# --- хранение: откат, остановленная и замёрзшая БД, исчерпанный пул ------------
|
||||
|
||||
|
||||
def test_members_failure_rolls_back_chat(client: httpx.Client, stand: Stand) -> None:
|
||||
alice, bob = register(client, "alice"), register(client, "bob")
|
||||
title = f"fault-{uuid.uuid4().hex}"
|
||||
stand("fail-members", title)
|
||||
try:
|
||||
response = client.post(
|
||||
CHATS,
|
||||
json={"title": title, "member_ids": [alice["id"], bob["id"]]},
|
||||
headers=headers(alice),
|
||||
)
|
||||
assert_error(response, 500, "internal_error")
|
||||
finally:
|
||||
stand("clear-fail-members")
|
||||
# ни чата, ни участников: вставка строки чата откатилась вместе с ними
|
||||
for actor in (alice, bob):
|
||||
assert chat_ids(client, actor) == []
|
||||
assert stand("count-chats", title) == "0"
|
||||
|
||||
|
||||
def test_database_stopped_and_back(client: httpx.Client, stand: Stand) -> None:
|
||||
alice = register(client, "alice")
|
||||
chat = create_chat(client, alice)
|
||||
with outage(stand, "stop", "postgres"):
|
||||
response, took = timed(lambda: send(client, alice, chat, "во время отказа"))
|
||||
error = assert_error(response, 503, "unavailable")
|
||||
print(f"postgres stopped: POST message -> 503 in {took:.3f}s")
|
||||
assert took < 2, f"503 took {took:.2f}s"
|
||||
for word in ("postgres", "sql", "connect", "asyncpg"):
|
||||
assert word not in error["message"].lower()
|
||||
after = send(client, alice, chat, "после возврата")
|
||||
assert after.status_code == 201, after.text
|
||||
# запись во время отказа не зафиксирована, новая — видна
|
||||
assert read_history(client, alice, chat, limit=50)[0] == [after.json()]
|
||||
|
||||
|
||||
def test_frozen_database_and_exhausted_pool(
|
||||
tight_client: httpx.Client,
|
||||
stand: Stand,
|
||||
) -> None:
|
||||
"""Замёрзшая БД держит запрос не дольше срока операции и закрытия
|
||||
соединения; пока пул занят, следующий запрос ждёт не дольше срока пула."""
|
||||
actor = register(tight_client, "pool")
|
||||
first: list[tuple[int, float]] = []
|
||||
|
||||
def hold_connection() -> None:
|
||||
with httpx.Client(base_url=str(tight_client.base_url), timeout=20) as holder:
|
||||
response, took = timed(lambda: holder.get(ME, headers=headers(actor)))
|
||||
first.append((response.status_code, took))
|
||||
|
||||
with outage(stand, "pause", "postgres"):
|
||||
thread = threading.Thread(target=hold_connection)
|
||||
thread.start()
|
||||
time.sleep(SLACK)
|
||||
response, took = timed(lambda: tight_client.get(ME, headers=headers(actor)))
|
||||
assert_error(response, 503, "unavailable")
|
||||
assert took < POOL_TIMEOUT + 0.5, f"pool wait took {took:.2f}s"
|
||||
thread.join()
|
||||
status, held = first[0]
|
||||
print(
|
||||
f"postgres paused: first request -> {status} in {held:.2f}s, "
|
||||
f"second (pool of 1 busy) -> {response.status_code} in {took:.2f}s",
|
||||
)
|
||||
assert status == 503
|
||||
assert held < OPERATION_TIMEOUT + CLOSE_TIMEOUT + 1, f"frozen db held {held:.2f}s"
|
||||
# срок сессии 2 с мог истечь за время паузы: пул проверяем новым входом
|
||||
fresh = register(tight_client, "pool")
|
||||
assert tight_client.get(ME, headers=headers(fresh)).status_code == 200
|
||||
|
||||
|
||||
# --- readiness -------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_readiness_without_database(client: httpx.Client, stand: Stand) -> None:
|
||||
with outage(stand, "stop", "postgres"):
|
||||
response, took = timed(lambda: client.get("/health/ready"))
|
||||
assert_error(response, 503, "unavailable")
|
||||
print(f"postgres stopped: /health/ready -> 503 in {took:.3f}s")
|
||||
assert took < READINESS_TIMEOUT + 0.5, f"ready took {took:.2f}s"
|
||||
assert client.get("/health/live").status_code == 200
|
||||
assert client.get("/health/ready").status_code == 200
|
||||
|
||||
|
||||
def test_readiness_without_cache(client: httpx.Client, stand: Stand) -> None:
|
||||
with outage(stand, "stop", "valkey"):
|
||||
assert client.get("/health/ready").status_code == 200
|
||||
|
||||
|
||||
# --- кэш карточки чата -------------------------------------------------------------
|
||||
|
||||
|
||||
def test_flush_cache_refills_on_read(client: httpx.Client, stand: Stand) -> None:
|
||||
alice, bob = register(client, "alice"), register(client, "bob")
|
||||
chat = create_chat(client, alice, bob)
|
||||
wait_cache_ready(client, stand, bob, chat)
|
||||
stand("flush-cache")
|
||||
assert stand("cache-has-chat", chat["id"]) == "0"
|
||||
assert read_chat(client, bob, chat).json() == chat
|
||||
assert stand("cache-has-chat", chat["id"]) == "1"
|
||||
|
||||
|
||||
def test_valkey_stopped_is_bypassed(client: httpx.Client, stand: Stand) -> None:
|
||||
alice, bob = register(client, "alice"), register(client, "bob")
|
||||
chat = create_chat(client, alice, bob)
|
||||
sent = [send(client, alice, chat, "до отказа").json()]
|
||||
with outage(stand, "stop", "valkey"):
|
||||
response, read_took = timed(lambda: read_chat(client, bob, chat))
|
||||
assert response.json() == chat
|
||||
assert read_took < CACHE_TIMEOUT + SLACK, f"read took {read_took:.2f}s"
|
||||
response, took = timed(lambda: send(client, alice, chat, "во время отказа"))
|
||||
assert response.status_code == 201, response.text
|
||||
print(
|
||||
f"valkey stopped: GET chat -> 200 in {read_took:.3f}s, "
|
||||
f"POST message -> 201 in {took:.3f}s",
|
||||
)
|
||||
assert took < CACHE_TIMEOUT + SLACK, f"send took {took:.2f}s"
|
||||
sent.append(response.json())
|
||||
assert read_history(client, bob, chat, limit=50)[0] == sent
|
||||
|
||||
|
||||
def test_valkey_paused_costs_one_timeout(client: httpx.Client, stand: Stand) -> None:
|
||||
alice, bob = register(client, "alice"), register(client, "bob")
|
||||
chat = create_chat(client, alice, bob)
|
||||
wait_cache_ready(client, stand, bob, chat)
|
||||
baseline = statistics.median(
|
||||
timed(lambda: read_chat(client, bob, chat))[1] for _ in range(5)
|
||||
)
|
||||
with outage(stand, "pause", "valkey"):
|
||||
response, took = timed(lambda: read_chat(client, bob, chat))
|
||||
assert response.json() == chat
|
||||
assert took < baseline + CACHE_TIMEOUT + SLACK, (
|
||||
f"read took {took:.2f}s, baseline {baseline:.3f}s"
|
||||
)
|
||||
# окно пропуска: следующий запрос срок не ждёт
|
||||
response, second = timed(lambda: read_chat(client, bob, chat))
|
||||
assert response.json() == chat
|
||||
print(
|
||||
f"valkey paused: baseline {baseline:.3f}s, first read {took:.3f}s, "
|
||||
f"second read {second:.3f}s",
|
||||
)
|
||||
assert second < CACHE_TIMEOUT, f"second read took {second:.2f}s"
|
||||
|
||||
|
||||
def test_valkey_back_without_api_restart(client: httpx.Client, stand: Stand) -> None:
|
||||
alice, bob = register(client, "alice"), register(client, "bob")
|
||||
chat = create_chat(client, alice, bob)
|
||||
with outage(stand, "stop", "valkey"):
|
||||
assert read_chat(client, bob, chat).status_code == 200
|
||||
# API не перезапускался; кэш снова в работе после окна пропуска
|
||||
time.sleep(CACHE_RETRY_AFTER + 0.5)
|
||||
assert read_chat(client, bob, chat).status_code == 200
|
||||
assert stand("cache-has-chat", chat["id"]) == "1"
|
||||
hits = int(stand("cache-hits"))
|
||||
assert read_chat(client, bob, chat).json() == chat
|
||||
assert int(stand("cache-hits")) > hits
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Гонки (уровень 4): одновременные запросы по отдельным соединениям.
|
||||
|
||||
- 100 сообщений от 10 клиентов → ровно 100 уникальных в истории
|
||||
(лаба 1, сохраняется);
|
||||
- 10 одновременных регистраций одного username → одна 201, девять 409:
|
||||
уникальность держит индекс PostgreSQL, а не проверка «сначала SELECT».
|
||||
|
||||
Параллельность настоящая: 10 потоков стартуют одновременно за
|
||||
`threading.Barrier`, у каждого свой клиент и своё соединение, открытое
|
||||
до барьера. Тест требует, чтобы хотя бы 2 запроса были в полёте
|
||||
одновременно, иначе гонка не доказана.
|
||||
"""
|
||||
|
||||
import threading
|
||||
from collections import Counter
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import httpx
|
||||
|
||||
from helpers import (
|
||||
USERS,
|
||||
ClientFactory,
|
||||
assert_error,
|
||||
create_chat,
|
||||
read_history,
|
||||
register,
|
||||
send,
|
||||
unique_password,
|
||||
unique_username,
|
||||
)
|
||||
|
||||
CLIENTS = 10
|
||||
MESSAGES_PER_CLIENT = 10
|
||||
|
||||
|
||||
class InFlight:
|
||||
"""Сколько запросов одновременно в полёте — максимум за прогон."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self.current = 0
|
||||
self.peak = 0
|
||||
|
||||
def __enter__(self) -> None:
|
||||
with self._lock:
|
||||
self.current += 1
|
||||
self.peak = max(self.peak, self.current)
|
||||
|
||||
def __exit__(self, *_exc: object) -> None:
|
||||
with self._lock:
|
||||
self.current -= 1
|
||||
|
||||
|
||||
def run_together[T](
|
||||
clients: list[httpx.Client],
|
||||
work: Callable[[int, httpx.Client], T],
|
||||
) -> list[T]:
|
||||
"""Каждый клиент в своём потоке; старт — одновременно, за барьером."""
|
||||
barrier = threading.Barrier(len(clients))
|
||||
|
||||
def worker(index: int) -> T:
|
||||
own = clients[index]
|
||||
# соединение открыто до барьера: после него сразу запросы
|
||||
own.get("/health/live")
|
||||
barrier.wait()
|
||||
return work(index, own)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=len(clients)) as pool:
|
||||
return list(pool.map(worker, range(len(clients))))
|
||||
|
||||
|
||||
def test_100_messages_from_10_clients(
|
||||
client: httpx.Client,
|
||||
new_client: ClientFactory,
|
||||
) -> None:
|
||||
users = [register(client, f"racer{index}") for index in range(CLIENTS)]
|
||||
chat = create_chat(client, *users, title="Гонка")
|
||||
in_flight = InFlight()
|
||||
|
||||
def send_all(index: int, own: httpx.Client) -> list[tuple[int, str, str]]:
|
||||
results = []
|
||||
for number in range(MESSAGES_PER_CLIENT):
|
||||
text = f"client {index} message {number}"
|
||||
with in_flight:
|
||||
response = send(own, users[index], chat, text)
|
||||
message_id = response.json().get("id", "") if response.is_success else ""
|
||||
results.append((response.status_code, text, message_id))
|
||||
return results
|
||||
|
||||
rows = run_together([new_client() for _ in range(CLIENTS)], send_all)
|
||||
results = [row for group in rows for row in group]
|
||||
|
||||
statuses = Counter(status for status, _, _ in results)
|
||||
items, sizes = read_history(client, users[0], chat, limit=30)
|
||||
ids = [item["id"] for item in items]
|
||||
keys = [(item["created_at"], item["id"]) for item in items]
|
||||
|
||||
print(
|
||||
f"statuses={dict(statuses)} peak_in_flight={in_flight.peak} "
|
||||
f"history={len(items)} unique_ids={len(set(ids))} pages={sizes}",
|
||||
)
|
||||
assert statuses == {201: CLIENTS * MESSAGES_PER_CLIENT}
|
||||
assert in_flight.peak >= 2, "requests never overlapped: race is not proven"
|
||||
assert len(items) == CLIENTS * MESSAGES_PER_CLIENT
|
||||
assert len(set(ids)) == len(ids)
|
||||
assert keys == sorted(keys)
|
||||
# в истории ровно то, что подтвердил сервер, и тексты не перепутаны
|
||||
assert {(item["id"], item["text"]) for item in items} == {
|
||||
(message_id, text) for _, text, message_id in results
|
||||
}
|
||||
assert {item["sender_id"] for item in items} == {user["id"] for user in users}
|
||||
|
||||
|
||||
def test_parallel_registration_of_one_username(new_client: ClientFactory) -> None:
|
||||
username = unique_username("same")
|
||||
in_flight = InFlight()
|
||||
|
||||
def register_same(_index: int, own: httpx.Client) -> httpx.Response:
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": "Двойник",
|
||||
"password": unique_password(),
|
||||
}
|
||||
with in_flight:
|
||||
return own.post(USERS, json=body)
|
||||
|
||||
responses = run_together([new_client() for _ in range(CLIENTS)], register_same)
|
||||
statuses = Counter(response.status_code for response in responses)
|
||||
|
||||
print(f"statuses={dict(statuses)} peak_in_flight={in_flight.peak}")
|
||||
assert in_flight.peak >= 2, "requests never overlapped: race is not proven"
|
||||
assert statuses == {201: 1, 409: CLIENTS - 1}
|
||||
for response in responses:
|
||||
if response.status_code == 409:
|
||||
assert_error(response, 409, "conflict")
|
||||
else:
|
||||
assert response.json()["username"] == username
|
||||
@@ -0,0 +1,59 @@
|
||||
"""X-Request-Id: поведение слоя, общее для любых его реализаций.
|
||||
|
||||
Эти тесты фиксируют то, что видит клиент, и не зависят от того, как
|
||||
написан middleware (в лабе 1 его переписали на чистое ASGI, трек «5»).
|
||||
Ответ 401 формирует AuthenticationMiddleware, а не роутер: id из
|
||||
входящего заголовка должен дойти и до него.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from helpers import USERS, assert_error
|
||||
|
||||
GENERATED_ID = re.compile(r"[0-9a-f]{32}")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "status", "code"),
|
||||
[
|
||||
("/health/live", 200, None),
|
||||
(f"{USERS}/me", 401, "unauthorized"),
|
||||
("/no-such-path", 404, "not_found"),
|
||||
],
|
||||
ids=["ok", "unauthorized", "unknown-path"],
|
||||
)
|
||||
def test_safe_incoming_request_id_is_echoed(
|
||||
client: httpx.Client,
|
||||
path: str,
|
||||
status: int,
|
||||
code: str | None,
|
||||
) -> None:
|
||||
response = client.get(path, headers={"X-Request-Id": "trace-42.a_b"})
|
||||
assert response.status_code == status
|
||||
assert response.headers["X-Request-Id"] == "trace-42.a_b"
|
||||
if code is not None:
|
||||
# тот же id и в теле ошибки: assert_error сверяет его с заголовком
|
||||
assert_error(response, status, code)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"incoming",
|
||||
["bad id", "x" * 65, "<script>"],
|
||||
ids=["space", "too-long", "markup"],
|
||||
)
|
||||
def test_unsafe_incoming_request_id_is_replaced(
|
||||
client: httpx.Client,
|
||||
incoming: str,
|
||||
) -> None:
|
||||
response = client.get("/health/live", headers={"X-Request-Id": incoming})
|
||||
assert response.status_code == 200
|
||||
assert GENERATED_ID.fullmatch(response.headers["X-Request-Id"])
|
||||
|
||||
|
||||
def test_generated_request_ids_are_unique(client: httpx.Client) -> None:
|
||||
ids = {client.get("/health/live").headers["X-Request-Id"] for _ in range(20)}
|
||||
assert len(ids) == 20
|
||||
assert all(GENERATED_ID.fullmatch(request_id) for request_id in ids)
|
||||
@@ -0,0 +1,228 @@
|
||||
"""Обязательные сценарии уровня 4 (README.md): каждый — отдельный тест.
|
||||
|
||||
Лаба 1 (сохраняются): неверный JSON, чужой чат, пустое сообщение,
|
||||
дубликат username, обход нескольких страниц истории. Лаба 2: неверный
|
||||
пароль и logout. Плюс health и порядок «сначала аутентификация», на
|
||||
который опирается архитектура. Гонки — `test_race.py`, срок сессии и
|
||||
отказы хранилищ — `test_failures.py` (make failure-checks).
|
||||
"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from helpers import (
|
||||
BASIC_CHALLENGE,
|
||||
BEARER_CHALLENGE,
|
||||
CHATS,
|
||||
ME,
|
||||
USERS,
|
||||
assert_error,
|
||||
assert_unauthorized,
|
||||
create_chat,
|
||||
headers,
|
||||
login_response,
|
||||
logout,
|
||||
messages_path,
|
||||
public,
|
||||
read_history,
|
||||
register,
|
||||
send,
|
||||
unique_password,
|
||||
unique_username,
|
||||
)
|
||||
|
||||
|
||||
def test_health_live_and_ready(client: httpx.Client) -> None:
|
||||
for path in ("/health/live", "/health/ready"):
|
||||
response = client.get(path)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
assert response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw",
|
||||
[
|
||||
b'{"username": "broken",', # оборван
|
||||
b"{'username': 'single_quotes'}", # не JSON
|
||||
b"[]", # JSON, но не объект
|
||||
],
|
||||
ids=["truncated", "not-json", "array"],
|
||||
)
|
||||
def test_malformed_json_is_400(client: httpx.Client, raw: bytes) -> None:
|
||||
response = client.post(
|
||||
USERS,
|
||||
content=raw,
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_malformed_json_with_token_is_400(client: httpx.Client) -> None:
|
||||
alice = register(client, "alice")
|
||||
chat = create_chat(client, alice)
|
||||
for path in (CHATS, messages_path(chat)):
|
||||
response = client.post(
|
||||
path,
|
||||
content=b'{"title": ',
|
||||
headers={**headers(alice), "Content-Type": "application/json"},
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_malformed_json_without_token_is_401(client: httpx.Client) -> None:
|
||||
"""Аутентификация раньше разбора тела: битый JSON без токена — 401."""
|
||||
response = client.post(
|
||||
CHATS,
|
||||
content=b'{"title": ',
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
assert_unauthorized(response, BEARER_CHALLENGE)
|
||||
|
||||
|
||||
def test_foreign_chat_is_404_like_missing_chat(client: httpx.Client) -> None:
|
||||
alice, bob, eve = (register(client, name) for name in ("alice", "bob", "eve"))
|
||||
chat = create_chat(client, alice, bob)
|
||||
assert send(client, alice, chat, "видно только участникам").status_code == 201
|
||||
missing = {"id": "11111111-1111-4111-8111-111111111111"}
|
||||
|
||||
for target in (chat, missing):
|
||||
errors = [
|
||||
assert_error(
|
||||
client.get(f"{CHATS}/{target['id']}", headers=headers(eve)),
|
||||
404,
|
||||
"not_found",
|
||||
),
|
||||
assert_error(
|
||||
client.get(messages_path(target), headers=headers(eve)),
|
||||
404,
|
||||
"not_found",
|
||||
),
|
||||
assert_error(send(client, eve, target, "чужое"), 404, "not_found"),
|
||||
]
|
||||
# чужой и несуществующий чат неотличимы по тексту ошибки
|
||||
assert {error["message"] for error in errors} == {"Not found"}
|
||||
|
||||
listed = client.get(CHATS, params={"limit": 100}, headers=headers(eve))
|
||||
assert listed.status_code == 200
|
||||
assert all(item["id"] != chat["id"] for item in listed.json()["items"])
|
||||
# участник по-прежнему видит свою историю, и чужого сообщения в ней нет
|
||||
items, _ = read_history(client, bob, chat, limit=50)
|
||||
assert [item["text"] for item in items] == ["видно только участникам"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", " ", "\n\t"], ids=["empty", "spaces", "ws"])
|
||||
def test_empty_message_is_400(client: httpx.Client, text: str) -> None:
|
||||
alice = register(client, "alice")
|
||||
chat = create_chat(client, alice)
|
||||
assert_error(send(client, alice, chat, text), 400, "invalid_request")
|
||||
items, _ = read_history(client, alice, chat, limit=50)
|
||||
assert items == []
|
||||
|
||||
|
||||
def test_duplicate_username_is_409(client: httpx.Client) -> None:
|
||||
first = register(client, "dup")
|
||||
second = client.post(
|
||||
USERS,
|
||||
json={
|
||||
"username": first["username"],
|
||||
"display_name": "Второй",
|
||||
"password": unique_password(),
|
||||
},
|
||||
)
|
||||
assert_error(second, 409, "conflict")
|
||||
# занятый username не меняет владельца: прежний пароль, прежние данные
|
||||
me = client.get(ME, headers=headers(first))
|
||||
assert me.json() == public(first)
|
||||
|
||||
|
||||
def test_history_walks_several_pages(client: httpx.Client) -> None:
|
||||
alice, bob = register(client, "alice"), register(client, "bob")
|
||||
chat = create_chat(client, alice, bob)
|
||||
sent = []
|
||||
for index in range(7):
|
||||
author = alice if index % 2 == 0 else bob
|
||||
response = send(client, author, chat, f"сообщение {index} 👋")
|
||||
assert response.status_code == 201
|
||||
sent.append(response.json())
|
||||
|
||||
items, sizes = read_history(client, bob, chat, limit=3)
|
||||
|
||||
assert sizes == [3, 3, 1]
|
||||
assert items == sent # без потерь, повторов и перестановок
|
||||
ids = [item["id"] for item in items]
|
||||
assert len(set(ids)) == len(ids)
|
||||
keys = [(item["created_at"], item["id"]) for item in items]
|
||||
assert keys == sorted(keys)
|
||||
|
||||
|
||||
def test_cursor_of_another_chat_is_400(client: httpx.Client) -> None:
|
||||
alice = register(client, "alice")
|
||||
first, second = create_chat(client, alice), create_chat(client, alice)
|
||||
for index in range(2):
|
||||
assert send(client, alice, first, f"m{index}").status_code == 201
|
||||
page = client.get(messages_path(first), params={"limit": 1}, headers=headers(alice))
|
||||
cursor = page.json()["next_cursor"]
|
||||
assert cursor
|
||||
|
||||
response = client.get(
|
||||
messages_path(second),
|
||||
params={"limit": 1, "cursor": cursor},
|
||||
headers=headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("target", ["history", "chats"])
|
||||
@pytest.mark.parametrize("placement", ["prefix", "suffix"])
|
||||
def test_corrupted_issued_cursor_is_400(
|
||||
client: httpx.Client,
|
||||
target: str,
|
||||
placement: str,
|
||||
) -> None:
|
||||
alice = register(client, "alice")
|
||||
first = create_chat(client, alice)
|
||||
create_chat(client, alice)
|
||||
for index in range(2):
|
||||
assert send(client, alice, first, f"m{index}").status_code == 201
|
||||
path = messages_path(first) if target == "history" else CHATS
|
||||
page = client.get(path, params={"limit": 1}, headers=headers(alice))
|
||||
assert page.status_code == 200
|
||||
cursor = page.json()["next_cursor"]
|
||||
assert cursor
|
||||
# Четыре символа не меняют padding: нестрогий декодер их игнорировал.
|
||||
corrupted = f"!!!!{cursor}" if placement == "prefix" else f"{cursor}!!!!"
|
||||
response = client.get(
|
||||
path,
|
||||
params={"limit": 1, "cursor": corrupted},
|
||||
headers=headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
valid = client.get(
|
||||
path,
|
||||
params={"limit": 1, "cursor": cursor},
|
||||
headers=headers(alice),
|
||||
)
|
||||
assert valid.status_code == 200
|
||||
assert valid.json()["items"] != page.json()["items"]
|
||||
|
||||
|
||||
def test_wrong_password_is_401(client: httpx.Client) -> None:
|
||||
alice = register(client, "alice")
|
||||
response = login_response(client, alice["username"], alice["password"] + "-wrong")
|
||||
assert_unauthorized(response, BASIC_CHALLENGE)
|
||||
assert "token" not in response.text
|
||||
# неизвестный username — тот же ответ: по нему не узнать, есть ли он
|
||||
unknown = login_response(client, unique_username("ghost"), alice["password"])
|
||||
assert_unauthorized(unknown, BASIC_CHALLENGE)
|
||||
assert unknown.json()["error"]["message"] == response.json()["error"]["message"]
|
||||
|
||||
|
||||
def test_logout_revokes_token(client: httpx.Client) -> None:
|
||||
alice = register(client, "alice")
|
||||
response = logout(client, alice)
|
||||
assert response.status_code == 204, response.text
|
||||
assert response.content == b""
|
||||
assert_unauthorized(client.get(ME, headers=headers(alice)), BEARER_CHALLENGE)
|
||||
# повтор выхода тем же токеном — 401
|
||||
assert_unauthorized(logout(client, alice), BEARER_CHALLENGE)
|
||||
Reference in New Issue
Block a user