Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert expected HTTPExceptions in FastAPI Pytest?

I have a simple router designed to throw an HTTPException:

@router.get('/404test')
async def test():
    raise HTTPException(HTTP_404_NOT_FOUND, "404 test!")

I want to assert that the exception was thrown, as per FastaAPI docs:

def test_test():
    response = client.get("/404test")
    assert response.status_code == 404

The exception is thrown before the assertion gets evaluated, marking test as failed:

>       raise HTTPException(HTTP_404_NOT_FOUND, "404 test!")
E       fastapi.exceptions.HTTPException: (404, '404 test!')

What am I missing to properly anticipate HTTPExceptions in my test?

like image 944
Jakub Strebeyko Avatar asked Jun 25 '26 04:06

Jakub Strebeyko


1 Answers

Assuming we have the following route set up in our fastapi app:

@router.get('/404test')
async def test():
    raise HTTPException(HTTP_404_NOT_FOUND, "404 test!")

I was able to get a pytest to work with the following code snippet:

from fastapi import HTTPException

def test_test():
    with pytest.raises(HTTPException) as err:
        client.get("/404test")
    assert err.value.status_code == 404
    assert err.value.detail == "404 test!"

It seems that the err is the actual HTTPException object, not the json representation. When you catch this error you can then make assertions on that HTTPException object.

Make sure you run the assertions (assert) outside of the with statement block because when the error is raised, it stops all execution within the block after the http call so your test will pass but the assertions will never evaluate.

You can reference the details and the status code and any other attributes on the Exception with err.value.XXX.

like image 89
R. Angi Avatar answered Jun 26 '26 16:06

R. Angi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!