Files
mtusi2026lab3/student-tests/test_pagination.py
T

80 lines
3.0 KiB
Python

"""Keyset pagination tests (carried over from lab2)."""
from __future__ import annotations
import base64
import json
import os
def _fake_cursor(payload) -> str:
raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def _fresh_chat(client, alice):
suffix = os.urandom(4).hex()
username = f"s_page_{suffix}"
password = "T3st-" + os.urandom(8).hex()
assert client.register(username, password).status == 201
peer_token = client.login(username, password).json["token"]
peer_id = client.me(peer_token).json["id"]
response = client.create_chat(alice["token"], [alice["id"], peer_id])
assert response.status == 201, response.body
return response.json
def test_full_traversal_without_duplicates(client, alice):
chat = _fresh_chat(client, alice)
expected = []
for index in range(5):
response = client.send(alice["token"], chat["id"], f"msg-{index}")
assert response.status == 201, response.body
expected.append(response.json["id"])
seen = []
cursor = None
while True:
page = client.list_messages(alice["token"], chat["id"], limit=2, cursor=cursor).json
assert len(page["items"]) <= 2
seen.extend(item["id"] for item in page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
assert len(seen) == 5
assert len(set(seen)) == 5, "duplicate across pages"
assert seen == expected, "pagination reordered history"
def test_cursor_from_other_chat_is_400(client, alice):
first = _fresh_chat(client, alice)
second = _fresh_chat(client, alice)
for index in range(3):
client.send(alice["token"], first["id"], f"a{index}")
client.send(alice["token"], second["id"], f"b{index}")
cursor = client.list_messages(alice["token"], first["id"], limit=1).json["next_cursor"]
assert cursor
foreign = client.list_messages(alice["token"], second["id"], limit=1, cursor=cursor)
assert foreign.status == 400, foreign.body
assert foreign.json["error"]["code"] == "invalid_request"
def test_garbage_cursor_is_400(client, alice):
chat = _fresh_chat(client, alice)
client.send(alice["token"], chat["id"], "hello")
response = client.list_messages(alice["token"], chat["id"], cursor="!!!not-a-cursor!!!")
assert response.status == 400, response.body
def test_well_formed_cursor_with_wrong_types_is_400(client, alice):
bad_payloads = [
{"r": "chats", "t": "2026-01-01T00:00:00.000000Z", "i": 1},
{"r": "chats", "t": "2026-01-01T00:00:00.000000Z", "i": []},
{"r": "chats", "t": "2026-01-01T00:00:00.000000Z", "i": True},
{"r": "chats", "t": "not-a-time", "i": "11111111-1111-4111-8111-111111111111"},
]
for payload in bad_payloads:
response = client.request(
"GET", "/api/v1/chats?cursor=" + _fake_cursor(payload), token=alice["token"]
)
assert response.status == 400, (payload, response.status, response.body)