82 lines
2.5 KiB
Python
82 lines
2.5 KiB
Python
import base64
|
|
from uuid import uuid4
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
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"]}
|
|
|
|
|
|
def register(
|
|
client: TestClient,
|
|
username: str | None = None,
|
|
display_name: str = "Тестовый пользователь",
|
|
password: str = PASSWORD,
|
|
) -> dict:
|
|
"""Регистрация без входа. Возвращает User + password (нужен для login)."""
|
|
actual_username = username or "user_" + uuid4().hex[:12]
|
|
response = 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}
|
|
|
|
|
|
def login(client: TestClient, user: dict) -> dict:
|
|
response = 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"]}
|
|
|
|
|
|
def create_user(client: TestClient, **kwargs) -> dict:
|
|
"""Регистрация + вход: актор с полями id, username, token, ..."""
|
|
return login(client, register(client, **kwargs))
|
|
|
|
|
|
def create_chat(
|
|
client: TestClient,
|
|
user: dict,
|
|
*members: dict,
|
|
title: str = "Тестовый чат",
|
|
) -> dict:
|
|
member_ids = [user["id"], *(member["id"] for member in members)]
|
|
response = 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 send_message(client: TestClient, user: dict, chat: dict, text: str):
|
|
return client.post(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
headers=bearer(user),
|
|
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
|