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。

注意事项

  • 当使用数据驱动测试时,确保测试数据具有代表性,能够覆盖各种边界情况和异常情况。
  • 尽量避免在测试函数中使用硬编码的值,而是使用参数化的输入和期望输出。
  • 保持测试数据的可维护性,定期审查和更新测试数据,以确保其与代码的实际需求保持一致。
相关推荐
5:002 天前
pytest框架-详解
pytest
丿罗小黑4 天前
Pytest项目_day15(yaml)
pytest
丿罗小黑4 天前
Pytest项目_day16(yaml和parametrize结合)
pytest
代码小念5 天前
Pytest+selenium UI自动化测试实战实例(超详细)
selenium·ui·pytest
丿罗小黑5 天前
Pytest项目_day11(fixture、conftest)
pytest
测试开发技术10 天前
软件测试中,pytest 运行完成后,如何自动发送邮件?
开发语言·python·pytest·接口测试·面试题
丿罗小黑10 天前
Pytest项目_day08(setup、teardown前置后置操作)
pytest
测试199810 天前
Pytest中实现自动生成测试用例脚本代码
自动化测试·软件测试·python·测试工具·测试用例·pytest·接口测试