扫描二维码关注或者微信搜一搜:编程智域 前端至全栈交流与成长
第一章:核心测试方法论
1.1 三层测试体系架构
# 第一层:模型级测试
def test_user_model_validation():
with pytest.raises(ValidationError):
User(age=-5)
# 第二层:依赖项测试
def test_auth_dependency():
assert auth_dependency(valid_token).status == "active"
# 第三层:端点集成测试
def test_user_endpoint():
response = client.get("/users/1")
assert response.json()["id"] == 1
1.2 参数化测试模式
import pytest
@pytest.mark.parametrize("input,expected", [
("admin", 200),
("guest", 403),
("invalid", 401)
])
def test_role_based_access(input, expected):
response = client.get(
"/admin",
headers={
"X-Role": input}
)
assert response.status_code == expected
第二章:请求模拟技术
2.1 多协议请求构造
from fastapi.testclient import TestClient
def test_multi_part_form():
response = TestClient(app).post(
"/upload",
files={
"file": ("test.txt", b"content")