#!/usr/bin/env python3 """Lab5: негативные и lifecycle-сценарии worker.""" import sys import time import uuid from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, LAB, arguments, check, run # noqa: E402 from image_probe import jpeg_size # noqa: E402 def wait_status(c, actor, att_id, want, timeout=60): deadline = time.monotonic() + timeout last = None while time.monotonic() < deadline: att = c.call("GET", "/api/v1/attachments/" + att_id, actor=actor, schema="Attachment")["json"] last = att["status"] if last in want: return att if last == "failed": raise AssertionError("attachment failed: %s" % att.get("error_code")) time.sleep(0.3) raise AssertionError("status %s not reached (last=%s)" % (want, last)) def main(): args = arguments("Lab5 negative + lifecycle") c = Client(args.base_url, args.ca_file) alice, bob, eve, chat = c.bootstrap() # 1. upload → 202 queued. att, content = c.attachment(alice, chat) check(att["status"] in ("queued", "processing"), "upload must be 202 queued") # 2. download пока queued/processing → 409. try: c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob) # если worker успел — это уже ready, не ошибка except Exception as exc: check("409" in str(exc) or "expected 200" in str(exc), "expected 409 or 200") # 3. ждём ready. ready = wait_status(c, bob, att["id"], {"ready"}, timeout=90) # 4. variants: ровно thumbnail, crop, optimized. names = {v["name"] for v in ready["variants"]} check(names == {"thumbnail", "crop", "optimized"}, "variants mismatch: %s" % names) thumb = next(v for v in ready["variants"] if v["name"] == "thumbnail") check((thumb["width"], thumb["height"]) == (256, 160), "thumbnail dims") check(thumb["content_type"] == "image/jpeg", "thumbnail type") crop = next(v for v in ready["variants"] if v["name"] == "crop") check((crop["width"], crop["height"]) == (128, 128), "crop dims") check(crop["content_type"] == "image/jpeg", "crop type") opt = next(v for v in ready["variants"] if v["name"] == "optimized") check(opt["content_type"] == "image/webp", "optimized type") # 5. скачать вариант thumbnail и проверить JPEG-размеры. t = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content?variant=thumbnail", actor=bob) check(t["headers"].get_content_type() == "image/jpeg", "thumbnail content-type") check(jpeg_size(t["bytes"]) == (256, 160), "actual JPEG dims") check(len(t["bytes"]) == thumb["size_bytes"], "thumbnail size") # 6. original неизменен. o = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob) check(o["bytes"] == content, "original changed") # 7. чужой не читает варианты. c.call("GET", "/api/v1/attachments/" + att["id"] + "/content?variant=thumbnail", 404, actor=eve) # 8. невалидный variant → 400. c.call("GET", "/api/v1/attachments/" + att["id"] + "/content?variant=big", 400, actor=bob) # 9. unknown id → 404. c.call("GET", "/api/v1/attachments/" + str(uuid.uuid4()) + "/content?variant=thumbnail", 404, actor=bob) # 10. failed-вложение нельзя прикрепить. # Сэмулировать failed в API нельзя; проверяем через БД отдельно (ручной шаг в REPORT). # Здесь проверяем, что queued прикрепляется. msg = c.message(alice, chat, "", attachments=[att["id"]])["json"] check(msg["attachment_ids"] == [att["id"]], "queued attachment linkable") print("PASS: lab5 lifecycle + negative") if __name__ == "__main__": run(main)