如何在 FastAPI Pytest 中断言预期的 HTTPException?

Jak*_*yko 6 python pytest fastapi

我有一个简单的路由器,旨在抛出HTTPException

@router.get('/404test')
async def test():
    raise HTTPException(HTTP_404_NOT_FOUND, "404 test!")
Run Code Online (Sandbox Code Playgroud)

我想断言抛出了异常,根据FastaAPI 文档

def test_test():
    response = client.get("/404test")
    assert response.status_code == 404
Run Code Online (Sandbox Code Playgroud)

在评估断言之前抛出异常,将测试标记为失败:

>       raise HTTPException(HTTP_404_NOT_FOUND, "404 test!")
E       fastapi.exceptions.HTTPException: (404, '404 test!')
Run Code Online (Sandbox Code Playgroud)

HTTPExceptions我在测试中缺少什么来正确预测?

Rya*_*ngi 5

假设我们在 fastapi 应用程序中设置了以下路由:

@router.get('/404test')
async def test():
    raise HTTPException(HTTP_404_NOT_FOUND, "404 test!")
Run Code Online (Sandbox Code Playgroud)

我能够使用以下代码片段进行 pytest 工作:

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!"
Run Code Online (Sandbox Code Playgroud)

看起来 err 是实际的 HTTPException 对象,而不是 json 表示形式。当您捕获此错误时,您可以对该 HTTPException 对象进行断言。

确保在语句块assert之外运行断言 () with,因为当引发错误时,它会在 http 调用之后停止块内的所有执行,因此您的测试将通过,但断言永远不会计算。

您可以使用 来引用异常的详细信息、状态代码以及任何其他属性err.value.XXX


小智 1

也许您可以使用以下示例代码来做到这一点。

~/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 ======================================
Run Code Online (Sandbox Code Playgroud)