"""Собственные тесты API (перенесены из lab1, переведены на пароль и Bearer). Тесты «чёрного ящика»: шлют настоящие HTTP-запросы на уже запущенный стенд (BASE_URL, по умолчанию http://127.0.0.1:8080 из Makefile). Запуск вместе с test_auth.py одной командой: make student-test """ import unittest import uuid from helpers import Client, 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}, 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) 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"]}) 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"}) 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_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 for bad in (["messages:" + chat_a["id"], "not-a-time", str(uuid.uuid4())], ["messages:" + chat_a["id"], "2026-01-01T00:00:00.000000Z", "not-a-uuid"]): 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()