feat: Саватеев А трек 4

This commit is contained in:
Enterxx2
2026-11-02 23:13:38 +03:00
parent 445cfe4789
commit 081d0fd2c8
76 changed files with 6387 additions and 77 deletions
+113
View File
@@ -1,11 +1,16 @@
"""Общие проверки для собственных black-box тестов"""
import base64
import json
import io
import struct
import subprocess
import uuid
import zlib
from pathlib import Path
import httpx
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
@@ -101,3 +106,111 @@ def psql(sql: str) -> str:
'psql -X -q -tA -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
stdin=sql,
).strip()
# --- Изображения и вложения (lab4) ---
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
MAX_IMAGE_PIXELS = 40_000_000
FIXTURE_PNG = ROOT / "tests/fixtures/sample.png"
def png_bytes(width: int = 32, height: int = 20, noise: bool = False) -> bytes:
"""Настоящий PNG; noise — плохо сжимаемое содержимое"""
image = (
Image.effect_noise((width, height), 64).convert("RGB")
if noise
else Image.new("RGB", (width, height), (200, 30, 90))
)
buffer = io.BytesIO()
image.save(buffer, "PNG")
return buffer.getvalue()
def jpeg_bytes(width: int = 32, height: int = 20, progressive: bool = False) -> bytes:
image = Image.effect_noise((width, height), 64).convert("RGB")
buffer = io.BytesIO()
image.save(buffer, "JPEG", quality=85, progressive=progressive)
return buffer.getvalue()
def bilevel_png(width: int, height: int) -> bytes:
"""Огромное по пикселям, но крошечное по байтам изображение (1 бит, нули)"""
buffer = io.BytesIO()
Image.new("1", (width, height)).save(buffer, "PNG")
return buffer.getvalue()
def png_chunk(chunk_type: bytes, data: bytes) -> bytes:
return (
struct.pack(">I", len(data))
+ chunk_type
+ data
+ struct.pack(">I", zlib.crc32(chunk_type + data))
)
def png_of_size(size: int) -> bytes:
"""
Валидный PNG ровно size байт: перед IEND вставляется chunk tEXt
с корректным CRC нужной длины.
"""
base = png_bytes()
iend = base[-12:]
padding = size - len(base) - 12
keyword = b"Comment\x00"
text = png_chunk(b"tEXt", keyword + b"a" * (padding - len(keyword)))
result = base[:-12] + text + iend
assert len(result) == size
return result
def upload_headers(user: dict, content_type: str = "image/png") -> dict[str, str]:
return {**auth(user), "Content-Type": content_type}
def upload_raw(
api: httpx.Client,
user: dict,
chat_id: str,
content: bytes,
content_type: str | None = "image/png",
filename: str = "image.png",
) -> httpx.Response:
"""POST сырых байт; content_type=None — без заголовка Content-Type"""
headers = auth(user) if content_type is None else upload_headers(user, content_type)
return api.post(
f"/api/v1/chats/{chat_id}/attachments",
params={"filename": filename},
content=content,
headers=headers,
)
def assert_not_server_error(response: httpx.Response) -> None:
"""Ошибка пользователя не превращается в 5xx и имеет формат контракта"""
assert response.status_code < 500, response.text
assert response.headers["X-Instance-Id"]
def last_json_line(output: str) -> dict:
"""Результат скрипта — последняя JSON-строка stdout; выше — журнал loguru"""
return json.loads(
next(line for line in reversed(output.splitlines()) if line.startswith("{"))
)
def container_json(service: str, script: str) -> dict:
"""
Python-скрипт внутри контейнера стенда: его сети, секреты и код из src.
Скрипт печатает результат одной JSON-строкой.
"""
prelude = "import sys\nsys.path.insert(0, 'src')\n"
output = compose("exec", "-T", service, "python", "-", stdin=prelude + script)
return last_json_line(output)
def run_janitor(*args: str) -> dict:
"""Один проход janitor внутри его контейнера; отчёт сверки"""
output = compose("exec", "-T", "janitor", "python", "src/janitor.py", "--once", *args)
return last_json_line(output)