🏆 1. Requests 库测试套件
项目地址 :https://github.com/psf/requests
学习重点:
-
参数化测试 (
@pytest.mark.parametrize) -
HTTP 接口测试的 Mock 技巧
-
复杂 Fixture 设计(如会话级缓存)
-
异常测试 (
pytest.raises)
实践亮点:
python
# 典型测试案例 (tests/test_requests.py)
@pytest.mark.parametrize(
"method", ["GET", "POST", "PUT", "PATCH", "DELETE"]
)
def test_http_methods(session, method):
# 使用内置 fixture 'session' 模拟 HTTP 会话
url = "http://httpbin.org/" + method.lower()
func = getattr(session, method.lower())
response = func(url)
assert response.status_code == 200
学习路径:
-
研究
tests/conftest.py中的全局 Fixture 设计 -
分析
test_requests.py中的 Mock 响应实现 -
学习
pytest.ini中的自定义配置
🧪 2. Pytest 自身测试套件
项目地址 :https://github.com/pytest-dev/pytest
学习重点:
-
元测试(测试框架自身的测试)
-
插件系统测试模式
-
临时目录管理 (
tmp_pathFixture) -
测试覆盖率优化 (pytest-cov)
经典案例:
python
# 测试插件加载 (testing/test_config.py)
def test_plugin_loading(testdir):
# testdir 是 pytest 内置 Fixture
testdir.makepyfile(
"""
import pytest
@pytest.hookimpl
def pytest_configure(config):
config.addinivalue_line("env", "TEST=123")
""")
result = testdir.runpytest()
assert result.ret == 0
学习价值:
-
深度理解 pytest 内部机制
-
学习超过 2000 个测试案例的设计模式
-
查看顶级 Fixture 实现(如
monkeypatch源码)
📦 3. FastAPI 测试套件
项目地址 :https://github.com/tiangolo/fastapi
学习重点:
-
异步测试 (
pytest.mark.asyncio) -
API 端到端测试 (TestClient)
-
数据库集成测试(回滚机制)
-
依赖注入测试
最佳实践:
python
# 数据库事务测试 (tests/test_db.py)
@pytest.mark.asyncio
async def test_transactional_db(async_client):
# 使用自动回滚的事务 Fixture
response = await async_client.post("/users/", json={"name": "Test"})
assert response.status_code == 201
user_id = response.json()["id"]
# 验证独立事务中数据不可见
async with AsyncClient(app=app, base_url="http://test") as ac:
response = await ac.get(f"/users/{user_id}")
assert response.status_code == 404 # 回滚后数据不存在
学习路径:
-
研究
tests/conftest.py中的数据库 Fixture 架构 -
分析异步测试实现 (
tests/test_main.py) -
学习 OpenAPI 规范验证测试
💡 推荐学习方式
| 技能 | 实践方法 | 目标 |
|---|---|---|
| Fixture 设计 | 复制项目的 conftest.py 改造 |
实现 Session 级 DB 连接 |
| 参数化测试 | 为现有测试添加新参数组合 | 覆盖边界值用例 |
| 插件开发 | 基于 pytest-requests 创建自定义插件 | 实现自动重试机制 |
| 覆盖率优化 | 用 pytest --cov 分析未被覆盖代码 |
将覆盖率提升至 95%+ |
建议按此顺序学习:Requests → Pytest → FastAPI,从基础测试模式逐步过渡到复杂场景。每个项目都包含 2000+ 测试案例,每天研究 10 个案例并动手复现,一个月即可掌握工业级测试开发技能。