Files
mtusi2026lab5/student-tests/conftest.py
T

147 lines
6.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Фикстуры собственных тестов. Все тесты — по 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("/")
# лаба 4: API с одним местом загрузки и уборщик стенда отказов
FAULT_UPLOADS_BASE_URL = os.environ.get("FAULT_UPLOADS_BASE_URL", "").rstrip("/")
# лаба 5: API с пределом незавершённых заданий
FAULT_BACKLOG_BASE_URL = os.environ.get("FAULT_BACKLOG_BASE_URL", "").rstrip("/")
FAULT_HOOK_TIMEOUT = 120
@pytest.hookimpl(trylast=True)
def pytest_collection_finish(session: pytest.Session) -> None:
"""Остановить сессию, если выбраны тесты `fault`, а их стенда нет.
Проверяем сразу после сбора, ещё до первого теста, — так без 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
and FAULT_UPLOADS_BASE_URL
and FAULT_BACKLOG_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
def uploads_client() -> Iterator[httpx.Client]:
"""Клиент к API, где на загрузки 1 место и 1 очередь, на ожидание места
1 с, а на всё тело 2 с."""
with httpx.Client(base_url=FAULT_UPLOADS_BASE_URL, timeout=15) as client:
yield client
@pytest.fixture
def backlog_client() -> Iterator[httpx.Client]:
"""Клиент к API, который отказывает (429) уже при трёх заданиях в работе."""
with httpx.Client(base_url=FAULT_BACKLOG_BASE_URL, timeout=15) as client:
yield client
@pytest.fixture(scope="session")
def stand() -> Callable[..., str]:
"""Функция-пульт стенда отказов: запускает hook и отдаёт его stdout.
Пример: `stand("stop", "postgres")`. Байты на stdin (нужны для
`put-object`) передаются аргументом `data`. Hook исполняется напрямую,
без shell, по образцу `ACTION_SCRIPT` из `tests/resilience.py`, так что
тестам самим вызывать docker не приходится.
"""
def call(*args: str, data: bytes | None = None) -> str:
result = subprocess.run(
[FAULT_HOOK, *args],
input=data,
capture_output=True,
timeout=FAULT_HOOK_TIMEOUT,
check=False,
)
stderr = result.stderr.decode(errors="replace")
assert result.returncode == 0, f"fault hook {' '.join(args)}: {stderr}"
return result.stdout.decode().strip()
return call