参数化测试 🔄

通过@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("模块级清理")
    

🔗 了解更多Fixture用法

插件系统 📦

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配置测试环境
  • 支持并行执行加速测试流程
    🔗 查看最佳实践