import hashlib import io import unittest from unittest.mock import patch from PIL import Image from main import thumbnail class ThumbnailTests(unittest.TestCase): def test_extreme_aspect_ratios(self): for dimensions, expected in [((1, 1000), (1, 256)), ((1000, 1), (256, 1)), ((1, 1), (1, 1)), ((256, 256), (256, 256))]: with self.subTest(dimensions=dimensions): source = io.BytesIO() Image.new('RGB', dimensions).save(source, 'PNG') data, size = thumbnail(source.getvalue()) self.assertEqual(size, expected) with Image.open(io.BytesIO(data)) as result: self.assertEqual(result.size, expected) def test_corrupt_input_rejected(self): source = io.BytesIO() Image.new('RGB', (10, 10)).save(source, 'PNG') for data in (b'', b'not an image', source.getvalue()[:40]): with self.subTest(data=data): with self.assertRaises((OSError, ValueError)): thumbnail(data) def test_pixel_limit_boundary(self): source = io.BytesIO() Image.new('RGB', (10, 10)).save(source, 'PNG') with patch.object(Image, 'MAX_IMAGE_PIXELS', 100): self.assertEqual(thumbnail(source.getvalue())[1], (10, 10)) with patch.object(Image, 'MAX_IMAGE_PIXELS', 99): with self.assertWarns(Image.DecompressionBombWarning): with self.assertRaises(ValueError): thumbnail(source.getvalue()) def test_size_floor_and_no_upscale(self): for dimensions, expected in [((320,200),(256,160)), ((7,3),(7,3)), ((1000,333),(256,85))]: source = io.BytesIO() Image.new('RGB', dimensions, 'red').save(source, 'PNG') data, size = thumbnail(source.getvalue()) self.assertEqual(size, expected) with Image.open(io.BytesIO(data)) as result: self.assertEqual(result.format, 'JPEG') self.assertEqual(result.size, expected) def test_transparency_is_white(self): source = io.BytesIO() Image.new('RGBA', (10,10), (0,0,0,0)).save(source, 'PNG') result, _ = thumbnail(source.getvalue()) with Image.open(io.BytesIO(result)) as image: self.assertTrue(all(value >= 250 for value in image.getpixel((5,5)))) def test_orientation_applied_and_exif_removed(self): source = io.BytesIO() exif = Image.Exif() exif[274] = 6 Image.new('RGB', (320,200), 'blue').save(source, 'JPEG', exif=exif) data = source.getvalue() original_hash = hashlib.sha256(data).hexdigest() result, size = thumbnail(data) self.assertEqual(size, (160,256)) self.assertEqual(hashlib.sha256(data).hexdigest(), original_hash) with Image.open(io.BytesIO(result)) as image: self.assertFalse(image.getexif()) if __name__ == '__main__': unittest.main()