推荐答案
在 FastAPI 中使用 pytest 进行测试时,通常需要编写测试用例来验证 API 的行为。以下是一个简单的示例,展示了如何使用 pytest 测试 FastAPI 应用。
// www.javascriptcn.com code example
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello World"}
client = TestClient(app)
def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}本题详细解读
1. 创建 FastAPI 应用
首先,我们需要创建一个 FastAPI 应用实例。在这个例子中,我们定义了一个简单的路由 /,它返回一个 JSON 响应 {"message": "Hello World"}。
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello World"}2. 使用 TestClient 进行测试
TestClient 是 FastAPI 提供的一个工具,用于模拟 HTTP 请求。我们可以使用它来测试我们的 API 端点。
from fastapi.testclient import TestClient client = TestClient(app)
3. 编写测试用例
接下来,我们编写一个测试用例 test_read_root,它使用 TestClient 发送一个 GET 请求到 / 路由,并验证响应的状态码和内容。
def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}4. 运行测试
最后,我们可以使用 pytest 命令来运行测试。确保你的测试文件命名为 test_*.py 或者 *_test.py,这样 pytest 可以自动发现并运行测试。
pytest
通过这种方式,你可以轻松地为 FastAPI 应用编写和运行测试,确保 API 的行为符合预期。