PyTest 夹具:如何解决警告 FastAPI 'app' 快捷方式已弃用?

问题描述 投票:0回答:1

我正在尝试解决执行 pytests 时出现的警告:

/usr/local/lib/python3.11/site-packages/httpx/_client.py:680: 
DeprecationWarning: The 'app' shortcut is now deprecated. 
Use the explicit style 'transport=WSGITransport(app=...)' instead.
warnings.warn(message, DeprecationWarning)

我知道这里也有人问过类似的问题:

如何使用 Annotated 和 Depends 为涉及 Pydantic 模型的依赖注入的 FastAPI 路由编写 pytest 测试?

但我仍然不知道如何避免这个警告。

我有这个Python测试装置:

@pytest.fixture
def client(app: FastAPI) -> Generator:
    with TestClient(app, base_url="http://localhost") as client:
        yield client

但是如果我将其更改为前面提到的链接中建议的内容:

@pytest.fixture
def client()-> Generator:
  """Fixture to create a FastAPI test client."""
  # instead of app = app, use this to avoid the DeprecationWarning:
  with TestClient(transport=ASGITransport(app=app), base_url="http://localhost") as 
 client:
      yield client

我的测试无法通过,而是出现了这个新错误:

TypeError: TestClient.__init__() got an unexpected keyword argument 'transport'
python pytest fastapi suppress-warnings
1个回答
0
投票

只需将 fastapi 和 starlette 升级到最新版本即可。此问题已在 starlette 0.37.2 中修复(https://www.starlette.io/release-notes/#0372):

如果您使用点:

pip install --upgrade fastapi starlette

并像以前一样使用

with TestClient(app, base_url="http://localhost") as client:

© www.soinside.com 2019 - 2024. All rights reserved.