Files
mtusi2026lab5/student-tests/test_pipeline.py
T

75 lines
2.8 KiB
Python

"""Variant pipeline tests (lab5): thumbnail/crop/optimized correctness."""
from __future__ import annotations
from pathlib import Path
from test_attachments import SAMPLE, wait_ready
ROOT = Path(__file__).resolve().parents[1]
def jpeg_size(data: bytes):
assert data[:2] == b"\xff\xd8", "not JPEG"
i = 2
sof = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
while i < len(data):
assert data[i] == 0xFF, "invalid JPEG marker"
while i < len(data) and data[i] == 0xFF:
i += 1
marker = data[i]
i += 1
if marker in {0xD9, 0xDA}:
break
if marker in {0x01, 0xD8} or 0xD0 <= marker <= 0xD7:
continue
length = int.from_bytes(data[i : i + 2], "big")
if marker in sof:
return (int.from_bytes(data[i + 5 : i + 7], "big"), int.from_bytes(data[i + 3 : i + 5], "big"))
i += length
raise AssertionError("JPEG dimensions not found")
def _variant(ready, name):
matches = [v for v in ready["variants"] if v["name"] == name]
assert len(matches) == 1, (name, ready["variants"])
return matches[0]
def test_variants_match_contract(client, alice, bob, chat):
import hashlib
att = client.upload_attachment(alice["token"], chat["id"], SAMPLE).json
ready = wait_ready(client, bob["token"], att["id"])
assert len(ready["variants"]) == 3
assert {v["name"] for v in ready["variants"]} == {"thumbnail", "crop", "optimized"}
thumb = _variant(ready, "thumbnail")
assert (thumb["width"], thumb["height"]) == (256, 160), thumb
assert thumb["content_type"] == "image/jpeg"
body = client.download(bob["token"], att["id"], variant="thumbnail")
assert body.content_type == "image/jpeg"
assert len(body.body) == thumb["size_bytes"]
assert hashlib.sha256(body.body).hexdigest() == thumb["sha256"]
assert jpeg_size(body.body) == (256, 160)
crop = _variant(ready, "crop")
assert (crop["width"], crop["height"]) == (128, 128), crop
crop_body = client.download(bob["token"], att["id"], variant="crop").body
assert jpeg_size(crop_body) == (128, 128)
optimized = _variant(ready, "optimized")
assert optimized["content_type"] == "image/webp"
opt_body = client.download(bob["token"], att["id"], variant="optimized").body
assert opt_body[:4] == b"RIFF" and opt_body[8:12] == b"WEBP", "not WebP"
# original remains byte-identical
assert client.download(bob["token"], att["id"]).body == SAMPLE
def test_missing_variant_is_404(client, alice, bob, chat):
from test_attachments import _assert_error
att = client.upload_attachment(alice["token"], chat["id"], SAMPLE).json
wait_ready(client, bob["token"], att["id"])
_assert_error(client.download(bob["token"], att["id"], variant="unknown"), 404, "not_found")