168 lines
7.9 KiB
Python
168 lines
7.9 KiB
Python
"""Пагинация по ключу: каждый элемент ровно один раз, в порядке из контракта.
|
|
|
|
Контракт обещает порядок (created_at, id). Записи, созданные разными запросами,
|
|
могут иметь одинаковую метку времени, поэтому граница страницы внутри такой
|
|
группы - случай, где наивная реализация ошибается: проверки ниже читают всю
|
|
историю через курсор и сравнивают её с одним чтением без пагинации.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import unittest
|
|
import uuid
|
|
|
|
import harness
|
|
|
|
HISTORY = 25
|
|
PAGE = 7
|
|
|
|
|
|
def order_key(item):
|
|
"""(created_at, id), где UUID сравнивается как целое число - так читает контракт."""
|
|
return (item["created_at"], uuid.UUID(item["id"]).int)
|
|
|
|
|
|
class MessageHistory(unittest.TestCase):
|
|
"""Чат с известной историей, читаемый страницами по семь."""
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.api = harness.client()
|
|
cls.alice = harness.account(cls.api, "page_alice")
|
|
cls.bob = harness.account(cls.api, "page_bob")
|
|
cls.chat = harness.chat(cls.api, cls.alice, [cls.bob], title="История")
|
|
cls.texts = ["Сообщение %02d" % index for index in range(HISTORY)]
|
|
for text in cls.texts:
|
|
harness.send(cls.api, cls.bob, cls.chat, text)
|
|
|
|
def page(self, cursor=None, limit=PAGE, actor=None):
|
|
path = "/api/v1/chats/%s/messages?limit=%d" % (self.chat["id"], limit)
|
|
if cursor is not None:
|
|
path += "&cursor=" + cursor
|
|
return self.api.call("GET", path, 200, actor=actor or self.alice,
|
|
schema="MessagePage")["json"]
|
|
|
|
def test_pages_cover_the_history_exactly_once(self):
|
|
collected, sizes, cursor, seen = [], [], None, set()
|
|
for _ in range(20):
|
|
body = self.page(cursor)
|
|
collected.extend(item["id"] for item in body["items"])
|
|
sizes.append(len(body["items"]))
|
|
cursor = body["next_cursor"]
|
|
if cursor is None:
|
|
break
|
|
self.assertNotIn(cursor, seen, "курсор повторился")
|
|
seen.add(cursor)
|
|
else:
|
|
self.fail("пагинация не завершилась в пределах защитного ограничения")
|
|
|
|
self.assertEqual(len(collected), HISTORY)
|
|
self.assertEqual(len(set(collected)), HISTORY, "элемент встретился на двух страницах")
|
|
self.assertEqual(sizes[:-1], [PAGE] * (len(sizes) - 1),
|
|
"каждая страница, кроме последней, должна быть полной")
|
|
self.assertLessEqual(sizes[-1], PAGE)
|
|
|
|
def test_small_pages_agree_with_a_single_large_one(self):
|
|
paged, cursor = [], None
|
|
while True:
|
|
body = self.page(cursor, limit=PAGE)
|
|
paged.extend(item["id"] for item in body["items"])
|
|
cursor = body["next_cursor"]
|
|
if cursor is None:
|
|
break
|
|
unpaged = [item["id"] for item in self.page(limit=100)["items"]]
|
|
self.assertEqual(paged, unpaged, "разбиение на страницы изменило результат")
|
|
|
|
def test_items_are_ordered_by_created_at_then_id(self):
|
|
items = self.page(limit=100)["items"]
|
|
self.assertEqual(len(items), HISTORY)
|
|
keys = [order_key(item) for item in items]
|
|
self.assertEqual(keys, sorted(keys), "история не упорядочена по (created_at, id)")
|
|
|
|
def test_the_second_page_starts_right_after_the_first(self):
|
|
first = self.page(limit=PAGE)
|
|
second = self.page(first["next_cursor"], limit=PAGE)
|
|
boundary = order_key(first["items"][-1])
|
|
self.assertLess(boundary, order_key(second["items"][0]))
|
|
self.assertTrue(
|
|
all(order_key(item) > boundary for item in second["items"]),
|
|
"страница вернула элемент на позиции курсора или раньше",
|
|
)
|
|
|
|
def test_a_cursor_from_another_chat_is_refused(self):
|
|
other = harness.chat(self.api, self.alice, [], title="Другой чат")
|
|
harness.send(self.api, self.alice, other, "Чужое сообщение")
|
|
cursor = self.page(limit=1)["next_cursor"]
|
|
self.assertIsNotNone(cursor)
|
|
response = self.api.call(
|
|
"GET", "/api/v1/chats/%s/messages?limit=1&cursor=%s" % (other["id"], cursor),
|
|
[400], actor=self.alice,
|
|
)
|
|
self.assertEqual(response["json"]["error"]["code"], "invalid_request")
|
|
|
|
def test_a_cursor_from_another_user_is_refused(self):
|
|
chat = harness.chat(self.api, self.bob, [], title="Чаты Боба")
|
|
harness.send(self.api, self.bob, chat, "Только Боб")
|
|
cursor = self.page(limit=1)["next_cursor"]
|
|
self.assertIsNotNone(cursor)
|
|
response = self.api.call(
|
|
"GET", "/api/v1/chats/%s/messages?limit=1&cursor=%s" % (chat["id"], cursor),
|
|
[400], actor=self.bob,
|
|
)
|
|
self.assertEqual(response["json"]["error"]["code"], "invalid_request")
|
|
|
|
def test_a_cursor_from_the_chat_list_is_refused_here(self):
|
|
chats = self.api.call("GET", "/api/v1/chats?limit=1", 200, actor=self.alice,
|
|
schema="ChatPage")["json"]
|
|
cursor = chats["next_cursor"]
|
|
self.assertIsNotNone(cursor, "для фикстуры нужно минимум два чата")
|
|
response = self.api.call(
|
|
"GET", "/api/v1/chats/%s/messages?limit=1&cursor=%s" % (self.chat["id"], cursor),
|
|
[400], actor=self.alice,
|
|
)
|
|
self.assertEqual(response["json"]["error"]["code"], "invalid_request")
|
|
|
|
|
|
class ChatList(unittest.TestCase):
|
|
"""Те же правила для списка чатов, где область видимости - текущий пользователь."""
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.api = harness.client()
|
|
cls.alice = harness.account(cls.api, "page_owner")
|
|
cls.chats = [harness.chat(cls.api, cls.alice, [], title="Чат %d" % index)
|
|
for index in range(5)]
|
|
|
|
def test_chat_pages_cover_the_list_exactly_once(self):
|
|
collected, cursor, seen = [], None, set()
|
|
for _ in range(20):
|
|
path = "/api/v1/chats?limit=2"
|
|
if cursor is not None:
|
|
self.assertNotIn(cursor, seen)
|
|
seen.add(cursor)
|
|
path += "&cursor=" + cursor
|
|
body = self.api.call("GET", path, 200, actor=self.alice, schema="ChatPage")["json"]
|
|
collected.extend(item["id"] for item in body["items"])
|
|
cursor = body["next_cursor"]
|
|
if cursor is None:
|
|
break
|
|
else:
|
|
self.fail("пагинация списка чатов не завершилась")
|
|
|
|
expected = {chat["id"] for chat in self.chats}
|
|
self.assertTrue(expected.issubset(set(collected)))
|
|
self.assertEqual(len(collected), len(set(collected)), "чат появился дважды")
|
|
keys = [order_key(item) for item in harness.all_chats(self.api, self.alice)]
|
|
self.assertEqual(keys, sorted(keys))
|
|
|
|
def test_a_cursor_from_one_user_is_refused_for_another(self):
|
|
bob = harness.account(self.api, "page_outsider")
|
|
cursor = self.api.call("GET", "/api/v1/chats?limit=1", 200, actor=self.alice,
|
|
schema="ChatPage")["json"]["next_cursor"]
|
|
self.assertIsNotNone(cursor)
|
|
response = self.api.call("GET", "/api/v1/chats?limit=1&cursor=" + cursor, [400], actor=bob)
|
|
self.assertEqual(response["json"]["error"]["code"], "invalid_request")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=2)
|