一、前言
Pytest中参数化语法
@pytest.mark.parametrize(‘参数名’,list) 可以实现测试用例参数化
-
如果只有一个参数,里面则是值的列表如:@pytest.mark.parametrize(“username”, [“yy”, “yy2”,
“yy3”]) 或者是 @pytest.mark.parametrize([“username”], [“yy”, “yy2”, “yy3”])
-
如果有多个参数,则需要用元组来存放值,一个元组对应一组参数的值,如:@pytest.mark.parametrize(“name,pwd”,
[(“yy1”, “123”), (“yy2”, “123”), (“yy3”, “123”)])
二、使用
1、一个参数一个值
示例代码:
@pytest.mark.parametrize('input', ['输入值1'])
def test01(input):
print('\n ', input)
assert input == '输入值1'
结果:

2、一个参数多个值
示例代码:
@pytest.mark.parametrize('input', ['输入值1','输入值2','输入值3','输入值4'])
def test01(input):
print(input)
结果:
3、多个参数多个值
代码示例1:
@pytest.mark.parametrize('user, pwd', [('root', '123'), ('admin', '456')])
def test_03(user, pwd):
db = {
'root': '202cb962ac59075b964b07152d234b70',
'admin': '250cf8b51c773f3f8dc8b4be867a9a02'
}
assert hashlib.md5(pwd.encode()).hexdigest() == db[user]
结果:
4、多个参数混合使用
代码示例,类似于笛卡尔积:
data1 = ['A', 'B']
data2 = ['1', '2']
data3 = ['python', 'C++', 'java', 'shell']
@pytest.mark.parametrize('a', data1)
@pytest.mark.parametrize('b', data2)
@pytest.mark.parametrize('c', data3)
def test_04(a, b, c):
print(f"生成新的组合为[{a} {b} {c}]")
结果:
5、参数化,传入字典数据
代码示例:
json = [{'user': 'admin', 'pwd': '123'}, {'user': 'root', 'pwd': '456'}]
@pytest.mark.parametrize('json', json)
def test_06(json):
print(f'\n {json}')
print(f'user: {json["user"]}, pwd: {json["pwd"]}')
结果:
6、装饰测试类
代码示例:
data6 = [(1, 2, 3), (2, 3, 5)]
@pytest.mark.parametrize('a,b,expect', data6)
class TestCase():
def test01(self, a, b, expect):
print(f'\n函数01 测试数据:{a}+{b}, 结果为{expect}')
assert a + b == expect
def test02(self, a, b, expect):
print(f'\n函数02 测试数据:{a}+{b}, 结果为{expect}')
assert a + b == expect
结果:
小结:
当装饰器 @pytest.mark.parametrize 装饰测试类时,会将数据集合传递给类的所有测试用例方法