forked from mtusi2026/mtusi2026lab5
feat: перенос логики с 4лабф
This commit is contained in:
@@ -0,0 +1,216 @@
|
||||
"""Общие проверки для собственных 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]
|
||||
|
||||
USER_FIELDS = ("id", "username", "display_name", "created_at")
|
||||
|
||||
|
||||
def unique_username(label: str) -> str:
|
||||
return f"st_{label}_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
|
||||
def unique_password() -> str:
|
||||
return f"Pw-{uuid.uuid4().hex}"
|
||||
|
||||
|
||||
def basic(username: str, password: str) -> dict[str, str]:
|
||||
"""Authorization: Basic; пароль кодируется в UTF-8"""
|
||||
raw = f"{username}:{password}".encode()
|
||||
return {"Authorization": "Basic " + base64.b64encode(raw).decode()}
|
||||
|
||||
|
||||
def auth(user: dict) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {user['token']}"}
|
||||
|
||||
|
||||
def message_headers(user: dict, key: str | None = None) -> dict[str, str]:
|
||||
"""Bearer и Idempotency-Key (новый, если не задан)"""
|
||||
return {**auth(user), "Idempotency-Key": key or uuid.uuid4().hex}
|
||||
|
||||
|
||||
def public_user(user: dict) -> dict:
|
||||
"""User из ответа API без тестовых полей token/password"""
|
||||
return {field: user[field] for field in USER_FIELDS}
|
||||
|
||||
|
||||
def assert_error(response: httpx.Response, status: int, code: str) -> None:
|
||||
"""Код ответа и единый формат ошибки: request_id совпадает с заголовком"""
|
||||
assert response.status_code == status, response.text
|
||||
assert response.headers["content-type"].startswith("application/json")
|
||||
error = response.json()["error"]
|
||||
assert error["code"] == code
|
||||
assert error["message"]
|
||||
assert error["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
def assert_unauthorized(response: httpx.Response, scheme: str = "Bearer") -> None:
|
||||
"""401 с challenge нужной схемы"""
|
||||
assert_error(response, 401, "unauthorized")
|
||||
assert response.headers["WWW-Authenticate"].startswith(scheme)
|
||||
|
||||
|
||||
def read_all_messages(
|
||||
api: httpx.Client, user: dict, chat_id: str, limit: int
|
||||
) -> tuple[list[dict], int]:
|
||||
"""Обход истории по next_cursor; возвращает сообщения и число страниц"""
|
||||
items: list[dict] = []
|
||||
pages = 0
|
||||
params: dict[str, str | int] = {"limit": limit}
|
||||
while True:
|
||||
response = api.get(
|
||||
f"/api/v1/chats/{chat_id}/messages", params=params, headers=auth(user)
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
page = response.json()
|
||||
items.extend(page["items"])
|
||||
pages += 1
|
||||
if page["next_cursor"] is None:
|
||||
return items, pages
|
||||
params = {"limit": limit, "cursor": page["next_cursor"]}
|
||||
|
||||
|
||||
def compose(*args: str, stdin: str | None = None) -> str:
|
||||
"""docker compose из корня репозитория; вывод не печатается (может быть секретен)"""
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT,
|
||||
input=stdin,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
check=True,
|
||||
)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def psql(sql: str) -> str:
|
||||
"""Запрос в PostgreSQL стенда изнутри контейнера; порт БД наружу не открыт"""
|
||||
return compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
'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)
|
||||
Reference in New Issue
Block a user