Copy the committed lab 1 sources as-is: src/, student-tests/, bench/, Dockerfile, docker-compose.yml, pyproject.toml, uv.lock, .python-version, config_example.toml, AGENTS.md, CLAUDE.md, .claude/, openspec/, .graphifyignore and KNOWN_ISSUES.md. Lab 1 evidence stays in the lab 1 repository. Merge the new skeleton files with own sections: Makefile (lab 2 targets plus own run, docker, bench and common targets), .gitignore, .dockerignore and .env.example. Rename the image to mtusi-messenger:lab2 and point AGENTS.md at lab 2. The application is still the in-memory lab 1 implementation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
5.7 KiB
Python
174 lines
5.7 KiB
Python
"""Спек `api-conventions`: JSON, ошибки, X-Request-Id, форматы."""
|
|
|
|
import json
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
from api_client import API, Actor, Api, unique_username
|
|
from contract import (
|
|
assert_created_at,
|
|
assert_error,
|
|
assert_ok,
|
|
assert_uuid,
|
|
json_body,
|
|
)
|
|
|
|
UNICODE_TEXT = "Привет, мир 👋"
|
|
|
|
|
|
@pytest.mark.spec("api-conventions", "Unicode сохраняется")
|
|
def test_unicode_round_trip(api: Api, bob: Actor) -> None:
|
|
alice = api.register(display_name=UNICODE_TEXT)
|
|
chat = api.create_chat(alice, bob, title=UNICODE_TEXT)
|
|
resp = api.request(
|
|
"POST",
|
|
f"{API}/chats/{chat['id']}/messages",
|
|
actor=alice,
|
|
json={"text": UNICODE_TEXT},
|
|
)
|
|
message = assert_ok(resp, 201, "Message")
|
|
# тело разбирается из байтов как UTF-8, без догадок httpx о кодировке
|
|
assert json.loads(resp.content.decode("utf-8"))["text"] == UNICODE_TEXT
|
|
|
|
me = assert_ok(
|
|
api.request("GET", f"{API}/users/me", actor=alice),
|
|
200,
|
|
"User",
|
|
)
|
|
stored_chat = assert_ok(
|
|
api.request("GET", f"{API}/chats/{chat['id']}", actor=bob),
|
|
200,
|
|
"Chat",
|
|
)
|
|
history = api.all_messages(bob, chat["id"])
|
|
assert alice.user["display_name"] == me["display_name"] == UNICODE_TEXT
|
|
assert chat["title"] == stored_chat["title"] == UNICODE_TEXT
|
|
assert [item["text"] for item in history] == [message["text"]]
|
|
assert message["text"] == UNICODE_TEXT
|
|
|
|
|
|
@pytest.mark.spec("api-conventions", "Длина в code points")
|
|
def test_length_in_code_points(api: Api, alice: Actor) -> None:
|
|
title = "👋" * 100
|
|
assert len(title.encode("utf-8")) > 100
|
|
chat = api.create_chat(alice, title=title)
|
|
assert chat["title"] == title
|
|
|
|
|
|
@pytest.mark.spec("api-conventions", "Успешный ответ")
|
|
def test_request_id_on_success(api: Api, alice: Actor) -> None:
|
|
responses = [
|
|
api.request("GET", "/health/live"),
|
|
api.request("GET", f"{API}/users/me", actor=alice),
|
|
api.request("GET", f"{API}/chats", actor=alice),
|
|
]
|
|
for resp in responses:
|
|
assert resp.status_code == 200
|
|
assert resp.headers.get("X-Request-Id", "").strip()
|
|
|
|
|
|
@pytest.mark.spec("api-conventions", "Разные запросы")
|
|
def test_request_ids_differ(api: Api) -> None:
|
|
first = api.request("GET", "/health/live").headers["X-Request-Id"]
|
|
second = api.request("GET", "/health/live").headers["X-Request-Id"]
|
|
assert first != second
|
|
|
|
|
|
@pytest.mark.spec("api-conventions", "Ошибка содержит request_id заголовка")
|
|
def test_error_request_id_matches_header(
|
|
api: Api,
|
|
alice: Actor,
|
|
eve: Actor,
|
|
chat: dict[str, Any],
|
|
) -> None:
|
|
# assert_error сверяет error.request_id с заголовком у каждой ошибки
|
|
assert_error(api.request("GET", f"{API}/chats/nope", actor=alice), 400)
|
|
assert_error(api.request("GET", f"{API}/users/me"), 401)
|
|
assert_error(
|
|
api.request("GET", f"{API}/chats/{chat['id']}", actor=eve),
|
|
404,
|
|
)
|
|
assert_error(api.request("DELETE", f"{API}/users"), 405)
|
|
resp = api.request(
|
|
"POST",
|
|
f"{API}/users",
|
|
json={"username": alice.user["username"], "display_name": "Alice"},
|
|
)
|
|
assert_error(resp, 409)
|
|
|
|
|
|
@pytest.mark.spec("api-conventions", "Нет тела FastAPI по умолчанию")
|
|
def test_no_fastapi_detail(api: Api, alice: Actor) -> None:
|
|
validation = api.request(
|
|
"POST",
|
|
f"{API}/users",
|
|
json={"username": "ab", "display_name": "x"},
|
|
)
|
|
not_found = api.request("GET", f"{API}/unknown", actor=alice)
|
|
for resp, status in ((validation, 400), (not_found, 404)):
|
|
assert_error(resp, status)
|
|
assert list(json_body(resp)) == ["error"]
|
|
|
|
|
|
@pytest.mark.spec("api-conventions", "Неизвестный путь")
|
|
def test_unknown_path(api: Api) -> None:
|
|
assert_error(api.request("GET", f"{API}/unknown"), 404)
|
|
|
|
|
|
@pytest.mark.spec("api-conventions", "Неподдерживаемый метод")
|
|
def test_method_not_allowed(api: Api) -> None:
|
|
assert_error(api.request("DELETE", f"{API}/users"), 405)
|
|
|
|
|
|
@pytest.mark.spec("api-conventions", "Лишнее поле")
|
|
def test_extra_field(api: Api, alice: Actor) -> None:
|
|
resp = api.request(
|
|
"POST",
|
|
f"{API}/users",
|
|
json={
|
|
"username": unique_username(),
|
|
"display_name": "Extra",
|
|
"is_admin": True,
|
|
},
|
|
)
|
|
assert_error(resp, 400)
|
|
resp = api.request(
|
|
"POST",
|
|
f"{API}/chats",
|
|
actor=alice,
|
|
json={"title": "Extra", "member_ids": [alice.id], "topic": "x"},
|
|
)
|
|
assert_error(resp, 400)
|
|
|
|
|
|
@pytest.mark.spec("api-conventions", "Неверный тип без приведения")
|
|
def test_wrong_type_is_not_coerced(api: Api) -> None:
|
|
username = unique_username()
|
|
resp = api.request(
|
|
"POST",
|
|
f"{API}/users",
|
|
json={"username": username, "display_name": 123},
|
|
)
|
|
assert_error(resp, 400)
|
|
# пользователь не создан: то же имя свободно
|
|
user = api.register(username=username, display_name="123").user
|
|
assert user["display_name"] == "123"
|
|
|
|
|
|
@pytest.mark.spec("api-conventions", "Формат created_at")
|
|
@pytest.mark.spec("api-conventions", "Формат id")
|
|
def test_id_and_created_at_format(
|
|
api: Api,
|
|
alice: Actor,
|
|
chat: dict[str, Any],
|
|
) -> None:
|
|
message = api.send_message(alice, chat["id"], "format")
|
|
for obj in (alice.user, chat, message):
|
|
assert_uuid(obj["id"])
|
|
assert_created_at(obj["created_at"])
|
|
for member_id in chat["member_ids"]:
|
|
assert_uuid(member_id)
|
|
assert_uuid(message["chat_id"])
|
|
assert_uuid(message["sender_id"])
|