能氐吨 发表于 2025-6-8 21:54:21

FastAPI测试策略:参数解析单元测试



扫描二维码关注或者微信搜一搜:编程智域 前端至全栈交流与成长
探索数千个预构建的 AI 应用,开启你的下一个伟大创意
第一章:核心测试方法论

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"] == 11.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")},
      data={"name": "test"}
    )
    assert response.status_code == 201


def test_graphql_query():
    response = client.post(
      "/graphql",
      json={"query": "query { user(id:1) { name } }"}
    )
    assert "errors" not in response.json()2.2 动态Header注入

class AuthTestClient(TestClient):
    def __init__(self, *args, **kwargs):
      super().__init__(*args, **kwargs)
      self.token = generate_test_token()

    def get(self, url, **kwargs):
      headers = kwargs.setdefault("headers", {})
      headers.setdefault("Authorization", f"Bearer {self.token}")
      return super().get(url, **kwargs)


test_client = AuthTestClient(app)第三章:Pydantic深度测试

3.1 自定义验证器测试

def test_custom_validator():
    with pytest.raises(ValidationError) as excinfo:
      Product(stock=-10)

    assert "库存不能为负" in str(excinfo.value)


def test_regex_validation():
    valid = {"email": "test@example.com"}
    invalid = {"email": "invalid-email"}

    assert EmailRequest(**valid)
    with pytest.raises(ValidationError):
      EmailRequest(**invalid)3.2 模型继承测试

class BaseUserTest:
    @pytest.fixture
    def model_class(self):
      return BaseUser


class TestAdminUser(BaseUserTest):
    @pytest.fixture
    def model_class(self):
      return AdminUser

    def test_admin_privilege(self, model_class):
      user = model_class(role="super_admin")
      assert user.has_privilege("all")第四章:测试覆盖率优化

4.1 边界条件覆盖策略

# 使用hypothesis生成测试数据from hypothesis import given, strategies as st@given(st.integers(min_value=0, max_value=150))def test_age_validation(age):    assert 0
页: [1]
查看完整版本: FastAPI测试策略:参数解析单元测试