Files
mtusi2026lab5/scripts/lab5_defense_evidence.py
T

86 lines
3.0 KiB
Python

#!/usr/bin/env python3
"""Capture lab5 grade-3/4 defense evidence (no tokens written)."""
from __future__ import annotations
import os
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "student-tests"))
import imagegen # noqa: E402
from helpers import call, chat_for, register, upload, wait_ready # noqa: E402
OUT = ROOT / "evidence" / "lab5-defense.txt"
def main() -> int:
lines: list[str] = []
def log(msg: str) -> None:
print(msg)
lines.append(msg)
alice, bob = register("ev_a"), register("ev_b")
chat = chat_for(alice, bob, title="ev")
data = imagegen.PUBLIC_PNG.read_bytes()
att = upload(alice["token"], chat["id"], data, "sample.png", "image/png", 202)["json"]
assert att["status"] == "queued"
call("GET", f"/api/v1/attachments/{att['id']}/content", 409, token=bob["token"])
ready = wait_ready(bob["token"], att)
names = sorted(v["name"] for v in ready["variants"])
thumb = call(
"GET",
f"/api/v1/attachments/{att['id']}/content?variant=thumbnail",
200,
token=bob["token"],
)
log(
f"PASS variants ready attachment={att['id']} "
f"thumb_ct={thumb['headers'].get_content_type()} names={names}"
)
stop = ROOT / "scripts" / ("stop-worker.cmd" if os.name == "nt" else "stop-worker.sh")
start = ROOT / "scripts" / ("start-worker.cmd" if os.name == "nt" else "start-worker.sh")
subprocess.run([str(stop)], check=True, cwd=str(ROOT))
try:
alice2 = register("ev_w")
chat2 = chat_for(alice2, title="wstop")
data2 = imagegen.rgb_png(64, 48)
att2 = upload(alice2["token"], chat2["id"], data2, "park.png", "image/png", 202)["json"]
call(
"POST",
f"/api/v1/chats/{chat2['id']}/messages",
201,
token=alice2["token"],
body={"text": "alive"},
)
call("GET", f"/api/v1/attachments/{att2['id']}/content", 409, token=alice2["token"])
meta = call("GET", f"/api/v1/attachments/{att2['id']}", 200, token=alice2["token"])["json"]
log(
f"PASS worker-down queued status={meta['status']} content=409 chat=201 "
f"attachment={att2['id']}"
)
finally:
subprocess.run([str(start)], check=True, cwd=str(ROOT))
ready2 = wait_ready(alice2["token"], att2, wait_seconds=90)
log(f"PASS worker-restart ready status={ready2['status']} attachment={att2['id']}")
u = register("ev_lo")
call("DELETE", "/api/v1/auth/sessions/current", 204, token=u["token"])
call("DELETE", "/api/v1/auth/sessions/current", 401, token=u["token"])
call("GET", "/api/v1/users/me", 401, token=u["token"])
log("PASS logout second DELETE=401 and /me=401")
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text("\n".join(lines) + "\n", encoding="utf-8")
print(f"WROTE {OUT}")
return 0
if __name__ == "__main__":
raise SystemExit(main())