import json import os from collections.abc import Callable, Iterator from pathlib import Path import httpx import pytest from helpers import auth, basic, unique_password, unique_username ROOT = Path(__file__).resolve().parents[1] DEFAULT_BASE_URL = json.loads((ROOT / "lab.json").read_text())["default_base_url"] REQUEST_TIMEOUT_SEC = 10 @pytest.fixture(scope="session") def base_url() -> str: return os.environ.get("BASE_URL") or DEFAULT_BASE_URL @pytest.fixture(scope="session") def api(base_url: str) -> Iterator[httpx.Client]: with httpx.Client(base_url=base_url, timeout=REQUEST_TIMEOUT_SEC) as client: yield client def register_and_login( client: httpx.Client, label: str, display_name: str | None = None ) -> dict: """Регистрация и вход; в словаре User плюс token и password для тестов""" username = unique_username(label) password = unique_password() body = { "username": username, "display_name": display_name or f"Студент {label}", "password": password, } response = client.post("/api/v1/users", json=body) assert response.status_code == 201, response.text user = response.json() session = client.post("/api/v1/auth/sessions", headers=basic(username, password)) assert session.status_code == 201, session.text return {**user, "token": session.json()["token"], "password": password} @pytest.fixture def make_user(api: httpx.Client) -> Callable[..., dict]: def create(label: str = "user", display_name: str | None = None) -> dict: return register_and_login(api, label, display_name) return create @pytest.fixture def make_chat(api: httpx.Client) -> Callable[..., dict]: def create(owner: dict, members: list[dict], title: str = "Тестовый чат") -> dict: body = {"title": title, "member_ids": [member["id"] for member in members]} response = api.post("/api/v1/chats", json=body, headers=auth(owner)) assert response.status_code == 201, response.text return response.json() return create @pytest.fixture def send_message(api: httpx.Client) -> Callable[..., dict]: def send(user: dict, chat: dict, text: str) -> dict: response = api.post( f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=auth(user), ) assert response.status_code == 201, response.text return response.json() return send