forked from mtusi2026/mtusi2026lab6
161 lines
6.7 KiB
Python
161 lines
6.7 KiB
Python
#!/usr/bin/env python3
|
||
"""Обработка изображений worker (уровень 4): правила вариантов и лимиты — проверка декодированием.
|
||
|
||
Запускается ВНУТРИ образа приложения (нужен Pillow):
|
||
docker compose --env-file .env run --rm --no-deps -T -v "$PWD/student-tests:/app/student-tests:ro" \
|
||
--entrypoint python worker student-tests/test_imgproc.py
|
||
Проверяет: размеры (вписывание, округление вниз, без увеличения), EXIF orientation, alpha на белом,
|
||
отсутствие EXIF/ICC в вариантах, детерминированность (основа идемпотентности), отличие pipeline v2,
|
||
лимиты пикселей/памяти/времени и классификацию ошибок (постоянная vs временная).
|
||
"""
|
||
import asyncio
|
||
import io
|
||
import json
|
||
import os
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
import types
|
||
from pathlib import Path
|
||
|
||
from PIL import Image, ImageCms, ImageDraw
|
||
|
||
sys.path.insert(0, "/app/src")
|
||
from messenger.worker import Permanent, Transient, Worker # noqa: E402
|
||
|
||
FIX = Path(__file__).parent / "fixtures"
|
||
results = []
|
||
|
||
|
||
def case(name):
|
||
def deco(fn):
|
||
t = time.monotonic()
|
||
try:
|
||
note = fn()
|
||
results.append(True)
|
||
print("PASS %-70s %.2fs %s" % (name, time.monotonic() - t, note or ""))
|
||
except Exception as exc: # noqa: BLE001
|
||
results.append(False)
|
||
print("FAIL %-70s %s: %s" % (name, type(exc).__name__, exc))
|
||
return fn
|
||
return deco
|
||
|
||
|
||
def run(data, version=1, mem=768, maxpx=40_000_000):
|
||
p = subprocess.run([sys.executable, "-m", "messenger.imgproc", str(maxpx), str(mem), "30", str(version)],
|
||
input=data, capture_output=True, env=dict(os.environ, PYTHONPATH="/app/src"))
|
||
head, _, rest = p.stdout.partition(b"\n")
|
||
info = json.loads(head)
|
||
if not info["ok"]:
|
||
return info
|
||
out, off = {}, 0
|
||
for v in info["variants"]:
|
||
body = rest[off:off + v["size_bytes"]]
|
||
off += v["size_bytes"]
|
||
im = Image.open(io.BytesIO(body))
|
||
im.load()
|
||
out[v["name"]] = (im, body, v)
|
||
return out
|
||
|
||
|
||
def enc(im, fmt, **kw):
|
||
b = io.BytesIO()
|
||
im.save(b, fmt, **kw)
|
||
return b.getvalue()
|
||
|
||
|
||
@case("fixture 320×200 → thumbnail 256×160, crop 128×128, optimized WebP 320×200")
|
||
def _():
|
||
o = run((FIX / "photo.jpg").read_bytes()) # 96×64 — меньше коробки: без увеличения
|
||
assert o["thumbnail"][0].size == (96, 64) and o["optimized"][0].size == (96, 64)
|
||
sample = Image.new("RGB", (320, 200), (10, 120, 200))
|
||
o = run(enc(sample, "PNG"))
|
||
assert o["thumbnail"][0].size == (256, 160) and o["crop"][0].size == (128, 128)
|
||
assert o["optimized"][0].format == "WEBP" and o["optimized"][0].size == (320, 200)
|
||
assert o["thumbnail"][0].format == "JPEG" and o["crop"][0].format == "JPEG"
|
||
|
||
|
||
@case("rounding down and minimum 1 px: 3000×10 → 256×1, 1280×4")
|
||
def _():
|
||
o = run(enc(Image.new("RGB", (3000, 10)), "PNG"))
|
||
assert o["thumbnail"][0].size == (256, 1) and o["optimized"][0].size == (1280, 4), \
|
||
(o["thumbnail"][0].size, o["optimized"][0].size)
|
||
|
||
|
||
@case("EXIF orientation 6 applied (400×200 stored → 128×256); orientation tag not copied")
|
||
def _():
|
||
o = run((FIX / "exif6.jpg").read_bytes())
|
||
t = o["thumbnail"][0]
|
||
assert t.size == (128, 256), t.size
|
||
# Левая жёлтая полоса исходника после поворота на 90° по часовой оказывается сверху.
|
||
top, bottom = t.getpixel((64, 10)), t.getpixel((64, 245))
|
||
assert top[0] > 200 and top[2] < 100 and bottom[2] > 120, (top, bottom)
|
||
assert not t.getexif(), "EXIF must be stripped"
|
||
|
||
|
||
@case("alpha composited on white for JPEG variants; WebP keeps alpha")
|
||
def _():
|
||
o = run((FIX / "alpha.png").read_bytes())
|
||
px = o["thumbnail"][0].getpixel((5, 5)) # прозрачная половина
|
||
assert all(v >= 250 for v in px), px
|
||
assert o["thumbnail"][0].getpixel((250, 80))[0] > 180 # непрозрачная красная половина
|
||
assert o["optimized"][0].mode == "RGBA" and o["optimized"][0].getpixel((5, 5))[3] == 0
|
||
|
||
|
||
@case("metadata removed: EXIF/XMP/ICC of the source are not in any variant")
|
||
def _():
|
||
im = Image.new("RGB", (500, 300), (200, 100, 50))
|
||
ex = Image.Exif()
|
||
ex[0x010F] = "SecretCameraMaker"
|
||
icc = ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB")).tobytes()
|
||
o = run(enc(im, "JPEG", exif=ex.tobytes(), icc_profile=icc))
|
||
for name, (img, body, _) in o.items():
|
||
assert b"SecretCameraMaker" not in body and not img.info.get("icc_profile") and not img.getexif(), name
|
||
|
||
|
||
@case("deterministic output (same bytes on re-run) — basis of idempotent effect; v2 differs")
|
||
def _():
|
||
data = enc(Image.new("RGB", (900, 600), (30, 200, 90)), "PNG")
|
||
a, b, v2 = run(data), run(data), run(data, version=2)
|
||
assert all(a[k][2]["sha256"] == b[k][2]["sha256"] for k in a)
|
||
assert a["thumbnail"][2]["sha256"] != v2["thumbnail"][2]["sha256"]
|
||
assert all(a[k][0].size == v2[k][0].size for k in a)
|
||
|
||
|
||
@case("limits: pixels by header (413-class), memory (RLIMIT_AS), undecodable → permanent")
|
||
def _():
|
||
big = enc(Image.new("L", (5000, 5000)), "PNG")
|
||
r = run(big, maxpx=10_000_000)
|
||
assert not isinstance(r, dict) or r.get("kind") == "too_large", r
|
||
r = run(enc(Image.new("RGB", (6000, 6000)), "PNG"), mem=200)
|
||
assert r.get("kind") == "resource_limit", r
|
||
r = run((FIX / "sof5.jpg").read_bytes())
|
||
assert r.get("kind") == "invalid_image", r
|
||
return "too_large / resource_limit / invalid_image"
|
||
|
||
|
||
@case("worker wall-clock timeout kills the subprocess → transient (retry), not a hang")
|
||
def _():
|
||
fake = types.SimpleNamespace(s=types.SimpleNamespace(max_image_pixels=40_000_000, worker_process_memory_mb=768,
|
||
job_timeout_seconds=0.05))
|
||
data = enc(Image.new("RGB", (4000, 3000)), "PNG")
|
||
t = time.monotonic()
|
||
try:
|
||
asyncio.run(Worker.run_pipeline(fake, data, 1))
|
||
raise AssertionError("no timeout")
|
||
except Transient as exc:
|
||
assert exc.code == "processing_timeout"
|
||
took = time.monotonic() - t
|
||
assert took < 2, took
|
||
fake.s.job_timeout_seconds = 30
|
||
try:
|
||
asyncio.run(Worker.run_pipeline(fake, (FIX / "sof5.jpg").read_bytes(), 1))
|
||
raise AssertionError("no error")
|
||
except Permanent as exc:
|
||
assert exc.code == "invalid_image"
|
||
return "killed after %.2fs; undecodable → Permanent(invalid_image)" % took
|
||
|
||
|
||
print("summary: %d passed, %d failed" % (sum(results), len(results) - sum(results)))
|
||
sys.exit(0 if all(results) else 1)
|