推荐答案
在 FastAPI 中,测试身份验证可以通过以下步骤进行:
- 创建测试客户端:使用
TestClient来模拟 HTTP 请求。 - 模拟身份验证:通过传递正确的身份验证头(如
Authorization头)来模拟已认证的用户。 - 验证响应:检查返回的响应状态码和内容是否符合预期。
以下是一个示例代码:
// www.javascriptcn.com code example
from fastapi.testclient import TestClient
from main import app # 假设你的 FastAPI 应用在 main.py 中
client = TestClient(app)
def test_authenticated_endpoint():
# 模拟身份验证
headers = {
"Authorization": "Bearer valid_token_here"
}
# 发送请求
response = client.get("/protected-endpoint", headers=headers)
# 验证响应
assert response.status_code == 200
assert response.json() == {"message": "You are authenticated"}
def test_unauthenticated_endpoint():
# 不传递身份验证头
response = client.get("/protected-endpoint")
# 验证响应
assert response.status_code == 401
assert response.json() == {"detail": "Not authenticated"}本题详细解读
1. 创建测试客户端
在 FastAPI 中,TestClient 是一个用于测试的工具,它可以模拟 HTTP 请求。通过 TestClient,你可以像发送 HTTP 请求一样调用你的 FastAPI 应用,并检查返回的响应。
from fastapi.testclient import TestClient from main import app client = TestClient(app)
2. 模拟身份验证
FastAPI 通常使用 OAuth2 或 JWT 进行身份验证。在测试中,你可以通过传递 Authorization 头来模拟已认证的用户。Authorization 头通常包含一个 Bearer Token。
headers = {
"Authorization": "Bearer valid_token_here"
}3. 验证响应
在发送请求后,你需要验证返回的响应是否符合预期。通常,你会检查状态码和响应内容。
- 已认证的请求:返回状态码
200和预期的 JSON 数据。 - 未认证的请求:返回状态码
401和错误信息。
// www.javascriptcn.com code example
# 已认证的请求
response = client.get("/protected-endpoint", headers=headers)
assert response.status_code == 200
assert response.json() == {"message": "You are authenticated"}
# 未认证的请求
response = client.get("/protected-endpoint")
assert response.status_code == 401
assert response.json() == {"detail": "Not authenticated"}通过这些步骤,你可以有效地测试 FastAPI 应用中的身份验证逻辑。