Files
mtusi2026lab2/student-tests/contract.py
T
ricoromaandClaude Opus 5.5 7b775a29a9 chore: carry over lab 1 solution into lab 2 skeleton
Copy the committed lab 1 sources as-is: src/, student-tests/, bench/,
Dockerfile, docker-compose.yml, pyproject.toml, uv.lock,
.python-version, config_example.toml, AGENTS.md, CLAUDE.md, .claude/,
openspec/, .graphifyignore and KNOWN_ISSUES.md. Lab 1 evidence stays
in the lab 1 repository.

Merge the new skeleton files with own sections: Makefile (lab 2
targets plus own run, docker, bench and common targets), .gitignore,
.dockerignore and .env.example. Rename the image to
mtusi-messenger:lab2 and point AGENTS.md at lab 2.

The application is still the in-memory lab 1 implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:11:46 +03:00

159 lines
5.5 KiB
Python

"""Проверка ответов по `contracts/openapi.json` и форматам контракта."""
import json
import re
from datetime import datetime, timedelta
from functools import cache
from pathlib import Path
from typing import Any
import httpx
from jsonschema import Draft202012Validator
from referencing import Registry, Resource
from referencing.jsonschema import DRAFT202012
CONTRACT_PATH = (
Path(__file__).resolve().parents[1] / "contracts" / "openapi.json"
)
_CONTRACT_URI = "urn:mtusi:contract"
UUID_RE = re.compile(
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
)
# RFC 3339 в UTC: шесть знаков долей секунды и суффикс Z
CREATED_AT_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$")
ID_KEYS = frozenset({"id", "chat_id", "sender_id"})
# признаки внутренностей сервиса в error.message
LEAK_RE = re.compile(r"Traceback|File \"|\.py\b|/app/|/src/|Error\(")
# статус -> code ошибки (спек api-conventions)
ERROR_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
405: "invalid_request",
409: "conflict",
500: "internal_error",
503: "unavailable",
}
@cache
def contract() -> dict[str, Any]:
return json.loads(CONTRACT_PATH.read_text(encoding="utf-8"))
@cache
def validator(schema: str) -> Draft202012Validator:
"""Валидатор `#/components/schemas/<schema>` внутри контракта."""
document = contract()
if schema not in document["components"]["schemas"]:
raise KeyError(f"no schema {schema!r} in {CONTRACT_PATH.name}")
resource = Resource.from_contents(
document,
default_specification=DRAFT202012,
)
registry = Registry().with_resource(_CONTRACT_URI, resource)
return Draft202012Validator(
{"$ref": f"{_CONTRACT_URI}#/components/schemas/{schema}"},
registry=registry,
)
def check_body(body: Any, schema: str) -> None:
"""Тело совпадает со схемой контракта, `id` и время — в его формате."""
errors = sorted(
validator(schema).iter_errors(body),
key=lambda error: list(map(str, error.path)),
)
assert not errors, f"{schema} schema: " + "; ".join(
f"/{'/'.join(map(str, error.path))}: {error.message}"
for error in errors
)
check_formats(body)
def check_formats(value: Any, path: str = "") -> None:
if isinstance(value, dict):
for key, item in value.items():
where = f"{path}/{key}"
if key in ID_KEYS:
assert_uuid(item, where)
elif key == "member_ids":
for number, member in enumerate(item):
assert_uuid(member, f"{where}/{number}")
elif key == "created_at":
assert_created_at(item, where)
else:
check_formats(item, where)
elif isinstance(value, list):
for number, item in enumerate(value):
check_formats(item, f"{path}/{number}")
def assert_uuid(value: Any, where: str = "id") -> None:
assert isinstance(value, str) and UUID_RE.fullmatch(value), (
f"{where}: {value!r} is not a lowercase UUID"
)
def assert_created_at(value: Any, where: str = "created_at") -> None:
assert isinstance(value, str) and CREATED_AT_RE.fullmatch(value), (
f"{where}: {value!r} is not RFC 3339 UTC with microseconds and Z"
)
parsed = datetime.fromisoformat(value)
assert parsed.utcoffset() == timedelta(0), f"{where}: {value!r} not UTC"
def assert_ok(resp: httpx.Response, status: int, schema: str) -> Any:
"""Успешный ответ: статус, JSON, `X-Request-Id`, тело по схеме."""
assert resp.status_code == status, describe(resp, f"expected {status}")
body = json_body(resp)
check_body(body, schema)
return body
def assert_error(resp: httpx.Response, status: int) -> dict[str, Any]:
"""Ошибка в формате контракта; `code` соответствует статусу."""
assert resp.status_code == status, describe(resp, f"expected {status}")
body = json_body(resp)
check_body(body, "Error")
error = body["error"]
assert error["code"] == ERROR_CODES[status], describe(
resp,
f"expected code {ERROR_CODES[status]}",
)
assert error["message"].strip(), describe(resp, "empty message")
assert not LEAK_RE.search(error["message"]), describe(
resp,
"message reveals internals",
)
assert error["request_id"] == resp.headers["X-Request-Id"], describe(
resp,
"request_id differs from X-Request-Id",
)
return error
def json_body(resp: httpx.Response) -> Any:
"""JSON-тело в UTF-8 и непустой `X-Request-Id`."""
request_id = resp.headers.get("X-Request-Id", "")
assert request_id.strip(), describe(resp, "no X-Request-Id")
media_type, _, params = resp.headers.get("Content-Type", "").partition(
";",
)
assert media_type.strip() == "application/json", describe(
resp,
"Content-Type is not application/json",
)
charset = params.strip().lower().removeprefix("charset=")
assert charset in ("", "utf-8"), describe(resp, f"charset {charset}")
return json.loads(resp.content.decode("utf-8"))
def describe(resp: httpx.Response, problem: str) -> str:
return (
f"{resp.request.method} {resp.request.url.path}: {problem}; "
f"got {resp.status_code} {resp.text[:300]}"
)