test: add automatic failure checks on a separate stand
make failure_checks brings up a throwaway compose project with its own PostgreSQL and Valkey, a default and a tight API (2 s sessions, pool of one), and runs the pytest tests marked fault through an explicit hook: session expiry, database stop and return, pool exhaustion, chat creation rollback, readiness, Valkey stop, hang, return and flush. The stand and its volume are removed on any outcome; the working stand is untouched. Regular runs deselect the fault tests, and 13 coverage exclusions go away. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
"""Настройка набора: адрес стенда, проверка доступности, фикстуры."""
|
||||
|
||||
import os
|
||||
from collections.abc import Iterator
|
||||
import subprocess
|
||||
from collections.abc import Callable, Iterator
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
@@ -11,6 +12,10 @@ from api_client import Actor, Api
|
||||
from spec_coverage import COLLECTED, Collected
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
||||
# 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)
|
||||
@@ -22,15 +27,35 @@ def pytest_collection_modifyitems(
|
||||
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 ошибками."""
|
||||
@@ -80,3 +105,37 @@ def eve(api: Api) -> Actor:
|
||||
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,12 @@
|
||||
# Override стенда отказов make failure_checks (student-tests/run_failures.py):
|
||||
# тот же docker-compose.yml под проектом mtusi-lab2-failures, со своим
|
||||
# volume и сетью. Порты Postgres и Valkey не публикуются: к ним ходит только
|
||||
# fault_hook.py через docker compose exec. Сервис api не запускается,
|
||||
# контейнеры API создаёт оркестратор (docker compose run -p 127.0.0.1:...).
|
||||
services:
|
||||
postgres:
|
||||
ports: !reset []
|
||||
valkey:
|
||||
ports: !reset []
|
||||
api:
|
||||
ports: !reset []
|
||||
Executable
+249
@@ -0,0 +1,249 @@
|
||||
#!/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 убрать триггер
|
||||
count-chats <title> число чатов с этим названием
|
||||
|
||||
Пароли не печатает: 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
|
||||
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 приложения
|
||||
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 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 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 == "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 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,258 @@
|
||||
"""`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`;
|
||||
- удаляет стенд вместе с 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
|
||||
# «тесный» API: короткий срок сессии и пул из одного соединения
|
||||
TIGHT_ENV = {
|
||||
"AUTH__SESSION_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 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)
|
||||
left = run(
|
||||
"docker",
|
||||
"volume",
|
||||
"ls",
|
||||
"-q",
|
||||
"--filter",
|
||||
f"label=com.docker.compose.project={project}",
|
||||
quiet=True,
|
||||
check=False,
|
||||
)
|
||||
return down.returncode == 0 and not left.stdout.strip()
|
||||
|
||||
|
||||
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"])
|
||||
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())
|
||||
@@ -57,26 +57,6 @@ EXCLUDED: dict[Scenario, Exclusion] = {
|
||||
reason="срок ключа виден только в Valkey",
|
||||
check="TTL ключа карточки через valkey-cli — evidence/cache/hits.md",
|
||||
),
|
||||
("chat-cache", "Valkey остановлен"): Exclusion(
|
||||
reason="нужно остановить Valkey, тесты стенд не трогают",
|
||||
check="evidence/cache/outage.md; автоматическая проверка — "
|
||||
"change failure-checks",
|
||||
),
|
||||
("chat-cache", "Valkey завис"): Exclusion(
|
||||
reason="нужен docker compose pause для Valkey",
|
||||
check="evidence/cache/outage.md: время ответа; автоматическая "
|
||||
"проверка — change failure-checks",
|
||||
),
|
||||
("chat-cache", "Valkey вернулся"): Exclusion(
|
||||
reason="нужно остановить и снова запустить Valkey",
|
||||
check="evidence/cache/outage.md: warning и info в журнале, "
|
||||
"ключи снова пишутся; автоматическая проверка — change "
|
||||
"failure-checks",
|
||||
),
|
||||
("chat-cache", "Очистка кэша"): Exclusion(
|
||||
reason="нужен FLUSHALL в Valkey, тесты стенд не трогают",
|
||||
check="evidence/cache/flush-restart.md",
|
||||
),
|
||||
("chat-cache", "Временная база"): Exclusion(
|
||||
reason="ключи видны только в Valkey, а набор не знает, на какой "
|
||||
"базе работает",
|
||||
@@ -89,38 +69,6 @@ EXCLUDED: dict[Scenario, Exclusion] = {
|
||||
"прежний токен читает те же данные — "
|
||||
"evidence/storage/test-persistence.md",
|
||||
),
|
||||
("data-storage", "Сбой при добавлении участников"): Exclusion(
|
||||
reason="нужен сбой БД посреди транзакции: штатным запросом его "
|
||||
"не вызвать, участники проверяются до вставки",
|
||||
check="одна транзакция и один commit в ChatService.create_chat; "
|
||||
"автоматическая проверка отката — change failure-checks",
|
||||
),
|
||||
("data-storage", "БД остановлена"): Exclusion(
|
||||
reason="нужно остановить Postgres, тесты стенд не трогают",
|
||||
check="evidence/storage/db-unavailable.md; автоматическая "
|
||||
"проверка — change failure-checks",
|
||||
),
|
||||
("data-storage", "БД вернулась"): Exclusion(
|
||||
reason="нужно остановить и снова запустить Postgres",
|
||||
check="evidence/storage/db-unavailable.md; автоматическая "
|
||||
"проверка — change failure-checks",
|
||||
),
|
||||
("data-storage", "Соединения исчерпаны"): Exclusion(
|
||||
reason="нужны пул из одного соединения и замороженный Postgres",
|
||||
check="evidence/storage/pool-timeout.md; автоматическая "
|
||||
"проверка — change failure-checks",
|
||||
),
|
||||
("health", "Хранилище не готово"): Exclusion(
|
||||
reason="нужно остановить Postgres, тесты стенд не трогают",
|
||||
check="evidence/storage/db-unavailable.md: /health/ready — 503, "
|
||||
"/health/live — 200; автоматическая проверка — change "
|
||||
"failure-checks",
|
||||
),
|
||||
("health", "Кэш недоступен"): Exclusion(
|
||||
reason="нужно остановить Valkey, тесты стенд не трогают",
|
||||
check="evidence/cache/outage.md: /health/ready — 200; "
|
||||
"автоматическая проверка — change failure-checks",
|
||||
),
|
||||
("identification", "Кнопка Authorize в Swagger"): Exclusion(
|
||||
reason="это интерфейс /docs в браузере",
|
||||
check="схемы bearerAuth и basicAuth, из которых строится кнопка, "
|
||||
@@ -132,27 +80,11 @@ EXCLUDED: dict[Scenario, Exclusion] = {
|
||||
check="поиск выданного токена по всем таблицам через psql — "
|
||||
"evidence/auth/passwords-and-tokens.md",
|
||||
),
|
||||
("sessions", "Истёкший токен"): Exclusion(
|
||||
reason="нужен сервис со сроком сессии 2 с, а обычный стенд — с 3600 с",
|
||||
check="AUTH__SESSION_TTL_SECONDS=2 — evidence/auth/expiry.md; "
|
||||
"автоматическая проверка — change failure-checks",
|
||||
),
|
||||
("sessions", "Срок не продлевается"): Exclusion(
|
||||
reason="нужен сервис со сроком сессии 2 с",
|
||||
check="запросы каждые 0,5 с при сроке 2 с — "
|
||||
"evidence/auth/expiry.md; автоматическая проверка — change "
|
||||
"failure-checks",
|
||||
),
|
||||
("sessions", "Прежний токен после рестарта"): Exclusion(
|
||||
reason="нужен рестарт стенда, тесты сервер не трогают",
|
||||
check="make test-persistence ACTION_SCRIPT=scripts/restart.sh — "
|
||||
"evidence/storage/test-persistence.md",
|
||||
),
|
||||
("sessions", "БД остановлена при запросе с токеном"): Exclusion(
|
||||
reason="нужно остановить Postgres, тесты стенд не трогают",
|
||||
check="evidence/auth/expiry.md; автоматическая проверка — "
|
||||
"change failure-checks",
|
||||
),
|
||||
("users", "Хэш в БД"): Exclusion(
|
||||
reason="нужен доступ к таблице users, а тесты ходят по HTTP",
|
||||
check="строки users через psql: префикс $argon2id$ и разные "
|
||||
@@ -163,10 +95,13 @@ EXCLUDED: dict[Scenario, Exclusion] = {
|
||||
|
||||
@dataclass
|
||||
class Collected:
|
||||
"""Что собрал pytest: маркеры `spec` и модули тестов."""
|
||||
"""Что собрал 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]()
|
||||
|
||||
@@ -34,10 +34,12 @@ def test_every_scenario_is_covered(request: pytest.FixtureRequest) -> None:
|
||||
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"{len(EXCLUDED)} excluded",
|
||||
f"{len(CAPABILITIES)} specs, {tested} tested "
|
||||
f"({by_fault} by make failure_checks), {len(EXCLUDED)} excluded",
|
||||
)
|
||||
assert not problems, "\n".join(problems)
|
||||
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
"""Проверки отказов: выполняет только `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
|
||||
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
|
||||
POOL_TIMEOUT_S = 1
|
||||
# срок проверки Postgres в /health/ready
|
||||
READINESS_TIMEOUT_S = 2
|
||||
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:
|
||||
path = f"{API}/chats/{chat['id']}/messages"
|
||||
with outage(stand, "stop", "postgres"):
|
||||
resp, took = timed(
|
||||
lambda: api.request(
|
||||
"POST",
|
||||
path,
|
||||
actor=alice,
|
||||
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")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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:
|
||||
path = f"{API}/chats/{chat['id']}/messages"
|
||||
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.request(
|
||||
"POST",
|
||||
path,
|
||||
actor=alice,
|
||||
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
|
||||
Reference in New Issue
Block a user