forked from mtusi2026/mtusi2026lab5
89 lines
2.7 KiB
Python
89 lines
2.7 KiB
Python
import base64
|
|
from uuid import uuid4
|
|
|
|
from httpx import AsyncClient
|
|
|
|
PASSWORD = "Correct-horse-battery-1"
|
|
|
|
|
|
def basic_header(username: str, password: str) -> dict[str, str]:
|
|
raw = f"{username}:{password}".encode()
|
|
return {"Authorization": "Basic " + base64.b64encode(raw).decode()}
|
|
|
|
|
|
def bearer(actor: dict) -> dict[str, str]:
|
|
return {"Authorization": "Bearer " + actor["token"]}
|
|
|
|
|
|
async def register(
|
|
client: AsyncClient,
|
|
username: str | None = None,
|
|
display_name: str = "Тестовый пользователь",
|
|
password: str = PASSWORD,
|
|
) -> dict:
|
|
"""Регистрация без входа. Возвращает User + password (нужен для login)."""
|
|
actual_username = username or "user_" + uuid4().hex[:12]
|
|
response = await client.post(
|
|
"/api/v1/users",
|
|
json={
|
|
"username": actual_username,
|
|
"display_name": display_name,
|
|
"password": password,
|
|
},
|
|
)
|
|
assert response.status_code == 201, response.text
|
|
return {**response.json(), "password": password}
|
|
|
|
|
|
async def login(client: AsyncClient, user: dict) -> dict:
|
|
response = await client.post(
|
|
"/api/v1/auth/sessions",
|
|
headers=basic_header(user["username"], user["password"]),
|
|
)
|
|
assert response.status_code == 201, response.text
|
|
return {**user, "token": response.json()["token"]}
|
|
|
|
|
|
async def create_user(client: AsyncClient, **kwargs) -> dict:
|
|
"""Регистрация + вход: актор с полями id, username, token, ..."""
|
|
return await login(client, await register(client, **kwargs))
|
|
|
|
|
|
async def create_chat(
|
|
client: AsyncClient,
|
|
user: dict,
|
|
*members: dict,
|
|
title: str = "Тестовый чат",
|
|
) -> dict:
|
|
member_ids = [user["id"], *(member["id"] for member in members)]
|
|
response = await client.post(
|
|
"/api/v1/chats",
|
|
headers=bearer(user),
|
|
json={"title": title, "member_ids": member_ids},
|
|
)
|
|
assert response.status_code == 201, response.text
|
|
return response.json()
|
|
|
|
|
|
def idempotency_header(key: str | None = None) -> dict[str, str]:
|
|
return {"Idempotency-Key": key or uuid4().hex}
|
|
|
|
|
|
async def send_message(
|
|
client: AsyncClient, user: dict, chat: dict, text: str, key: str | None = None
|
|
):
|
|
"""POST сообщения требует Idempotency-Key; по умолчанию — новый ключ."""
|
|
return await client.post(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
headers={**bearer(user), **idempotency_header(key)},
|
|
json={"text": text},
|
|
)
|
|
|
|
|
|
def assert_request_id(response) -> str:
|
|
header_id = response.headers.get("X-Request-Id")
|
|
assert header_id
|
|
if response.status_code >= 400:
|
|
assert response.json()["error"]["request_id"] == header_id
|
|
return header_id
|