from io import BytesIO import pytest from PIL import Image from messenger.attachments.domain.errors import UnreadableImage from messenger.attachments.infrastructure.images import render_variants from pictures import SAMPLE LIMIT = 40_000_000 def encoded(image: Image.Image, kind: str = "PNG", **options: object) -> bytes: buffer = BytesIO() image.save(buffer, kind, **options) return buffer.getvalue() def thumbnail(data: bytes) -> Image.Image: (rendition,) = render_variants(data, LIMIT) assert (rendition.name, rendition.content_type, rendition.extension) == ( "thumbnail", "image/jpeg", "jpg", ) image = Image.open(BytesIO(rendition.data)) assert image.format == "JPEG" assert image.size == (rendition.width, rendition.height) assert not image.getexif() return image def test_fixture_gives_256_by_160() -> None: assert thumbnail(SAMPLE).size == (256, 160) @pytest.mark.parametrize( ("mode", "size", "fitted"), [ ("L", (17, 1000), (4, 256)), ("RGB", (64, 64), (64, 64)), ("RGB", (3000, 2), (256, 1)), ("I;16", (300, 200), (256, 170)), ("CMYK", (801, 601), (256, 192)), ], ) def test_sizes_round_down_and_never_upscale( mode: str, size: tuple[int, int], fitted: tuple[int, int] ) -> None: kind = "JPEG" if mode == "CMYK" else "PNG" assert thumbnail(encoded(Image.new(mode, size), kind)).size == fitted @pytest.mark.parametrize("mode", ["RGBA", "LA"]) def test_transparency_is_composed_on_white(mode: str) -> None: transparent = Image.new(mode, (300, 300), (0,) * len(mode)) assert thumbnail(encoded(transparent)).convert("RGB").getpixel((5, 5)) == (255, 255, 255) def test_palette_transparency_is_composed_on_white() -> None: palette = Image.new("P", (200, 100)) image = thumbnail(encoded(palette, transparency=0)) assert image.size == (200, 100) assert image.convert("RGB").getpixel((5, 5)) == (255, 255, 255) @pytest.mark.parametrize(("orientation", "fitted"), [(6, (128, 256)), (3, (256, 128))]) def test_exif_orientation_is_applied_before_sizing( orientation: int, fitted: tuple[int, int] ) -> None: exif = Image.Exif() exif[0x0112] = orientation data = encoded(Image.new("RGB", (400, 200), (10, 200, 10)), "JPEG", exif=exif) assert thumbnail(data).size == fitted @pytest.mark.parametrize( "data", [b"", b"garbage", SAMPLE[: len(SAMPLE) // 2], b"GIF89a" + bytes(20)], ids=["empty", "garbage", "truncated", "gif"], ) def test_undecodable_data_is_a_permanent_error(data: bytes) -> None: with pytest.raises(UnreadableImage): render_variants(data, LIMIT) def test_pixel_limit_is_checked_before_decoding() -> None: with pytest.raises(UnreadableImage): render_variants(SAMPLE, 320 * 200 - 1)