363 lines
14 KiB
Python
363 lines
14 KiB
Python
"""Короткие обёртки над API. Проверка формы ответа — здесь, а не в каждом тесте.
|
||
|
||
Пользователь теста — «актёр»: словарь `User` из ответа API плюс его
|
||
синтетический пароль (`password`) и токен текущей сессии (`token`).
|
||
Для сравнения с ответами API — `public(actor)`. Пароли и токены
|
||
синтетические и никуда не печатаются.
|
||
|
||
С лабы 3 отправка сообщения — только через `send()`: по умолчанию новый
|
||
`Idempotency-Key` на каждый вызов, `key=None` — без заголовка, строка —
|
||
этот ключ. Прямой POST без ключа получил бы 400 раньше проверки, которую
|
||
хочет увидеть тест (404 постороннему, 401 после выхода). С лабы 4 —
|
||
`attachment_ids=` у `send()` и загрузка `upload()` / `uploaded()`.
|
||
"""
|
||
|
||
import base64
|
||
import hashlib
|
||
from collections.abc import Callable, Iterable
|
||
from pathlib import Path
|
||
from typing import Any
|
||
from uuid import uuid4
|
||
|
||
import httpx
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
USERS = "/api/v1/users"
|
||
ME = f"{USERS}/me"
|
||
CHATS = "/api/v1/chats"
|
||
ATTACHMENTS = "/api/v1/attachments"
|
||
SESSIONS = "/api/v1/auth/sessions"
|
||
CURRENT_SESSION = f"{SESSIONS}/current"
|
||
# синтетические изображения: PNG skeleton 320×200 и JPEG, сделанный из него
|
||
SAMPLE_PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||
SAMPLE_JPEG = (ROOT / "student-tests" / "fixtures" / "sample.jpg").read_bytes()
|
||
ATTACHMENT_FIELDS = frozenset(
|
||
{
|
||
"id",
|
||
"chat_id",
|
||
"owner_id",
|
||
"filename",
|
||
"content_type",
|
||
"size_bytes",
|
||
"sha256",
|
||
"status",
|
||
"variants",
|
||
"error_code",
|
||
"created_at",
|
||
"updated_at",
|
||
}
|
||
)
|
||
# WWW-Authenticate у 401 (contracts/README.md): вход и остальные запросы
|
||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||
USER_FIELDS = frozenset({"id", "username", "display_name", "created_at"})
|
||
IDEMPOTENCY_KEY = "Idempotency-Key"
|
||
INSTANCE_ID = "X-Instance-Id"
|
||
# «нет аргумента» у send(): None значит «без заголовка ключа»
|
||
NEW_KEY = object()
|
||
|
||
# фикстура new_client: каждый вызов — новый клиент со своим соединением
|
||
type ClientFactory = Callable[[], httpx.Client]
|
||
|
||
|
||
def headers(actor: dict[str, Any]) -> dict[str, str]:
|
||
"""Идентификация с лабы 2: Bearer-токен сессии. Собирается только здесь."""
|
||
return bearer_header(actor["token"])
|
||
|
||
|
||
def bearer_header(token: str) -> dict[str, str]:
|
||
return {"Authorization": f"Bearer {token}"}
|
||
|
||
|
||
def basic_header(username: str, password: str) -> dict[str, str]:
|
||
"""`Authorization: Basic` из username и пароля в UTF-8."""
|
||
return basic_raw(f"{username}:{password}".encode())
|
||
|
||
|
||
def basic_raw(raw: bytes) -> dict[str, str]:
|
||
"""`Authorization: Basic` из произвольных байтов, в том числе битых."""
|
||
return {"Authorization": "Basic " + base64.b64encode(raw).decode("ascii")}
|
||
|
||
|
||
def unique_username(label: str) -> str:
|
||
# состояние стенда общее: username не должен повторяться
|
||
return f"{label}_{uuid4().hex[:12]}"
|
||
|
||
|
||
def unique_password() -> str:
|
||
"""Синтетический пароль 12–128 символов, свой у каждого вызова."""
|
||
return f"pw-{uuid4().hex}"
|
||
|
||
|
||
def public(actor: dict[str, Any]) -> dict[str, Any]:
|
||
"""Поля `User` из контракта: без пароля и токена теста."""
|
||
return {key: actor[key] for key in USER_FIELDS}
|
||
|
||
|
||
def login_response(
|
||
client: httpx.Client, username: str, password: str
|
||
) -> httpx.Response:
|
||
return client.post(SESSIONS, headers=basic_header(username, password))
|
||
|
||
|
||
def login(client: httpx.Client, actor: dict[str, Any]) -> str:
|
||
"""Новая сессия пользователя; ответ проверяется по форме `Session`."""
|
||
response = login_response(client, actor["username"], actor["password"])
|
||
assert response.status_code == 201, response.text
|
||
session = response.json()
|
||
assert set(session) == {"token", "token_type", "expires_at", "user"}
|
||
assert session["token_type"] == "Bearer"
|
||
assert session["expires_at"].endswith("Z")
|
||
assert session["user"] == public(actor)
|
||
assert len(session["token"]) >= 32
|
||
return session["token"]
|
||
|
||
|
||
def logout(client: httpx.Client, actor: dict[str, Any]) -> httpx.Response:
|
||
return client.delete(CURRENT_SESSION, headers=headers(actor))
|
||
|
||
|
||
def register(
|
||
client: httpx.Client,
|
||
label: str = "user",
|
||
*,
|
||
password: str | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Регистрация с паролем и сразу вход: у актёра есть токен."""
|
||
password = password or unique_password()
|
||
body = {
|
||
"username": unique_username(label),
|
||
"display_name": f"Тест {label}",
|
||
"password": password,
|
||
}
|
||
response = client.post(USERS, json=body)
|
||
assert response.status_code == 201, response.text
|
||
user = response.json()
|
||
# пароля и его хэша в ответе нет: только поля User
|
||
assert set(user) == USER_FIELDS
|
||
assert user["username"] == body["username"]
|
||
actor = {**user, "password": password}
|
||
actor["token"] = login(client, actor)
|
||
return actor
|
||
|
||
|
||
def create_chat(
|
||
client: httpx.Client,
|
||
owner: dict[str, Any],
|
||
*others: dict[str, Any],
|
||
title: str = "Тестовый чат",
|
||
) -> dict[str, Any]:
|
||
member_ids = [owner["id"], *(user["id"] for user in others)]
|
||
response = client.post(
|
||
CHATS,
|
||
json={"title": title, "member_ids": member_ids},
|
||
headers=headers(owner),
|
||
)
|
||
assert response.status_code == 201, response.text
|
||
return response.json()
|
||
|
||
|
||
def messages_path(chat: dict[str, Any]) -> str:
|
||
return f"{CHATS}/{chat['id']}/messages"
|
||
|
||
|
||
def new_key() -> str:
|
||
"""Свой Idempotency-Key у каждого вызова: ASCII из шаблона контракта."""
|
||
return f"key-{uuid4().hex}"
|
||
|
||
|
||
def send(
|
||
client: httpx.Client,
|
||
user: dict[str, Any],
|
||
chat: dict[str, Any],
|
||
text: str,
|
||
*,
|
||
key: Any = NEW_KEY,
|
||
attachment_ids: list[str] | None = None,
|
||
) -> httpx.Response:
|
||
"""POST сообщения с ключом идемпотентности (лаба 3).
|
||
|
||
`key` не задан — новый ключ; `None` — без заголовка; строка или байты
|
||
— этот ключ (байты — для не-ASCII значений, httpx шлёт их как есть).
|
||
`attachment_ids` (лаба 4) не задан — поля в теле нет.
|
||
"""
|
||
request_headers = headers(user)
|
||
if key is NEW_KEY:
|
||
key = new_key()
|
||
if key is not None:
|
||
request_headers[IDEMPOTENCY_KEY] = key
|
||
body: dict[str, Any] = {"text": text}
|
||
if attachment_ids is not None:
|
||
body["attachment_ids"] = attachment_ids
|
||
return client.post(messages_path(chat), json=body, headers=request_headers)
|
||
|
||
|
||
def attachments_path(chat: dict[str, Any]) -> str:
|
||
return f"{CHATS}/{chat['id']}/attachments"
|
||
|
||
|
||
def upload(
|
||
client: httpx.Client,
|
||
user: dict[str, Any] | None,
|
||
chat: dict[str, Any],
|
||
data: Any = SAMPLE_PNG,
|
||
*,
|
||
content_type: str | None = "image/png",
|
||
filename: str | None = "sample.png",
|
||
query: str | None = None,
|
||
) -> httpx.Response:
|
||
"""POST вложения: сырые байты (или итератор блоков), не multipart.
|
||
|
||
`user=None` — без идентификации; `content_type=None` — без заголовка;
|
||
`query` — строка запроса как есть (вместо `filename`), для проверок
|
||
кодировки имени.
|
||
"""
|
||
request_headers = headers(user) if user else {}
|
||
if content_type is not None:
|
||
request_headers["Content-Type"] = content_type
|
||
url = attachments_path(chat)
|
||
if query is not None:
|
||
url += "?" + query
|
||
params = None
|
||
else:
|
||
params = {"filename": filename} if filename is not None else None
|
||
return client.post(url, params=params, content=data, headers=request_headers)
|
||
|
||
|
||
def uploaded(
|
||
client: httpx.Client,
|
||
user: dict[str, Any],
|
||
chat: dict[str, Any],
|
||
data: bytes = SAMPLE_PNG,
|
||
*,
|
||
content_type: str = "image/png",
|
||
filename: str = "sample.png",
|
||
) -> dict[str, Any]:
|
||
"""Загрузка, которая должна пройти: 201 и `Attachment` по контракту."""
|
||
response = upload(
|
||
client, user, chat, data, content_type=content_type, filename=filename
|
||
)
|
||
assert response.status_code == 201, response.text
|
||
attachment = response.json()
|
||
assert set(attachment) == ATTACHMENT_FIELDS
|
||
assert attachment["status"] == "ready"
|
||
assert attachment["variants"] == []
|
||
assert attachment["error_code"] is None
|
||
assert attachment["chat_id"] == chat["id"]
|
||
assert attachment["owner_id"] == user["id"]
|
||
assert attachment["filename"] == filename
|
||
assert attachment["content_type"] == content_type
|
||
assert attachment["size_bytes"] == len(data)
|
||
assert attachment["sha256"] == hashlib.sha256(data).hexdigest()
|
||
instance_id(response)
|
||
return attachment
|
||
|
||
|
||
def attachment_meta(
|
||
client: httpx.Client, user: dict[str, Any] | None, attachment_id: str
|
||
) -> httpx.Response:
|
||
return client.get(
|
||
f"{ATTACHMENTS}/{attachment_id}", headers=headers(user) if user else {}
|
||
)
|
||
|
||
|
||
def attachment_content(
|
||
client: httpx.Client, user: dict[str, Any] | None, attachment_id: str, **params: str
|
||
) -> httpx.Response:
|
||
return client.get(
|
||
f"{ATTACHMENTS}/{attachment_id}/content",
|
||
params=params or None,
|
||
headers=headers(user) if user else {},
|
||
)
|
||
|
||
|
||
def assert_content(response: httpx.Response, data: bytes, content_type: str) -> None:
|
||
"""Байты оригинала через API: тот же SHA-256, истинный тип, без redirect."""
|
||
assert response.status_code == 200, response.text
|
||
assert response.content == data
|
||
assert response.headers["content-type"] == content_type
|
||
assert response.headers["content-length"] == str(len(data))
|
||
assert response.headers["x-content-type-options"] == "nosniff"
|
||
assert "location" not in response.headers
|
||
assert not any(name.lower().startswith("x-amz-") for name in response.headers)
|
||
instance_id(response)
|
||
|
||
|
||
def instance_id(response: httpx.Response) -> str:
|
||
"""X-Instance-Id ответа API: непустой у каждого ответа (с лабы 3)."""
|
||
value = response.headers.get(INSTANCE_ID, "")
|
||
assert value, f"missing {INSTANCE_ID} on {response.status_code}"
|
||
return value
|
||
|
||
|
||
def assert_replicas(seen: Iterable[str], expected: int) -> None:
|
||
"""Ответы пришли не меньше чем от двух реплик (если их ≥ 2 за BASE_URL)."""
|
||
distinct = set(seen)
|
||
assert len(distinct) >= min(expected, 2), (
|
||
f"{len(distinct)} replica(s) answered, expected at least "
|
||
f"{min(expected, 2)} of {expected}"
|
||
)
|
||
|
||
|
||
def read_history(
|
||
client: httpx.Client,
|
||
user: dict[str, Any],
|
||
chat: dict[str, Any],
|
||
*,
|
||
limit: int,
|
||
) -> tuple[list[dict[str, Any]], list[int]]:
|
||
"""Вся история обходом по курсору: сообщения и размеры страниц."""
|
||
items: list[dict[str, Any]] = []
|
||
sizes: list[int] = []
|
||
params: dict[str, Any] = {"limit": limit}
|
||
while True:
|
||
response = client.get(messages_path(chat), params=params, headers=headers(user))
|
||
assert response.status_code == 200, response.text
|
||
page = response.json()
|
||
assert set(page) == {"items", "next_cursor"}
|
||
items.extend(page["items"])
|
||
sizes.append(len(page["items"]))
|
||
if page["next_cursor"] is None:
|
||
return items, sizes
|
||
params = {"limit": limit, "cursor": page["next_cursor"]}
|
||
|
||
|
||
def chat_ids(client: httpx.Client, user: dict[str, Any]) -> list[str]:
|
||
"""Id всех чатов пользователя обходом списка по курсору."""
|
||
ids: list[str] = []
|
||
params: dict[str, Any] = {"limit": 100}
|
||
while True:
|
||
response = client.get(CHATS, params=params, headers=headers(user))
|
||
assert response.status_code == 200, response.text
|
||
page = response.json()
|
||
ids.extend(item["id"] for item in page["items"])
|
||
if page["next_cursor"] is None:
|
||
return ids
|
||
params = {"limit": 100, "cursor": page["next_cursor"]}
|
||
|
||
|
||
def assert_error(response: httpx.Response, status: int, code: str) -> dict[str, Any]:
|
||
"""Ошибка API в формате контракта; request_id совпадает с заголовком.
|
||
|
||
Ошибку создаёт API, поэтому у неё есть и X-Instance-Id (ответы самого
|
||
HAProxy — 502/503/504 — тесты здесь не проверяют).
|
||
"""
|
||
assert response.status_code == status, response.text
|
||
assert response.headers["content-type"].startswith("application/json")
|
||
body = response.json()
|
||
assert set(body) == {"error"}
|
||
error = body["error"]
|
||
assert set(error) == {"code", "message", "request_id"}
|
||
assert error["code"] == code
|
||
assert error["message"]
|
||
assert error["request_id"] == response.headers["X-Request-Id"]
|
||
instance_id(response)
|
||
return error
|
||
|
||
|
||
def assert_unauthorized(response: httpx.Response, challenge: str) -> dict[str, Any]:
|
||
"""401 в формате контракта с нужным вызовом в `WWW-Authenticate`."""
|
||
error = assert_error(response, 401, "unauthorized")
|
||
assert response.headers.get("WWW-Authenticate") == challenge
|
||
return error
|