Skip to content

Commit

Permalink
test: Update tests/test_exceptions.py to include coverage for in [m…
Browse files Browse the repository at this point in the history
  • Loading branch information
lealre committed Dec 10, 2024
1 parent 8a99adf commit 13418c2
Showing 1 changed file with 27 additions and 21 deletions.
48 changes: 27 additions & 21 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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!"}

0 comments on commit 13418c2

Please sign in to comment.