简体   繁体   中英

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?

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 .

May be you can do this using the following sample code.

~/Desktop/fastapi_sample  $ cat service.py                                 
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/wrong")
async def wrong_url():
    raise HTTPException(status_code=400, detail="404 test!")

~/Desktop/fastapi_sample $ cat test_service.py                            
from fastapi.testclient import TestClient
from fastapi_sample.service import app
client = TestClient(app)


def test_read_item_bad_token():
    response = client.get("/wrong")
    assert response.status_code == 400
    assert response.json() == {"detail": "404 test!"}%                                                                                                        
    
~/Desktop/fastapi_sample $ pytest                                         
==================================================================== test session starts ====================================
platform darwin -- Python 3.7.9, pytest-6.1.0, py-1.9.0, pluggy-0.13.1
rootdir: /Users/i869007/Desktop/workspace/SAP/cxai/fastapi_postgres_tutorial
collected 1 item

test_service.py .                                                                                                                                      [100%]

===================================================================== 1 passed in 0.78s ======================================

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM