"""Geometry checks for the image contract. Runs without the stand.""" import io import struct import sys import zlib from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / "tests")) from app.images import decode_image, inspect_upload, pipeline_params, render_variants from image_probe import jpeg_size from PIL import Image def check(condition, message): if not condition: raise SystemExit(message) def png_chunk(tag, data): crc = zlib.crc32(tag + data) & 0xFFFFFFFF return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", crc) def main(): sample = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() content_type, width, height = inspect_upload(sample, "image/png", 10485760, 40000000) check(content_type == "image/png" and (width, height) == (320, 200), "sample header mismatch") rendered = render_variants(decode_image(sample, 40000000), pipeline_params(1)) check(jpeg_size(rendered["thumbnail"]["bytes"]) == (256, 160), "thumbnail geometry") check((rendered["thumbnail"]["width"], rendered["thumbnail"]["height"]) == (256, 160), "thumbnail metadata") check(jpeg_size(rendered["crop"]["bytes"]) == (128, 128), "crop geometry") check(rendered["optimized"]["bytes"][8:12] == b"WEBP", "optimized is not WebP") check((rendered["optimized"]["width"], rendered["optimized"]["height"]) == (320, 200), "optimized geometry") tiny = io.BytesIO() Image.new("RGB", (20, 10), (1, 2, 3)).save(tiny, format="PNG") tiny_rendered = render_variants(decode_image(tiny.getvalue(), 40000000), pipeline_params(1)) check((tiny_rendered["thumbnail"]["width"], tiny_rendered["thumbnail"]["height"]) == (20, 10), "small thumbnail was upscaled") check((tiny_rendered["crop"]["width"], tiny_rendered["crop"]["height"]) == (128, 128), "small crop was not upscaled") oriented = io.BytesIO() source = Image.new("RGB", (320, 200), (255, 0, 0)) exif = source.getexif() exif[274] = 6 source.save(oriented, format="JPEG", exif=exif) turned = decode_image(oriented.getvalue(), 40000000) check(turned.size == (200, 320), "EXIF orientation was ignored") turned_variants = render_variants(turned, pipeline_params(1)) check((turned_variants["thumbnail"]["width"], turned_variants["thumbnail"]["height"]) == (160, 256), "oriented thumbnail geometry") version_one = rendered["thumbnail"]["bytes"] version_two = render_variants(decode_image(sample, 40000000), pipeline_params(2))["thumbnail"]["bytes"] check(version_one != version_two, "pipeline versions are indistinguishable") bomb = b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", struct.pack(">IIBBBBB", 8000, 8000, 8, 2, 0, 0, 0)) + png_chunk(b"IEND", b"") try: inspect_upload(bomb, "image/png", 10485760, 40000000) except Exception as exc: check(getattr(exc, "status", None) == 413, "pixel bomb was not rejected as too large") else: raise SystemExit("pixel bomb was accepted") print("PASS: image contract geometry") if __name__ == "__main__": main()