Files
mtusi2026lab4/student-tests/test_pagination.py
T
ricoromaandClaude Opus 5.5 5d5d8f9d2a chore: carry lab 3 over
- carry the lab 3 solution over from mtusi2026lab3-safronov
  (solution/bvt2301-safronov, ce89eba): src, migrations, student-tests,
  bench, openspec, .claude, infra/haproxy and infra/valkey, own scripts,
  Dockerfile, compose, pyproject and uv lock
- merge Makefile, .gitignore and .dockerignore (the lab 3 versions only
  add lines to the skeleton, which is the same in lab 4) and
  .env.example (lab 4 skeleton names listed in the header)
- rename the compose project to mtusi-lab4 and the image to :lab4 so
  the stand does not reuse the lab 3 containers and volumes
- update AGENTS.md for lab 4: current lab, origin commit, contract and
  test files of the new skeleton

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:32:33 +03:00

263 lines
9.1 KiB
Python

"""Спек `pagination`: `limit`, `next_cursor`, курсоры обоих списков."""
import base64
import json
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_errors, assert_ok
# подмена в содержимом курсора: какие поля заменить
type Change = Callable[[dict[str, Any]], dict[str, Any]]
# подмены выданного курсора, которые дают 400 (сценарий «Изменённый
# курсор»): ключ элемента не строка, тот же id в другой записи, версия
# не ровно целое 1
CURSOR_CHANGES: dict[str, Change] = {
"i=[]": lambda _: {"i": []},
"i={}": lambda _: {"i": {}},
"i=123": lambda _: {"i": 123},
"i=false": lambda _: {"i": False},
"i without hyphens": lambda payload: {"i": payload["i"].replace("-", "")},
"i upper case": lambda payload: {"i": payload["i"].upper()},
"v=true": lambda _: {"v": True},
"v=1.0": lambda _: {"v": 1.0},
}
# и которые принимаются: незнакомое поле игнорируется, иначе новое
# необязательное поле ломало бы курсоры при поочерёдной замене реплик
CURSOR_KEPT: dict[str, Change] = {
"unchanged": lambda _: {},
"extra field": lambda _: {"x": 1},
}
@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)
def cursor_payload(cursor: str) -> dict[str, Any]:
"""Содержимое курсора сервиса: base64url без `=` от JSON."""
padded = cursor + "=" * (-len(cursor) % 4)
return json.loads(base64.urlsafe_b64decode(padded))
def encode_payload(payload: dict[str, Any]) -> str:
"""Курсор из содержимого — так же, как его кодирует сервис."""
raw = json.dumps(payload, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
def tamper(cursor: str, change: Change) -> str:
"""Выданный курсор с одной подменой в содержимом.
Без подмены перекодирование обязано вернуть ту же строку: иначе формат
курсора изменился, и 400 на подмену ничего бы не доказывал.
"""
payload = cursor_payload(cursor)
assert encode_payload(payload) == cursor, (
f"cursor format changed, re-encoded payload differs: {payload}"
)
return encode_payload(payload | change(payload))
@dataclass(frozen=True)
class IssuedCursor:
"""Список и курсор его второй страницы, выданный сервером."""
listing: Listing
cursor: str
@pytest.fixture
def issued(
listing: Listing,
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> IssuedCursor:
"""В истории два сообщения, у Алисы два чата: у обоих списков есть
вторая страница при `limit=1`."""
fill(api, alice, chat["id"], 2)
api.create_chat(alice, bob, title="second")
first = assert_ok(listing.page(limit=1), 200, listing.schema)
assert first["next_cursor"], "no second page"
return IssuedCursor(listing=listing, cursor=first["next_cursor"])
@pytest.mark.spec("pagination", "Изменённый курсор")
def test_tampered_cursor(issued: IssuedCursor) -> None:
"""Курсор не собирается с нуля: с чужими `v` или `s` его отсекла бы
проверка версии или области раньше разбора ключа."""
page = issued.listing.page
schema = issued.listing.schema
# контроль: без подмены и с незнакомым полем — та же вторая страница
second = assert_ok(page(cursor=issued.cursor), 200, schema)
for name, change in CURSOR_KEPT.items():
kept = assert_ok(
page(cursor=tamper(issued.cursor, change)),
200,
schema,
)
assert kept == second, f"{name}: another page"
assert_errors(
{
name: page(cursor=tamper(issued.cursor, change))
for name, change in CURSOR_CHANGES.items()
},
400,
)