Files
mtusi2026lab4/tests/error_headers.py
T
2026-11-12 19:38:03 +03:00

54 lines
1.7 KiB
Python

"""Неожиданное исключение не раскрывает детали и сохраняет обязательные headers.
Маршрут добавлен только в этот изолированный процесс, не в работающий API.
"""
import asyncio
import json
from src.main import INSTANCE_ID, app
@app.get("/_audit_unexpected_error")
async def unexpected():
raise RuntimeError("audit-internal-detail")
async def main():
messages = []
async def receive():
await asyncio.Event().wait()
async def send(message):
messages.append(message)
scope = {
"type": "http",
"asgi": {"version": "3.0", "spec_version": "2.4"},
"http_version": "1.1",
"method": "GET",
"scheme": "http",
"path": "/_audit_unexpected_error",
"raw_path": b"/_audit_unexpected_error",
"query_string": b"",
"root_path": "",
"headers": [],
"server": ("localhost", 80),
"client": ("127.0.0.1", 1),
}
await app(scope, receive, send)
start = next(m for m in messages if m["type"] == "http.response.start")
payload = json.loads(
b"".join(m.get("body", b"") for m in messages if m["type"] == "http.response.body")
)
headers = dict(start["headers"])
assert start["status"] == 500
assert headers[b"x-instance-id"].decode() == INSTANCE_ID
assert payload["error"]["request_id"] == headers[b"x-request-id"].decode()
assert payload["error"]["code"] == "internal_error"
assert "audit-internal-detail" not in json.dumps(payload)
print("PASS: 500 has X-Request-Id/X-Instance-Id and hides internal exception details")
asyncio.run(main())