"""Chats, membership (foreign chat -> 404), messages and keyset pagination.""" from __future__ import annotations import uuid import pytest def key(item: dict) -> tuple[str, int]: # Fixed-width RFC 3339 strings compare like timestamps; ids compare as UUID integers. return item["created_at"], uuid.UUID(item["id"]).int # ---------------------------------------------------------------- chats def test_create_chat_and_read_it(api): alice, bob = api.user("alice"), api.user("bob") chat = api.chat(alice, bob, title="Проект по ВНП 🚀") assert chat["member_ids"] == [alice["id"], bob["id"]] assert chat["title"] == "Проект по ВНП 🚀" assert api.call("GET", f"/api/v1/chats/{chat['id']}", 200, user=bob, schema="Chat").json() == chat @pytest.mark.parametrize("case", ["duplicate", "unknown", "without_caller", "empty", "too_many", "not_uuid", "blank_title", "long_title", "extra_field", "ids_not_list"]) def test_invalid_chat_is_400(api, case): alice, bob = api.user("alice"), api.user("bob") body = {"title": "Чат", "member_ids": [alice["id"], bob["id"]]} if case == "duplicate": body["member_ids"] = [alice["id"], bob["id"], bob["id"].upper()] elif case == "unknown": body["member_ids"] = [alice["id"], str(uuid.uuid4())] elif case == "without_caller": body["member_ids"] = [bob["id"]] elif case == "empty": body["member_ids"] = [] elif case == "too_many": body["member_ids"] = [alice["id"]] + [str(uuid.uuid4()) for _ in range(100)] elif case == "not_uuid": body["member_ids"] = [alice["id"], "bob"] elif case == "blank_title": body["title"] = " " elif case == "long_title": body["title"] = "т" * 101 elif case == "extra_field": body["owner_id"] = alice["id"] elif case == "ids_not_list": body["member_ids"] = alice["id"] api.call("POST", "/api/v1/chats", 400, user=alice, json_body=body) def test_chat_with_only_the_caller_is_allowed(api): alice = api.user("alice") assert api.chat(alice)["member_ids"] == [alice["id"]] def test_chat_list_contains_only_own_chats_in_order(api): alice, bob, eve = api.user("alice"), api.user("bob"), api.user("eve") created = [api.chat(alice, bob, title=f"Чат {i}") for i in range(5)] api.chat(eve, title="Чат Евы") listed = api.call("GET", "/api/v1/chats?limit=100", 200, user=bob, schema="ChatPage").json() assert listed == {"items": created, "next_cursor": None} assert api.call("GET", "/api/v1/chats", 200, user=eve).json()["items"][0]["title"] == "Чат Евы" assert len(api.call("GET", "/api/v1/chats", 200, user=eve).json()["items"]) == 1 def test_chat_list_pagination(api): alice = api.user("alice") created = [api.chat(alice, title=f"Чат {i}") for i in range(5)] first = api.call("GET", "/api/v1/chats?limit=2", 200, user=alice).json() second = api.call("GET", f"/api/v1/chats?limit=2&cursor={first['next_cursor']}", 200, user=alice).json() third = api.call("GET", f"/api/v1/chats?limit=2&cursor={second['next_cursor']}", 200, user=alice).json() assert first["items"] + second["items"] + third["items"] == created assert third["next_cursor"] is None def test_chat_cursor_of_another_user_is_400(api): alice, bob = api.user("alice"), api.user("bob") for i in range(3): api.chat(alice, bob, title=f"Чат {i}") cursor = api.call("GET", "/api/v1/chats?limit=1", 200, user=alice).json()["next_cursor"] api.call("GET", f"/api/v1/chats?limit=1&cursor={cursor}", 400, user=bob) # ------------------------------------------------------ foreign chat -> 404 def test_foreign_chat_is_indistinguishable_from_missing_chat(api): alice, bob, eve = api.user("alice"), api.user("bob"), api.user("eve") chat = api.chat(alice, bob) api.send(alice, chat, "секрет") missing = str(uuid.uuid4()) for chat_id in (chat["id"], missing): base = f"/api/v1/chats/{chat_id}" errors = [ api.call("GET", base, 404, user=eve).json(), api.call("GET", base + "/messages", 404, user=eve).json(), api.call("POST", base + "/messages", 404, user=eve, json_body={"text": "чужое"}).json(), # Even an invalid body or cursor does not reveal that the chat exists. api.call("POST", base + "/messages", 404, user=eve, json_body={"text": ""}).json(), api.call("GET", base + "/messages?cursor=garbage", 404, user=eve).json(), ] assert all(e["error"]["code"] == "not_found" for e in errors) assert all(e["error"]["message"] == errors[0]["error"]["message"] for e in errors) def test_invalid_chat_id_is_400_after_authentication(api): alice = api.user("alice") api.call("GET", "/api/v1/chats/not-a-uuid", 401) api.call("GET", "/api/v1/chats/not-a-uuid", 400, user=alice) api.call("GET", "/api/v1/chats/not-a-uuid/messages", 400, user=alice) # -------------------------------------------------------------- messages def test_message_sender_is_derived_from_identity(api): alice, bob = api.user("alice"), api.user("bob") chat = api.chat(alice, bob) first = api.send(alice, chat, "Привет, Боб! 👋") second = api.send(bob, chat, "Привет, Алиса") assert (first["sender_id"], second["sender_id"]) == (alice["id"], bob["id"]) assert first["chat_id"] == second["chat_id"] == chat["id"] assert first["text"] == "Привет, Боб! 👋" assert key(first) < key(second) @pytest.mark.parametrize("body", [ {"text": ""}, {"text": " \n\t "}, {"text": "я" * 4001}, {"text": None}, {"text": 42}, {}, {"text": "ok", "sender_id": str(uuid.uuid4())}, # sender cannot be chosen by the client {"text": "ok", "attachment_ids": []}, # attachments appear only in lab4 ]) def test_invalid_message_is_400(api, body): alice = api.user("alice") chat = api.chat(alice) error = api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, user=alice, json_body=body).json() assert error["error"]["code"] == "invalid_request" assert api.call("GET", f"/api/v1/chats/{chat['id']}/messages", 200, user=alice).json()["items"] == [] def test_message_limit_is_4000_code_points(api): alice = api.user("alice") chat = api.chat(alice) text = "🙂" * 4000 # 4000 code points, 16000 UTF-8 bytes assert api.send(alice, chat, text)["text"] == text assert api.send(alice, chat, " отступы и\nпереносы сохраняются ")["text"] == " отступы и\nпереносы сохраняются " # ------------------------------------------------------------ pagination def test_history_walks_several_pages_without_loss_or_duplicates(api): alice, bob = api.user("alice"), api.user("bob") chat = api.chat(alice, bob) sent = [api.send(alice if i % 2 else bob, chat, f"сообщение {i}") for i in range(25)] items, pages = api.history(bob, chat, limit=7) assert pages == 4 # 7 + 7 + 7 + 4 assert items == sent # same order, nothing lost or repeated assert items == sorted(items, key=key) assert len({m["id"] for m in items}) == 25 def test_limit_may_change_between_pages_and_default_is_50(api): alice = api.user("alice") chat = api.chat(alice) sent = [api.send(alice, chat, f"m{i}") for i in range(60)] base = f"/api/v1/chats/{chat['id']}/messages" first = api.call("GET", base, 200, user=alice).json() assert len(first["items"]) == 50 and first["next_cursor"] rest = api.call("GET", f"{base}?limit=100&cursor={first['next_cursor']}", 200, user=alice).json() assert first["items"] + rest["items"] == sent and rest["next_cursor"] is None def test_exact_page_boundary_has_null_cursor(api): alice = api.user("alice") chat = api.chat(alice) for i in range(3): api.send(alice, chat, f"m{i}") page = api.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=3", 200, user=alice).json() assert len(page["items"]) == 3 and page["next_cursor"] is None def test_new_message_after_last_page_is_reachable_from_cursor(api): alice = api.user("alice") chat = api.chat(alice) api.send(alice, chat, "m0") api.send(alice, chat, "m1") base = f"/api/v1/chats/{chat['id']}/messages" page = api.call("GET", f"{base}?limit=1", 200, user=alice).json() newer = api.send(alice, chat, "m2") tail = api.call("GET", f"{base}?limit=10&cursor={page['next_cursor']}", 200, user=alice).json() assert [m["text"] for m in tail["items"]] == ["m1", "m2"] and tail["items"][-1] == newer @pytest.mark.parametrize("query", ["limit=0", "limit=101", "limit=-1", "limit=abc", "limit=1.5", "limit=", "limit=%D9%A3", "limit=1&limit=2", "cursor=", "cursor=garbage", "cursor=%%%", "cursor=djF8bXx4fDF8Mg"]) def test_invalid_limit_or_cursor_is_400(api, query): alice = api.user("alice") chat = api.chat(alice) api.send(alice, chat, "m") api.call("GET", f"/api/v1/chats/{chat['id']}/messages?{query}", 400, user=alice) def test_cursor_from_another_chat_is_400(api): alice = api.user("alice") chat_a, chat_b = api.chat(alice, title="A"), api.chat(alice, title="B") for chat in (chat_a, chat_b): api.send(alice, chat, "1") api.send(alice, chat, "2") cursor = api.call("GET", f"/api/v1/chats/{chat_a['id']}/messages?limit=1", 200, user=alice).json()["next_cursor"] api.call("GET", f"/api/v1/chats/{chat_b['id']}/messages?cursor={cursor}", 400, user=alice) # A cursor of the chat list is not a message cursor either. api.chat(alice, title="C") chats_cursor = api.call("GET", "/api/v1/chats?limit=1", 200, user=alice).json()["next_cursor"] api.call("GET", f"/api/v1/chats/{chat_a['id']}/messages?cursor={chats_cursor}", 400, user=alice) def test_invalid_cursor_is_400_even_for_empty_history(api): alice = api.user("alice") chat = api.chat(alice) # no messages at all api.call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor=garbage", 400, user=alice) api.call("GET", "/api/v1/chats?cursor=garbage", 400, user=api.user("bob")) # user without chats