87 lines
3.1 KiB
Python
87 lines
3.1 KiB
Python
"""X-Request-Id и X-Instance-Id: поведение слоя, общее для любых его реализаций.
|
||
|
||
Эти тесты фиксируют то, что видит клиент, и не зависят от того, как
|
||
написан middleware (в лабе 1 его переписали на чистое ASGI, трек «5»).
|
||
Ответ 401 формирует AuthenticationMiddleware, а не роутер: id из
|
||
входящего заголовка должен дойти и до него. С лабы 3 у каждого ответа
|
||
API есть ещё непустой X-Instance-Id — на успехе, ошибке, health, 404
|
||
неизвестного пути и 405 (500 по HTTP не вызвать: заголовок ему ставит
|
||
`handlers.error_response`).
|
||
"""
|
||
|
||
import re
|
||
|
||
import httpx
|
||
import pytest
|
||
|
||
from helpers import ME, USERS, assert_error, instance_id
|
||
|
||
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)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("method", "path", "status"),
|
||
[
|
||
("GET", "/health/live", 200),
|
||
("GET", "/health/ready", 200),
|
||
("POST", USERS, 400),
|
||
("GET", ME, 401),
|
||
("GET", "/no-such-path", 404),
|
||
# вне /api/v1: под ним без токена раньше 405 отвечает 401
|
||
("DELETE", "/health/live", 405),
|
||
],
|
||
ids=["live", "ready", "bad-request", "unauthorized", "unknown-path", "method"],
|
||
)
|
||
def test_instance_id_on_every_response(
|
||
client: httpx.Client,
|
||
method: str,
|
||
path: str,
|
||
status: int,
|
||
) -> None:
|
||
response = client.request(method, path, json={} if method == "POST" else None)
|
||
assert response.status_code == status, response.text
|
||
assert instance_id(response)
|