Files
mtusi2026lab6/student-tests/worker_pause.py

72 lines
2.9 KiB
Python

#!/usr/bin/env python3
"""Reproduce the worker-offline trajectory on a running test stack."""
import argparse
import hashlib
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check
from image_probe import jpeg_size
def compose(*args):
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, timeout=90)
def wait_api(client):
end = time.monotonic() + 45
while time.monotonic() < end:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(0.5)
raise Failure("API did not recover")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--pause", type=int, default=0, help="Extra seconds with worker stopped")
parser.add_argument("--no-restart", action="store_true", help="Keep API up during telemetry demo")
args = parser.parse_args()
client = Client(args.base_url)
actor, peer, _, chat = client.bootstrap()
compose("stop", "worker")
try:
upload, original = client.attachment(actor, chat)
message = client.message(actor, chat, "", attachments=[upload["id"]])["json"]
check(message["attachment_ids"] == [upload["id"]], "message lost queued attachment")
meta = "/api/v1/attachments/" + upload["id"]
client.call("GET", meta + "/content", 409, actor=peer)
print("202 queued, привязка к сообщению 201, скачивание 409.", flush=True)
if args.pause:
time.sleep(args.pause)
if not args.no_restart:
compose("restart", "broker", "api")
wait_api(client)
queued = client.call("GET", meta, actor=peer, schema="Attachment")["json"]
check(queued["status"] == "queued", "restart lost the pending job")
print("После рестарта без worker задача осталась queued.", flush=True)
finally:
compose("start", "worker")
ready = client.wait_ready(peer, upload)
variants = {item["name"]: item for item in ready["variants"]}
check({"thumbnail", "crop", "optimized"} <= variants.keys(), "missing generated variants")
downloaded = client.call("GET", meta + "/content", actor=peer)["bytes"]
thumb = client.call("GET", meta + "/content?variant=thumbnail", actor=peer)["bytes"]
check(downloaded == original, "original changed")
check(jpeg_size(thumb) == (256, 160), "thumbnail dimensions changed")
check(variants["thumbnail"]["sha256"] == hashlib.sha256(thumb).hexdigest(), "thumbnail hash changed")
print(json.dumps({"status": ready["status"], "thumbnail": "256x160",
"variants": sorted(variants), "original_matches": True}, indent=2))
if __name__ == "__main__":
main()