diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index ffc8883b3..40cbd9a6e 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -33,20 +33,6 @@ def with_headers(request: Request) -> None: raise HTTPException(status_code=200, headers={"x-potato": "always"}) -class BadBodyException(HTTPException): - pass - - -async def read_body_and_raise_exc(request: Request) -> None: - await request.body() - raise BadBodyException(422) - - -async def handler_that_reads_body(request: Request, exc: BadBodyException) -> JSONResponse: - body = await request.body() - return JSONResponse(status_code=422, content={"body": body.decode()}) - - class HandledExcAfterResponse: async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: response = PlainTextResponse("OK", status_code=200) @@ -63,15 +49,11 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: Route("/with_headers", endpoint=with_headers), Route("/handled_exc_after_response", endpoint=HandledExcAfterResponse()), WebSocketRoute("/runtime_error", endpoint=raise_runtime_error), - Route("/consume_body_in_endpoint_and_handler", endpoint=read_body_and_raise_exc, methods=["POST"]), ] ) -app = ExceptionMiddleware( - router, - handlers={BadBodyException: handler_that_reads_body}, # type: ignore[dict-item] -) +app = ExceptionMiddleware(router, handlers=None) @pytest.fixture @@ -194,7 +176,31 @@ def test_exception_middleware_deprecation() -> None: starlette.exceptions.ExceptionMiddleware -def test_request_in_app_and_handler_is_the_same_object(client: TestClient) -> None: - response = client.post("/consume_body_in_endpoint_and_handler", content=b"Hello!") +class BadBodyException(HTTPException): + pass + + +async def read_body_and_raise_exc(request: Request) -> None: + await request.body() + raise BadBodyException(422) + + +async def handler_that_reads_body(request: Request, exc: BadBodyException) -> JSONResponse: + body = await request.body() + return JSONResponse(status_code=422, content={"body": body.decode()}) + + +def test_request_in_app_and_handler_is_the_same_object(test_client_factory: TestClientFactory) -> None: + app = ExceptionMiddleware( + Router( + routes=[ + Route("/consume_body_in_endpoint_and_handler", endpoint=read_body_and_raise_exc, methods=["POST"]), + ] + ), + handlers={BadBodyException: handler_that_reads_body}, # type: ignore[dict-item] + ) + with test_client_factory(app) as client: + response = client.post("/consume_body_in_endpoint_and_handler", content=b"Hello!") + assert response.status_code == 422 assert response.json() == {"body": "Hello!"}