feat: add replicated messenger and reproducible lab3 stand

This commit is contained in:
2026-10-15 13:43:39 +03:00
parent 0ab3a341aa
commit 84dd7fec0a
106 changed files with 17235 additions and 24 deletions
+119
View File
@@ -0,0 +1,119 @@
"""Фикстуры собственных тестов. Все тесты — по 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`). Без них такие тесты не запускаются.
Сколько реплик за `BASE_URL`, набор узнаёт из `EXPECT_REPLICAS`, а не
угадывает по ответам: иначе сломанный LB давал бы пропуск вместо
падения. `make student-test` берёт его из `API_REPLICAS`, против одного
процесса (`make run`, стенд отказов) — 1: тестам реплик (фикстура
`replicas`) тогда нечего проверять, они пропускаются с причиной.
"""
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("/")
EXPECT_REPLICAS = int(os.environ.get("EXPECT_REPLICAS", "1"))
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 replicas() -> int:
"""Число реплик за BASE_URL; против одного процесса — пропуск теста."""
if EXPECT_REPLICAS < 2:
pytest.skip("one API process behind BASE_URL (EXPECT_REPLICAS=1)")
return EXPECT_REPLICAS
@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