FastAPI测试客户端:POST请求体构造与验证最佳实践指南
def test_create_item_with_invalid_data():
invalid_payload = {"price": -10}
response = client.post("/items/", json=invalid_payload)
assert response.status_code == 422
errors = response.json()["detail"]
assert any(e["loc"] == ["body","price"] for e in errors)
assert any(e["msg"] == "ensure this value is greater than 0" for e in errors)
def test_create_nested_order():
order_data = {
"user": {
"id": "U123",
"addresses": [{
"city": "Shanghai",
"geo": {"lat": 31.23, "lng": 121.47}
}]
},
"items": [{
"sku": "A001",
"specs": {"color": "red", "sizes": ["S", "M"]}
}]
}
response = client.post("/orders", json=order_data)
assert response.json()["shipping_code"].startswith("SH")
def test_protected_endpoint():
auth_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
response = client.post(
"/secure-data",
json={"payload": "test"},
headers={"Authorization": f"Bearer {auth_token}"}
)
assert response.status_code == 200
@pytest.fixture def admin_client():
with TestClient(app) as client:
client.headers.update({"Authorization": f"Bearer {get_admin_token()}"})
yield client