Files
mtusi2026lab7-safronov/student-tests/conftest.py
ricoromaandClaude Opus 5.5 6353889349 feat: run a per-run OpenBao for failure checks, bench, CI and driver stands
Every stand with its own storages now brings up its own OpenBao and acts
as its operator: materials live in the run's temporary directory and are
removed on any outcome; the working stand's OpenBao is never touched.

- make failure_checks: own OpenBao, 20 s / 60 s token roles, six new
  OpenBao fault checks, hook actions and the secrets log summary
- bao.py rewrite and waiting for the active node after unseal
- bench/: OpenBao in every fresh stand, "before" variants get secrets
  via ${...} references, passport stand.secrets and limits.openbao
- CI job: BAO_ADDRESS, run OpenBao operator, override with openbao,
  cleaner and migrate pairs, test_ci_override.py
- driver: shared temporary stand for freeze-lb and reconcile-signal

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 18:21:57 +03:00

282 lines
11 KiB
Python
Raw Permalink 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.
"""Настройка набора: адрес стенда, проверка доступности, фикстуры."""
import os
import ssl
import subprocess
from collections.abc import Callable, Iterator
from typing import Any
import httpx
import pytest
from api_client import (
CA_FILE,
TLS_SERVER_NAME,
Actor,
Api,
TlsSettingsError,
tls_context,
tls_extensions,
)
from spec_coverage import COLLECTED, Collected
# с лабы 7 — HTTPS балансировщика (change pki-ingress-mtls)
BASE_URL = os.environ.get("BASE_URL", "https://localhost:8443").rstrip("/")
# сколько реплик API за BASE_URL: стенд с LB — API_REPLICAS (make
# student_test), один процесс — 1 (make test_isolated, драйвер в консоли).
# Режим задаётся явно, а не угадывается по ответам: иначе сломанный LB
# давал бы пропуск вместо падения
EXPECT_REPLICAS = int(os.environ.get("EXPECT_REPLICAS", "2"))
# hook стенда отказов и «тесный» API задаёт make failure_checks
FAULT_HOOK = os.environ.get("FAULT_HOOK", "")
FAULT_TIGHT_BASE_URL = os.environ.get("FAULT_TIGHT_BASE_URL", "").rstrip("/")
# «узкий по загрузкам» API стенда отказов (change upload-memory)
FAULT_UPLOADS_BASE_URL = os.environ.get("FAULT_UPLOADS_BASE_URL", "").rstrip(
"/",
)
# API стенда отказов с коротким сроком вызова S3 (change fix-upload-put-flake)
FAULT_S3_BASE_URL = os.environ.get("FAULT_S3_BASE_URL", "").rstrip("/")
# «узкий по заданиям» API стенда отказов (change track1-queue-overload)
FAULT_BACKLOG_BASE_URL = os.environ.get("FAULT_BACKLOG_BASE_URL", "").rstrip(
"/",
)
# OpenBao стенда отказов (change openbao-tooling, design, решение 2): адрес и
# каталог материалов оператора прогона, сроки токенов ролей и срок ожидания
# OpenBao при старте API — проверки сверяют с ними стенд
FAULT_BAO_ENV = (
"FAULT_BAO_ADDRESS",
"FAULT_BAO_OPERATOR_DIR",
"FAULT_BAO_TOKEN_TTL_S",
"FAULT_BAO_TOKEN_MAX_TTL_S",
"FAULT_SECRETS_STARTUP_TIMEOUT_S",
)
FAULT_HOOK_TIMEOUT_S = 120
# срок клиента «узкого» API: больше ожидания места, срока тела и шагов
UPLOADS_CLIENT_TIMEOUT_S = 30
# срок клиента API с коротким сроком S3: медленное скачивание оригинала
# в несколько MiB длится дольше 5 с по умолчанию у `Api`
S3_CLIENT_TIMEOUT_S = 30
@pytest.hookimpl(tryfirst=True)
def pytest_collection_modifyitems(
config: pytest.Config,
items: list[pytest.Item],
) -> None:
"""Маркеры `spec` всех собранных тестов, до отбора по `-k` / `-m`."""
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
and FAULT_UPLOADS_BASE_URL
and FAULT_S3_BASE_URL
and FAULT_BACKLOG_BASE_URL
and all(os.environ.get(name) for name in FAULT_BAO_ENV)
):
pytest.exit(
"fault checks need the failure stand and its hook: "
"run make failure_checks",
returncode=2,
)
def cert_verification_error(
exc: BaseException,
) -> ssl.SSLCertVerificationError | None:
"""Ошибка проверки сертификата в цепочке причин (httpx → httpcore)."""
seen: set[int] = set()
current: BaseException | None = exc
while current is not None and id(current) not in seen:
if isinstance(current, ssl.SSLCertVerificationError):
return current
seen.add(id(current))
current = current.__cause__ or current.__context__
return None
@pytest.fixture(scope="session", autouse=True)
def _server_reachable() -> None:
"""Без сервера прогон останавливается одной строкой, а не 100 ошибками.
Так же — сертификат сервера, который не проходит проверку по `CA_FILE`
и имени сервера (`TLS_SERVER_NAME`, иначе hostname адреса): адрес, CA,
имя и причина одной строкой, код 2 до первого теста. Клиентский
сертификат без ключа (или наоборот) — тоже код 2.
"""
try:
context = tls_context()
except TlsSettingsError as exc:
pytest.exit(f"{exc} (for {BASE_URL})", returncode=2)
except (OSError, ssl.SSLError) as exc:
pytest.exit(
f"cannot load CA_FILE {CA_FILE!r} or the client certificate "
f"for {BASE_URL}: {exc}",
returncode=2,
)
try:
with httpx.Client(timeout=2, verify=context) as client:
resp = client.get(
f"{BASE_URL}/health/live",
extensions=tls_extensions(),
)
except httpx.HTTPError as exc:
cause = cert_verification_error(exc)
if cause is not None:
server_name = TLS_SERVER_NAME or httpx.URL(BASE_URL).host
pytest.exit(
f"server certificate at {BASE_URL} failed verification "
f"(CA_FILE {CA_FILE!r}, server name {server_name!r}): "
f"{cause.verify_message}",
returncode=2,
)
pytest.exit(
f"server is not reachable at {BASE_URL}: {exc!r}",
returncode=2,
)
if resp.status_code != 200:
pytest.exit(
f"{BASE_URL}/health/live answered {resp.status_code}: "
"another service on this port?",
returncode=2,
)
@pytest.fixture(scope="session")
def base_url() -> str:
return BASE_URL
@pytest.fixture(scope="session")
def expect_replicas() -> int:
return EXPECT_REPLICAS
@pytest.fixture
def replicas() -> int:
"""Тест реплик: нужны ≥ 2 реплики за балансировщиком.
Против одного процесса тест пропускается с причиной, а не считается
пройденным.
"""
if EXPECT_REPLICAS < 2:
pytest.skip(
f"one API process (EXPECT_REPLICAS={EXPECT_REPLICAS}): "
"replica checks need the stand with the load balancer",
)
return EXPECT_REPLICAS
@pytest.fixture(scope="session")
def api() -> Iterator[Api]:
with Api(BASE_URL) as client:
yield client
@pytest.fixture
def alice(api: Api) -> Actor:
return api.register(display_name="Алиса")
@pytest.fixture
def bob(api: Api) -> Actor:
return api.register(display_name="Боб")
@pytest.fixture
def eve(api: Api) -> Actor:
"""Посторонний: ни в одном чате фикстур не состоит."""
return api.register(display_name="Ева")
@pytest.fixture
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, stdin: bytes = b"") -> str:
# stdin — байты: тело объекта, который hook пишет мимо API
# (`put-object`, design change track2-reconciler, решение 11)
result = subprocess.run(
[FAULT_HOOK, *args],
input=stdin,
capture_output=True,
timeout=FAULT_HOOK_TIMEOUT_S,
check=False,
)
stderr = result.stderr.decode(errors="replace").strip()
assert result.returncode == 0, f"fault hook {' '.join(args)}: {stderr}"
return result.stdout.decode().strip()
return call
@pytest.fixture(scope="session")
def tight_api() -> Iterator[Api]:
"""API стенда отказов со сроками сессии и ключа идемпотентности 2 с и
пулом из одного соединения."""
with Api(FAULT_TIGHT_BASE_URL) as client:
yield client
@pytest.fixture(scope="session")
def uploads_api() -> Iterator[Api]:
"""API стенда отказов с одним местом загрузки, одной загрузкой в
очереди, ожиданием места 1 с и сроком тела 3 с (`FAULT_UPLOADS_ENV`)."""
with Api(
FAULT_UPLOADS_BASE_URL,
timeout=UPLOADS_CLIENT_TIMEOUT_S,
) as client:
yield client
@pytest.fixture(scope="session")
def s3_api() -> Iterator[Api]:
"""API стенда отказов со сроком вызова S3 1 с (`FAULT_S3_ENV`)."""
with Api(FAULT_S3_BASE_URL, timeout=S3_CLIENT_TIMEOUT_S) as client:
yield client
@pytest.fixture(scope="session")
def backlog_api() -> Iterator[Api]:
"""API стенда отказов с малым пределом незавершённых заданий
(`FAULT_BACKLOG_ENV`)."""
with Api(
FAULT_BACKLOG_BASE_URL,
timeout=UPLOADS_CLIENT_TIMEOUT_S,
) as client:
yield client