pytest 之数据驱动

以下有4种数据驱动的方法:

1. 使用 @pytest.mark.parametrize 装饰器

@pytest.mark.parametrize 是 pytest 中用于数据驱动测试的最常用装饰器。它允许你为测试函数提供多组输入数据和期望输出。

python 复制代码
import pytest  
  
@pytest.mark.parametrize("input, expected", [  
    (1, 2),  
    (2, 4),  
    (3, 6),  
])  
def test_multiply(input, expected):  
    assert input * 2 == expected

2. 使用 CSV 或 JSON 文件作为数据源

如果测试数据存储在 CSV 或 JSON 文件中,可以使用 Python 的标准库(如 csv 或 json)来读取数据,并在测试函数中使用这些数据。

例如,假设有一个 CSV 文件 test_data.csv,内容如下:

input expected
1 2
2 4
3 6

你可以这样读取并使用数据:

python 复制代码
import csv  
import pytest  
  
@pytest.mark.parametrize("input, expected", [  
    tuple(row) for row in csv.reader(open("test_data.csv")) if row  # Skip empty rows  
])  
def test_multiply(input, expected):  
    assert int(input) * 2 == int(expected)

3. 使用 pytest_generate_tests 钩子

对于更复杂的场景,你可以使用 pytest_generate_tests 钩子来自定义数据生成逻辑。这通常在你的 conftest.py 文件中完成。

4. 使用第三方插件

还有一些第三方插件可以帮助你实现更复杂的数据驱动测试,例如 pytest-cases。

注意事项

  • 当使用数据驱动测试时,确保测试数据具有代表性,能够覆盖各种边界情况和异常情况。
  • 尽量避免在测试函数中使用硬编码的值,而是使用参数化的输入和期望输出。
  • 保持测试数据的可维护性,定期审查和更新测试数据,以确保其与代码的实际需求保持一致。
相关推荐
小陈的进阶之路6 小时前
Selenium 常用操作 API
python·自动化·pytest
紫丁香7 小时前
pytest_自动化测试5
python·功能测试·单元测试·集成测试·pytest
姚青&7 小时前
Pytest fixture 参数化(params 参数)
开发语言·python·pytest
小张贼嚣张8 小时前
Pytest 核心特性与技术优势
pytest
姚青&9 小时前
Pytest 配置文件
pytest
姚青&16 小时前
Pytest 插件
pytest
姚青&20 小时前
Pytest 测试用例生命周期管理-yield
测试用例·pytest
紫丁香1 天前
pytest_自动化测试3
开发语言·python·功能测试·单元测试·集成测试·pytest
小罗和阿泽1 天前
接口测试系列 接口自动化测试 pytest框架(二)
pytest
姚青&1 天前
Pytest 测试用例生命周期管理-自动注册(conftest.py)
测试用例·pytest