feat: carry lab 2 over and add X-Instance-Id and idempotency keys
- carry the lab 2 solution over and plan lab 3 (PLAN.md, OpenSpec change instance-id-idempotency) - rename the compose project to mtusi-lab3 and the image to :lab3 - add X-Instance-Id to every response and instance_id to every log record ([app] instance_id, hostname by default) - require Idempotency-Key on POST messages: keys table in Postgres, key and message in one transaction, replay returns the same 201, another body gets 409, TTL from [idempotency] ttl_seconds - send the key from student-tests, k6 scenarios and the skill driver; add idempotency, X-Instance-Id, key race and fault tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,164 @@
|
||||
"""Сверка тестов со сценариями основных спеков `openspec/specs/`."""
|
||||
|
||||
import re
|
||||
from collections.abc import Iterable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SPECS_DIR = Path(__file__).resolve().parents[1] / "openspec" / "specs"
|
||||
# основные спеки поведения API; спеки контейнера, логов и конфига
|
||||
# проверяются evidence, а не HTTP-тестами
|
||||
CAPABILITIES = (
|
||||
"api-conventions",
|
||||
"identification",
|
||||
"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="чтения таблицы chats (seq_scan + idx_scan) и "
|
||||
"keyspace_hits Valkey за 50 чтений — evidence/cache/hits.md",
|
||||
),
|
||||
("chat-cache", "Срок записи"): Exclusion(
|
||||
reason="срок ключа виден только в Valkey",
|
||||
check="TTL ключа карточки через valkey-cli — evidence/cache/hits.md",
|
||||
),
|
||||
("chat-cache", "Временная база"): Exclusion(
|
||||
reason="ключи видны только в Valkey, а набор не знает, на какой "
|
||||
"базе работает",
|
||||
check="число ключей с префиксами рабочей и тестовой базы после "
|
||||
"make test_isolated — evidence/cache/hits.md",
|
||||
),
|
||||
("data-storage", "Прежний пользователь после рестарта"): Exclusion(
|
||||
reason="нужен рестарт стенда, тесты сервер не трогают",
|
||||
check="make test-persistence ACTION_SCRIPT=scripts/restart.sh: "
|
||||
"прежний токен читает те же данные — "
|
||||
"evidence/storage/test-persistence.md",
|
||||
),
|
||||
("identification", "Кнопка Authorize в Swagger"): Exclusion(
|
||||
reason="это интерфейс /docs в браузере",
|
||||
check="схемы bearerAuth и basicAuth, из которых строится кнопка, "
|
||||
"проверяет тест сценария «Схема в openapi.json»; кнопку — вручную "
|
||||
"(REPORT.md, таблица доказательств)",
|
||||
),
|
||||
("sessions", "Токена нет в хранилище"): Exclusion(
|
||||
reason="нужен доступ к таблицам PostgreSQL, а тесты ходят по HTTP",
|
||||
check="поиск выданного токена по всем таблицам через psql — "
|
||||
"evidence/auth/passwords-and-tokens.md",
|
||||
),
|
||||
("sessions", "Прежний токен после рестарта"): Exclusion(
|
||||
reason="нужен рестарт стенда, тесты сервер не трогают",
|
||||
check="make test-persistence ACTION_SCRIPT=scripts/restart.sh — "
|
||||
"evidence/storage/test-persistence.md",
|
||||
),
|
||||
("users", "Хэш в БД"): Exclusion(
|
||||
reason="нужен доступ к таблице users, а тесты ходят по HTTP",
|
||||
check="строки users через psql: префикс $argon2id$ и разные "
|
||||
"хэши одинаковых паролей — evidence/auth/passwords-and-tokens.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
|
||||
Reference in New Issue
Block a user