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_parametrize07[test_case_1]、test_addition[test_case_2] 和 test_addition[test_case_3],方便区分和查看。

相关推荐
yaoh.wang2 小时前
力扣(LeetCode) 13: 罗马数字转整数 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
Lei活在当下3 小时前
【项目踩坑实录】并发环境下,Glide缓存引起的图片加载异常
android·debug·glide
小鸡吃米…3 小时前
Python PyQt6教程七-控件
数据库·python
1916zz4 小时前
Extreme programing 方利喆 _ 江贤晟
python
长安牧笛4 小时前
智能鞋柜—脚气终结者,内置温湿度传感器和紫外线灯,晚上回家,把鞋放进去,自动检测湿度,湿度超标就启动烘干+紫外线杀菌,第二天穿鞋干燥无异味。
python
weixin_457760004 小时前
PIL库将图片位深度是1、8、32统一转换为24的方法
python
my_power5205 小时前
检出git项目到android studio该如何配置
android·git·android studio
Lucky高5 小时前
Pandas库入门
python·pandas
小鸡吃米…6 小时前
Python PyQt6教程三-菜单与工具栏
开发语言·python
Jack电子实验室6 小时前
【杭电HDU】校园网(DeepL/Srun)自动登录教程
python·嵌入式硬件·计算机网络·自动化