Files
mtusi2026lab2/tests/test_errors.py
T

75 lines
2.3 KiB
Python

import logging
import json
from fastapi.testclient import TestClient
from tests.helpers import assert_request_id
def test_missing_token_returns_401(client: TestClient):
response = client.get("/api/v1/users/me")
assert response.status_code == 401
assert response.json()["error"]["code"] == "unauthorized"
assert_request_id(response)
def test_garbage_token_returns_401(client: TestClient):
response = client.get(
"/api/v1/users/me", headers={"Authorization": "Bearer garbage"}
)
assert response.status_code == 401
assert response.json()["error"]["code"] == "unauthorized"
assert_request_id(response)
def test_malformed_json_returns_400(client: TestClient):
response = client.post(
"/api/v1/users",
content='{"username":"alice",',
headers={"Content-Type": "application/json"},
)
assert response.status_code == 400
assert response.json()["error"]["code"] == "invalid_request"
assert_request_id(response)
def test_not_found_returns_404(client: TestClient):
response = client.get("/no-such-path")
assert response.status_code == 404
assert response.json()["error"]["code"] == "not_found"
assert_request_id(response)
def test_method_not_allowed_preserves_405(client: TestClient):
response = client.delete("/api/v1/users")
assert response.status_code == 405
assert response.json()["error"]["code"] == "invalid_request"
assert_request_id(response)
def test_unhandled_exception_is_hidden_from_client(client_no_raise: TestClient, caplog):
with caplog.at_level(logging.ERROR, logger="app.errors.handlers"):
response = client_no_raise.get("/__test__/explode")
assert response.status_code == 500
payload = response.json()
assert payload["error"]["code"] == "internal_error"
assert payload["error"]["message"] == "Внутренняя ошибка сервера"
assert "test-secret" not in json.dumps(payload, ensure_ascii=False)
assert "Traceback" not in json.dumps(payload, ensure_ascii=False)
assert "Unhandled error request_id=" in caplog.text
assert "test-secret" in caplog.text
assert_request_id(response)
def test_success_response_contains_request_id(client: TestClient):
response = client.get("/health/live")
assert response.status_code == 200
assert response.headers.get("X-Request-Id")