使用 httpx AsyncClient 进行测试时如何禁用 fast-api 上的服务器异常?

Hou*_*man 7 python fastapi httpx

我们有一个 FastApi 应用程序并使用 httpx AsyncClient 进行测试。我们遇到一个问题,单元测试在本地运行良好,但在 CI 服务器上失败(Github Actions)。

经过进一步研究,我们通过设置找到了这个建议的解决方案raise_server_exceptions=FalseFalse

client = TestClient(app, raise_server_exceptions=False)
Run Code Online (Sandbox Code Playgroud)

但这适用于同步客户端。我们正在使用异步客户端。

@pytest.fixture
async def client(test_app):
    async with AsyncClient(app=test_app, base_url="http://testserver") as client:
        yield client
Run Code Online (Sandbox Code Playgroud)

AsyncClient 不支持该raise_app_exceptions=False选项。

有人对此有经验吗?谢谢

小智 2

该问题是由FastApi版本引起的。您可以使用fastapi==0.65.0,即使没有ASGITransport 对象和raise_app_exceptions=False标志,您也可以运行检查自定义异常引发的测试。

另外,fastapi 版本应该冻结在需求文件中。

你可以在这里阅读更多