forked from mtusi2026/mtusi2026lab4
51 lines
1.9 KiB
Python
51 lines
1.9 KiB
Python
"""Offline checks of image content, size limits, and MIME detection."""
|
|
import io
|
|
from pathlib import Path
|
|
import struct
|
|
import sys
|
|
import unittest
|
|
import zlib
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'app'))
|
|
from PIL import Image
|
|
from images import validate_image, InvalidImage, TooManyPixels
|
|
|
|
class Images(unittest.TestCase):
|
|
def picture(self, fmt):
|
|
file = io.BytesIO()
|
|
Image.new('RGB', (320, 200), (20, 30, 40)).save(file, fmt)
|
|
file.seek(0)
|
|
return file
|
|
|
|
def test_png_and_jpeg(self):
|
|
for fmt, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
|
|
file = self.picture(fmt)
|
|
before = file.getvalue()
|
|
validate_image(file, mime)
|
|
self.assertEqual(file.tell(), 0)
|
|
self.assertEqual(file.read(), before)
|
|
|
|
def test_mime_substitution(self):
|
|
with self.assertRaises(InvalidImage):
|
|
validate_image(self.picture('PNG'), 'image/jpeg')
|
|
|
|
def test_not_image(self):
|
|
for content in [b'', b'hello', b'<script>alert(1)</script>']:
|
|
with self.assertRaises(InvalidImage):
|
|
validate_image(io.BytesIO(content), 'image/png')
|
|
|
|
def test_truncated_pixels(self):
|
|
file = self.picture('JPEG')
|
|
with self.assertRaises(InvalidImage):
|
|
validate_image(io.BytesIO(file.getvalue()[:-20]), 'image/jpeg')
|
|
|
|
def test_pixel_limit_before_decode(self):
|
|
def chunk(kind, data):
|
|
return struct.pack('>I', len(data))+kind+data+struct.pack('>I', zlib.crc32(kind+data)&0xffffffff)
|
|
huge = b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB', 8000,8000,8,2,0,0,0))
|
|
huge += chunk(b'IDAT', zlib.compress(b'\x00'))+chunk(b'IEND', b'')
|
|
with self.assertRaises(TooManyPixels):
|
|
validate_image(io.BytesIO(huge), 'image/png')
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main(verbosity=2)
|