深入理解 FastAPI 测试:TestClient带你飞起来
fastapi.testclient.TestClient
是 FastAPI 提供的一个测试客户端,它允许你在不启动外部 HTTP 服务器的情况下,对 FastAPI 应用进行测试。这对于单元测试和集成测试非常有用。以下是如何使用 TestClient
来测试你的 FastAPI 应用的步骤:
-
创建 FastAPI 应用实例:
首先,你需要创建一个 FastAPI 应用实例。from fastapi import FastAPIapp = FastAPI()
-
定义路由和依赖项:
在你的 FastAPI 应用中定义路由和任何必要的依赖项。@app.get("/items/{item_id}") def read_item(item_id: int, q: str = None):return {"item_id": item_id, "q": q}
-
创建 TestClient 实例:
使用你的 FastAPI 应用实例创建一个TestClient
对象。from fastapi.testclient import TestClientclient = TestClient(app)
-
使用 TestClient 发送请求:
使用TestClient
的方法(如get
,post
,put
,delete
等)来模拟客户端请求。response = client.get("/items/123")
-
检查响应:
检查响应的状态码、内容和其他信息,确保它们符合预期。assert response.status_code == 200 assert response.json() == {"item_id": 123, "q": None}
-
使用请求体和查询参数:
你可以传递请求体和查询参数来测试不同的路由行为。response = client.get("/items/123", params={"q": "some query"}) assert response.json() == {"item_id": 123, "q": "some query"}
-
测试 POST 请求:
对于 POST 请求,你可以传递 JSON 数据作为请求体。response = client.post("/items/", json={"item_id": 123, "name": "New item"}) assert response.status_code == 200
-
测试异常和错误处理:
你还可以测试异常和错误处理,确保你的应用能够正确处理错误情况。response = client.get("/items/abc") # 非整数 ID assert response.status_code == 422 # 假设你的应用对这种情况返回 422 Unprocessable Entity
-
集成测试:
你可以编写集成测试来测试多个路由和依赖项之间的交互。 -
使用测试夹具:
在测试中,你可以使用测试夹具(fixtures)来设置和清理测试环境。
下面是一个完整的测试示例,展示了如何使用 TestClient
来测试一个简单的 FastAPI 应用:
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strprice: floattax: float = None@app.post("/items/")
async def create_item(item: Item):return {"name": item.name, "price": item.price, "tax": item.tax}client = TestClient(app)def test_create_item():response = client.post("/items/", json={"name": "Item1", "price": 10.5, "tax": 1.5})assert response.status_code == 200assert response.json() == {"name": "Item1", "price": 10.5, "tax": 1.5}# 运行测试
test_create_item()
使用 TestClient
进行测试可以帮助你确保你的 API 按照预期工作,同时也可以作为文档的一部分来展示 API 的使用方式。这样如果你在jupyter-notebook内写代码并且带上TescClient你会飞起来