Files
mtusi2026lab3/student-tests/test_api_conventions.py
T
ricoromaandClaude Opus 5.5 af4bca08c9 feat: carry lab 2 over and add X-Instance-Id and idempotency keys
- carry the lab 2 solution over and plan lab 3 (PLAN.md, OpenSpec
  change instance-id-idempotency)
- rename the compose project to mtusi-lab3 and the image to :lab3
- add X-Instance-Id to every response and instance_id to every log
  record ([app] instance_id, hostname by default)
- require Idempotency-Key on POST messages: keys table in Postgres,
  key and message in one transaction, replay returns the same 201,
  another body gets 409, TTL from [idempotency] ttl_seconds
- send the key from student-tests, k6 scenarios and the skill driver;
  add idempotency, X-Instance-Id, key race and fault tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 19:42:36 +03:00

245 lines
8.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Спек `api-conventions`: JSON, ошибки, X-Request-Id, X-Instance-Id,
форматы."""
import json
from typing import Any
import httpx
import pytest
from api_client import (
API,
Actor,
Api,
new_key,
registration,
unique_username,
)
from contract import (
assert_created_at,
assert_error,
assert_instance_id,
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.post_message(alice, chat["id"], 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
def business_responses(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> list[tuple[httpx.Response, int]]:
"""Успехи 200 и 201 и ошибки 400, 401, 404 и 409 — с ожидаемым
статусом."""
key = new_key()
sent = api.post_message(alice, chat["id"], key=key, json={"text": "a"})
return [
(api.request("GET", f"{API}/users/me", actor=alice), 200),
(sent, 201),
(api.request("GET", f"{API}/chats/nope", actor=alice), 400),
(api.request("GET", f"{API}/users/me"), 401),
(api.request("GET", f"{API}/chats/{chat['id']}", actor=eve), 404),
(
api.post_message(alice, chat["id"], key=key, json={"text": "b"}),
409,
),
]
def service_responses(api: Api) -> list[tuple[httpx.Response, int]]:
"""Health, неизвестный путь и неподдерживаемый метод."""
return [
(api.request("GET", "/health/live"), 200),
(api.request("GET", "/health/ready"), 200),
(api.request("GET", f"{API}/unknown"), 404),
(api.request("DELETE", f"{API}/users"), 405),
]
@pytest.mark.spec("api-conventions", "Instance id в успешном ответе и ошибке")
def test_instance_id_on_success_and_error(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
for resp, status in business_responses(api, alice, eve, chat):
assert resp.status_code == status, resp.text
assert_instance_id(resp)
@pytest.mark.spec(
"api-conventions",
"Instance id в health и служебных ответах",
)
def test_instance_id_on_service_responses(api: Api) -> None:
for resp, status in service_responses(api):
assert resp.status_code == status, resp.text
assert_instance_id(resp)
@pytest.mark.spec("api-conventions", "Одно значение на процесс")
def test_one_instance_id_per_process(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
# набор этого change идёт против одного процесса API (make
# test_isolated, консоль); стенд с балансировщиком — change replicas-lb
responses = business_responses(api, alice, eve, chat)
responses += service_responses(api)
values = {assert_instance_id(resp) for resp, _ in responses}
assert len(values) == 1, f"one process answered with {values}"
@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"])