Files
mtusi2026lab6/student-tests/test_pipeline.py

188 lines
10 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Асинхронный pipeline вложений (уровни 3–4): 202/queued → ready, варианты по контракту, failed,
409 для неготовых, запрет прикреплять failed, идемпотентность повторной доставки, безопасный replay.
Размеры вариантов проверяются по РЕАЛЬНЫМ байтам (JPEG SOF и заголовок WebP), а не только по JSON.
Стенд должен работать с worker; volumes не трогаются. Для операторских шагов используется
`python -m messenger jobs …` в контейнере worker (нужен docker compose в PATH).
"""
import hashlib
import sys
import time
import zlib
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from image_probe import jpeg_size # noqa: E402
from common import (BASE_URL, Client, Suite, check, events, jobs_cli, login, make_png, new_user, upload, # noqa: E402
wait_status)
FIX = Path(__file__).parent / "fixtures"
c = Client(BASE_URL, timeout=30)
s = Suite("attachment pipeline (" + BASE_URL + ")")
alice = new_user(c, "pa"); login(c, alice)
bob = new_user(c, "pb"); login(c, bob)
eve = new_user(c, "pe"); login(c, eve)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "pipeline", "member_ids": [alice["id"], bob["id"]]})["json"]
def webp_size(data):
check(data[:4] == b"RIFF" and data[8:12] == b"WEBP", "optimized is not WebP")
kind = data[12:16]
if kind == b"VP8 ":
return int.from_bytes(data[26:28], "little") & 0x3FFF, int.from_bytes(data[28:30], "little") & 0x3FFF
if kind == b"VP8L":
b = int.from_bytes(data[21:25], "little")
return (b & 0x3FFF) + 1, ((b >> 14) & 0x3FFF) + 1
if kind == b"VP8X":
return int.from_bytes(data[24:27], "little") + 1, int.from_bytes(data[27:30], "little") + 1
raise AssertionError("unknown WebP chunk %r" % kind)
def flat_png(w, h, rgb=(40, 160, 90)):
"""Однотонный RGB PNG любого размера (stdlib): хорошо сжимается, годится для проверки размеров."""
row = b"\x00" + bytes(rgb) * w
raw = zlib.compress(row * h, 6)
def chunk(t, d):
return len(d).to_bytes(4, "big") + t + d + zlib.crc32(t + d).to_bytes(4, "big")
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", w.to_bytes(4, "big") + h.to_bytes(4, "big") + bytes([8, 2, 0, 0, 0]))
+ chunk(b"IDAT", raw) + chunk(b"IEND", b""))
def fit(w, h, box):
m = max(w, h)
return (w, h) if m <= box else (max(1, w * box // m), max(1, h * box // m))
def check_variants(att, logical_w, logical_h):
"""Все три варианта: заявленные метаданные = реальные байты; размеры — по правилам контракта."""
got = {v["name"]: v for v in att["variants"]}
check(set(got) == {"thumbnail", "crop", "optimized"}, "variants %s" % sorted(got))
expect = {"thumbnail": ("image/jpeg", fit(logical_w, logical_h, 256)), "crop": ("image/jpeg", (128, 128)),
"optimized": ("image/webp", fit(logical_w, logical_h, 1280))}
for name, (ctype, dims) in expect.items():
v = got[name]
r = c.call("GET", "/api/v1/attachments/%s/content?variant=%s" % (att["id"], name), actor=bob)
body = r["bytes"]
check(r["headers"].get_content_type() == ctype == v["content_type"], name + " content type")
check(len(body) == v["size_bytes"] and hashlib.sha256(body).hexdigest() == v["sha256"], name + " checksum")
real = jpeg_size(body) if ctype == "image/jpeg" else webp_size(body)
check(real == dims == (v["width"], v["height"]), "%s: real %s, meta %s, expected %s"
% (name, real, (v["width"], v["height"]), dims))
return got
@s.case("upload → 202 queued snapshot, then ready; original byte-exact; three variants by contract")
def _():
data = (Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sample.png").read_bytes()
att, _ = upload(c, alice, chat, data, filename="sample.png")
check(att["status"] in ("queued", "processing", "ready") and att["error_code"] is None, "202 snapshot")
t = time.monotonic()
ready = wait_status(c, bob, att["id"], ("ready", "failed"))
check(ready["status"] == "ready", "not ready: %s" % ready)
took = time.monotonic() - t
orig = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"]
check(orig == data and ready["sha256"] == hashlib.sha256(data).hexdigest(), "original changed")
check_variants(ready, 320, 200)
return "ready %.2fs after 202; thumbnail 256×160, crop 128×128, optimized 320×200 WebP" % took
@s.case("big image: optimized fits 1280 without upscale, thumbnail rounds down")
def _():
att, _ = upload(c, alice, chat, flat_png(3001, 1999), filename="big.png")
ready = wait_status(c, alice, att["id"], ("ready", "failed"))
check(ready["status"] == "ready", "not ready")
got = check_variants(ready, 3001, 1999)
return "thumbnail %sx%s, optimized %sx%s" % (got["thumbnail"]["width"], got["thumbnail"]["height"],
got["optimized"]["width"], got["optimized"]["height"])
@s.case("EXIF orientation applied (stored 400×200, orientation 6 → 200×400); tiny image not upscaled")
def _():
att, _ = upload(c, alice, chat, (FIX / "exif6.jpg").read_bytes(), "image/jpeg", "exif6.jpg")
ready = wait_status(c, alice, att["id"], ("ready", "failed"))
check_variants(ready, 200, 400)
tiny, _ = upload(c, alice, chat, make_png(40, 30), filename="tiny.png")
ready = wait_status(c, alice, tiny["id"], ("ready", "failed"))
got = check_variants(ready, 40, 30)
check((got["thumbnail"]["width"], got["thumbnail"]["height"]) == (40, 30), "tiny thumbnail upscaled")
att, _ = upload(c, alice, chat, (FIX / "alpha.png").read_bytes(), filename="alpha.png")
check_variants(wait_status(c, alice, att["id"], ("ready", "failed")), 300, 200)
@s.case("variant parameter: unknown → 400; default original; outsider → 404")
def _():
att, data = upload(c, alice, chat, make_png(64, 64))
wait_status(c, alice, att["id"], "ready")
c.call("GET", "/api/v1/attachments/%s/content?variant=../../x" % att["id"], 400, actor=bob)
c.call("GET", "/api/v1/attachments/%s/content?variant=preview" % att["id"], 400, actor=bob)
check(c.call("GET", "/api/v1/attachments/%s/content?variant=original" % att["id"], actor=bob)["bytes"] == data, "orig")
for v in ("", "?variant=thumbnail"):
c.call("GET", "/api/v1/attachments/%s/content%s" % (att["id"], v), 404, actor=eve)
c.call("GET", "/api/v1/attachments/%s" % att["id"], 404, actor=eve)
@s.case("undecodable image → failed with safe error_code, no retries; content 409; cannot attach (409)")
def _():
att, _ = upload(c, alice, chat, (FIX / "sof5.jpg").read_bytes(), "image/jpeg", "sof5.jpg")
failed = wait_status(c, alice, att["id"], ("ready", "failed"))
check(failed["status"] == "failed" and failed["error_code"] == "invalid_image", "got %s/%s"
% (failed["status"], failed["error_code"]))
check(failed["variants"] == [], "failed must have no variants")
for v in ("", "?variant=thumbnail"):
c.call("GET", "/api/v1/attachments/%s/content%s" % (att["id"], v), 409, actor=bob)
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 409, actor=alice,
body={"text": "x", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": "failed-" + att["id"]})
ev = [e["event"] for e in events(att["id"])]
check(ev.count("claimed") == 1 and "retry_scheduled" not in ev and ev[-1] == "failed", "permanent: %s" % ev)
reg = jobs_cli("failed", "--limit", "500")["failed"]
check(any(r["attachment_id"] == att["id"] and r["error_code"] == "invalid_image" for r in reg), "not in registry")
return "events %s; listed in failed registry" % ev
@s.case("queued/processing attachment can be attached to a message right away")
def _():
att, _ = upload(c, alice, chat, make_png(50, 50))
m = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=bob, schema="Message",
body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": "q-" + att["id"]})["json"]
check(m["attachment_ids"] == [att["id"]], "message lost attachment")
wait_status(c, alice, att["id"], "ready")
@s.case("duplicate deliveries of a finished job are no-ops (5 raw duplicates)")
def _():
att, _ = upload(c, alice, chat, make_png(80, 60))
before = wait_status(c, alice, att["id"], "ready")
job = jobs_cli("status", att["id"])["jobs"][0]
jobs_cli("publish-raw", "--job", job["job_id"], "--count", "5")
time.sleep(3)
ev = [e["event"] for e in events(att["id"])]
after = c.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]
check(ev.count("committed") == 1 and ev.count("duplicate_ignored") == 5, "events %s" % ev)
check(after["variants"] == before["variants"] and after["updated_at"] == before["updated_at"], "result changed")
return "committed ×1, duplicate_ignored ×5, metadata unchanged"
@s.case("replay is safe: ready → noop; failed (permanent) → re-executed once, failed again")
def _():
att, _ = upload(c, alice, chat, make_png(30, 30))
wait_status(c, alice, att["id"], "ready")
r = jobs_cli("replay", "--attachment", att["id"], "--reason", "test ready")
check(r["result"] == "noop" and r["status"] == "ready", "replay of ready must be noop: %s" % r)
bad, _ = upload(c, alice, chat, (FIX / "sof5.jpg").read_bytes(), "image/jpeg", "sof5-replay.jpg")
wait_status(c, alice, bad["id"], "failed")
r = jobs_cli("replay", "--attachment", bad["id"], "--reason", "operator retry", "--operator", "student")
check(r["result"] == "replayed" and r["attempt"] == 2, "replay: %s" % r)
wait_status(c, alice, bad["id"], "failed")
ev = [e for e in events(bad["id"])]
rp = [e for e in ev if e["event"] == "replayed"]
check(len(rp) == 1 and rp[0]["detail"]["operator"] == "student", "audit record missing")
check([e["event"] for e in ev].count("failed") == 2, "expected second failure")
return "ready: %s; failed: replayed (audit by %s) → failed again (permanent error)" % (r and "noop", "student")
s.run()