exception_handlers not triggered during unit tests
See original GitHub issueHi, I’m using exception_handlers to handle 500 and 503 HTTP codes. However when unit testing, they are ignored. If I start the server and test the route, the handler works properly.
# main.py
@app.exception_handler(Exception)
def handle_500_error(request: Request, exception: Exception) -> JSONResponse:
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content=json.dumps({"detail":'Internal Server Error, contact support'}),
)
@app.exception_handler(OperationalError)
def handle_503_error(request: Request, exception: Exception) -> JSONResponse:
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content=json.dumps({"detail":'Service Unavailable, contact support'}),
# function
@router.get("/{partner_id}")
def get_partner_by_id(partner_id: str, db: Session = Depends(get_db)):
"""
Retrieve a partner from the database by given id
:param [partner_id]: id to be searched
:returns: partner data
"""
db_partner = search_partner_by_id(db=db, partner_id=partner_id)
if not db_partner:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Partner not found"
)
return Partner.from_orm(db_partner).dict(by_alias=True)
# test
def test_get_partner_by_id_503(client: TestClient, valid_body: dict) -> None:
with patch(
"partner_api.routers.partners.search_partner_by_id", side_effect=OperationalError
):
query = f"/partners/{valid_body['id']}"
response = client.get(query)
assert (
response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
), response.json()
Environment
Python 3.8.6 fastapi==0.63.0
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:5 (1 by maintainers)
Top Results From Across the Web
ControllerAdvice not triggered on unit testing - Stack Overflow
I need to test @ControllerAdvice methods which are in service layer. But I faced two issues: ExceptionHandlers not triggered. And even if it ......
Read more >apex - How to unit test exception handling when the source of ...
So, in your place, I would create class called OtherClassMethodResult, that would include information about exceptions and probably something ...
Read more >How to test a controller in Spring Boot - a practical guide
How to test Spring Boot controllers: a practical guide with examples of unit tests and integration tests with and without MockMvc.
Read more >Unit testing $provide.decorator("$exceptionHandler") is this ...
I have tried loading my whole app in the test i.e. 'myApp' but this to just hang ... my service and ensure it...
Read more >Testing Exceptions with Spring MockMvc | Baeldung
User management is very complex, when implemented properly. No surprise here. Not having to roll all of that out manually, ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@lays147 This may be indeed the same issue as #2799 In my case, the solution was to update one of the argument from the
TestClient
:raise_server_exceptions
which is by default set to True. You are not showing how you build the test client, but if you create it this way:the server should not raise the exceptions when they occur, but instead return the http error you are expecting. In the docs from starlette
@Kludex thanks for the tip. Ok, but that does not explain why both handlers work when I have the server running and testing via curl or why the handler for
OperationalError
does not work during the unit test. Also, the code sample is reproducible, as you can see on the test I’m mocking the database function to raise the exception, one just need to setup the fast API app.