Python - 模拟函数和断言异常

Python - mock function and assert exception

我用 FastAPI 构建了一个 API 与 DynamoDB 交互。 在我开始测试驱动开发的旅程时,我对模拟什么感到疑惑。 这是get方法,main.py:

router = FastAPI()

@router.get("/{device_id}")
def get_data(request: Request, device_id: str, query: DataQuery = Depends(DataQuery.depends)):
    da_service = DaService()
    try:
        start_time, end_time = DaService.validate_dates(query.start, query.end)
        return 'OK'
    except WrongDataFormat as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail='Internal Server Error')

在我开始创建成功测试的测试文件中,test_main.py:

from fastapi.testclient import TestClient
from unittest import mock
from utils.exceptions import WrongDataFormat
from endpoints.datalake import router

client = TestClient(router)

def test_success_response():
    with mock.patch('endpoints.datalake.DataApiService.get_datalake_data'):
        response = client.get('/xxxxx', params = {'start': '1629886483', 'end': '1629886504'})
        assert response.status_code == 200
        assert isinstance(response.json(), dict)

现在我想创建异常 WrongDataFormat 时的测试 returned,但我没有成功...这就是我现在拥有的:

def test_exception_response_():
    response = client.get('/xxxxx', params = {'2021-08-28', 'end': '2021-12-25'})
    assert response.status_code == 400

如何将函数 main.validate_dates 模拟为 return 异常 WrongDataFormat 并正确声明它?

如果您想测试响应的状态代码和消息,您必须使用 TestClient(app),其中 app 是 FastAPI 应用程序。将异常转换为适当的响应是应用程序的任务,而不是路由器(您正在测试的路由器)。

client = TestClient(app)

通过这种方式,您可以测试应用程序的 API(恕我直言,这是最有用的测试表面)。