question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

exception_handlers not triggered during unit tests

See original GitHub issue

Hi, 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:open
  • Created 3 years ago
  • Reactions:2
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
gusmithcommented, Oct 1, 2021

@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:

client = TestClient(app, raise_server_exceptions=False)

the server should not raise the exceptions when they occur, but instead return the http error you are expecting. In the docs from starlette

By default the TestClient will raise any exceptions that occur in the application. Occasionally you might want to test the content of 500 error responses, rather than allowing client to raise the server exception. In this case you should use client = TestClient(app, raise_server_exceptions=False).

2reactions
lays147commented, Feb 28, 2021

@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.

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found