|
| 1 | +import json |
| 2 | +import uuid |
| 3 | +from typing import NoReturn |
| 4 | + |
| 5 | +from starlette.middleware import Middleware |
| 6 | + |
| 7 | +from starlette_context import plugins |
| 8 | +from starlette.applications import Starlette |
| 9 | + |
| 10 | +from starlette.requests import Request |
| 11 | +from starlette.responses import JSONResponse |
| 12 | +from starlette.testclient import TestClient |
| 13 | + |
| 14 | +from starlette_context import middleware |
| 15 | +from starlette_context.header_keys import HeaderKeys |
| 16 | +from starlette_context import context |
| 17 | + |
| 18 | + |
| 19 | +class CustomException(Exception): |
| 20 | + pass |
| 21 | + |
| 22 | + |
| 23 | +async def custom_exception_handler(request: Request, exc: Exception): |
| 24 | + return JSONResponse({"exception": "handled"}, headers=context.data) |
| 25 | + |
| 26 | + |
| 27 | +async def general_exception_handler(request: Request, exc: Exception): |
| 28 | + return JSONResponse({"exception": "handled"}, headers=context.data) |
| 29 | + |
| 30 | + |
| 31 | +middleware = [ |
| 32 | + Middleware( |
| 33 | + middleware.ContextMiddleware, plugins=(plugins.RequestIdPlugin(),) |
| 34 | + ) |
| 35 | +] |
| 36 | +exception_handlers = { |
| 37 | + CustomException: custom_exception_handler, |
| 38 | + Exception: general_exception_handler, |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +app = Starlette(exception_handlers=exception_handlers, middleware=middleware,) |
| 43 | + |
| 44 | +headers = {HeaderKeys.request_id: uuid.uuid4().hex} |
| 45 | + |
| 46 | + |
| 47 | +@app.route("/") |
| 48 | +async def index(_) -> NoReturn: |
| 49 | + raise RuntimeError |
| 50 | + |
| 51 | + |
| 52 | +@app.route("/custom-exc") |
| 53 | +async def index(_) -> NoReturn: |
| 54 | + raise CustomException |
| 55 | + |
| 56 | + |
| 57 | +client = TestClient(app) |
| 58 | + |
| 59 | + |
| 60 | +def test_exception_handling_that_is_not_resulting_in_500(): |
| 61 | + resp = client.get("/custom-exc", headers=headers) |
| 62 | + assert json.loads(resp.content) == {"exception": "handled"} |
| 63 | + assert ( |
| 64 | + resp.headers.get(HeaderKeys.request_id) |
| 65 | + == headers[HeaderKeys.request_id] |
| 66 | + ) |
0 commit comments