"""Shared fixtures: an isolated in-process app per test + OpenAPI schema validation.""" from __future__ import annotations import json import os import sys import uuid from pathlib import Path import pytest from jsonschema import Draft202012Validator from starlette.testclient import TestClient ROOT = Path(__file__).resolve().parents[1] # MESSENGER_SRC lets scripts/race_mutation_check.py run the same tests against a patched copy. sys.path.insert(0, os.environ.get("MESSENGER_SRC", str(ROOT / "src"))) from messenger.app import create_app # noqa: E402 from messenger.config import Settings # noqa: E402 SPEC = json.loads((ROOT / "contracts" / "openapi.json").read_text(encoding="utf-8")) SETTINGS = Settings(host="127.0.0.1", port=8080, env="test", log_level="warning", shutdown_timeout=1.0, max_body_bytes=64 * 1024) def schema_errors(value, name: str) -> list[str]: """Validate against components/schemas/ of the course contract (JSON Schema 2020-12).""" schema = {"$ref": f"#/components/schemas/{name}", "components": SPEC["components"]} validator = Draft202012Validator(schema, format_checker=Draft202012Validator.FORMAT_CHECKER) return [e.message for e in validator.iter_errors(value)] class Api: """Thin helper over TestClient that checks the invariants every response must satisfy.""" def __init__(self, client: TestClient): self.client = client def call(self, method: str, path: str, expected: int, *, user=None, json_body=None, raw=None, headers=None, schema=None): h = dict(headers or {}) if user is not None: h["X-User-Id"] = user["id"] if json_body is not None: raw = json.dumps(json_body, ensure_ascii=False).encode("utf-8") h.setdefault("Content-Type", "application/json") response = self.client.request(method, path, content=raw, headers=h) assert response.status_code == expected, (method, path, response.status_code, response.text) request_id = response.headers.get("x-request-id") assert request_id, "every response must carry X-Request-Id" if response.status_code >= 400: body = response.json() assert schema_errors(body, "Error") == [] assert body["error"]["request_id"] == request_id assert "Traceback" not in response.text elif schema: assert schema_errors(response.json(), schema) == [], response.text return response def user(self, label: str = "u", display_name: str | None = None) -> dict: body = {"username": f"{label}_{uuid.uuid4().hex[:10]}", "display_name": display_name or f"Студент {label}"} return self.call("POST", "/api/v1/users", 201, json_body=body, schema="User").json() def chat(self, owner: dict, *members: dict, title: str = "Тестовый чат") -> dict: ids = [owner["id"], *(m["id"] for m in members)] return self.call("POST", "/api/v1/chats", 201, user=owner, json_body={"title": title, "member_ids": ids}, schema="Chat").json() def send(self, user: dict, chat: dict, text: str) -> dict: return self.call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, user=user, json_body={"text": text}, schema="Message").json() def history(self, user: dict, chat: dict, limit: int) -> tuple[list[dict], int]: """Walk all pages; returns (items, number_of_pages).""" items, pages, cursor = [], 0, None while True: query = f"?limit={limit}" + (f"&cursor={cursor}" if cursor else "") page = self.call("GET", f"/api/v1/chats/{chat['id']}/messages{query}", 200, user=user, schema="MessagePage").json() pages += 1 items.extend(page["items"]) cursor = page["next_cursor"] if cursor is None: return items, pages assert len(page["items"]) == limit, "a non-final page must be full" @pytest.fixture def app(): return create_app(SETTINGS) @pytest.fixture def api(app) -> Api: with TestClient(app, raise_server_exceptions=False) as client: yield Api(client)