FastAPI testing with Pytest
非常短,一下就講完了。
內容
TestClient
# main.py
from fastapi import FastAPIapp = FastAPI()@app.get("/")
async def read_main():
return {"msg": "Hello World"}
測試方式,使用 TestClient
模擬網頁服務,然後就可以針對此 object 來做像是 get, post 等等的互動 (*´∀`)~♥
# test_main.py
from fastapi.testclient import TestClientfrom .main import appclient = TestClient(app)def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"msg": "Hello World"}
延伸的用法
加上 Header
response = client.get("/items/baz", headers={"X-Token": "coneofsilence"})
再加上 json parameters
response = client.post(
"/items/",
headers={"X-Token": "hailhydra"},
json={
"id": "bazz",
"title": "Bazz",
"description": "Drop the bazz"
}
)
更多方法
可參考 requests ,它們的呼叫方法一樣
要注意的
因為這邊吃得是 json 格式,不是 pydantic 格式,因此需要轉換,你可以使用 jsonable_encoder
,可參考下面的網站看更多
from datetime import datetime
from typing import Optionalfrom fastapi.encoders import jsonable_encoder
from pydantic import BaseModelclass Item(BaseModel):
title: str
timestamp: datetime
description: Optional[str] = Noneapp = FastAPI()@app.put("/items/{id}")
def update_item(id: str, item: Item):
json_compatible_item_data = jsonable_encoder(item)
fake_db[id] = json_compatible_item_data
結論
自架的服務,用這個測試
如果是別人架的,要模擬 requests,可以用 response 這個套件 ヽ(✿゚▽゚)ノ
好用有趣推推