69 lines
2.5 KiB
Python
69 lines
2.5 KiB
Python
import io
|
|
import unittest
|
|
|
|
from PIL import Image
|
|
|
|
from src.worker import crop, decode_image, optimized, thumbnail
|
|
|
|
|
|
def encoded_image(image, image_format="PNG", **save_options):
|
|
buffer = io.BytesIO()
|
|
image.save(buffer, format=image_format, **save_options)
|
|
return buffer.getvalue()
|
|
|
|
|
|
class ImageVariantTests(unittest.TestCase):
|
|
def test_variants_follow_contract_dimensions_and_formats(self):
|
|
image = decode_image(encoded_image(Image.new("RGB", (320, 200), "navy")))
|
|
|
|
thumb_bytes, thumb_width, thumb_height = thumbnail(image)
|
|
crop_bytes, crop_width, crop_height = crop(image)
|
|
webp_bytes, webp_width, webp_height = optimized(image)
|
|
|
|
self.assertEqual((thumb_width, thumb_height), (256, 160))
|
|
self.assertEqual((crop_width, crop_height), (128, 128))
|
|
self.assertEqual((webp_width, webp_height), (320, 200))
|
|
self.assertEqual(Image.open(io.BytesIO(thumb_bytes)).format, "JPEG")
|
|
self.assertEqual(Image.open(io.BytesIO(crop_bytes)).format, "JPEG")
|
|
self.assertEqual(Image.open(io.BytesIO(webp_bytes)).format, "WEBP")
|
|
self.assertEqual(Image.open(io.BytesIO(webp_bytes)).getexif(), {})
|
|
|
|
def test_small_optimized_image_is_not_upscaled(self):
|
|
image = decode_image(encoded_image(Image.new("RGB", (64, 32), "white")))
|
|
|
|
_, width, height = optimized(image)
|
|
|
|
self.assertEqual((width, height), (64, 32))
|
|
|
|
def test_large_optimized_image_fits_inside_1280(self):
|
|
image = decode_image(encoded_image(Image.new("RGB", (1600, 800), "white")))
|
|
|
|
_, width, height = optimized(image)
|
|
|
|
self.assertEqual((width, height), (1280, 640))
|
|
|
|
def test_crop_and_thumbnail_composite_transparency_on_white(self):
|
|
image = decode_image(encoded_image(Image.new("RGBA", (320, 200), (0, 0, 0, 0))))
|
|
thumb_bytes, _, _ = thumbnail(image)
|
|
crop_bytes, _, _ = crop(image)
|
|
|
|
self.assertEqual(Image.open(io.BytesIO(thumb_bytes)).getpixel((0, 0)), (255, 255, 255))
|
|
self.assertEqual(Image.open(io.BytesIO(crop_bytes)).getpixel((0, 0)), (255, 255, 255))
|
|
|
|
def test_decode_applies_exif_orientation(self):
|
|
exif = Image.Exif()
|
|
exif[274] = 6
|
|
data = encoded_image(Image.new("RGB", (320, 200), "navy"), "JPEG", exif=exif)
|
|
|
|
image = decode_image(data)
|
|
|
|
self.assertEqual(image.size, (200, 320))
|
|
|
|
def test_decode_rejects_non_image_payload(self):
|
|
with self.assertRaises((ValueError, OSError)):
|
|
decode_image(b"not an image")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|