【问题标题】:How to assert expected HTTPExceptions in FastAPI Pytest?如何在 FastAPI Pytest 中断言预期的 HTTPExceptions?
【发布时间】:2021-03-28 14:58:44
【问题描述】:

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

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

我想断言异常被抛出,按照FastaAPI docs

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

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

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

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

【问题讨论】:

  • 似乎在get操作周围添加with pytest.raises(HTTPException) as e:...形式的“上下文管理器”,然后像assert e.value.status_code == 404, response.text一样断言就可以了。但也许有更优雅的方式?

标签: python pytest fastapi


【解决方案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 ======================================

【讨论】:

    【解决方案2】:

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

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

    我能够得到一个 pytest 来使用以下代码 sn-p:

    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!"
    

    似乎 err 是实际的 HTTPException 对象,而不是 json 表示。当您发现此错误时,您可以对该 HTTPException 对象进行断言。

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

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

    【讨论】:

      猜你喜欢
      • 2021-04-13
      • 2021-12-22
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多