forked from mtusi2026/mtusi2026lab4
120 lines
4.7 KiB
Python
120 lines
4.7 KiB
Python
"""Проверка разбора изображений без сервера: файлы настоящие, а испорченные версии не должны ронять разбор."""
|
|
import io
|
|
import random
|
|
import struct
|
|
import sys
|
|
import unittest
|
|
import zlib
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
|
import images # noqa: E402
|
|
|
|
from samples import REAL_IMAGES, make_png, png_chunk # noqa: E402
|
|
|
|
LIMIT = 40_000_000
|
|
|
|
|
|
def inspect(data, limit=LIMIT):
|
|
return images.inspect(io.BytesIO(data), limit)
|
|
|
|
|
|
class RealImagesTest(unittest.TestCase):
|
|
def test_real_images_are_accepted(self):
|
|
for name, (content_type, data) in REAL_IMAGES.items():
|
|
with self.subTest(name):
|
|
self.assertEqual(inspect(data), content_type)
|
|
|
|
def test_course_fixture(self):
|
|
path = Path(__file__).resolve().parents[1] / "tests/fixtures/sample.png"
|
|
self.assertEqual(inspect(path.read_bytes()), "image/png")
|
|
|
|
def test_jpeg_with_data_after_end(self):
|
|
# камеры дописывают после конца изображения превью
|
|
self.assertEqual(inspect(REAL_IMAGES["jpeg_baseline"][1] + b"\xff\xd8" + b"x" * 50), "image/jpeg")
|
|
|
|
def test_marker_on_block_border(self):
|
|
data = bytearray(REAL_IMAGES["jpeg_baseline"][1])
|
|
start = data.index(b"\xff\xda")
|
|
length = struct.unpack(">H", data[start + 2:start + 4])[0]
|
|
padded = data[:start + 2 + length] + b"\x12" * (images.BLOCK - 3) + b"\xff\x00" * 40 + data[start + 2 + length:]
|
|
self.assertEqual(inspect(bytes(padded)), "image/jpeg")
|
|
|
|
|
|
class BrokenImagesTest(unittest.TestCase):
|
|
def assert_not_image(self, data):
|
|
with self.assertRaises(images.NotAnImage):
|
|
inspect(data)
|
|
|
|
def test_truncated(self):
|
|
for name, (_, data) in REAL_IMAGES.items():
|
|
for size in (0, 1, 2, 3, 8, 12, len(data) // 2, len(data) - 1):
|
|
with self.subTest(name=name, size=size):
|
|
self.assert_not_image(data[:size])
|
|
|
|
def test_not_images(self):
|
|
for data in (b"", b"GIF89a" + b"\x00" * 20, b"%PDF-1.7", b"<svg></svg>", b"\xff\xd8", b"\x89PNG\r\n\x1a\n"):
|
|
with self.subTest(start=data[:8]):
|
|
self.assert_not_image(data)
|
|
|
|
def test_png_bad_crc(self):
|
|
data = bytearray(make_png(8, 8))
|
|
data[-20] ^= 0xFF
|
|
self.assert_not_image(bytes(data))
|
|
|
|
def test_png_data_after_end(self):
|
|
self.assert_not_image(make_png(8, 8) + b"<script>")
|
|
|
|
def test_png_with_wrong_amount_of_pixels(self):
|
|
self.assert_not_image(make_png(8, 8, b"\x00" * 10))
|
|
self.assert_not_image(make_png(8, 8, b"\x00" * 10000))
|
|
|
|
def test_png_data_is_not_zlib(self):
|
|
header = struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0)
|
|
data = b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", header) + png_chunk(b"IDAT", b"not zlib") + png_chunk(b"IEND", b"")
|
|
self.assert_not_image(data)
|
|
|
|
def test_png_zero_size(self):
|
|
self.assert_not_image(make_png(0, 8, b""))
|
|
|
|
def test_jpeg_without_frame_or_scan(self):
|
|
self.assert_not_image(b"\xff\xd8\xff\xd9")
|
|
self.assert_not_image(b"\xff\xd8\xff\xe0\x00\x04ab\xff\xd9")
|
|
|
|
def test_random_corruption_never_crashes(self):
|
|
random.seed(20261030)
|
|
for name, (_, original) in REAL_IMAGES.items():
|
|
for _ in range(1500):
|
|
data = bytearray(original)
|
|
for _ in range(random.randint(1, 8)):
|
|
data[random.randrange(len(data))] = random.randrange(256)
|
|
try:
|
|
inspect(bytes(data))
|
|
except (images.NotAnImage, images.TooManyPixels):
|
|
pass
|
|
|
|
|
|
class PixelLimitTest(unittest.TestCase):
|
|
def test_png_bomb_is_rejected_before_unpacking(self):
|
|
header = struct.pack(">IIBBBBB", 50000, 50000, 8, 2, 0, 0, 0)
|
|
# данные заголовка верны, а распаковать пришлось бы 7,5 ГБ
|
|
data = b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", header) + png_chunk(b"IDAT", zlib.compress(b"\x00" * 1000))
|
|
with self.assertRaises(images.TooManyPixels):
|
|
inspect(data)
|
|
|
|
def test_jpeg_over_limit(self):
|
|
data = bytearray(REAL_IMAGES["jpeg_baseline"][1])
|
|
start = data.index(b"\xff\xc0")
|
|
data[start + 5:start + 9] = struct.pack(">HH", 20000, 20000)
|
|
with self.assertRaises(images.TooManyPixels):
|
|
inspect(bytes(data))
|
|
|
|
def test_limit_is_exact(self):
|
|
self.assertEqual(inspect(make_png(10, 10), limit=100), "image/png")
|
|
with self.assertRaises(images.TooManyPixels):
|
|
inspect(make_png(10, 10), limit=99)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|