我正在尝试解决执行 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 中修复。
如果您使用点:
pip install --upgrade fastapi starlette
并像以前一样使用
with TestClient(app, base_url="http://localhost") as client:
。
我遇到了忽略警告并不能解决问题的问题。在尝试了多种解决方案后,我发现问题是由于
FastAPI
和 Starlette
软件包版本不兼容造成的。他们都需要彼此兼容。以下命令对我有用:
pip uninstall fastapi starlette pydantic -y
pip install fastapi==0.115.6