forked from mtusi2026/mtusi2026lab4
Добавить вложения: S3, метаданные в PostgreSQL и очистка незавершённых загрузок
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
import base64
|
||||
import json
|
||||
import unittest
|
||||
import urllib.parse
|
||||
|
||||
from api import call, history, new_chat, new_user, send
|
||||
|
||||
|
||||
class MessagePaginationTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.user = new_user()
|
||||
cls.chat = new_chat(cls.user)
|
||||
cls.sent = [send(cls.user, cls.chat, "сообщение %d" % number)[1] for number in range(25)]
|
||||
cls.path = "/api/v1/chats/" + cls.chat["id"] + "/messages"
|
||||
|
||||
def test_walk_several_pages(self):
|
||||
items, sizes = history(self.user, self.chat, limit=10)
|
||||
self.assertEqual(sizes, [10, 10, 5])
|
||||
self.assertEqual(items, self.sent)
|
||||
|
||||
def test_no_duplicates_and_order(self):
|
||||
items, _ = history(self.user, self.chat, limit=7)
|
||||
ids = [item["id"] for item in items]
|
||||
self.assertEqual(len(ids), len(set(ids)))
|
||||
keys = [(item["created_at"], item["id"]) for item in items]
|
||||
self.assertEqual(keys, sorted(keys))
|
||||
|
||||
def test_exact_page_has_no_cursor(self):
|
||||
_, page, _ = call("GET", self.path + "?limit=25", user=self.user)
|
||||
self.assertEqual(len(page["items"]), 25)
|
||||
self.assertIsNone(page["next_cursor"])
|
||||
|
||||
def test_default_limit(self):
|
||||
_, page, _ = call("GET", self.path, user=self.user)
|
||||
self.assertEqual(len(page["items"]), 25)
|
||||
|
||||
def test_limit_can_change_between_pages(self):
|
||||
_, first, _ = call("GET", self.path + "?limit=3", user=self.user)
|
||||
cursor = urllib.parse.quote(first["next_cursor"], safe="")
|
||||
_, second, _ = call("GET", self.path + "?limit=100&cursor=" + cursor, user=self.user)
|
||||
self.assertEqual(first["items"] + second["items"], self.sent)
|
||||
|
||||
def test_bad_limit(self):
|
||||
for limit in ("0", "101", "-1", "abc", "1.5", ""):
|
||||
with self.subTest(limit=limit):
|
||||
self.assertEqual(call("GET", self.path + "?limit=" + limit, user=self.user)[0], 400)
|
||||
|
||||
def test_bad_cursor(self):
|
||||
for cursor in ("garbage", "", "e30=", "%D0%B9"):
|
||||
with self.subTest(cursor=cursor):
|
||||
self.assertEqual(call("GET", self.path + "?cursor=" + cursor, user=self.user)[0], 400)
|
||||
|
||||
def test_cursor_format_is_checked(self):
|
||||
_, first, _ = call("GET", self.path + "?limit=3", user=self.user)
|
||||
good = first["next_cursor"]
|
||||
scope, created_at, item_id = json.loads(base64.urlsafe_b64decode(good))
|
||||
|
||||
def encode(value, **options):
|
||||
return base64.urlsafe_b64encode(json.dumps(value, **options).encode()).decode()
|
||||
|
||||
# тест знает внутренний формат cursor: собранный заново правильный cursor совпадает с выданным
|
||||
self.assertEqual(encode([scope, created_at, item_id]), good)
|
||||
bad = {
|
||||
"посторонний символ внутри base64": good[:5] + "!" + good[5:],
|
||||
"пробел внутри base64": good[:5] + " " + good[5:],
|
||||
"перевод строки в конце": good + "\n",
|
||||
"лишний знак =": good + "=",
|
||||
"обрезанный": good[:-4],
|
||||
"время не в формате сервера": encode([scope, "вчера", item_id]),
|
||||
"время без микросекунд": encode([scope, created_at[:19] + "Z", item_id]),
|
||||
"время с неполными микросекундами": encode([scope, created_at[:21] + "Z", item_id]),
|
||||
"время со смещением вместо Z": encode([scope, created_at[:-1] + "+00:00", item_id]),
|
||||
"несуществующая дата": encode([scope, "2026-13-45T25:61:61.000000Z", item_id]),
|
||||
"число вместо времени": encode([scope, 1234567890, item_id]),
|
||||
"id не UUID": encode([scope, created_at, "abc"]),
|
||||
"UUID в верхнем регистре": encode([scope, created_at, item_id.upper()]),
|
||||
"UUID без дефисов": encode([scope, created_at, item_id.replace("-", "")]),
|
||||
"null вместо id": encode([scope, created_at, None]),
|
||||
"лишний элемент": encode([scope, created_at, item_id, "x"]),
|
||||
"не хватает элемента": encode([scope, created_at]),
|
||||
"объект вместо списка": encode({"scope": scope, "created_at": created_at, "id": item_id}),
|
||||
"тот же JSON без пробелов": encode([scope, created_at, item_id], separators=(",", ":")),
|
||||
"пустой список": encode([]),
|
||||
}
|
||||
for name, cursor in bad.items():
|
||||
with self.subTest(name):
|
||||
path = self.path + "?cursor=" + urllib.parse.quote(cursor, safe="")
|
||||
status, body, _ = call("GET", path, user=self.user)
|
||||
self.assertEqual(status, 400)
|
||||
self.assertEqual(body["error"]["code"], "invalid_request")
|
||||
# правильный cursor при этом продолжает работать
|
||||
self.assertEqual(call("GET", self.path + "?cursor=" + urllib.parse.quote(good, safe=""), user=self.user)[0], 200)
|
||||
|
||||
def test_cursor_from_another_chat(self):
|
||||
other = new_chat(self.user, title="Другой чат")
|
||||
send(self.user, other, "раз")
|
||||
send(self.user, other, "два")
|
||||
_, page, _ = call("GET", "/api/v1/chats/" + other["id"] + "/messages?limit=1", user=self.user)
|
||||
cursor = urllib.parse.quote(page["next_cursor"], safe="")
|
||||
self.assertEqual(call("GET", self.path + "?cursor=" + cursor, user=self.user)[0], 400)
|
||||
|
||||
def test_new_message_appears_after_last_page(self):
|
||||
user = new_user()
|
||||
chat = new_chat(user)
|
||||
send(user, chat, "раз")
|
||||
send(user, chat, "два")
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
_, first, _ = call("GET", path + "?limit=1", user=user)
|
||||
_, created, _ = send(user, chat, "три")
|
||||
cursor = urllib.parse.quote(first["next_cursor"], safe="")
|
||||
_, rest, _ = call("GET", path + "?limit=100&cursor=" + cursor, user=user)
|
||||
self.assertEqual([item["text"] for item in rest["items"]], ["два", "три"])
|
||||
self.assertEqual(rest["items"][-1], created)
|
||||
|
||||
|
||||
class ChatPaginationTest(unittest.TestCase):
|
||||
def test_walk_chat_list(self):
|
||||
user = new_user()
|
||||
created = [new_chat(user, title="Чат %d" % number) for number in range(5)]
|
||||
items, cursor = [], None
|
||||
while True:
|
||||
path = "/api/v1/chats?limit=2"
|
||||
if cursor:
|
||||
path += "&cursor=" + urllib.parse.quote(cursor, safe="")
|
||||
status, page, _ = call("GET", path, user=user)
|
||||
self.assertEqual(status, 200)
|
||||
self.assertLessEqual(len(page["items"]), 2)
|
||||
items += page["items"]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(items, created)
|
||||
|
||||
def test_chat_cursor_belongs_to_user(self):
|
||||
alice, bob = new_user("alice"), new_user("bob")
|
||||
for number in range(2):
|
||||
new_chat(alice, bob, title="Общий %d" % number)
|
||||
_, page, _ = call("GET", "/api/v1/chats?limit=1", user=alice)
|
||||
cursor = urllib.parse.quote(page["next_cursor"], safe="")
|
||||
self.assertEqual(call("GET", "/api/v1/chats?cursor=" + cursor, user=bob)[0], 400)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user