forked from mtusi2026/mtusi2026lab2
156 lines
4.9 KiB
Python
156 lines
4.9 KiB
Python
"""Общие помощники для тестов отказов.
|
|
|
|
Скрипты запускаются из корня репозитория:
|
|
|
|
python student-tests/test_postgres_down.py
|
|
python student-tests/test_redis_down.py
|
|
|
|
Имена контейнеров не хардкодятся: они берутся из `docker compose ps -q`,
|
|
поэтому тест переживает смену имени каталога/проекта Compose.
|
|
"""
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
# 127.0.0.1 вместо localhost: на Windows localhost может резолвиться в IPv6 и
|
|
# добавлять секунды к каждому запросу, что исказило бы замеры бюджета.
|
|
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
|
|
# Бюджет наблюдаемого ответа: API обязан уложиться заметно ниже 6 секунд.
|
|
RESPONSE_BUDGET_SECONDS = float(os.environ.get("RESPONSE_BUDGET_SECONDS", "6.0"))
|
|
|
|
|
|
def compose(*args, check=True):
|
|
command = [
|
|
"docker",
|
|
"compose",
|
|
"--env-file",
|
|
".env",
|
|
*args,
|
|
]
|
|
completed = subprocess.run(
|
|
command,
|
|
cwd=ROOT,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
if check and completed.returncode != 0:
|
|
raise RuntimeError(
|
|
"docker compose %s failed: %s"
|
|
% (" ".join(args), (completed.stderr or completed.stdout).strip())
|
|
)
|
|
return completed
|
|
|
|
|
|
def container_id(service):
|
|
completed = compose("ps", "-q", service)
|
|
identifier = completed.stdout.strip()
|
|
if not identifier:
|
|
raise RuntimeError(
|
|
"service %r is not running; start the stack with "
|
|
"`docker compose --env-file .env up -d`" % service
|
|
)
|
|
return identifier
|
|
|
|
|
|
def container_health(identifier):
|
|
completed = subprocess.run(
|
|
[
|
|
"docker",
|
|
"inspect",
|
|
"--format={{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}",
|
|
identifier,
|
|
],
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
return completed.stdout.strip()
|
|
|
|
|
|
def stop_service(service):
|
|
compose("stop", service)
|
|
|
|
|
|
def start_service(service):
|
|
compose("start", service)
|
|
|
|
|
|
def wait_healthy(identifier, timeout_seconds=60):
|
|
deadline = time.monotonic() + timeout_seconds
|
|
while time.monotonic() < deadline:
|
|
if container_health(identifier) == "healthy":
|
|
return
|
|
time.sleep(0.5)
|
|
raise RuntimeError("container %s did not become healthy" % identifier)
|
|
|
|
|
|
def call(method, path, body=None, headers=None, timeout=20):
|
|
"""Возвращает (status, payload, elapsed_seconds)."""
|
|
request_headers = {"Accept": "application/json"}
|
|
request_headers.update(headers or {})
|
|
data = None
|
|
if body is not None:
|
|
data = json.dumps(body).encode()
|
|
request_headers["Content-Type"] = "application/json"
|
|
request = urllib.request.Request(
|
|
BASE_URL + path,
|
|
data=data,
|
|
headers=request_headers,
|
|
method=method,
|
|
)
|
|
started = time.monotonic()
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
raw = response.read().decode() or "{}"
|
|
status = response.status
|
|
except urllib.error.HTTPError as error:
|
|
raw = error.read().decode() or "{}"
|
|
status = error.code
|
|
elapsed = time.monotonic() - started
|
|
try:
|
|
payload = json.loads(raw)
|
|
except ValueError:
|
|
payload = {"raw": raw}
|
|
return status, payload, elapsed
|
|
|
|
|
|
def wait_ready(timeout_seconds=60):
|
|
deadline = time.monotonic() + timeout_seconds
|
|
last = None
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
status, payload, _ = call("GET", "/health/ready", timeout=5)
|
|
last = (status, payload)
|
|
if status == 200:
|
|
return
|
|
except (urllib.error.URLError, OSError) as error:
|
|
last = error
|
|
time.sleep(0.5)
|
|
raise RuntimeError("API did not become ready; last result: %r" % (last,))
|
|
|
|
|
|
def assert_within_budget(elapsed, label):
|
|
if elapsed >= RESPONSE_BUDGET_SECONDS:
|
|
raise AssertionError(
|
|
"%s took %.2fs, budget is %.1fs"
|
|
% (label, elapsed, RESPONSE_BUDGET_SECONDS)
|
|
)
|
|
|
|
|
|
def assert_error_payload(payload, expected_code):
|
|
error = payload.get("error")
|
|
if not isinstance(error, dict):
|
|
raise AssertionError("response has no error object: %r" % (payload,))
|
|
if error.get("code") != expected_code:
|
|
raise AssertionError(
|
|
"expected error code %r, got %r" % (expected_code, error.get("code"))
|
|
)
|
|
if not error.get("request_id"):
|
|
raise AssertionError("error payload has no request_id")
|
|
if not error.get("message"):
|
|
raise AssertionError("error payload has no message")
|