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。

注意事项

  • 当使用数据驱动测试时,确保测试数据具有代表性,能够覆盖各种边界情况和异常情况。
  • 尽量避免在测试函数中使用硬编码的值,而是使用参数化的输入和期望输出。
  • 保持测试数据的可维护性,定期审查和更新测试数据,以确保其与代码的实际需求保持一致。
相关推荐
2601_9620782317 小时前
Python接口自动化框架:pytest
python·pytest·接口自动化·测试框架·restfulapi
2601_9620781920 小时前
Appium+Python+pytest自动化测试框架详解
自动化测试·python·appium·pytest·移动应用
2601_962284503 天前
安卓APP UI自动化测试:Python + UiAutomator2 + pytest + pytest-html
python·pytest·uiautomator2·ui自动化测试·安卓app
2601_962300813 天前
基于pytest的接口自动化测试:使用requests模块的实战项目与接口关联方法详解
接口自动化测试·测试用例·pytest·接口关联·requests模块
2601_962300813 天前
Python + Requests + Pytest + Excel + Allure:接口自动化测试项目实战
python·excel·pytest·allure·requests
11路没有终点4 天前
Pytest 安装、版本与第一个测试用例
测试用例·pytest
11路没有终点5 天前
pytest 参数化与 Mark 标记
pytest
2601_962296285 天前
五种Python自动化测试框架汇总,附学习方法
自动化测试·pytest·unittest·robotframework·python框架
11路没有终点5 天前
pytest Fixture 进阶:conftest 与依赖注入
pytest
2601_962387828 天前
web自动化测试实战教程【selenium/unittest/pytest】【共193课
selenium·pytest·devops·web自动化测试·unittest