我有一个简单的FastAPI应用程序,我正在尝试pytest
为它创建测试。
我的目标是测试应用程序在出现不同错误时的行为方式。
我的应用中有一个简单的健康检查路线:
from fastapi import APIRouter
router = APIRouter()
@router.get("/health")
async def health():
return "It's working ✨"
现在在我的 pytest 模块中,我试图修补上面的函数,以便它引发不同的错误。我正在使用unittest.mock
,但我的行为很奇怪。
import pytest
from unittest import mock
from fastapi import HTTPException
from starlette.testclient import TestClient
import app.api.health
from app.main import app # this is my application (FastAPI instance) with the `router` attached
@pytest.fixture()
def client():
with TestClient(app) as test_client:
yield test_client
def test_simple(client):
def mock_health_function():
raise HTTPException(status_code=400, detail='gibberish')
with mock.patch('app.api.health.health', mock_health_function):
response = client.get(HEALTHCHECK_PATH)
with pytest.raises(HTTPException): # this check passes successfully - my exception is raised
app.api.health.health()
assert response.status_code != 200 # this check does not pass. The original function was called as if nothing was patched
尽管在测试中调用了完全相同的函数,但当我到达端点时,API 测试客户端仍然调用原始函数。
mock.patch
测试中不直接调用函数,为什么不能正常工作?
或者也许我应该以不同的方式解决我的问题?