Files
mtusi2026lab6-fork/student-tests/worker_recovery.py
T

58 lines
2.6 KiB
Python

"""Demonstrate accepted upload recovery while the worker is stopped."""
import hashlib
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check
from image_probe import jpeg_size
def compose(*args):
subprocess.run(["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT, check=True)
def main():
client = Client("http://localhost:8080", timeout=10)
alice, bob, _, chat = client.bootstrap()
print("Created synthetic users and chat", flush=True)
compose("stop", "worker")
print("Stopped worker", flush=True)
try:
attachment, original = client.attachment(alice, chat)
print("Upload returned queued", flush=True)
sent = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
check(sent["attachment_ids"] == [attachment["id"]], "message did not retain attachment reference")
client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content",
409, actor=bob)
print("Message linked; content correctly unavailable while queued", flush=True)
# The worker stays stopped while the API and durable broker are restarted.
compose("restart", "api1", "api2", "redis-broker", "lb")
print("Restarted API and broker with worker stopped", flush=True)
compose("start", "worker")
print("Started worker", flush=True)
ready = client.wait_ready(bob, attachment)
original_response = client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content",
actor=bob)
check(original_response["bytes"] == original, "recovered original bytes changed")
check(hashlib.sha256(original_response["bytes"]).hexdigest() == attachment["sha256"],
"recovered original SHA-256 mismatch")
thumbnail_meta = next(v for v in ready["variants"] if v["name"] == "thumbnail")
thumbnail = client.call("GET", "/api/v1/attachments/" + attachment["id"] +
"/content?variant=thumbnail", actor=bob)
check(thumbnail["headers"].get_content_type() == "image/jpeg", "thumbnail is not JPEG")
check(jpeg_size(thumbnail["bytes"]) == (256, 160), "thumbnail dimensions mismatch")
check(hashlib.sha256(thumbnail["bytes"]).hexdigest() == thumbnail_meta["sha256"],
"thumbnail checksum mismatch")
print("PASS: worker recovery; upload stayed queued through API/broker restart and became ready")
finally:
compose("start", "worker")
if __name__ == "__main__":
main()