【问题标题】:How to disable server exceptions on fast-api when testing with httpx AsyncClient?使用httpx AsyncClient进行测试时如何禁用fast-api上的服务器异常?
【发布时间】:2021-10-12 14:20:47
【问题描述】:

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

经过进一步研究,我们通过将raise_server_exceptions=False 设置为False 发现了这个proposed solution

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 选项。

有人有这方面的经验吗? 谢谢

【问题讨论】:

    标签: python fastapi httpx


    【解决方案1】:

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

    【讨论】:

    • 啊,我明白了。这是0.70.0 版本中的一个错误。
    【解决方案2】:

    对于httpx v0.14.0+,您需要使用httpx.ASGITransport。 摘自official documentation

    对于一些更复杂的情况,您可能需要自定义 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:
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 2013-10-16
      • 1970-01-01
      相关资源
      最近更新 更多