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。

注意事项

  • 当使用数据驱动测试时,确保测试数据具有代表性,能够覆盖各种边界情况和异常情况。
  • 尽量避免在测试函数中使用硬编码的值,而是使用参数化的输入和期望输出。
  • 保持测试数据的可维护性,定期审查和更新测试数据,以确保其与代码的实际需求保持一致。
相关推荐
小熊出擊1 天前
【pytest】finalizer 执行顺序:FILO 原则
python·测试工具·单元测试·pytest
小熊出擊2 天前
【pytest】使用 marker 向 fixture 传递数据
python·pytest
wa的一声哭了2 天前
Deep Learning Optimizer | Adam、AdamW
人工智能·深度学习·神经网络·机器学习·自然语言处理·transformer·pytest
专职4 天前
pytest生成测试用例,allure生成测试报告
测试用例·pytest
小丁爱养花7 天前
接口自动化测试 - pytest [1]
python·自动化·pytest
向上的车轮8 天前
如何用AI工具开发一个轻量化CRM系统(七):AI生成pytest测试脚本
pytest
慌糖9 天前
自动化接口框架搭建分享-pytest第三部分
运维·自动化·pytest
Script kid9 天前
Pytest框架速成
数据库·pytest
小熊出擊9 天前
[pytest] 一文掌握 fixture 的作用域(scope)机制
python·功能测试·单元测试·自动化·pytest
小熊出擊10 天前
[pytest] autouse 参数:自动使用fixture
python·测试工具·单元测试·自动化·pytest