forked from mtusi2026/mtusi2026lab6
186 lines
8.3 KiB
Python
186 lines
8.3 KiB
Python
"""Общая обвязка собственных проверок студента (stdlib, Python 3.9+).
|
||
|
||
Переиспользует HTTP-клиент публичных тестов (tests/client.py), не изменяя его. Команды управления
|
||
стендом и доступа к SQL задаются переменными окружения; по умолчанию — Compose из этого репозитория.
|
||
"""
|
||
import base64
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import shlex
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
import traceback
|
||
import uuid
|
||
import zlib
|
||
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"),
|
||
# lab5: worker и брокер (volumes не трогаются)
|
||
"stop_worker": os.environ.get("STOP_WORKER", DC + " stop worker"),
|
||
"start_worker": os.environ.get("START_WORKER", DC + " start worker"),
|
||
"restart_broker": os.environ.get("RESTART_BROKER", DC + " restart nats"),
|
||
"restart_api": os.environ.get("RESTART_API", DC + " restart api"),
|
||
}
|
||
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]
|
||
|
||
|
||
S3_ADMIN = os.environ.get("S3_ADMIN", DC + " run --rm --no-deps -T --entrypoint python s3-init -")
|
||
API_EXEC = os.environ.get("API_EXEC", DC + " exec -T api")
|
||
|
||
|
||
def s3_admin(op, key, data=None):
|
||
"""Операция с bucket admin-ключом В ОБХОД API (внедрение отказов на стороне S3)."""
|
||
args = [op, key] + ([base64.b64encode(data).decode()] if data is not None else [])
|
||
script = (ROOT / "student-tests" / "s3_admin.py").read_bytes()
|
||
out = subprocess.run(shlex.split(S3_ADMIN) + args, cwd=ROOT, input=script, capture_output=True,
|
||
check=True, timeout=120)
|
||
return out.stdout.decode().strip()
|
||
|
||
|
||
# Операторские команды выполняются в контейнере API (тот же образ; worker может быть остановлен).
|
||
JOBS_EXEC = os.environ.get("JOBS_EXEC", DC + " exec -T api")
|
||
|
||
|
||
def jobs_cli(*args, expect=(0,)):
|
||
"""python -m messenger jobs … внутри контейнера API; возвращает JSON-ответ (stdout)."""
|
||
out = subprocess.run(shlex.split(JOBS_EXEC) + ["python", "-m", "messenger", "jobs"] + [str(a) for a in args],
|
||
cwd=ROOT, capture_output=True, text=True, timeout=300)
|
||
if out.returncode not in expect:
|
||
raise Failure("jobs %s exit %d: %s" % (args[0], out.returncode, (out.stderr or out.stdout).strip()[-300:]))
|
||
return json.loads(out.stdout)
|
||
|
||
|
||
def events(attachment_id):
|
||
"""Журнал событий работ вложения: список (event, attempt, lease_token, worker, detail)."""
|
||
return jobs_cli("status", attachment_id)["events"]
|
||
|
||
|
||
def wait_status(c, actor, att_id, statuses, timeout=90, interval=0.3):
|
||
"""Ждать, пока GET метаданных вернёт один из statuses; возвращает Attachment."""
|
||
statuses = (statuses,) if isinstance(statuses, str) else tuple(statuses)
|
||
deadline = time.monotonic() + timeout
|
||
last = None
|
||
while time.monotonic() < deadline:
|
||
last = c.call("GET", "/api/v1/attachments/" + att_id, actor=actor, schema="Attachment")["json"]
|
||
if last["status"] in statuses:
|
||
return last
|
||
time.sleep(interval)
|
||
raise Failure("attachment %s: status %s, expected %s within %ss" % (att_id, last and last["status"], statuses, timeout))
|
||
|
||
|
||
def make_png(width=16, height=16, seed=None):
|
||
"""Валидный RGB PNG (stdlib), уникальный по seed — для разных SHA-256."""
|
||
seed = seed if seed is not None else uuid.uuid4().bytes
|
||
rnd = hashlib.sha256(seed).digest()
|
||
rows = b"".join(b"\x00" + bytes((rnd[(x + y) % 32] ^ x ^ y) & 0xFF for x in range(width * 3)) for y in range(height))
|
||
|
||
def chunk(t, d):
|
||
return len(d).to_bytes(4, "big") + t + d + zlib.crc32(t + d).to_bytes(4, "big")
|
||
ihdr = width.to_bytes(4, "big") + height.to_bytes(4, "big") + bytes([8, 2, 0, 0, 0])
|
||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")
|
||
|
||
|
||
def upload(c, actor, chat, data=None, content_type="image/png", filename="pic.png", expected=202, headers=None):
|
||
from urllib.parse import quote
|
||
data = make_png() if data is None else data
|
||
h = {"Content-Type": content_type}
|
||
h.update(headers or {})
|
||
r = c.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(filename), expected,
|
||
actor=actor, raw=data, headers=h, schema="Attachment" if expected == 202 else None)
|
||
return (r["json"], data) if expected == 202 else r
|
||
|
||
|
||
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",
|
||
"s3_admin", "jobs_cli", "events", "wait_status", "make_png", "upload",
|
||
"BASE_URL", "TTL_BASE_URL", "TTL_SECONDS", "json"]
|