多亏了Starlette,测试FastAPI应用变得简单而愉快。
它是基于Request的,所以非常熟悉和直观。
有了它,你可以直接用FastAPI使用pytest。
使用TestClient
导入TestClient
创建一个TestClient,将你的FastAPI传递给它。
创建一个以test_ 开头的函数(pytest的标准)
使用TestClient 对象的方法和使用requests一样。
用标准Python表达式写简单的assert语句。
from fastapi import FastAPIfrom fastapi.testclient import TestClientapp = FastAPI()@app.get("/")async def read_main():return {"msg": "Hello World"}client = TestClient(app)def test_read_main():response = client.get("/")assert response.status_code == 200assert response.json() == {"msg": "Hello World"}
:::info
Tip
注意,测试函数是正常的def,而不是async def
对客户端的调用也是正常调用,不使用 await
这让你可以直接使用pytest,而不会出现异常的情况。
:::
:::tips
技术细节
也可以使用from starlette.testclient import TestClient.
FastAPI 提供了相同的方法 fastapi.testclient 仅仅是一个便利,依然来自于Starlette.
:::
:::info
Tip
如果你想在你的测试中除了向FastAPI应用程序发送请求之外,还想调用异步函数(例如异步数据库函数),请看看高级教程中的异步测试。
:::
分离测试
在真实的应用中,你可能会把你的测试放在不同的文件中。
而你的FastAPI应用也可能由多个文件/模块等组成。
FastAPI应用文件
假设你的FastAPI应用有一个main.py文件
from fastapi import FastAPIapp = FastAPI()@app.get("/")async def read_main():return {"msg": "Hello World"}
测试文件
然后,在你的测试目录中可以有一个test_main.py文件,导入app的main模块(main.py)
from fastapi.testclient import TestClientfrom .main import appclient = TestClient(app)def test_read_main():response = client.get("/")assert response.status_code == 200assert response.json() == {"msg": "Hello World"}
测试:扩展示例
现在让我们扩展这个例子,并添加更多细节,看看如何测试不同的部分。
扩展FastAPI app文件
比方说,你的FastAPI应用有一个main_b.py文件。
有一个GET操作可以返回一个错误。
有一个POST操作可以返回一个内部错误。
这两种路径操作都需要一个X-Token头。
from typing import Optionalfrom fastapi import FastAPI, Header, HTTPExceptionfrom pydantic import BaseModelfake_secret_token = "coneofsilence"fake_db = {"foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},"bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},}app = FastAPI()class Item(BaseModel):id: strtitle: strdescription: Optional[str] = None@app.get("/items/{item_id}", response_model=Item)async def read_main(item_id: str, x_token: str = Header(...)):if x_token != fake_secret_token:raise HTTPException(status_code=400, detail="Invalid X-Token header")if item_id not in fake_db:raise HTTPException(status_code=404, detail="Item not found")return fake_db[item_id]@app.post("/items/", response_model=Item)async def create_item(item: Item, x_token: str = Header(...)):if x_token != fake_secret_token:raise HTTPException(status_code=400, detail="Invalid X-Token header")if item.id in fake_db:raise HTTPException(status_code=400, detail="Item already exists")fake_db[item.id] = itemreturn item
扩展测试文件
有一个test_main_b.py文件
from fastapi.testclient import TestClientfrom .main_b import appclient = TestClient(app)def test_read_item():response = client.get("/items/foo", headers={"X-Token": "coneofsilence"})assert response.status_code == 200assert response.json() == {"id": "foo","title": "Foo","description": "There goes my hero",}def test_read_item_bad_token():response = client.get("/items/foo", headers={"X-Token": "hailhydra"})assert response.status_code == 400assert response.json() == {"detail": "Invalid X-Token header"}def test_read_inexistent_item():response = client.get("/items/baz", headers={"X-Token": "coneofsilence"})assert response.status_code == 404assert response.json() == {"detail": "Item not found"}def test_create_item():response = client.post("/items/",headers={"X-Token": "coneofsilence"},json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"},)assert response.status_code == 200assert response.json() == {"id": "foobar","title": "Foo Bar","description": "The Foo Barters",}def test_create_item_bad_token():response = client.post("/items/",headers={"X-Token": "hailhydra"},json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"},)assert response.status_code == 400assert response.json() == {"detail": "Invalid X-Token header"}def test_create_existing_item():response = client.post("/items/",headers={"X-Token": "coneofsilence"},json={"id": "foo","title": "The Foo ID Stealers","description": "There goes my stealer",},)assert response.status_code == 400assert response.json() == {"detail": "Item already exists"}
每当你需要客户端在请求中传递信息,而你又不知道如何传递时,你可以搜索(Google)如何在requests中传递信息。
那你就在你的测试中做同样的事情:
- 要传递一个路径或查询参数,将其添加到URL本身。
- 要传递一个JSON体,需要向参数json传递一个Python对象(例如dict)。
- 如果你需要发送 Form Data而不是JSON,请使用data参数代替。
- 要传递头文件,请在头文件参数中使用dict。
- 对于cookie,在cookie参数中的dict。
关于如何将数据传递到后端(使用请求或TestClient)的更多信息,请查看 Requests documentation.
:::info
info
请注意,TestClient接收的是可以转换为JSON的数据,而不是Pydantic模型。
如果您的测试中有一个Pydantic模型,并且您想在测试期间将其数据发送到应用程序,您可以使用JSON Compatible Encoder中描述的 JSON Compatible Encoder.
:::
运行
需要安装pytest
pip install pytest
它将自动检测文件和测试,执行它们,并将结果报告给你。
运行测试与:
pytest================ test session starts ================platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1rootdir: /home/user/code/superawesome-cli/appplugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1collected 6 items████████████████████████████████████████ 100%test_main.py ...... [100%]================= 1 passed in 0.03s =================
