forked from mtusi2026/mtusi2026lab5
181 lines
9.1 KiB
Python
181 lines
9.1 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Прогон ВСЕХ проверок lab5 (и унаследованных lab2–4) с сохранением вывода в evidence/ (Windows/macOS/Linux).
|
|
Стенд должен быть запущен: docker compose --env-file .env up -d --build
|
|
|
|
python student-tests/collect_evidence.py --base-url http://localhost:8080
|
|
python student-tests/collect_evidence.py --only smoke,attachments # выборочно
|
|
|
|
Каждый шаг пишет evidence/<имя>.txt (команда, время, stdout/stderr, код выхода).
|
|
Ошибка одного шага не останавливает остальные; в конце — сводка PASS/FAIL.
|
|
Hook-и: на Windows scripts/*.cmd, иначе scripts/*.sh. Секреты не печатаются.
|
|
"""
|
|
import argparse
|
|
import datetime as dt
|
|
import hashlib
|
|
import os
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
EVIDENCE = ROOT / "evidence"
|
|
PY = sys.executable
|
|
WIN = os.name == "nt"
|
|
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
|
SAMPLE_SHA = hashlib.sha256((ROOT / "tests/fixtures/sample.png").read_bytes()).hexdigest()
|
|
|
|
|
|
def hook(name: str) -> str:
|
|
return str(ROOT / "scripts" / (name + (".cmd" if WIN else ".sh")))
|
|
|
|
|
|
# Публичные tests/ читают JSON без явной кодировки: на Windows (cp1251) это падает.
|
|
# UTF-8 mode Python для всех дочерних процессов, сами тесты не меняем.
|
|
ENV = {**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}
|
|
|
|
|
|
def run(cmd: list[str], log, timeout: int = 900) -> int:
|
|
log.write(f"\n$ {' '.join(cmd)}\n")
|
|
log.flush()
|
|
try:
|
|
p = subprocess.run(cmd, cwd=ROOT, env=ENV, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
|
text=True, encoding="utf-8", errors="replace", timeout=timeout)
|
|
except subprocess.TimeoutExpired:
|
|
log.write("TIMEOUT\n")
|
|
return 124
|
|
log.write(p.stdout)
|
|
log.write(f"[exit {p.returncode}]\n")
|
|
return p.returncode
|
|
|
|
|
|
def ports_closed(log) -> int:
|
|
"""MinIO (9000 API, 9001 консоль) не опубликован на хосте."""
|
|
bad = 0
|
|
for port in (9000, 9001):
|
|
s = socket.socket()
|
|
s.settimeout(1)
|
|
try:
|
|
s.connect(("127.0.0.1", port))
|
|
log.write(f"127.0.0.1:{port} OPEN <- не должно быть\n")
|
|
bad += 1
|
|
except OSError as exc:
|
|
log.write(f"127.0.0.1:{port} closed ({type(exc).__name__}) ok\n")
|
|
finally:
|
|
s.close()
|
|
return bad
|
|
|
|
|
|
def drain(log, limit: int = 600) -> int:
|
|
"""Ждать, пока в очереди не останется queued/processing (не дольше limit секунд)."""
|
|
import json
|
|
t0 = time.monotonic()
|
|
while time.monotonic() - t0 < limit:
|
|
out = subprocess.run(COMPOSE + ["exec", "-T", "api", "python", "-m", "app.tools", "queue"], cwd=ROOT,
|
|
capture_output=True, text=True, encoding="utf-8", errors="replace").stdout
|
|
try:
|
|
jobs = json.loads(out.strip().splitlines()[-1])["jobs_by_status"]
|
|
except (ValueError, IndexError, KeyError):
|
|
jobs = {}
|
|
busy = jobs.get("queued", 0) + jobs.get("processing", 0)
|
|
if jobs and busy == 0:
|
|
log.write(f"queue drained in {time.monotonic() - t0:.1f} s: {jobs}\n")
|
|
return 0
|
|
time.sleep(3)
|
|
log.write(f"queue NOT drained in {limit} s\n")
|
|
return 1
|
|
|
|
|
|
def steps(base: str):
|
|
t = ["--base-url", base]
|
|
yield "check", [[PY, "scripts/check_contract.py"]]
|
|
yield "stand", [COMPOSE + ["ps"], COMPOSE + ["config", "--images"],
|
|
COMPOSE + ["exec", "-T", "api", "python", "-m", "app.migrate"]]
|
|
yield "smoke", [[PY, "tests/smoke.py", *t]]
|
|
yield "student-tests", [[PY, "student-tests/run.py", *t], [PY, "student-tests/idempotency.py", *t]]
|
|
yield "attachments", [[PY, "student-tests/attachments.py", *t]]
|
|
# lab5: брокер, worker, отказы и восстановление
|
|
yield "broker-config", [COMPOSE + ["exec", "-T", "broker", "redis-cli", "CONFIG", "GET", "append*"],
|
|
COMPOSE + ["exec", "-T", "broker", "redis-cli", "CONFIG", "GET", "maxmemory-policy"],
|
|
COMPOSE + ["exec", "-T", "api", "python", "-m", "app.tools", "queue"]]
|
|
yield "worker-limits", [COMPOSE + ["exec", "-T", "api", "python", "-m", "app.tools", "limits-selftest"]]
|
|
for sc in ("worker-down", "broker-down", "redelivery", "crash-s3", "crash-ack", "outbox", "retry-replay", "lease"):
|
|
yield f"jobs-{sc}", [[PY, "student-tests/jobs.py", *t, "--scenario", sc]]
|
|
yield "jobs-registry", [COMPOSE + ["exec", "-T", "api", "python", "-m", "app.replay", "--list"],
|
|
COMPOSE + ["exec", "-T", "api", "python", "-m", "app.replay", "--dlq"],
|
|
COMPOSE + ["exec", "-T", "api", "python", "-m", "app.tools", "queue"],
|
|
COMPOSE + ["--profile", "fault", "stop", "api-fault", "worker-fault"]]
|
|
yield "s3-bootstrap", [COMPOSE + ["run", "--rm", "s3-init"], COMPOSE + ["run", "--rm", "s3-init"]]
|
|
yield "s3-private", [COMPOSE + ["exec", "-T", "api", "python", "-m", "app.tools", "private-check"],
|
|
"PORTS"]
|
|
yield "no-local-file", [COMPOSE + ["exec", "-T", "--index", str(i), "api", "python", "-m", "app.tools",
|
|
"find-local", SAMPLE_SHA] for i in (1, 2)] + [
|
|
COMPOSE + ["exec", "-T", "worker", "python", "-m", "app.tools", "find-local", SAMPLE_SHA]] + [
|
|
["docker", "inspect", "-f", "{{.Name}} mounts={{json .Mounts}}"] + "API_IDS".split()]
|
|
yield "orphans", [COMPOSE + ["--profile", "fault", "up", "-d", "api-fault"], "SLEEP",
|
|
[PY, "student-tests/orphans.py", *t, "--fault-url", "http://localhost:8082"],
|
|
COMPOSE + ["--profile", "fault", "stop", "api-fault"]]
|
|
yield "s3-outage", [[PY, "student-tests/s3_outage.py", *t]]
|
|
yield "upload-memory", [[PY, "student-tests/upload_memory.py", *t, "--concurrency", "10",
|
|
"--output", "evidence/upload-memory-10.json"],
|
|
[PY, "student-tests/upload_memory.py", *t, "--concurrency", "20",
|
|
"--output", "evidence/upload-memory-20.json"]]
|
|
# upload-memory ставит в очередь 90 больших картинок: ждём, пока worker их обработает,
|
|
# иначе вложение следующих тестов встанет в конец очереди (это и есть queue lag).
|
|
yield "queue-drain", ["DRAIN", COMPOSE + ["exec", "-T", "api", "python", "-m", "app.tools", "queue"]]
|
|
yield "persistence", [COMPOSE + ["ps"], [PY, "tests/resilience.py", "--mode", "persistence",
|
|
"--action-script", hook("restart"), *t], COMPOSE + ["ps"]]
|
|
yield "failover", [[PY, "tests/resilience.py", "--mode", "failover", "--action-script", hook("stop-one"), *t],
|
|
[hook("restore-api")], "SLEEP",
|
|
[PY, "tests/resilience.py", "--mode", "failover", "--action-script", hook("stop-one"), *t],
|
|
[hook("restore-api")]]
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--base-url", default="http://localhost:8080")
|
|
ap.add_argument("--only", default="")
|
|
args = ap.parse_args()
|
|
only = {x.strip() for x in args.only.split(",") if x.strip()}
|
|
EVIDENCE.mkdir(exist_ok=True)
|
|
commit = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True,
|
|
text=True).stdout.strip() or "no-git"
|
|
summary = []
|
|
for name, cmds in steps(args.base_url):
|
|
if only and name not in only:
|
|
continue
|
|
path = EVIDENCE / f"{name}.txt"
|
|
print(f"== {name} -> {path.relative_to(ROOT)}")
|
|
with open(path, "w", encoding="utf-8") as log:
|
|
log.write(f"# {name}\n# date: {dt.datetime.now().isoformat(timespec='seconds')} commit: {commit}\n")
|
|
failed = 0
|
|
for cmd in cmds:
|
|
if cmd == "SLEEP":
|
|
time.sleep(8)
|
|
continue
|
|
if cmd == "DRAIN":
|
|
failed += drain(log)
|
|
continue
|
|
if cmd == "PORTS":
|
|
failed += ports_closed(log)
|
|
continue
|
|
if "API_IDS" in cmd:
|
|
ids = subprocess.run(COMPOSE + ["ps", "-q", "api"], cwd=ROOT, capture_output=True,
|
|
text=True).stdout.split()
|
|
cmd = [c for c in cmd if c != "API_IDS"] + ids
|
|
code = run(cmd, log)
|
|
failed += 1 if code else 0
|
|
status = "PASS" if not failed else f"FAIL ({failed})"
|
|
summary.append((name, status))
|
|
print(" ", status)
|
|
print("\nSummary:")
|
|
for name, status in summary:
|
|
print(f" {name:18} {status}")
|
|
sys.exit(0 if all(s == "PASS" for _, s in summary) else 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|