Files
mtusi2026lab5/student-tests/test_identification.py
T
ricoromaandClaude Opus 5.5 04f859282d chore: port lab 4 solution into the lab 5 skeleton
Source: mtusi2026lab4-safronov, solution/bvt2301-safronov, 2546deb.
Contracts, public tests and evidence of lab 4 are not carried over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:09:12 +03:00

121 lines
4.2 KiB
Python

"""Спек `identification`: Bearer на защищённых эндпоинтах с лабы 2.
Единственный модуль, который собирает `Authorization` и `X-User-Id`
сам, а не через `Actor.headers()`: проверяются именно заголовки.
"""
import secrets
from typing import Any
import pytest
from api_client import API, Actor, Api, basic_auth, bearer_auth
from contract import (
BEARER_CHALLENGE,
assert_error,
assert_ok,
assert_unauthorized,
contract,
)
ME = f"{API}/users/me"
@pytest.mark.spec("identification", "Действующий токен")
def test_valid_token(api: Api, alice: Actor) -> None:
resp = api.request("GET", ME, headers=bearer_auth(alice.token))
assert assert_ok(resp, 200, "User") == alice.user
@pytest.mark.spec("identification", "Нет заголовка")
def test_no_header(api: Api) -> None:
assert_unauthorized(api.request("GET", ME), BEARER_CHALLENGE)
@pytest.mark.spec("identification", "Неизвестный токен")
def test_unknown_token(api: Api) -> None:
for token in (secrets.token_urlsafe(32), "x"):
resp = api.request("GET", ME, headers=bearer_auth(token))
assert_unauthorized(resp, BEARER_CHALLENGE)
# схема без токена — тот же ответ
resp = api.request("GET", ME, headers={"Authorization": "Bearer"})
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("identification", "Basic на бизнес-эндпоинте")
def test_basic_on_business_endpoint(api: Api, alice: Actor) -> None:
resp = api.request(
"GET",
ME,
headers=basic_auth(alice.username, alice.password),
)
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("identification", "Только X-User-Id")
def test_only_user_id_header(api: Api, alice: Actor) -> None:
resp = api.request("GET", ME, headers={"X-User-Id": alice.id})
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("identification", "X-User-Id не меняет владельца")
def test_user_id_header_ignored(api: Api, alice: Actor, eve: Actor) -> None:
resp = api.request(
"GET",
ME,
headers={**bearer_auth(alice.token), "X-User-Id": eve.id},
)
assert assert_ok(resp, 200, "User") == alice.user
@pytest.mark.spec("identification", "Чужой чат без заголовка")
def test_chat_without_token(api: Api, chat: dict[str, Any]) -> None:
resp = api.request("GET", f"{API}/chats/{chat['id']}")
assert_unauthorized(resp, BEARER_CHALLENGE)
@pytest.mark.spec("identification", "Невалидное поле без заголовка")
def test_invalid_field_without_token(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
# с ключом: кроме токена в запросе неверно только поле
resp = api.post_message(None, chat["id"], json={"text": ""})
assert_unauthorized(resp, BEARER_CHALLENGE)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("identification", "Битый JSON без заголовка")
def test_malformed_json_without_token(
api: Api,
chat: dict[str, Any],
) -> None:
# согласованное расхождение: битый JSON отклоняется до аутентификации
resp = api.post_message(
None,
chat["id"],
headers={"Content-Type": "application/json"},
content=b"{bad",
)
assert_error(resp, 400)
@pytest.mark.spec("identification", "Схема в openapi.json")
def test_security_schemes_in_openapi(api: Api) -> None:
resp = api.request("GET", "/openapi.json")
assert resp.status_code == 200
served = resp.json()
schemes = served["components"]["securitySchemes"]
expected = contract()["components"]["securitySchemes"]
assert schemes["bearerAuth"] == expected["bearerAuth"]
assert schemes["basicAuth"] == expected["basicAuth"]
assert "devUser" not in schemes
paths = served["paths"]
assert paths[ME]["get"]["security"] == [{"bearerAuth": []}]
assert paths[f"{API}/auth/sessions"]["post"]["security"] == [
{"basicAuth": []},
]
assert not paths[f"{API}/users"]["post"].get("security")