"""Спек `api-conventions`: JSON, ошибки, X-Request-Id, форматы.""" import json from typing import Any import pytest from api_client import API, Actor, Api, registration, 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=registration(alice.username, "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=registration("ab", "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={**registration(unique_username(), "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=registration(username, 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"])