import json import os from pathlib import Path from uuid import uuid4 import httpx import pytest from jsonschema import Draft202012Validator, FormatChecker CONTRACT = json.loads( (Path(__file__).parents[1] / "contracts/openapi.json").read_text() ) BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8085") PASSWORD = "Synthetic-Password-🌍-123" TOKENS = {} def check(result: httpx.Response, status: int, schema: str) -> dict: assert result.status_code == status, result.text assert result.headers["x-request-id"] assert result.headers["x-instance-id"] assert result.headers["content-type"].startswith("application/json") payload = result.json() spec = {"$ref": f"#/components/schemas/{schema}", **CONTRACT} Draft202012Validator(spec, format_checker=FormatChecker()).validate( payload ) if schema == "Error": assert payload["error"]["request_id"] == result.headers["x-request-id"] assert ( payload["error"]["code"] == { 400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type", 429: "rate_limited", 500: "internal_error", 503: "unavailable", }[status] ) return payload def register(client: httpx.Client, **overrides) -> dict: data = { "username": "u_" + uuid4().hex[:24], "display_name": "Алиса 🌍", "password": PASSWORD, } data.update(overrides) user = check(client.post("/api/v1/users", json=data), 201, "User") session = check( client.post( "/api/v1/auth/sessions", auth=httpx.BasicAuth(data["username"], data["password"]), ), 201, "Session", ) TOKENS[user["id"]] = session["token"] return user @pytest.fixture def client(): with httpx.Client( base_url=BASE_URL, timeout=15, trust_env=False ) as client: yield client @pytest.fixture def actors(client): return register(client), register(client), register(client) @pytest.fixture def chat(client, actors): alice, bob, _ = actors return check( client.post( "/api/v1/chats", headers=headers(alice), json={"title": "Учёба 🌍", "member_ids": [alice["id"], bob["id"]]}, ), 201, "Chat", ) def headers(actor: dict) -> dict: return { "Authorization": "Bearer " + TOKENS[actor["id"]], "Idempotency-Key": uuid4().hex, } def history(client, actor, chat_id, limit=7): found, cursor = [], None while True: params = {"limit": limit} if cursor: params["cursor"] = cursor page = check( client.get( f"/api/v1/chats/{chat_id}/messages", headers=headers(actor), params=params, ), 200, "MessagePage", ) found.extend(page["items"]) cursor = page["next_cursor"] if cursor is None: return found