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。

注意事项

  • 当使用数据驱动测试时,确保测试数据具有代表性,能够覆盖各种边界情况和异常情况。
  • 尽量避免在测试函数中使用硬编码的值,而是使用参数化的输入和期望输出。
  • 保持测试数据的可维护性,定期审查和更新测试数据,以确保其与代码的实际需求保持一致。
相关推荐
<花开花落>7 天前
将Python第三方库转换为真正的 pytest 插件
pytest
春风又。10 天前
接口自动化——初识pytest
python·测试工具·自动化·pytest
南部余额10 天前
playwright解决重复登录问题,通过pytest夹具自动读取storage_state用户状态信息
前端·爬虫·python·ui·pytest·pylawright
小码哥说测试13 天前
接口自动化进阶 —— Pytest全局配置pytest.ini文件详解!
自动化测试·软件测试·测试工具·自动化·pytest·测试工程师
天才测试猿13 天前
Python常用自动化测试框架—Pytest
自动化测试·软件测试·python·功能测试·测试工具·测试用例·pytest
Rhys..14 天前
2、pytest核心功能(进阶用法)
开发语言·python·pytest
一只天蝎的晋升之路15 天前
Python中常用的测试框架-pytest和unittest
开发语言·python·pytest
明月与玄武15 天前
pytest-xdist 进行高效并行自动化测试
pytest·pytest-xdist·进行高效并行自动化测试
测试笔记(自看)15 天前
Python+Requests+Pytest+YAML+Allure接口自动化框架
python·自动化·pytest·allure
活跃家族16 天前
Jsonpath使用
python·pytest