161 lines
5.8 KiB
Python
161 lines
5.8 KiB
Python
"""Изображения для тестов вложений: генерируются здесь, в 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]
|
||
|
||
|
||
def jpeg_without_tables(data: bytes) -> bytes:
|
||
"""JPEG без сегментов DQT: маркеры на месте, структурная проверка API
|
||
его пропускает (202), а декодер отказывает — так выглядит `failed`."""
|
||
out = bytearray(data[:2])
|
||
pos = 2
|
||
while pos < len(data):
|
||
marker = data[pos + 1]
|
||
if marker == 0xDA:
|
||
out += data[pos:]
|
||
break
|
||
(length,) = struct.unpack_from(">H", data, pos + 2)
|
||
if marker != 0xDB:
|
||
out += data[pos : pos + 2 + length]
|
||
pos += 2 + length
|
||
assert b"\xff\xdb" not in bytes(out[: out.find(b"\xff\xda")])
|
||
return bytes(out)
|
||
|
||
|
||
# --- лаба 5: изображения для вариантов (Pillow, только в тестах) ---------
|
||
|
||
|
||
def pillow_image(
|
||
width: int,
|
||
height: int,
|
||
*,
|
||
fmt: str,
|
||
mode: str = "RGB",
|
||
orientation: int | None = None,
|
||
) -> bytes:
|
||
"""Картинка нужного размера; полосы, чтобы поворот был заметен."""
|
||
import io
|
||
|
||
from PIL import Image
|
||
|
||
image = Image.new(mode, (width, height), (200, 30, 30, 128)[: len(mode)])
|
||
for x in range(0, width, max(1, width // 8)):
|
||
for y in range(height):
|
||
image.putpixel((x, y), (10, 10, 200, 255)[: len(mode)])
|
||
buffer = io.BytesIO()
|
||
if orientation is not None:
|
||
exif = Image.Exif()
|
||
exif[0x0112] = orientation
|
||
image.save(buffer, format=fmt, exif=exif.tobytes())
|
||
else:
|
||
image.save(buffer, format=fmt)
|
||
return buffer.getvalue()
|
||
|
||
|
||
def decoded(data: bytes) -> tuple[str, tuple[int, int], str, bool]:
|
||
"""Формат, размеры, режим и есть ли EXIF у полученного варианта."""
|
||
import io
|
||
|
||
from PIL import Image
|
||
|
||
image = Image.open(io.BytesIO(data))
|
||
image.load()
|
||
return image.format, image.size, image.mode, bool(image.getexif())
|