FastAPI 测试
用 TestClient 和 pytest 检查请求契约,隔离应用状态并安全恢复依赖覆盖。
学完这一章,你能够
- 用 TestClient 和 pytest 检查请求契约,隔离应用状态并安全恢复依赖覆盖。
TestClient 测应用,服务器测试测传输
TestClient 将请求交给 ASGI 应用,无需启动 Uvicorn 或使用 TCP。其 HTTP 客户端接口可传 json、params 和 headers。本机记录 FastAPI、Starlette 和实际客户端版本。旧版常装 httpx,本工程依赖当前 Starlette 使用的 httpx2。
本站用 with TestClient(app) 进入应用生命周期。目录示例在启动时设置状态,退出后恢复。测试路由逻辑时可用这种进程内方式,浏览器、TLS 和代理行为还需实际服务器。
把输入与断言放在一起
先 POST 自编样本并检查 201 与字段,再 GET 相同编号核对数据。PUT 后重新 GET 验证结果真实更新。DELETE 返回 204,无正文,再读取确认 404。既检查状态,也检查正文和副作用。
使用 params 发送 offset、limit,使用 headers 发送 X-Lab-Tag。输入错误编号时断言 422 及 path.key,省略价格时定位 body.price。找不到资源的 404 与输入格式错误是两个分支。
pytest 发现、输出和依赖覆盖
把测试放进 tests/test_lab.py。pytest 会发现 test_ 文件与函数,可以运行整个目录或在文件后用 :: 指定函数。-v 增加输出细节,-s 关闭捕获。本站运行整组,并对依赖覆盖测试实际使用 -v -s。
app.dependency_overrides 用原依赖函数作键。测试暂时替换 get_label,在 finally 中移除本次添加项,再请求确认真实实现恢复。创建新应用能隔离记录、覆盖和生命周期。已有其他覆盖时应恢复各自的原值。
创建、更新、删除和依赖覆盖的测试
展开查看收起
from datetime import datetime,timedelta,timezone
import json
import os
from pathlib import Path
from secrets import token_bytes
import sqlite3
import jwt
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.exc import IntegrityError
from database import SessionLocal,database_path,engine
from db_models import Account,Note
from main import app
from security_lab import (audience,fixture_password,hasher,issue,issuer,members,
signing_key,verify_password)
from catalog_lab import get_label,make_catalog
def check(name,inputs,expected,actual,operation="Run the named assertion on the local application."):
assert actual==expected,(name,inputs,expected,actual)
if output:=os.environ.get("MBSKY_CASE_OUTPUT"):
with Path(output).open("a",encoding="utf8") as stream:
stream.write(json.dumps(dict(name=name,input=inputs,expected=expected,actual=actual,operation=operation),
ensure_ascii=False)+"\n")
def pair(response):
return [response.status_code,response.json()]
def token_headers(value):
return {"Authorization":"Bearer "+value}
def test_security_password_and_docs():
with TestClient(app) as c:
base={"grant_type":"password","username":"reader","password":fixture_password}
result=c.post("/token",data=base)
token=result.json()["access_token"]
outcome=jwt.decode(token,signing_key,algorithms=["HS256"],issuer=issuer,audience=audience)
check("password form issues JWT","local synthetic login",[200,"bearer","reader",300,True],
[result.status_code,result.json()["token_type"],outcome["sub"],outcome["exp"]-outcome["iat"],
outcome["nbf"]==outcome["iat"]])
for name,data in (("wrong password",{**base,"password":"wrong"}),
("unknown account",{**base,"username":"absent"}),
("inactive account at login",{**base,"username":"inactive"})):
r=c.post("/token",data=data)
check(name,name,[401,"Bearer",{"detail":"credentials invalid"}],
[r.status_code,r.headers["www-authenticate"],r.json()])
missing=c.post("/token",data={k:v for k,v in base.items() if k!="grant_type"})
check("strict password form needs grant_type","missing grant_type",422,missing.status_code)
headers=token_headers(token)
check("current public member","valid bearer",[200,{"handle":"reader","disabled":False}],
pair(c.get("/members/me",headers=headers)))
check("protected notes derive owner","valid bearer",[200,[{"title":"北岸","owner":"reader"}]],
pair(c.get("/members/me/notes",headers=headers)))
check("inactive bearer rejected","valid token for inactive account",[403,{"detail":"account inactive"}],
pair(c.get("/members/me",headers=token_headers(issue("inactive")))))
doc=c.get("/openapi.json").json()
scheme=doc["components"]["securitySchemes"]["OAuth2PasswordBearer"]
check("OAuth schema tokenUrl","OpenAPI",[{"OAuth2PasswordBearer":[]}, "token"],
[doc["paths"]["/members/me"]["get"]["security"][0],scheme["flows"]["password"]["tokenUrl"]])
first=members["reader"].password_hash
second=hasher.hash(fixture_password)
check("Argon2id hash and verify","one synthetic password",[True,True,True,False],
[first.startswith("$argon2id$"),first!=second,verify_password(fixture_password,second),
verify_password("wrong",second)],"Hash the same fixture twice and verify correct and wrong input.")
def test_token_rejection_and_alternatives():
with TestClient(app) as c:
now=datetime.now(timezone.utc)
claims={"sub":"reader","iss":issuer,"aud":audience,"iat":now,"nbf":now,"exp":now+timedelta(minutes=5)}
encode=lambda value,key=signing_key,algorithm="HS256": jwt.encode(value,key,algorithm=algorithm)
invalid=[
("no bearer",{}),("malformed JWT",token_headers("not-a-token")),
("invalid signature",token_headers(encode(claims,key=token_bytes(32)))),
("algorithm outside allowlist",token_headers(encode(claims,key=token_bytes(48),algorithm="HS384"))),
("expired JWT",token_headers(issue("reader",timedelta(seconds=-10)))),
("future not-before",token_headers(encode({**claims,"nbf":now+timedelta(minutes=1)}))),
("wrong audience",token_headers(encode({**claims,"aud":"other"}))),
("wrong issuer",token_headers(encode({**claims,"iss":"other"}))),
("missing subject",token_headers(encode({k:v for k,v in claims.items() if k!="sub"}))),
("unknown subject",token_headers(issue("absent"))),
]
for name,headers in invalid:
r=c.get("/members/me",headers=headers)
check(name,name,[401,"Bearer"],[r.status_code,r.headers["www-authenticate"]])
accepted=c.get("/legacy-basic",auth=("reader",fixture_password))
denied=c.get("/legacy-basic",auth=("reader","wrong"))
check("Basic success and challenge","synthetic credentials",
[[200,{"channel":"basic"}],401,"Basic"],[pair(accepted),denied.status_code,denied.headers["www-authenticate"]])
answers=[c.get("/key/header",headers={"X-Lab-Key":"fixture-key"}),
c.get("/key/query",params={"lab_key":"fixture-key"}),
c.get("/key/cookie",headers={"Cookie":"lab_key=fixture-key"})]
check("API keys in three locations","synthetic header, query and cookie",
[[200,{"channel":v}] for v in ("header","query","cookie")],[pair(r) for r in answers])
check("API key missing or wrong","none and invalid",[401,401],
[c.get("/key/header").status_code,c.get("/key/header",headers={"X-Lab-Key":"wrong"}).status_code])
def test_catalog_methods_and_errors():
lab=make_catalog()
with TestClient(lab) as c:
check("TestClient startup and root","GET /",[200,{"ready":True}],pair(c.get("/")))
original={"name":"北岸","price":4.5}
check("TestClient POST body",original,[201,{"id":1,**original}],pair(c.post("/samples",json=original)))
check("TestClient GET record",1,[200,original],pair(c.get("/samples/1")))
altered={"name":"南岸","price":7.5}
check("TestClient PUT then GET",altered,[[200,altered],[200,altered]],
[pair(c.put("/samples/1",json=altered)),pair(c.get("/samples/1"))])
removed=c.delete("/samples/1")
check("TestClient DELETE then 404",1,[204,"",[404,{"detail":"sample missing"}]],
[removed.status_code,removed.content.hex(),pair(c.get("/samples/1"))])
invalid=c.get("/samples/wrong")
check("TestClient path error", "wrong",[422,["path","key"]],
[invalid.status_code,invalid.json()["detail"][0]["loc"]])
invalid=c.post("/samples",json={"name":"north"})
check("TestClient body error","price omitted",[422,["body","price"]],
[invalid.status_code,invalid.json()["detail"][0]["loc"]])
check("TestClient lifespan shutdown","leave TestClient context",False,lab.state.started)
def test_catalog_request_context_and_override():
lab=make_catalog()
with TestClient(lab) as c:
r=c.get("/context",params={"offset":5,"limit":20},headers={"X-Lab-Tag":"fixture"})
check("TestClient query and headers","offset=5 limit=20 X-Lab-Tag",
[200,{"offset":5,"limit":20,"x_lab_tag":"fixture"}],pair(r))
before=c.get("/label").json()["label"]
try:
lab.dependency_overrides[get_label]=lambda:"overridden"
during=c.get("/label").json()["label"]
finally:
del lab.dependency_overrides[get_label]
after=c.get("/label").json()["label"]
check("dependency override restored","before, during, after",["live label","overridden","live label"],
[before,during,after])
isolated=make_catalog()
with TestClient(isolated) as c:
check("factory creates isolated test state","fresh app GET record",404,c.get("/samples/1").status_code)
def test_sqlalchemy_round_trip():
with TestClient(app) as c:
app.state.db_events=[]
data={"email":"local-fixture@example.test","password":"long-local-fixture"}
create=c.post("/db/accounts",json=data)
record=create.json()
key=record["id"]
check("ORM account output","create independent account",[201,{"id":key,"email":data["email"],"active":True}],
pair(create))
check("ORM duplicate and missing account","repeat email and read absent id",[409,404],
[c.post("/db/accounts",json=data).status_code,c.get("/db/accounts/90000").status_code])
check("ORM filters and paginates","read with offset 0, limit 1",[[record],[]],
[c.get("/db/accounts?offset=0&limit=1").json(),c.get("/db/accounts?offset=10000&limit=1").json()])
new=c.post(f"/db/accounts/{key}/notes",json={"title":"水位记录"})
note=new.json()["id"]
check("ORM note owner and missing owner","existing and missing foreign key",
[[201,{"id":note,"owner_id":key,"title":"水位记录"}],404],
[pair(new),c.post("/db/accounts/90000/notes",json={"title":"missing"}).status_code])
with SessionLocal() as session:
account=session.get(Account,key)
check("ORM relationship traversal","follow both sides of account-note mapping",
[["水位记录"],key],[[row.title for row in account.notes],session.get(Note,note).owner.id])
replacement=c.put(f"/db/notes/{note}",json={"title":"风向记录"})
check("ORM update read delete","replace note, list, delete",[200,"风向记录",204,[]],
[replacement.status_code,c.get("/db/notes").json()[0]["title"],
c.delete(f"/db/notes/{note}").status_code,c.get("/db/notes").json()])
events=app.state.db_events
check("session lifecycle and checkin","successful and failing requests",[True,True,0],
[all(events[i][0]==events[i+1][0] and events[i][1:]==("open",)
and events[i+1][1:]==("close",) for i in range(0,len(events),2)),
len(events)==len(set(events)),engine.pool.checkedout()])
connection=sqlite3.connect(database_path)
try:
encoded=connection.execute("SELECT password_hash FROM accounts WHERE id=?",(key,)).fetchone()[0]
finally:
connection.close()
check("SQLite stores Argon2id","query disk independently",[True,True,False],
[encoded.startswith("$argon2id$"),verify_password(data["password"],encoded),encoded==data["password"]])
with SessionLocal() as session:
assert session.get(Account,key).email==data["email"]
session.add(Note(owner_id=90000,title="invalid"))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
check("SQLite FK and rollback recovery","direct invalid foreign key then SELECT",data["email"],
session.get(Account,key).email)
def test_blog_api_and_contract():
with TestClient(app) as c:
check("blog root JSON","GET /",[200,{"message":"欢迎来到蓝色天空网观测日记"}],pair(c.get("/")))
check("blog dynamic path","GET /hello/蓝湾",[200,{"greeting":"你好,蓝湾"}],pair(c.get("/hello/蓝湾")))
schema=c.get("/openapi.json").json()
op=schema["paths"]["/hello/{name}"]["get"]
check("blog schema metadata","/openapi.json",["蓝色天空网观测日记","1.0.0",True,"string"],
[schema["info"]["title"],schema["info"]["version"],op["parameters"][0]["required"],
op["parameters"][0]["schema"]["type"]])
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
完整开发工程
解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
进入覆盖前和清理后是 live label,覆盖时是 overridden。