"""Спек `identification`: заголовок `X-User-Id` лабы 1. Единственный модуль, который собирает заголовок сам, а не через `Actor.headers()`: проверяется именно заголовок. На лабе 2 модуль переписывается вместе со спеком. """ import uuid from typing import Any import pytest from api_client import API, Actor, Api from contract import assert_error, assert_ok, contract ME = f"{API}/users/me" @pytest.mark.spec("identification", "Корректный заголовок") def test_valid_header(api: Api, alice: Actor) -> None: resp = api.request("GET", ME, headers={"X-User-Id": alice.id}) assert assert_ok(resp, 200, "User") == alice.user @pytest.mark.spec("identification", "Нет заголовка") def test_no_header(api: Api) -> None: assert_error(api.request("GET", ME), 401) @pytest.mark.spec("identification", "Не UUID") def test_not_uuid(api: Api) -> None: resp = api.request("GET", ME, headers={"X-User-Id": "not-a-uuid"}) assert_error(resp, 401) @pytest.mark.spec("identification", "Неизвестный пользователь") def test_unknown_user(api: Api) -> None: resp = api.request("GET", ME, headers={"X-User-Id": str(uuid.uuid4())}) assert_error(resp, 401) @pytest.mark.spec("identification", "Чужой чат без заголовка") def test_chat_without_header(api: Api, chat: dict[str, Any]) -> None: assert_error(api.request("GET", f"{API}/chats/{chat['id']}"), 401) @pytest.mark.spec("identification", "Невалидное поле без заголовка") def test_invalid_field_without_header( api: Api, alice: Actor, chat: dict[str, Any], ) -> None: resp = api.request( "POST", f"{API}/chats/{chat['id']}/messages", json={"text": ""}, ) assert_error(resp, 401) assert api.all_messages(alice, chat["id"]) == [] @pytest.mark.spec("identification", "Битый JSON без заголовка") def test_malformed_json_without_header( api: Api, chat: dict[str, Any], ) -> None: # согласованное расхождение: битый JSON отклоняется до идентификации resp = api.request( "POST", f"{API}/chats/{chat['id']}/messages", headers={"Content-Type": "application/json"}, content=b"{bad", ) assert_error(resp, 400) @pytest.mark.spec("identification", "Схема в openapi.json") def test_security_scheme_in_openapi(api: Api) -> None: resp = api.request("GET", "/openapi.json") assert resp.status_code == 200 served = resp.json() expected = contract()["components"]["securitySchemes"]["devUser"] assert served["components"]["securitySchemes"]["devUser"] == expected assert served["paths"][ME]["get"]["security"] == [{"devUser": []}] assert not served["paths"][f"{API}/users"]["post"].get("security")