Files
mtusi2026lab3/student-tests/api/test_pagination.py
T
ArtyomandClaude Opus 5.5 a59e3a39a8 Carry over the lab 2 fixes made after 8cddb09
Brings the system changes of lab 2 from 8cddb09..102579e onto the lab 3
code, resolving each conflict by meaning:

- the request pipeline counts the body bytes actually received, so a
  chunked body over the limit gets 413 instead of reaching the app;
- logout revokes through a SessionRevocations port and withdraws the
  mark when PostgreSQL rejects the delete, so 503 means the session
  still works; PostgresSessionDirectory loses its no-op invalidate;
- an empty cursor is 400 on history and on the chat list;
- EventBus.project and the test that allowed importing an event across
  zones are gone, the config rules speak of the schema foreign key;
- the worker waits one second less than the rest of the shutdown
  budget, so it cancels a stuck request with 500 and exits 0 instead
  of being killed by the gunicorn master. Lab 3 keeps 3 s after the
  drain window for the database timeouts, so SHUTDOWN_TIMEOUT_SECONDS
  becomes 6 s and the stop hooks wait 7 s, still under the 8 s grace;
- the lab 3 single statement post already locks the chat only for a
  member, so lab 2's LOCK_CHAT edit is not needed; its test is kept;
- lab 2 tests come along with Idempotency-Key where lab 3 needs it;
  the short TTL after restart runs without api-shortttl by shortening
  the session in the database; test_drain adds a stuck request;
- make validate uses .venv with openapi-spec-validator, PYTEST_ARGS,
  faults-evidence, down with the bench profile, the image is tagged by
  the compose project, start probes every 200 ms, cache evidence fails
  without a tombstone and checks the key expiry, kdf.txt shows the
  seed stub apart.

The track 2 tooling of lab 2 (track.py, postgres-restore and the
database argument of migrate) and its evidence scripts stay out.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 02:32:49 +03:00

157 lines
6.1 KiB
Python

from urllib.parse import quote
import pytest
from httpx import AsyncClient
from conftest import actor, keyed, make_chat, register
TOTAL = 12
async def fill(client: AsyncClient, chat: dict, sender: dict, count: int) -> list[str]:
texts = []
for index in range(count):
text = f"сообщение {index:02d}"
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": text},
headers=keyed(sender),
)
assert response.status_code == 201, response.text
texts.append(text)
return texts
async def walk(client: AsyncClient, chat: dict, reader: dict, limits: list[int]) -> list[str]:
collected: list[str] = []
cursor: str | None = None
step = 0
while True:
limit = limits[min(step, len(limits) - 1)]
query = f"?limit={limit}"
if cursor:
query += f"&cursor={quote(cursor, safe='')}"
response = await client.get(
f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader)
)
assert response.status_code == 200, response.text
page = response.json()
assert len(page["items"]) <= limit
collected.extend(item["text"] for item in page["items"])
cursor = page["next_cursor"]
step += 1
if cursor is None:
return collected
async def test_full_walk_has_no_gaps_or_repeats(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
expected = await fill(client, chat, alice, TOTAL)
assert await walk(client, chat, bob, [5]) == expected
async def test_limit_may_change_between_pages(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
expected = await fill(client, chat, alice, TOTAL)
assert await walk(client, chat, alice, [1, 7, 3, 100]) == expected
async def test_last_page_closes_history(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
await fill(client, chat, alice, 2)
first = (
await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=2", headers=actor(alice))
).json()
assert len(first["items"]) == 2
assert first["next_cursor"] is None
async def test_cursor_is_shared_between_members(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
await fill(client, chat, alice, 3)
page = (
await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=actor(alice))
).json()
cursor = quote(page["next_cursor"], safe="")
response = await client.get(
f"/api/v1/chats/{chat['id']}/messages?limit=1&cursor={cursor}", headers=actor(bob)
)
assert response.status_code == 200
async def test_cursor_from_another_chat_is_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
first = await make_chat(client, alice)
second = await make_chat(client, alice)
await fill(client, first, alice, 3)
await fill(client, second, alice, 3)
page = (
await client.get(f"/api/v1/chats/{first['id']}/messages?limit=1", headers=actor(alice))
).json()
cursor = quote(page["next_cursor"], safe="")
response = await client.get(
f"/api/v1/chats/{second['id']}/messages?limit=1&cursor={cursor}", headers=actor(alice)
)
assert response.status_code == 400
assert response.json()["error"]["code"] == "invalid_request"
@pytest.mark.parametrize("cursor", ["garbage", "1.2.3.4", "%20", ""])
async def test_broken_cursor_is_rejected(client: AsyncClient, cursor: str) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
await fill(client, chat, alice, 1)
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
response = await client.get(f"{path}?limit=1&cursor={cursor}", headers=actor(alice))
assert response.status_code == 400, f"{path}?cursor={cursor} → {response.status_code}"
assert response.json()["error"]["code"] == "invalid_request"
@pytest.mark.parametrize("limit", ["0", "-1", "101", "abc", "1.5", ""])
async def test_limit_out_of_range(client: AsyncClient, limit: str) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
response = await client.get(f"{path}?limit={limit}", headers=actor(alice))
assert response.status_code == 400, f"{path}?limit={limit} → {response.status_code}"
async def test_default_limit_is_50(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
await fill(client, chat, alice, 51)
page = (await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))).json()
assert len(page["items"]) == 50
assert page["next_cursor"] is not None
async def test_unknown_query_parameter_is_ignored(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
await fill(client, chat, alice, 2)
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
response = await client.get(f"{path}?limit=1&unknown=x", headers=actor(alice))
assert response.status_code == 200, response.text
assert len(response.json()["items"]) == 1
async def test_chat_list_pagination(client: AsyncClient) -> None:
alice = await register(client, "alice")
created = [(await make_chat(client, alice))["id"] for _ in range(5)]
collected: list[str] = []
cursor: str | None = None
while True:
query = "?limit=2" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
page = (await client.get(f"/api/v1/chats{query}", headers=actor(alice))).json()
collected.extend(item["id"] for item in page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
assert collected == created