我正在尝试解决执行 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'
只需将 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: