"""Обязательные сценарии уровня 4 (README.md): каждый — отдельный тест. Лаба 1 (сохраняются): неверный JSON, чужой чат, пустое сообщение, дубликат username, обход нескольких страниц истории. Лаба 2: неверный пароль и logout. Плюс health и порядок «сначала аутентификация», на который опирается архитектура. Гонки — `test_race.py`, срок сессии и отказы хранилищ — `test_failures.py` (make failure-checks). """ import httpx import pytest from helpers import ( BASIC_CHALLENGE, BEARER_CHALLENGE, CHATS, ME, USERS, assert_error, assert_unauthorized, create_chat, headers, login_response, logout, messages_path, public, read_history, register, send, unique_password, unique_username, ) def test_health_live_and_ready(client: httpx.Client) -> None: for path in ("/health/live", "/health/ready"): response = client.get(path) assert response.status_code == 200 assert response.json() == {"status": "ok"} assert response.headers["X-Request-Id"] @pytest.mark.parametrize( "raw", [ b'{"username": "broken",', # оборван b"{'username': 'single_quotes'}", # не JSON b"[]", # JSON, но не объект ], ids=["truncated", "not-json", "array"], ) def test_malformed_json_is_400(client: httpx.Client, raw: bytes) -> None: response = client.post( USERS, content=raw, headers={"Content-Type": "application/json"}, ) assert_error(response, 400, "invalid_request") def test_malformed_json_with_token_is_400(client: httpx.Client) -> None: alice = register(client, "alice") chat = create_chat(client, alice) for path in (CHATS, messages_path(chat)): response = client.post( path, content=b'{"title": ', headers={**headers(alice), "Content-Type": "application/json"}, ) assert_error(response, 400, "invalid_request") def test_malformed_json_without_token_is_401(client: httpx.Client) -> None: """Аутентификация раньше разбора тела: битый JSON без токена — 401.""" response = client.post( CHATS, content=b'{"title": ', headers={"Content-Type": "application/json"}, ) assert_unauthorized(response, BEARER_CHALLENGE) def test_foreign_chat_is_404_like_missing_chat(client: httpx.Client) -> None: alice, bob, eve = (register(client, name) for name in ("alice", "bob", "eve")) chat = create_chat(client, alice, bob) assert send(client, alice, chat, "видно только участникам").status_code == 201 missing = {"id": "11111111-1111-4111-8111-111111111111"} for target in (chat, missing): errors = [ assert_error( client.get(f"{CHATS}/{target['id']}", headers=headers(eve)), 404, "not_found", ), assert_error( client.get(messages_path(target), headers=headers(eve)), 404, "not_found", ), assert_error(send(client, eve, target, "чужое"), 404, "not_found"), ] # чужой и несуществующий чат неотличимы по тексту ошибки assert {error["message"] for error in errors} == {"Not found"} listed = client.get(CHATS, params={"limit": 100}, headers=headers(eve)) assert listed.status_code == 200 assert all(item["id"] != chat["id"] for item in listed.json()["items"]) # участник по-прежнему видит свою историю, и чужого сообщения в ней нет items, _ = read_history(client, bob, chat, limit=50) assert [item["text"] for item in items] == ["видно только участникам"] @pytest.mark.parametrize("text", ["", " ", "\n\t"], ids=["empty", "spaces", "ws"]) def test_empty_message_is_400(client: httpx.Client, text: str) -> None: alice = register(client, "alice") chat = create_chat(client, alice) assert_error(send(client, alice, chat, text), 400, "invalid_request") items, _ = read_history(client, alice, chat, limit=50) assert items == [] @pytest.mark.parametrize( "text", [ "a\x00b", "\x00", "\x00Привет 👋\x00\x00", r"a\u0000b", "\x00" * 4000, "👋" * 3999 + "\x00", ], ids=["embedded", "only-nul", "unicode", "literal-escape", "max-nul", "max-unicode"], ) def test_message_with_nul_round_trips(client: httpx.Client, text: str) -> None: alice = register(client, "alice") chat = create_chat(client, alice) sent = [] for value in ("before", text, "after"): response = send(client, alice, chat, value) assert response.status_code == 201, response.text message = response.json() assert message["text"] == value assert message["chat_id"] == chat["id"] assert message["sender_id"] == alice["id"] assert response.headers["X-Request-Id"] sent.append(message) items, sizes = read_history(client, alice, chat, limit=1) assert sizes == [1, 1, 1] assert items == sent def test_message_with_nul_over_limit_is_400(client: httpx.Client) -> None: alice = register(client, "alice") chat = create_chat(client, alice) assert_error(send(client, alice, chat, "\x00" * 4001), 400, "invalid_request") items, _ = read_history(client, alice, chat, limit=50) assert items == [] @pytest.mark.parametrize( "value", [ "a\x00b", "\x00", "\x00Привет 👋\x00", r"a\u0000b", "\x00" * 100, "👋" * 99 + "\x00", ], ids=["embedded", "only-nul", "unicode", "literal-escape", "max-nul", "max-unicode"], ) def test_user_display_name_with_nul_round_trips( client: httpx.Client, value: str ) -> None: username, password = unique_username("nul_name"), unique_password() response = client.post( USERS, json={"username": username, "display_name": value, "password": password}, ) assert response.status_code == 201, response.text user = response.json() assert user["display_name"] == value session = login_response(client, username, password) assert session.status_code == 201 assert session.json()["user"] == user actor = {**user, "token": session.json()["token"]} me = client.get(ME, headers=headers(actor)) assert me.status_code == 200 assert me.json() == user @pytest.mark.parametrize( "value", [ "a\x00b", "\x00", "\x00Привет 👋\x00", r"a\u0000b", "\x00" * 100, "👋" * 99 + "\x00", ], ids=["embedded", "only-nul", "unicode", "literal-escape", "max-nul", "max-unicode"], ) def test_chat_title_with_nul_round_trips(client: httpx.Client, value: str) -> None: alice = register(client, "alice") chat = create_chat(client, alice, title=value) assert chat["title"] == value # Карточка читается через кэш, список — напрямую из PostgreSQL. for _ in range(2): response = client.get(f"{CHATS}/{chat['id']}", headers=headers(alice)) assert response.status_code == 200 assert response.json() == chat response = client.get(CHATS, headers=headers(alice)) assert response.status_code == 200 assert response.json()["items"] == [chat] @pytest.mark.parametrize("field", ["display_name", "title"]) def test_unicode_metadata_with_nul_over_limit_is_400( client: httpx.Client, field: str ) -> None: if field == "display_name": response = client.post( USERS, json={ "username": unique_username("long_name"), "display_name": "\x00" * 101, "password": unique_password(), }, ) else: alice = register(client, "alice") response = client.post( CHATS, json={"title": "\x00" * 101, "member_ids": [alice["id"]]}, headers=headers(alice), ) assert_error(response, 400, "invalid_request") def test_duplicate_username_is_409(client: httpx.Client) -> None: first = register(client, "dup") second = client.post( USERS, json={ "username": first["username"], "display_name": "Второй", "password": unique_password(), }, ) assert_error(second, 409, "conflict") # занятый username не меняет владельца: прежний пароль, прежние данные me = client.get(ME, headers=headers(first)) assert me.json() == public(first) def test_history_walks_several_pages(client: httpx.Client) -> None: alice, bob = register(client, "alice"), register(client, "bob") chat = create_chat(client, alice, bob) sent = [] for index in range(7): author = alice if index % 2 == 0 else bob response = send(client, author, chat, f"сообщение {index} 👋") assert response.status_code == 201 sent.append(response.json()) items, sizes = read_history(client, bob, chat, limit=3) assert sizes == [3, 3, 1] assert items == sent # без потерь, повторов и перестановок ids = [item["id"] for item in items] assert len(set(ids)) == len(ids) keys = [(item["created_at"], item["id"]) for item in items] assert keys == sorted(keys) def test_cursor_of_another_chat_is_400(client: httpx.Client) -> None: alice = register(client, "alice") first, second = create_chat(client, alice), create_chat(client, alice) for index in range(2): assert send(client, alice, first, f"m{index}").status_code == 201 page = client.get(messages_path(first), params={"limit": 1}, headers=headers(alice)) cursor = page.json()["next_cursor"] assert cursor response = client.get( messages_path(second), params={"limit": 1, "cursor": cursor}, headers=headers(alice), ) assert_error(response, 400, "invalid_request") @pytest.mark.parametrize("target", ["history", "chats"]) @pytest.mark.parametrize("placement", ["prefix", "suffix"]) def test_corrupted_issued_cursor_is_400( client: httpx.Client, target: str, placement: str, ) -> None: alice = register(client, "alice") first = create_chat(client, alice) create_chat(client, alice) for index in range(2): assert send(client, alice, first, f"m{index}").status_code == 201 path = messages_path(first) if target == "history" else CHATS page = client.get(path, params={"limit": 1}, headers=headers(alice)) assert page.status_code == 200 cursor = page.json()["next_cursor"] assert cursor # Четыре символа не меняют padding: нестрогий декодер их игнорировал. corrupted = f"!!!!{cursor}" if placement == "prefix" else f"{cursor}!!!!" response = client.get( path, params={"limit": 1, "cursor": corrupted}, headers=headers(alice), ) assert_error(response, 400, "invalid_request") valid = client.get( path, params={"limit": 1, "cursor": cursor}, headers=headers(alice), ) assert valid.status_code == 200 assert valid.json()["items"] != page.json()["items"] def test_wrong_password_is_401(client: httpx.Client) -> None: alice = register(client, "alice") response = login_response(client, alice["username"], alice["password"] + "-wrong") assert_unauthorized(response, BASIC_CHALLENGE) assert "token" not in response.text # неизвестный username — тот же ответ: по нему не узнать, есть ли он unknown = login_response(client, unique_username("ghost"), alice["password"]) assert_unauthorized(unknown, BASIC_CHALLENGE) assert unknown.json()["error"]["message"] == response.json()["error"]["message"] def test_logout_revokes_token(client: httpx.Client) -> None: alice = register(client, "alice") response = logout(client, alice) assert response.status_code == 204, response.text assert response.content == b"" assert_unauthorized(client.get(ME, headers=headers(alice)), BEARER_CHALLENGE) # повтор выхода тем же токеном — 401 assert_unauthorized(logout(client, alice), BEARER_CHALLENGE)