Pytest之parametrize参数化

文章目录

1.前言

在 pytest 中,parametrize 是一个非常实用的装饰器,它允许你对测试函数进行参数化,即使用不同的参数组合多次运行同一个测试函数,从而更高效地进行测试覆盖。

基本语法:

python 复制代码
@pytest.mark.parametrize(argnames, argvalues)
  • argnames:这是一个字符串,表示要传入测试函数的参数名。如果有多个参数,参数名之间用逗号分隔。
  • argvalues:这是一个可迭代对象(如列表、元组等),其中每个元素代表一组参数值。如果 argnames 中有多个参数名,那么 argvalues 中的每个元素应该是一个包含对应数量值的元组。

2.单参数

以下是一个简单的单参数单次循环的案例:

python 复制代码
import pytest

@pytest.mark.parametrize('key',['value'])
def test_parametrize01(key):
    print(key)

运行结果:

除此之外,我们还是进行多次循环。

python 复制代码
@pytest.mark.parametrize('char','String')
def test_parametrize02(char):
    print(char)

这里的可迭代对象是一个字符串,那么会将字符串每一个字符都赋值给参数

运行结果:

除了使用字符串,可以用列表

python 复制代码
@pytest.mark.parametrize('type',['int','boolean','double'])
def test_parametrize03(type):
    print(type)

运行结果:

3.多参数

除了单参数外,还可以使用多参数

示例:

python 复制代码
@pytest.mark.parametrize("a, b, expected", [(1, 2, 3), (4, 5, 9), (0, 0, 0)])
def test_parametrize04(a, b, expected):
    result = a + b
    assert result == expected

🌟可迭代对象的类型是列表,里面的值是用的元组

运行结果:

可以使用多个 pytest.mark.parametrize 装饰器来组合不同的参数化维度。

示例:

python 复制代码
@pytest.mark.parametrize('x',[1,2])
@pytest.mark.parametrize('y',[3,4])
def test_parametrize05(x,y):
    print(f'x = {x},y = {y}')

运行结果:

4.字典形式

字典形式的可迭代参数也很简单

示例:

python 复制代码
@pytest.mark.parametrize('student',[{'name':'zhangsan','age':18}])
def test_parametrize06(student):
    print(f"学生的姓名: {student['name']},年龄:{student['age']}")

运行结果:

5.parametrize 结合 ids 参数

parametrize 装饰器还支持 ids 参数,用于为每组参数值指定一个自定义的标识,这样在测试报告中可以更清晰地看到每个测试用例使用的是哪组参数。

python 复制代码
@pytest.mark.parametrize("a, b, expected", [(1, 2, 3), (4, 5, 9), (0, 0, 0)],
                         ids=["test_case_1", "test_case_2", "test_case_3"])
def test_parametrize07(a, b, expected):
    result = a + b
    assert result == expected

运行结果:

在测试结果中,每组参数对应的测试用例会显示为 test_parametrize07test_case_1、test_additiontest_case_2 和 test_additiontest_case_3,方便区分和查看。

相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
千里马学框架2 天前
一起学 Android 14:ShellTransition 屏幕旋转过程深度剖析
android·智能手机·性能优化·framework·性能·屏幕旋转·rotation
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
美狐美颜SDK开放平台2 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
AFinalStone2 天前
Android7 SystemUI源码解析(七)Keyguard锁屏模块深度解析
android·systemui
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
致远ccc2 天前
Google Play 上架前如何测试 App?多国家 Android 环境测试
android·app测试·googleplay·多国家应用测试
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas