一、直接在标签上传参:
一个参数多个值
@ pytest.mark.parametrize("参数", (参数值1, 参数值2, 参数值3))
示例:
import pytest
# 单个参数的情况
@pytest.mark.parametrize("a", (1, 2, 3, 4))
def test_add(a):print("\na的值")
结果:
============================= test session starts =============================
collecting ... collected 4 itemstest3.py::test_add[1] PASSED [ 25%]
a的值test3.py::test_add[2] PASSED [ 50%]
a的值test3.py::test_add[3] PASSED [ 75%]
a的值test3.py::test_add[4] PASSED [100%]
a的值============================== 4 passed in 0.10s ==============================Process finished with exit code 0
多个参数多个值的情况
# 单个参数的情况
# 格式:@pytest.mark.parametrize("参数",参数值)
@pytest.mark.parametrize("a", (1, 2, 3, 4))
def test_add(a):print("\na的值")# 多个参数多个值的情况
# 格式:@pytest.mark.parametrize("参数a, 参数b",([a1, b1],[a2,b2],[a3, b3]))
@pytest.mark.parametrize("b,c,d", ([1, 2, 3], [4, 5, 6], [7, 8, 0]))
def test_add2(b, c, d):print('\nb,c,d的值分别为:', f'{b}, {c}, {d}')
二、数据结构
列表(list)形式
# 单个参数的情况
data1 = [1, 2, 3, 4]@pytest.mark.parametrize("a", data1)
def test_add(a):print('\na的值:', a)# 多个参数多个值得情况data2 = [(1, 2, 3),(4, 5, 6),(0, 8, 9)
]@pytest.mark.parametrize("a,b,c", data2)
def test_add2(a, b, c):print('\na,b,c的值分别为:', f'{a},{b},{c}')
输出
============================= test session starts =============================
collecting ... collected 7 items
parametrize02_list.py::test_add[1] PASSED [ 14%]
a的值: 1
parametrize02_list.py::test_add[2] PASSED [ 28%]
a的值: 2
parametrize02_list.py::test_add[3] PASSED [ 42%]
a的值: 3
parametrize02_list.py::test_add[4] PASSED [ 57%]
a的值: 4
parametrize02_list.py::test_add2[1-2-3] PASSED [ 71%]
a,b,c的值分别为: 1,2,3
parametrize02_list.py::test_add2[4-5-6] PASSED [ 85%]
a,b,c的值分别为: 4,5,6
parametrize02_list.py::test_add2[0-8-9] PASSED [100%]
a,b,c的值分别为: 0,8,9
============================== 7 passed in 0.05s ==============================
Process finished with exit code 0
字典(dictionary)形式
import pytestuserinfo = [{"username": "小李", "password": "123456"},{"username": "大白", "password": "894561"}
]@pytest.mark.parametrize('info', userinfo)
def test_add(info):print(info)
输出:
============================= test session starts =============================
collecting ... collected 2 itemsparametrize03_dic.py::test_add[info0] PASSED [ 50%]{'username': '小李', 'password': '123456'}parametrize03_dic.py::test_add[info1] PASSED [100%]{'username': '大白', 'password': '894561'}
元组(tuple)形式
# 元组形式:
import pytestdata1 = [(1, 2, 3), (4, 5, 6)]@pytest.mark.parametrize("a,b,c", data1)
def test_case1(a, b, c):print(a, b, c)
输出
============================= test session starts =============================
collecting ... collected 2 itemsparametrize04_tuple.py::test_case1[1-2-3] PASSED [ 50%]1 2 3parametrize04_tuple.py::test_case1[4-5-6] PASSED [100%]4 5 6============================== 2 passed in 0.03s ==============================Process finished with exit code 0