forked from mtusi2026/mtusi2026lab3
Lab 3: HAProxy + 2 replicas, idempotency, graceful shutdown, track 1
This commit is contained in:
@@ -0,0 +1,111 @@
|
||||
"""Общая обвязка собственных проверок студента (stdlib, Python 3.9+).
|
||||
|
||||
Переиспользует HTTP-клиент публичных тестов (tests/client.py), не изменяя его. Команды управления
|
||||
стендом и доступа к SQL задаются переменными окружения; по умолчанию — Compose из этого репозитория.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
DC = os.environ.get("COMPOSE", "docker compose --env-file .env")
|
||||
PSQL = os.environ.get("PSQL", DC + " exec -T postgres psql -U messenger -d messenger")
|
||||
COMMANDS = {
|
||||
"stop_db": os.environ.get("STOP_DB", DC + " stop postgres"),
|
||||
"start_db": os.environ.get("START_DB", DC + " start postgres"),
|
||||
"stop_cache": os.environ.get("STOP_CACHE", DC + " stop redis"),
|
||||
"start_cache": os.environ.get("START_CACHE", DC + " start redis"),
|
||||
}
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
||||
TTL_BASE_URL = os.environ.get("TTL_BASE_URL", "http://127.0.0.1:8081")
|
||||
TTL_SECONDS = float(os.environ.get("TTL_SECONDS", "2"))
|
||||
|
||||
|
||||
def sh(name_or_cmd, timeout=90):
|
||||
cmd = COMMANDS.get(name_or_cmd, name_or_cmd)
|
||||
subprocess.run(shlex.split(cmd), cwd=ROOT, check=True, timeout=timeout,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def sql(query):
|
||||
"""Одна SQL-команда через psql (-At); возвращает строки результата. Только синтетические данные."""
|
||||
out = subprocess.run(shlex.split(PSQL) + ["-X", "-At", "-v", "ON_ERROR_STOP=1", "-c", query],
|
||||
cwd=ROOT, check=True, capture_output=True, text=True, timeout=60)
|
||||
return [line for line in out.stdout.splitlines() if line]
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
return "Basic " + base64.b64encode((username + ":" + password).encode("utf-8")).decode()
|
||||
|
||||
|
||||
def new_user(c, label="s", password=None):
|
||||
username = ("st_" + label + "_" + uuid.uuid4().hex[:10])[:32]
|
||||
password = password or ("Pw-" + uuid.uuid4().hex)
|
||||
user = c.call("POST", "/api/v1/users", 201, schema="User",
|
||||
body={"username": username, "display_name": "Тест " + label, "password": password})["json"]
|
||||
return {"id": user["id"], "user": user, "username": username, "password": password}
|
||||
|
||||
|
||||
def login(c, actor, expected=201):
|
||||
r = c.call("POST", "/api/v1/auth/sessions", expected, headers={"Authorization": basic(actor["username"], actor["password"])},
|
||||
schema="Session" if expected == 201 else None)
|
||||
if expected == 201:
|
||||
actor["token"] = r["json"]["token"]
|
||||
actor["expires_at"] = r["json"]["expires_at"]
|
||||
return r
|
||||
|
||||
|
||||
def wait_until(probe, timeout=60, interval=0.5):
|
||||
deadline = time.monotonic() + timeout
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if probe():
|
||||
return time.monotonic()
|
||||
except Failure as exc:
|
||||
last = exc
|
||||
time.sleep(interval)
|
||||
raise Failure("condition not reached in %ss (%s)" % (timeout, last))
|
||||
|
||||
|
||||
class Suite:
|
||||
def __init__(self, name):
|
||||
self.name, self.results = name, []
|
||||
|
||||
def case(self, title):
|
||||
def decorator(fn):
|
||||
self.results.append((title, fn))
|
||||
return fn
|
||||
return decorator
|
||||
|
||||
def run(self):
|
||||
passed = failed = 0
|
||||
print("## " + self.name)
|
||||
for title, fn in self.results:
|
||||
start = time.monotonic()
|
||||
try:
|
||||
note = fn()
|
||||
passed += 1
|
||||
print("PASS %-62s %6.2fs%s" % (title, time.monotonic() - start, (" " + note) if note else ""))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
failed += 1
|
||||
print("FAIL %-62s %s" % (title, exc))
|
||||
if os.environ.get("DEBUG"):
|
||||
traceback.print_exc()
|
||||
print("summary: %d passed, %d failed" % (passed, failed))
|
||||
raise SystemExit(1 if failed else 0)
|
||||
|
||||
|
||||
__all__ = ["Client", "Failure", "check", "sh", "sql", "basic", "new_user", "login", "wait_until", "Suite",
|
||||
"BASE_URL", "TTL_BASE_URL", "TTL_SECONDS", "json"]
|
||||
Reference in New Issue
Block a user