Files
mtusi2026lab4/student-tests/images.py
T

102 lines
3.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Изображения для тестов вложений: генерируются здесь, в git не лежат.
PNG — на стандартной библиотеке (zlib, CRC): любые IHDR, «бомба»
распаковки, огромные размеры в заголовке, порча байта, хвост после IEND,
шум заданного размера (не сжимается — тело того размера, что нужно). JPEG
— синтетический `student-tests/fixtures/sample.jpg` (320×200, сделан из
`tests/fixtures/sample.png`); его портят обрезкой и подменой маркеров.
"""
import random
import struct
import zlib
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
def chunk(kind: bytes, body: bytes) -> bytes:
crc = zlib.crc32(kind + body)
return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", crc)
def ihdr(width: int, height: int, *, depth: int = 8, color_type: int = 2) -> bytes:
return chunk(
b"IHDR", struct.pack(">IIBBBBB", width, height, depth, color_type, 0, 0, 0)
)
def png(width: int, height: int, *, seed: int | None = None) -> bytes:
"""RGB 8 бит, фильтр строки 0; `seed` — шум (почти не сжимается),
иначе однотонное изображение."""
row_bytes = width * 3
if seed is None:
rows = (b"\x00" + b"\x80" * row_bytes) * height
else:
rng = random.Random(seed)
rows = b"".join(b"\x00" + rng.randbytes(row_bytes) for _ in range(height))
return (
PNG_SIGNATURE
+ ihdr(width, height)
+ chunk(b"IDAT", zlib.compress(rows, 1))
+ chunk(b"IEND", b"")
)
def png_of_size(size: int, *, seed: int = 1) -> bytes:
"""Настоящий PNG ровно `size` байт: шум по ширине 1024 и хвост нулей
после IEND (часть оригинала, проверка его допускает)."""
width = 1024
height = 1
image = png(width, height, seed=seed)
# шум сжимается слабо: ~3 байта на пиксель
while len(image) < size - 4096:
height = max(height + 1, int(height * (size - 4096) / len(image)))
image = png(width, height, seed=seed)
while len(image) > size:
height -= 1
image = png(width, height, seed=seed)
return image + b"\x00" * (size - len(image))
def png_huge_header(width: int = 10_000, height: int = 5_000) -> bytes:
"""Маленький файл с огромными размерами в IHDR: лимит пикселей должен
сработать по заголовку, до распаковки."""
return (
PNG_SIGNATURE
+ ihdr(width, height)
+ chunk(b"IDAT", zlib.compress(b"\x00" * 16))
+ chunk(b"IEND", b"")
)
def png_bomb() -> bytes:
"""IHDR 100×100, а поток IDAT распаковывается в 64 MiB: «бомба»."""
return (
PNG_SIGNATURE
+ ihdr(100, 100)
+ chunk(b"IDAT", zlib.compress(b"\x00" * (64 * 1024 * 1024), 9))
+ chunk(b"IEND", b"")
)
def flip_byte(data: bytes, offset: int) -> bytes:
"""Изменённый байт: у PNG в IDAT это рвёт CRC чанка."""
changed = bytearray(data)
changed[offset] ^= 0xFF
return bytes(changed)
def png_bad_crc(data: bytes) -> bytes:
# первый байт данных IDAT: сигнатура 8, IHDR 25, длина и тип IDAT 8
return flip_byte(data, len(PNG_SIGNATURE) + 25 + 8)
def truncated(data: bytes, keep: float = 0.5) -> bytes:
return data[: int(len(data) * keep)]
def jpeg_without_eoi(data: bytes) -> bytes:
"""JPEG без маркера конца: обрезаны последние два байта."""
assert data.endswith(b"\xff\xd9")
return data[:-2]