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

打印 上一主题 下一主题

主题 970|帖子 970|积分 2910



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

1.1 三层测试体系架构
  1. # 第一层:模型级测试
  2. def test_user_model_validation():
  3.     with pytest.raises(ValidationError):
  4.         User(age=-5)
  5. # 第二层:依赖项测试
  6. def test_auth_dependency():
  7.     assert auth_dependency(valid_token).status == "active"
  8. # 第三层:端点集成测试
  9. def test_user_endpoint():
  10.     response = client.get("/users/1")
  11.     assert response.json()["id"] == 1
复制代码
1.2 参数化测试模式
  1. import pytest
  2. @pytest.mark.parametrize("input,expected", [
  3.     ("admin", 200),
  4.     ("guest", 403),
  5.     ("invalid", 401)
  6. ])
  7. def test_role_based_access(input, expected):
  8.     response = client.get(
  9.         "/admin",
  10.         headers={"X-Role": input}
  11.     )
  12.     assert response.status_code == expected
复制代码
第二章:请求模仿技术

2.1 多协议请求构造
  1. from fastapi.testclient import TestClient
  2. def test_multi_part_form():
  3.     response = TestClient(app).post(
  4.         "/upload",
  5.         files={"file": ("test.txt", b"content")},
  6.         data={"name": "test"}
  7.     )
  8.     assert response.status_code == 201
  9. def test_graphql_query():
  10.     response = client.post(
  11.         "/graphql",
  12.         json={"query": "query { user(id:1) { name } }"}
  13.     )
  14.     assert "errors" not in response.json()
复制代码
2.2 动态Header注入
  1. class AuthTestClient(TestClient):
  2.     def __init__(self, *args, **kwargs):
  3.         super().__init__(*args, **kwargs)
  4.         self.token = generate_test_token()
  5.     def get(self, url, **kwargs):
  6.         headers = kwargs.setdefault("headers", {})
  7.         headers.setdefault("Authorization", f"Bearer {self.token}")
  8.         return super().get(url, **kwargs)
  9. test_client = AuthTestClient(app)
复制代码
第三章:Pydantic深度测试

3.1 自界说验证器测试
  1. def test_custom_validator():
  2.     with pytest.raises(ValidationError) as excinfo:
  3.         Product(stock=-10)
  4.     assert "库存不能为负" in str(excinfo.value)
  5. def test_regex_validation():
  6.     valid = {"email": "test@example.com"}
  7.     invalid = {"email": "invalid-email"}
  8.     assert EmailRequest(**valid)
  9.     with pytest.raises(ValidationError):
  10.         EmailRequest(**invalid)
复制代码
3.2 模型继承测试
  1. class BaseUserTest:
  2.     @pytest.fixture
  3.     def model_class(self):
  4.         return BaseUser
  5. class TestAdminUser(BaseUserTest):
  6.     @pytest.fixture
  7.     def model_class(self):
  8.         return AdminUser
  9.     def test_admin_privilege(self, model_class):
  10.         user = model_class(role="super_admin")
  11.         assert user.has_privilege("all")
复制代码
第四章:测试覆盖率优化

4.1 边界条件覆盖战略

[code]# 使用hypothesis天生测试数据from hypothesis import given, strategies as st@given(st.integers(min_value=0, max_value=150))def test_age_validation(age):    assert 0

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

西河刘卡车医

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表