Files
mtusi2026lab2/student-tests/test_request_id.py
T

60 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""X-Request-Id: поведение слоя, общее для любых его реализаций.
Эти тесты фиксируют то, что видит клиент, и не зависят от того, как
написан middleware (в лабе 1 его переписали на чистое ASGI, трек «5»).
Ответ 401 формирует AuthenticationMiddleware, а не роутер: id из
входящего заголовка должен дойти и до него.
"""
import re
import httpx
import pytest
from helpers import USERS, assert_error
GENERATED_ID = re.compile(r"[0-9a-f]{32}")
@pytest.mark.parametrize(
("path", "status", "code"),
[
("/health/live", 200, None),
(f"{USERS}/me", 401, "unauthorized"),
("/no-such-path", 404, "not_found"),
],
ids=["ok", "unauthorized", "unknown-path"],
)
def test_safe_incoming_request_id_is_echoed(
client: httpx.Client,
path: str,
status: int,
code: str | None,
) -> None:
response = client.get(path, headers={"X-Request-Id": "trace-42.a_b"})
assert response.status_code == status
assert response.headers["X-Request-Id"] == "trace-42.a_b"
if code is not None:
# тот же id и в теле ошибки: assert_error сверяет его с заголовком
assert_error(response, status, code)
@pytest.mark.parametrize(
"incoming",
["bad id", "x" * 65, "<script>"],
ids=["space", "too-long", "markup"],
)
def test_unsafe_incoming_request_id_is_replaced(
client: httpx.Client,
incoming: str,
) -> None:
response = client.get("/health/live", headers={"X-Request-Id": incoming})
assert response.status_code == 200
assert GENERATED_ID.fullmatch(response.headers["X-Request-Id"])
def test_generated_request_ids_are_unique(client: httpx.Client) -> None:
ids = {client.get("/health/live").headers["X-Request-Id"] for _ in range(20)}
assert len(ids) == 20
assert all(GENERATED_ID.fullmatch(request_id) for request_id in ids)