6

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

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

client = TestClient(app, raise_server_exceptions=False)

但是,这是针对同步客户端的。我们正在使用异步客户端。

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

AsyncClient 不支持该raise_app_exceptions=False选项。

这个事情谁有经验?谢谢

4

2 回答 2

2

该问题是由 FastApi 版本引起的。您可以使用fastapi==0.65.0,即使没有ASGITransport 对象和 raise_app_exceptions=False 标志,您也可以运行检查自定义异常引发的测试。此外,fastapi 版本应该被冻结在需求文件中。你可以在这里阅读更多

于 2021-10-13T09:43:13.400 回答
1

对于httpxv0.14.0+,您需要使用httpx.ASGITransport. 摘自官方文档

对于一些更复杂的情况,您可能需要自定义 ASGI 传输。这使您可以:

  • 通过设置 raise_app_exceptions=False 来检查 500 个错误响应而不是引发异常。
  • 通过设置 root_path 将 ASGI 应用程序挂载到子路径。
  • 通过设置客户端使用给定的客户端地址进行请求。

例如:

# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",
# on port 123.
transport = httpx.ASGITransport(app=app, raise_app_exceptions=False,
 client=("1.2.3.4", 123))
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
    ...
于 2021-10-12T14:44:42.527 回答