179 lines
8.1 KiB
Python
179 lines
8.1 KiB
Python
"""Фикстуры собственных тестов. Все тесты — по HTTP против запущенного стенда.
|
||
|
||
`BASE_URL` (по умолчанию `https://localhost:8443`): compose-стенд
|
||
(`make up`), сервис на хосте (`make run`) или отдельный стенд
|
||
`make test-isolated`. Состояние общее и растёт от прогона к прогону:
|
||
тесты не рассчитывают на пустой сервер.
|
||
|
||
Лаба 7: сертификат сервера `https://` проверяется всегда — по `CA_FILE`
|
||
(по умолчанию CA стенда `.pki/stand/ca.crt`, пустая строка — системное
|
||
хранилище) и hostname; выключателя проверки нет. Ошибка проверки — одна
|
||
строка с адресом, CA и именем сервера и код 2 до первого теста. Стенд
|
||
отказов (`stand.py failures`) ходит к API без LB клиентом в роли LB:
|
||
`TLS_CLIENT_CERT` / `TLS_CLIENT_KEY` — пара `haproxy` PKI прогона,
|
||
`TLS_SERVER_NAME=api` — имя сервера при адресе `https://127.0.0.1:<порт>`.
|
||
Клиенты — только `helpers.http_client()`.
|
||
|
||
Проверки отказов (маркер `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 ssl
|
||
import subprocess
|
||
from collections.abc import Callable, Iterator
|
||
|
||
import httpx
|
||
import pytest
|
||
|
||
from helpers import CA_FILE, TLS_SERVER_NAME, ClientFactory, http_client
|
||
|
||
BASE_URL = os.environ.get("BASE_URL", "https://localhost:8443").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(request: pytest.FixtureRequest) -> None:
|
||
"""Без сервера — одна понятная строка, а не десяток ошибок.
|
||
|
||
Прогону из одних юнит-тестов (маркер `unit`, `make unit-test`) сервер
|
||
не нужен: они проверяют модули `src` в процессе pytest.
|
||
"""
|
||
items = request.session.items
|
||
if items and all(item.get_closest_marker("unit") for item in items):
|
||
return
|
||
try:
|
||
with http_client(BASE_URL, timeout=2) as probe:
|
||
response = probe.get("/health/live")
|
||
except httpx.ConnectError as exc:
|
||
# ошибка проверки сертификата — тоже ConnectError; причина — в цепочке
|
||
cause: BaseException | None = exc
|
||
while cause is not None and not isinstance(cause, ssl.SSLCertVerificationError):
|
||
cause = cause.__cause__ or cause.__context__
|
||
if isinstance(cause, ssl.SSLCertVerificationError):
|
||
pytest.exit(
|
||
f"TLS certificate of {BASE_URL} failed verification "
|
||
f"(CA_FILE={CA_FILE or 'system store'}, "
|
||
f"server name {TLS_SERVER_NAME or 'from the URL'}): "
|
||
f"{cause.verify_message}",
|
||
returncode=2,
|
||
)
|
||
pytest.exit(f"server is not reachable at {BASE_URL}: {exc!r}", returncode=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 = http_client(BASE_URL)
|
||
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 http_client(FAULT_TIGHT_BASE_URL) as client:
|
||
yield client
|
||
|
||
|
||
@pytest.fixture
|
||
def uploads_client() -> Iterator[httpx.Client]:
|
||
"""Клиент к API, где на загрузки 1 место и 1 очередь, на ожидание места
|
||
1 с, а на всё тело 2 с."""
|
||
with http_client(FAULT_UPLOADS_BASE_URL) as client:
|
||
yield client
|
||
|
||
|
||
@pytest.fixture
|
||
def backlog_client() -> Iterator[httpx.Client]:
|
||
"""Клиент к API, который отказывает (429) уже при трёх заданиях в работе."""
|
||
with http_client(FAULT_BACKLOG_BASE_URL) 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
|