forked from mtusi2026/mtusi2026lab4
50 lines
2.1 KiB
Python
50 lines
2.1 KiB
Python
"""Управление стендом для тестов отказов: останавливает и запускает сервисы через docker compose."""
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
sys.path.insert(0, str(ROOT / "student-tests"))
|
|
|
|
from api import BASE_URL, call # noqa: E402
|
|
|
|
|
|
def compose(*args):
|
|
command = ["docker", "compose", "--env-file", ".env", "-f", "compose.yaml", "-f", "compose.test.yaml", *args]
|
|
result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True)
|
|
if result.returncode:
|
|
raise AssertionError("compose %s: %s" % (" ".join(args[:4]), result.stderr[-600:]))
|
|
return result.stdout
|
|
|
|
|
|
def sql(query):
|
|
"""Выполняет запрос через psql внутри контейнера postgres и возвращает вывод без оформления."""
|
|
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", query).strip()
|
|
|
|
|
|
def wait_ready(base_url=BASE_URL, seconds=60):
|
|
"""Ждёт устойчивой готовности: балансировщик мог ещё не отметить отказ, поэтому одного ответа 200 мало."""
|
|
deadline = time.monotonic() + seconds
|
|
stable_since = None
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
ready = call("GET", "/health/ready", base_url=base_url)[0] == 200
|
|
except OSError:
|
|
ready = False
|
|
if not ready:
|
|
stable_since = None
|
|
elif stable_since is None:
|
|
stable_since = time.monotonic()
|
|
elif time.monotonic() - stable_since >= 3:
|
|
return
|
|
time.sleep(0.3)
|
|
raise AssertionError("стенд не стал готов за %d секунд" % seconds)
|
|
|
|
|
|
def timed(*args, **kwargs):
|
|
"""Как call, но первым элементом возвращает время ответа в секундах."""
|
|
started = time.monotonic()
|
|
result = call(*args, **kwargs)
|
|
return (time.monotonic() - started, *result)
|