参数化测试 🔄
通过@pytest.mark.parametrize
可同时测试多组数据
- 支持列表、元组、字典等数据结构
- 示例:
@pytest.mark.parametrize("a,b", [(1,2), (3,4), (5,6)]) def test_add(a, b): assert a + b == 7
自定义Fixture 📦
使用fixture实现测试前置准备
- 通过
@pytest.fixture
定义 - 可重用、可依赖、可参数化
- 示例:
@pytest.fixture(scope="module") def setup_module(): print("模块级初始化") yield print("模块级清理")
插件系统 📦
pytest生态拥有丰富的插件支持
- 常用插件:pytest-html(生成HTML报告)、pytest-xdist(并行执行)
- 安装方式:
pip install pytest-<plugin_name>
- 配置文件:
pytest.ini
可自定义插件行为
测试覆盖率 📊
使用pytest-cov
分析代码覆盖率
pytest --cov=my_project
📊 报告展示未覆盖的代码行数
高级断言技巧 ✅
- 使用
assert
关键字直接断言结果 - 结合
pytest.raises
捕获异常 - 使用
pytest.approx
进行浮点数比较
assert result == pytest.approx(3.1415, 0.01)
持续集成集成 🔄
- 配合CI工具(如Jenkins/GitHub Actions)自动化测试
- 通过
pytest.ini
配置测试环境 - 支持并行执行加速测试流程
🔗 查看最佳实践