forked from mtusi2026/mtusi2026lab4
178 lines
7.1 KiB
Python
178 lines
7.1 KiB
Python
"""Сверка с настоящим декодером. Pillow здесь судья: загружает изображение полностью и без уменьшения.
|
||
|
||
Главное правило: файл, который Pillow отвергает, отвергаем и мы. Обратное тоже проверяется на настоящих
|
||
файлах: всё, что Pillow умеет записать, должно приниматься.
|
||
"""
|
||
import io
|
||
import random
|
||
import struct
|
||
import sys
|
||
import unittest
|
||
import warnings
|
||
import zlib
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parents[2]
|
||
sys.path[:0] = [str(ROOT / "src"), str(ROOT / "student-tests")]
|
||
from PIL import Image, ImageFile # noqa: E402
|
||
|
||
import images # noqa: E402
|
||
from samples import REAL_IMAGES, make_png, png_chunk # noqa: E402
|
||
|
||
LIMIT = 40_000_000
|
||
ImageFile.LOAD_TRUNCATED_IMAGES = False
|
||
warnings.simplefilter("ignore")
|
||
|
||
|
||
def pillow_accepts(data):
|
||
try:
|
||
with Image.open(io.BytesIO(data), formats=["PNG", "JPEG"]) as image:
|
||
image.load()
|
||
with Image.open(io.BytesIO(data), formats=["PNG", "JPEG"]) as image:
|
||
image.verify()
|
||
return True
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def we_accept(data):
|
||
try:
|
||
images.inspect(io.BytesIO(data), LIMIT)
|
||
return True
|
||
except (images.NotAnImage, images.TooManyPixels):
|
||
return False
|
||
|
||
|
||
def picture(mode, size=(64, 48)):
|
||
image = Image.effect_noise(size, 60).convert("RGB")
|
||
return image.convert(mode) if mode != "RGB" else image
|
||
|
||
|
||
def encoded(image, **options):
|
||
out = io.BytesIO()
|
||
image.save(out, **options)
|
||
return out.getvalue()
|
||
|
||
|
||
def valid_corpus():
|
||
corpus = {}
|
||
for mode in ("1", "L", "LA", "P", "PA", "RGB", "RGBA", "I;16"):
|
||
try:
|
||
corpus["png-" + mode] = encoded(picture(mode), format="PNG")
|
||
except (OSError, ValueError):
|
||
pass
|
||
corpus["png-optimized"] = encoded(picture("RGB"), format="PNG", optimize=True)
|
||
corpus["png-1x1"] = encoded(picture("RGB", (1, 1)), format="PNG")
|
||
corpus["png-text"] = encoded(picture("L"), format="PNG", dpi=(72, 72))
|
||
for mode in ("L", "RGB", "CMYK"):
|
||
corpus["jpeg-" + mode] = encoded(picture(mode), format="JPEG")
|
||
for subsampling in (0, 1, 2):
|
||
corpus["jpeg-sub-%d" % subsampling] = encoded(picture("RGB"), format="JPEG", subsampling=subsampling)
|
||
corpus["jpeg-progressive"] = encoded(picture("RGB"), format="JPEG", progressive=True)
|
||
corpus["jpeg-optimized"] = encoded(picture("RGB"), format="JPEG", optimize=True)
|
||
corpus["jpeg-restart"] = encoded(picture("RGB"), format="JPEG", restart_marker_blocks=4)
|
||
corpus["jpeg-1x1"] = encoded(picture("RGB", (1, 1)), format="JPEG")
|
||
corpus["jpeg-flat"] = encoded(Image.new("L", (512, 512), 128), format="JPEG")
|
||
corpus["jpeg-flat-progressive"] = encoded(Image.new("RGB", (512, 512), (9, 9, 9)), format="JPEG", progressive=True)
|
||
corpus["jpeg-exif"] = encoded(picture("RGB"), format="JPEG", exif=b"Exif\x00\x00MM\x00*\x00\x00\x00\x08\x00\x00")
|
||
corpus.update({name: data for name, (_, data) in REAL_IMAGES.items()})
|
||
return corpus
|
||
|
||
|
||
class ValidFilesTest(unittest.TestCase):
|
||
def test_every_valid_file_is_accepted(self):
|
||
for name, data in valid_corpus().items():
|
||
with self.subTest(name):
|
||
self.assertTrue(pillow_accepts(data), "образец сам не принят Pillow")
|
||
self.assertTrue(we_accept(data))
|
||
|
||
|
||
class AgreementTest(unittest.TestCase):
|
||
def assert_no_false_accept(self, name, candidates):
|
||
false_accepts = []
|
||
rejected = accepted = 0
|
||
for data in candidates:
|
||
ours = we_accept(data)
|
||
theirs = pillow_accepts(data)
|
||
accepted += ours
|
||
rejected += not ours
|
||
if ours and not theirs:
|
||
false_accepts.append(data)
|
||
print("%s: принято %d, отвергнуто %d, принято вопреки Pillow %d" % (name, accepted, rejected, len(false_accepts)))
|
||
self.assertEqual(false_accepts[:1], [], "%s: принято %d файлов, которые Pillow отвергает" % (name, len(false_accepts)))
|
||
|
||
def test_random_bytes_changed(self):
|
||
rng = random.Random(20261031)
|
||
corpus = valid_corpus()
|
||
|
||
def mutated():
|
||
for name, original in corpus.items():
|
||
for _ in range(200):
|
||
data = bytearray(original)
|
||
for _ in range(rng.randint(1, 6)):
|
||
data[rng.randrange(len(data))] = rng.randrange(256)
|
||
yield bytes(data)
|
||
|
||
self.assert_no_false_accept("замена байтов", mutated())
|
||
|
||
def test_cut_files(self):
|
||
rng = random.Random(1031)
|
||
corpus = valid_corpus()
|
||
|
||
def cut():
|
||
for original in corpus.values():
|
||
for _ in range(40):
|
||
end = rng.randrange(len(original))
|
||
yield original[:end]
|
||
yield original[:end] + b"\xff\xd9"
|
||
|
||
self.assert_no_false_accept("обрезка", cut())
|
||
|
||
def test_png_with_recomputed_crc(self):
|
||
"""Самый важный случай: заголовок и CRC верны, испорчено только содержимое. Именно такой файл и был в замечании."""
|
||
rng = random.Random(7)
|
||
|
||
def forged():
|
||
for _ in range(1500):
|
||
width, height = rng.randint(1, 12), rng.randint(1, 12)
|
||
size = (1 + width * 3) * height
|
||
raw = bytearray(rng.choice(b"\x00\x01\x02\x03\x04") for _ in range(size))
|
||
for _ in range(rng.randint(0, 3)):
|
||
raw[rng.randrange(size)] = rng.randrange(256)
|
||
yield make_png(width, height, bytes(raw))
|
||
|
||
self.assert_no_false_accept("PNG с верными CRC", forged())
|
||
|
||
def test_jpeg_with_headers_rebuilt(self):
|
||
rng = random.Random(9)
|
||
original = REAL_IMAGES["jpeg_baseline"][1]
|
||
scan = original.index(b"\xff\xda")
|
||
length = struct.unpack(">H", original[scan + 2:scan + 4])[0]
|
||
head = original[:scan + 2 + length]
|
||
|
||
def forged():
|
||
for _ in range(800):
|
||
body = bytes(rng.randrange(255) for _ in range(rng.randint(0, 300)))
|
||
yield head + body.replace(b"\xff", b"\x00") + b"\xff\xd9"
|
||
|
||
self.assert_no_false_accept("JPEG с настоящими заголовками", forged())
|
||
|
||
def test_png_chunks_shuffled(self):
|
||
rng = random.Random(3)
|
||
signature = b"\x89PNG\r\n\x1a\n"
|
||
chunks = [b"IHDR", b"PLTE", b"IDAT", b"IEND", b"tEXt"]
|
||
|
||
def forged():
|
||
header = struct.pack(">IIBBBBB", 2, 2, 8, 3, 0, 0, 0)
|
||
bodies = {b"IHDR": header, b"PLTE": b"\x01\x02\x03", b"IDAT": zlib.compress(b"\x00\x00\x00" * 2),
|
||
b"IEND": b"", b"tEXt": b"a\x00b"}
|
||
for _ in range(600):
|
||
order = rng.choices(chunks, k=rng.randint(1, 6))
|
||
yield signature + b"".join(png_chunk(kind, bodies[kind]) for kind in order)
|
||
|
||
self.assert_no_false_accept("порядок блоков PNG", forged())
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|