Лабораторная работа 6

This commit is contained in:
2026-11-13 01:27:57 +03:00
parent 470d9d6f1e
commit 2dbdcf898c
218 changed files with 22057 additions and 37 deletions
+93
View File
@@ -0,0 +1,93 @@
"""Синтетические изображения для тестов вложений (только стандартная библиотека).
PNG собирается вручную (zlib + CRC32), поэтому можно получить и корректные
файлы заданного размера, и намеренно испорченные варианты. JPEG — небольшие
fixtures из student-tests/fixtures (синтетические, сгенерированы Pillow).
"""
import os
import struct
import zlib
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
PNG_SIG = b"\x89PNG\r\n\x1a\n"
MAX_UPLOAD = 10 * 1024 * 1024
def chunk(ctype: bytes, data: bytes) -> bytes:
return struct.pack(">I", len(data)) + ctype + data + struct.pack(">I", zlib.crc32(ctype + data) & 0xFFFFFFFF)
def ihdr(width, height, depth=8, color=2, interlace=0) -> bytes:
return chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, depth, color, 0, 0, interlace))
def png(width=16, height=16, color=2, depth=8, fill=b"\x40", level=6, extra=b"") -> bytes:
channels = {0: 1, 2: 3, 4: 2, 6: 4}[color]
row = b"\x00" + (fill * (width * channels * depth // 8 + 1))[: (width * channels * depth + 7) // 8]
raw = row * height
return PNG_SIG + ihdr(width, height, depth, color) + extra + chunk(b"IDAT", zlib.compress(raw, level)) + chunk(b"IEND", b"")
def noise_png(target_bytes: int) -> bytes:
"""Несжимаемый RGB PNG размером около target_bytes (шум, zlib level 0)."""
width = 1024
row_bytes = 1 + width * 3
height = max(1, (target_bytes - 200) // row_bytes)
raw = b"".join(b"\x00" + os.urandom(width * 3) for _ in range(height))
return PNG_SIG + ihdr(width, height) + chunk(b"IDAT", zlib.compress(raw, 0)) + chunk(b"IEND", b"")
def png_of_exact_size(size: int) -> bytes:
"""Корректный PNG ровно size байт: маленькая картинка + вспомогательный чанк-заполнитель."""
base = png(8, 8)
pad = size - len(base) - 12
assert pad >= 0
filler = chunk(b"zzPd", b"\x00" * pad) # строчная первая буква: вспомогательный, игнорируется
data = base[:8 + 25] + filler + base[8 + 25:]
assert len(data) == size
return data
def huge_dimensions_png(width=8000, height=6000) -> bytes:
"""48 Мп 1-битная картинка: файл ~50 КБ, распаковка была бы огромной (pixel bomb)."""
row = b"\x00" + b"\x00" * ((width + 7) // 8)
return PNG_SIG + ihdr(width, height, depth=1, color=0) + chunk(b"IDAT", zlib.compress(row * height, 9)) + chunk(b"IEND", b"")
def bad_crc_png() -> bytes:
data = bytearray(png(16, 16))
data[8 + 8 + 13] ^= 0xFF # CRC чанка IHDR
return bytes(data)
def truncated_png() -> bytes:
data = png(64, 64, fill=b"\x13\x37\x99")
return data[: len(data) // 2]
def wrong_length_png() -> bytes:
"""Все CRC верны, но распакованных данных меньше, чем требует IHDR."""
raw = b"\x00" + b"\x10" * 3 * 4
return PNG_SIG + ihdr(4, 10) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
def sample_png() -> bytes:
# В compose-сети (ops.py in-network) монтируется только student-tests/,
# поэтому копия публичного fixture лежит и в student-tests/fixtures.
public = ROOT / "tests" / "fixtures" / "sample.png"
return (public if public.is_file() else HERE / "fixtures" / "sample.png").read_bytes()
def sample_jpeg() -> bytes:
return (HERE / "fixtures" / "sample.jpg").read_bytes()
def progressive_jpeg() -> bytes:
return (HERE / "fixtures" / "sample_progressive.jpg").read_bytes()
def truncated_jpeg() -> bytes:
data = sample_jpeg()
return data[: len(data) - 400]