"""Lab5 grade 3/4: async states, thumbnail/crop/webp, worker-stopped 409, replay safety.""" from __future__ import annotations import hashlib import subprocess import time from pathlib import Path import imagegen from helpers import call, chat_for, register, upload, wait_ready ROOT = Path(__file__).resolve().parents[1] def _jpeg_dims(data: bytes): try: from PIL import Image import io img = Image.open(io.BytesIO(data)) return img.size except Exception: # Minimal SOF parser assert data[:2] == b"\xff\xd8" i = 2 while i < len(data) - 8: if data[i] != 0xFF: i += 1 continue marker = data[i + 1] if marker in (0xC0, 0xC1, 0xC2): height = int.from_bytes(data[i + 5:i + 7], "big") width = int.from_bytes(data[i + 7:i + 9], "big") return width, height if marker == 0xD9 or marker == 0xDA: break if marker == 0x01 or 0xD0 <= marker <= 0xD7: i += 2 continue length = int.from_bytes(data[i + 2:i + 4], "big") i += 2 + length raise AssertionError("JPEG SOF not found") def test_queued_linkable_then_ready_variants(): alice, bob = register("q_a"), register("q_b") chat = chat_for(alice, bob, title="lab5") data = imagegen.PUBLIC_PNG.read_bytes() # 320x200 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"]) msg = call( "POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=alice["token"], body={"text": "", "attachment_ids": [att["id"]]}, )["json"] assert msg["attachment_ids"] == [att["id"]] ready = wait_ready(bob["token"], att) names = {v["name"]: v for v in ready["variants"]} assert set(names) >= {"thumbnail", "crop", "optimized"} thumb = call( "GET", f"/api/v1/attachments/{att['id']}/content?variant=thumbnail", 200, token=bob["token"], ) assert thumb["headers"].get_content_type() == "image/jpeg" assert _jpeg_dims(thumb["bytes"]) == (256, 160) assert hashlib.sha256(thumb["bytes"]).hexdigest() == names["thumbnail"]["sha256"] crop = call( "GET", f"/api/v1/attachments/{att['id']}/content?variant=crop", 200, token=bob["token"], ) assert crop["headers"].get_content_type() == "image/jpeg" assert _jpeg_dims(crop["bytes"]) == (128, 128) opt = call( "GET", f"/api/v1/attachments/{att['id']}/content?variant=optimized", 200, token=bob["token"], ) assert opt["headers"].get_content_type() == "image/webp" assert opt["bytes"][:4] == b"RIFF" def test_worker_stopped_upload_stays_queued(): import os if os.environ.get("RUN_DOCKER_TESTS") != "1": print("SKIP test_worker_stopped_upload_stays_queued (set RUN_DOCKER_TESTS=1)") return 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: alice = register("wstop") chat = chat_for(alice, title="worker-stop") data = imagegen.rgb_png(64, 48) att = upload(alice["token"], chat["id"], data, "park.png", "image/png", 202)["json"] assert att["status"] == "queued" # Text path still works while worker is down. call( "POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=alice["token"], body={"text": "still-alive"}, ) call("GET", f"/api/v1/attachments/{att['id']}/content", 409, token=alice["token"]) time.sleep(2) meta = call("GET", f"/api/v1/attachments/{att['id']}", 200, token=alice["token"])["json"] assert meta["status"] in ("queued", "processing") finally: subprocess.run([str(start)], check=True, cwd=str(ROOT)) ready = wait_ready(alice["token"], att, wait_seconds=90) assert ready["status"] == "ready"