"""Фикстуры собственных тестов. Все тесты — по 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