chore: port lab 6 solution into the lab 7 skeleton

Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065.
Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public
tests, README, REPORT and evidence of lab 6 are not carried over; infra
and scripts of the lab 7 skeleton stay as they are.
Makefile is the lab 6 one with the lab 7 skeleton part restored
(HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore
are taken from lab 6 because both skeletons have the same files;
.env.example is the lab 6 one without changes.
The compose project, image and CI prefix are renamed to lab7, and
references to the previous lab now name lab6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 03:59:04 +03:00
co-authored by Claude Opus 5.5
parent 20afc2c790
commit 089d78609d
687 changed files with 178271 additions and 40 deletions
+217
View File
@@ -0,0 +1,217 @@
"""Настройка набора: адрес стенда, проверка доступности, фикстуры."""
import os
import subprocess
from collections.abc import Callable, Iterator
from typing import Any
import httpx
import pytest
from api_client import Actor, Api
from spec_coverage import COLLECTED, Collected
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").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(
"/",
)
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
):
pytest.exit(
"fault checks need the failure stand and its hook: "
"run make failure_checks",
returncode=2,
)
@pytest.fixture(scope="session", autouse=True)
def _server_reachable() -> None:
"""Без сервера прогон останавливается одной строкой, а не 100 ошибками."""
try:
resp = 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 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