Files
mtusi2026lab3/student-tests/test_pagination.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

164 lines
5.0 KiB
Python

"""Спек `pagination`: `limit`, `next_cursor`, курсоры обоих списков."""
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
import httpx
import pytest
from api_client import Actor, Api, order_key
from contract import assert_error, assert_ok
@dataclass(frozen=True)
class Listing:
"""Постраничный список: запрос страницы и схема ответа."""
page: Callable[..., httpx.Response]
schema: str
@pytest.fixture(params=["messages", "chats"])
def listing(
request: pytest.FixtureRequest,
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> Listing:
"""История чата или список чатов Алисы: правила `limit` общие."""
if request.param == "messages":
return Listing(
page=lambda **params: api.messages_page(
alice,
chat["id"],
**params,
),
schema="MessagePage",
)
return Listing(
page=lambda **params: api.chats_page(alice, **params),
schema="ChatPage",
)
def fill(api: Api, actor: Actor, chat_id: str, count: int) -> list[dict]:
return [
api.send_message(actor, chat_id, f"page-{number}")
for number in range(count)
]
@pytest.mark.spec("pagination", "Ноль")
def test_limit_zero(listing: Listing) -> None:
assert_error(listing.page(limit=0), 400)
@pytest.mark.spec("pagination", "Больше максимума и не число")
def test_limit_out_of_range(listing: Listing) -> None:
for limit in (101, -1, "abc", "1.5"):
assert_error(listing.page(limit=limit), 400)
# границы диапазона допустимы
for limit in (1, 100):
assert_ok(listing.page(limit=limit), 200, listing.schema)
@pytest.mark.spec("pagination", "По умолчанию")
def test_default_limit(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
fill(api, alice, chat["id"], 60)
page = assert_ok(
api.messages_page(alice, chat["id"]),
200,
"MessagePage",
)
assert len(page["items"]) == 50
assert page["next_cursor"]
@pytest.mark.spec("pagination", "Последняя полная страница")
def test_last_full_page(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
sent = fill(api, alice, chat["id"], 2)
page = assert_ok(
api.messages_page(alice, chat["id"], limit=2),
200,
"MessagePage",
)
assert page["items"] == sorted(sent, key=order_key)
assert page["next_cursor"] is None
@pytest.mark.spec("pagination", "Полный обход")
def test_full_walk(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
sent = fill(api, alice, chat["id"], 7)
pages = api.message_pages(alice, chat["id"], limits=(3, 2))
assert [len(page["items"]) for page in pages] == [3, 2, 2]
items = [item for page in pages for item in page["items"]]
assert items == sorted(sent, key=order_key)
def test_chat_list_walk(api: Api, alice: Actor, bob: Actor) -> None:
"""Список чатов обходится так же, как история."""
created = [api.create_chat(alice, bob, title=f"c{n}") for n in range(5)]
pages = api.chat_pages(bob, limits=(2,))
items = [item for page in pages for item in page["items"]]
assert items == sorted(created, key=order_key)
@pytest.mark.spec("pagination", "Курсор другого чата")
def test_cursor_of_other_chat(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
other = api.create_chat(alice, bob, title="B")
fill(api, alice, chat["id"], 2)
fill(api, alice, other["id"], 2)
first = assert_ok(
api.messages_page(alice, chat["id"], limit=1),
200,
"MessagePage",
)
resp = api.messages_page(
alice,
other["id"],
limit=1,
cursor=first["next_cursor"],
)
assert_error(resp, 400)
def test_cursor_of_other_list(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
"""Курсор списка чатов не подходит истории, и наоборот."""
api.create_chat(alice, bob)
fill(api, alice, chat["id"], 2)
chats_cursor = assert_ok(
api.chats_page(alice, limit=1),
200,
"ChatPage",
)["next_cursor"]
history_cursor = assert_ok(
api.messages_page(alice, chat["id"], limit=1),
200,
"MessagePage",
)["next_cursor"]
assert chats_cursor
assert history_cursor
assert_error(
api.messages_page(alice, chat["id"], cursor=chats_cursor),
400,
)
assert_error(api.chats_page(alice, cursor=history_cursor), 400)
@pytest.mark.spec("pagination", "Повреждённый курсор")
def test_garbage_cursor(listing: Listing) -> None:
# eyJ4IjoxfQ — корректный base64 от {"x":1}, но не курсор сервиса
for cursor in ("garbage", "eyJ4IjoxfQ", "!!!"):
assert_error(listing.page(cursor=cursor), 400)