165 lines
10 KiB
Python
165 lines
10 KiB
Python
"""Собственные тесты API (перенесены из lab1, переведены на пароль и Bearer).
|
||
|
||
Тесты «чёрного ящика»: шлют настоящие HTTP-запросы на уже запущенный стенд
|
||
(BASE_URL, по умолчанию http://127.0.0.1:8080 из Makefile; с lab3 это балансировщик,
|
||
и запросы обслуживают разные реплики). С lab3 POST сообщения несёт Idempotency-Key.
|
||
Запуск вместе с остальными test_*.py одной командой: make student-test
|
||
"""
|
||
import unittest
|
||
import uuid
|
||
|
||
from helpers import Client, basic, idempotency, read_history
|
||
|
||
PASSWORD = "Test-password-123"
|
||
|
||
|
||
class MessengerApiTest(unittest.TestCase):
|
||
@classmethod
|
||
def setUpClass(cls):
|
||
cls.api = Client()
|
||
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap() # eve не состоит в чате
|
||
|
||
def messages_path(self, chat_id):
|
||
return f"/api/v1/chats/{chat_id}/messages"
|
||
|
||
def send(self, actor, chat_id, text, expected=201):
|
||
schema = "Message" if expected == 201 else None # клиент разбирает JSON успешного ответа только со схемой
|
||
return self.api.call("POST", self.messages_path(chat_id), expected, actor=actor,
|
||
body={"text": text}, headers=idempotency(), schema=schema)
|
||
|
||
def new_chat(self):
|
||
body = {"title": "Тест", "member_ids": [self.alice["id"], self.bob["id"]]}
|
||
return self.api.call("POST", "/api/v1/chats", 201, actor=self.alice, body=body, schema="Chat")["json"]
|
||
|
||
def test_malformed_json_returns_400(self):
|
||
json_header = {"Content-Type": "application/json"}
|
||
for raw in (b'{"username": "abc",', b"not json", b""):
|
||
self.api.call("POST", "/api/v1/users", 400, raw=raw, headers=json_header)
|
||
self.api.call("POST", self.messages_path(self.chat["id"]), 400,
|
||
actor=self.alice, raw=raw, headers={**json_header, **idempotency()})
|
||
|
||
def test_wrong_types_and_extra_fields_return_400(self):
|
||
self.api.call("POST", "/api/v1/users", 400,
|
||
body={"username": 123, "display_name": "x", "password": PASSWORD})
|
||
self.api.call("POST", "/api/v1/users", 400,
|
||
body={"username": "valid_name", "display_name": "x", "password": PASSWORD, "is_admin": True})
|
||
self.api.call("POST", "/api/v1/users", 400,
|
||
body={"username": "Bad Name!", "display_name": "x", "password": PASSWORD})
|
||
# Отправителя нельзя подставить: он берётся из сессии.
|
||
self.api.call("POST", self.messages_path(self.chat["id"]), 400, actor=self.alice,
|
||
body={"text": "hi", "sender_id": self.bob["id"]}, headers=idempotency())
|
||
|
||
def test_outsider_gets_404_for_foreign_chat(self):
|
||
chat_id = self.chat["id"]
|
||
self.api.call("GET", f"/api/v1/chats/{chat_id}", 404, actor=self.eve)
|
||
self.api.call("GET", self.messages_path(chat_id), 404, actor=self.eve)
|
||
self.send(self.eve, chat_id, "чужое", expected=404)
|
||
# Несуществующий чат выглядит так же, как чужой: существование не раскрывается.
|
||
self.api.call("GET", f"/api/v1/chats/{uuid.uuid4()}", 404, actor=self.eve)
|
||
|
||
def test_auth_checked_before_access_and_body(self):
|
||
# Без токена — всегда 401, даже если тело кривое или чат чужой: сначала «кто ты».
|
||
self.api.call("POST", self.messages_path(self.chat["id"]), 401, raw=b"not json",
|
||
headers={"Content-Type": "application/json", **idempotency()})
|
||
self.api.call("GET", f"/api/v1/chats/{uuid.uuid4()}", 401)
|
||
|
||
def test_empty_blank_and_too_long_messages_return_400(self):
|
||
for text in ("", " ", "\n\t "):
|
||
self.send(self.alice, self.chat["id"], text, expected=400)
|
||
self.send(self.alice, self.chat["id"], "я" * 4001, expected=400)
|
||
self.send(self.alice, self.chat["id"], "я" * 4000) # ровно на границе — можно
|
||
|
||
def test_duplicate_username_returns_409(self):
|
||
body = {"username": "dup_" + uuid.uuid4().hex[:12], "display_name": "Первый", "password": PASSWORD}
|
||
self.api.call("POST", "/api/v1/users", 201, body=body)
|
||
self.api.call("POST", "/api/v1/users", 409, body=dict(body, display_name="Второй"))
|
||
|
||
def test_unicode_roundtrip(self):
|
||
text = "Привет 👋 你好 ﷽ é"
|
||
sent = self.send(self.alice, self.chat["id"], text)["json"]
|
||
self.assertEqual(sent["text"], text)
|
||
history, _ = read_history(self.api, self.bob, self.chat["id"])
|
||
self.assertIn(text, [m["text"] for m in history])
|
||
# Длина считается в символах Unicode: 100 эмодзи можно, 101 — нет.
|
||
name = "n_" + uuid.uuid4().hex[:12]
|
||
self.api.call("POST", "/api/v1/users", 400,
|
||
body={"username": name, "display_name": "👋" * 101, "password": PASSWORD})
|
||
self.api.call("POST", "/api/v1/users", 201,
|
||
body={"username": name, "display_name": "👋" * 100, "password": PASSWORD})
|
||
|
||
def test_nul_character_is_stored(self):
|
||
# Замечание к MR: U+0000 допустим по контракту и должен сохраняться как есть, а не давать 500.
|
||
name = "nul_" + uuid.uuid4().hex[:10]
|
||
password = "Pass\u0000word-123"
|
||
user = self.api.call("POST", "/api/v1/users", 201, schema="User",
|
||
body={"username": name, "display_name": "A\u0000B", "password": password})["json"]
|
||
self.assertEqual(user["display_name"], "A\u0000B")
|
||
session = self.api.call("POST", "/api/v1/auth/sessions", 201, schema="Session",
|
||
headers={"Authorization": basic(name, password)})["json"]
|
||
self.assertEqual(session["user"]["display_name"], "A\u0000B")
|
||
chat = self.api.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
|
||
body={"title": "T\u0000itle", "member_ids": [self.alice["id"], self.bob["id"]]})["json"]
|
||
self.assertEqual(chat["title"], "T\u0000itle")
|
||
sent = self.send(self.alice, chat["id"], "hello\u0000world")["json"]
|
||
self.assertEqual(sent["text"], "hello\u0000world")
|
||
history, _ = read_history(self.api, self.bob, chat["id"])
|
||
self.assertEqual([m["text"] for m in history], ["hello\u0000world"])
|
||
got = self.api.call("GET", f"/api/v1/chats/{chat['id']}", actor=self.bob, schema="Chat")["json"]
|
||
self.assertEqual(got["title"], "T\u0000itle")
|
||
# username с U+0000 существовать не может: вход — обычный 401, а не 500.
|
||
self.api.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic("ab\u0000c", password)})
|
||
|
||
def test_pagination_walks_several_pages(self):
|
||
chat = self.new_chat()
|
||
sent = [self.send(self.alice, chat["id"], f"msg {i}")["json"] for i in range(7)]
|
||
history, pages = read_history(self.api, self.bob, chat["id"], limit=3)
|
||
self.assertEqual(pages, 3) # 3 + 3 + 1
|
||
self.assertEqual([m["id"] for m in history], [m["id"] for m in sent]) # без потерь, дублей и перестановок
|
||
|
||
def test_chat_list_pagination(self):
|
||
created = [self.new_chat()["id"] for _ in range(3)]
|
||
seen, cursor = [], None
|
||
while True:
|
||
query = "?limit=2" + (f"&cursor={cursor}" if cursor else "")
|
||
page = self.api.call("GET", "/api/v1/chats" + query, actor=self.bob, schema="ChatPage")["json"]
|
||
seen += [c["id"] for c in page["items"]]
|
||
cursor = page["next_cursor"]
|
||
if cursor is None:
|
||
break
|
||
self.assertEqual(len(seen), len(set(seen)))
|
||
self.assertEqual(seen[-3:], created) # новые чаты в конце, порядок (created_at, id)
|
||
|
||
def test_bad_cursor_returns_400(self):
|
||
chat_a, chat_b = self.new_chat(), self.new_chat()
|
||
for i in range(2):
|
||
self.send(self.alice, chat_a["id"], f"a{i}")
|
||
first = self.api.call("GET", self.messages_path(chat_a["id"]) + "?limit=1",
|
||
actor=self.alice, schema="MessagePage")["json"]
|
||
foreign_cursor = first["next_cursor"]
|
||
self.api.call("GET", self.messages_path(chat_b["id"]) + "?cursor=" + foreign_cursor, 400, actor=self.alice)
|
||
self.api.call("GET", self.messages_path(chat_a["id"]) + "?cursor=garbage", 400, actor=self.alice)
|
||
# Курсор правильной формы, но с испорченным временем/UUID: 400, а не ошибка БД (500).
|
||
import base64
|
||
import json
|
||
scope = "messages:" + chat_a["id"]
|
||
for bad in ([scope, "not-a-time", str(uuid.uuid4())],
|
||
[scope, "2026-01-01T00:00:00.000000Z", "not-a-uuid"],
|
||
[scope, "2026-01-01T00:00:00", str(uuid.uuid4())], # без часового пояса
|
||
[scope, "0001-01-01T00:00:00+14:00", str(uuid.uuid4())], # в UTC это год 0
|
||
[scope, "9999-12-31T23:59:59-14:00", str(uuid.uuid4())]): # в UTC это год 10000
|
||
forged = base64.urlsafe_b64encode(json.dumps(bad).encode()).decode()
|
||
self.api.call("GET", self.messages_path(chat_a["id"]) + "?cursor=" + forged, 400, actor=self.alice)
|
||
for limit in ("0", "101", "abc"):
|
||
self.api.call("GET", self.messages_path(chat_a["id"]) + "?limit=" + limit, 400, actor=self.alice)
|
||
|
||
def test_chat_membership_rules(self):
|
||
alice, bob = self.alice["id"], self.bob["id"]
|
||
for members in ([bob], [alice, alice], [alice, str(uuid.uuid4())]): # без себя, дубль, неизвестный
|
||
self.api.call("POST", "/api/v1/chats", 400, actor=self.alice, body={"title": "x", "member_ids": members})
|
||
chats = self.api.call("GET", "/api/v1/chats?limit=100", actor=self.eve, schema="ChatPage")["json"]
|
||
self.assertNotIn(self.chat["id"], [c["id"] for c in chats["items"]])
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|