@pytest.mark.parametrize 允许在测试函数或类中定义多组参数和 fixtures。
参数化场景:
只有测试数据和预期结果不一样,但操作步骤是一样的测试用例是可以用上参数化的。
创建test_cases02.py文件
示例一:未参数化
1.脚本代码:
# 未作参数化示例
import pytestdef test_case01():assert 3 + 4 == 9def test_case02():assert 6 + 1 == 7def test_case03():assert 3 * 4 == 15if __name__ == '__main__':pytest.main(['-s', '-v', '-k' 'test_cases02'])
可以看到,三个用例都是先计算,然后断言某个值,重复写三个类似的用例有些冗余。
2.运行结果:
============================= test session starts =============================
collecting ... collected 3 itemstest_cases02.py::test_case01 FAILED [ 33%]
test_cases02.py:4 (test_case01)
7 != 9Expected :9
Actual :7
<Click to see difference>def test_case01():
> assert 3 + 4 == 9
E assert (3 + 4) == 9test_cases02.py:6: AssertionErrortest_cases02.py::test_case02 PASSED [ 66%]
test_cases02.py::test_case03 FAILED [100%]
test_cases02.py:12 (test_case03)
12 != 15Expected :15
Actual :12
<Click to see difference>def test_case03():
> assert 3 * 4 == 15
E assert (3 * 4) == 15test_cases02.py:14: AssertionError========================= 2 failed, 1 passed in 0.14s =========================Process finished with exit code 1
示例二:参数化(优化代码)
脚本代码:
# 参数化(优化代码)
import pytest@pytest.mark.parametrize("test_input, expected", [("3+4", 6), ("2+5", 7), ("6*9", 48)])
def test_case01(test_input, expected):print(f"测试数据{test_input},预期结果{expected}")assert eval(test_input) == expected
2、运行结果:
可以看到,只有一条用例,但是利用参数化输入三组不同的测试数据和预期结果,最终执行的测试用例数还是3条,可以节省很多代码。
============================= test session starts =============================
collecting ... collected 3 itemstest_cases02.py::test_case01[3+4-6]
test_cases02.py::test_case01[2+5-7]
test_cases02.py::test_case01[6*9-48] ========================= 2 failed, 1 passed in 0.12s =========================
FAILED [ 33%]测试数据3+4,预期结果6test_cases02.py:4 (test_case01[3+4-6])
7 != 6Expected :6
Actual :7
<Click to see difference>test_input = '3+4', expected = 6@pytest.mark.parametrize("test_input, expected", [("3+4", 6), ("2+5", 7), ("6*9", 48)])def test_case01(test_input, expected):print(f"测试数据{test_input},预期结果{expected}")
> assert eval(test_input) == expected
E AssertionError: assert 7 == 6
E + where 7 = eval('3+4')test_cases02.py:8: AssertionError
PASSED [ 66%]测试数据2+5,预期结果7
FAILED [100%]测试数据6*9,预期结果48test_cases02.py:4 (test_case01[6*9-48])
54 != 48Expected :48
Actual :54
<Click to see difference>test_input = '6*9', expected = 48@pytest.mark.parametrize("test_input, expected", [("3+4", 6), ("2+5", 7), ("6*9", 48)])def test_case01(test_input, expected):print(f"测试数据{test_input},预期结果{expected}")
> assert eval(test_input) == expected
E AssertionError: assert 54 == 48
E + where 54 = eval('6*9')test_cases02.py:8: AssertionErrorProcess finished with exit code 1
1、参数
def parametrize(self, argnames, argvalues, indirect=False, ids=None, scope=None):
主要参数:
1)argnames:参数名,是个字符串,如中间用逗号分隔则表示为多个参数名。
创建test_cases03.py文件
参数名也可以是list或者tuple里的字符串。
脚本代码:
import pytest@pytest.mark.parametrize(["name", "pwd"], [("AllTests", "123456"), ("qq", "85135506")])
def test_case1(name, pwd):print(name, pwd)@pytest.mark.parametrize(("name", "pwd"), [("wangmcn", "567890"), ("admin", "123qwe")])
def test_case3(name, pwd):print(name, pwd)@pytest.mark.parametrize("name, pwd", [("root", "root"), ("guest", "guest")])
def test_case3(name, pwd):print(name, pwd)
运行结果:
============================= test session starts =============================
collecting ... collected 4 itemstest_cases03.py::test_case1[AllTests-123456] PASSED [ 25%]AllTests 123456test_cases03.py::test_case1[qq-85135506] PASSED [ 50%]qq 85135506test_cases03.py::test_case3[root-root] PASSED [ 75%]root roottest_cases03.py::test_case3[guest-guest] PASSED [100%]guest guest============================== 4 passed in 0.05s ==============================Process finished with exit code 0
2)argvalues:参数值,参数组成的列表,列表中有几个元素,就会生成几条用例。
创建 test_cases04.py 文件
脚本代码:
import pytest# 如果只有一个参数,里面则是值的列表
@pytest.mark.parametrize("name", ["AllTests", "wangmcn", "admin"])
def test_case01(name):print(name)# 如果有多个参数,list包含tuple
@pytest.mark.parametrize(["name", "pwd"], [("AllTests", "123456"), ("qq", "45646144")])
def test_case02(name, pwd):print(name, pwd)# 如果有多个参数,tuple包含list
@pytest.mark.parametrize(("name", "pwd"), (["AllTests", "123456"], ["qq", "45646144"]))
def test_case03(name, pwd):print(name, pwd)# 如果有多个参数,list包含list
@pytest.mark.parametrize(["name", "pwd"], [["AllTests", "123456"], ["qq", "45646144"]])
def test_case03(name, pwd):print(name, pwd)
运行结果:
============================= test session starts =============================
collecting ... collected 7 items
test_cases04.py::test_case01[AllTests] PASSED [ 14%]AllTests
test_cases04.py::test_case01[wangmcn] PASSED [ 28%]wangmcn
test_cases04.py::test_case01[admin] PASSED [ 42%]admin
test_cases04.py::test_case02[AllTests-123456] PASSED [ 57%]AllTests 123456
test_cases04.py::test_case02[qq-45646144] PASSED [ 71%]qq 45646144
test_cases04.py::test_case03[AllTests-123456] PASSED [ 85%]AllTests 123456
test_cases04.py::test_case03[qq-45646144] PASSED [100%]qq 45646144
============================== 7 passed in 0.05s ==============================
Process finished with exit code 0
3)ids:用例的ID。传一个字符串列表,可以标识每一个测试用例,自定义测试数据结果的显示,为了增加可读性。
注:ids的长度需要与测试数据列表的长度一致。
创建test_cases05.py文件
脚本代码:
import pytestmy_data = [(1, 2, 3), (4, 5, 9)]ids = ["a:{} + b:{} = expect:{}".format(a, b, expect) for a, b, expect in my_data]@pytest.mark.parametrize("a, b, expect", my_data, ids=ids)
def test_parametrize_case(a, b, expect):print("测试数据为{}-{}".format(a, b))assert a + b == expect
运行结果:
============================= test session starts =============================
collecting ... collected 2 itemstest_cases05.py::test_parametrize_case[a:1 + b:2 = expect:3] PASSED [ 50%]测试数据为1-2test_cases05.py::test_parametrize_case[a:4 + b:5 = expect:9] PASSED [100%]测试数据为4-5============================== 2 passed in 0.03s ==============================Process finished with exit code 0
2、装饰测试类
创建test_cases06.py文件
脚本代码:
import pytestmy_data = [(1, 2, 3), (4, 5, 9)]@pytest.mark.parametrize("a, b, expect", my_data)
class TestParametrize:def test_parametrize_case1(self, a, b, expect):print("\n测试用例case1:测试数据为{}+{}".format(a, b))assert a + b == expectdef test_parametrize_case2(self, a, b, expect):print("\n测试用例case1:测试数据为{}+{}".format(a, b))assert a + b == expect
运行结果:
当装饰器 @pytest.mark.parametrize 装饰测试类时,会将数据集合传递给类的所有测试用例方法。
============================= test session starts =============================
collecting ... collected 4 itemstest_cases06.py::TestParametrize::test_parametrize_case1[1-2-3] PASSED [ 25%]
测试用例case1:测试数据为1+2test_cases06.py::TestParametrize::test_parametrize_case1[4-5-9] PASSED [ 50%]
测试用例case1:测试数据为4+5test_cases06.py::TestParametrize::test_parametrize_case2[1-2-3] PASSED [ 75%]
测试用例case1:测试数据为1+2test_cases06.py::TestParametrize::test_parametrize_case2[4-5-9] PASSED [100%]
测试用例case1:测试数据为4+5============================== 4 passed in 0.05s ==============================Process finished with exit code 0
3、多个参数化装饰器
- 一个函数或一个类可以装饰多个 @pytest.mark.parametrize
- 当参数化装饰器有很多个的时候,用例数等于n(个)*n(个)*n(个)n(个)…
创建test_cases07.py文件。
脚本代码:
import pytestmy_data1 = [1, 2, 3]
my_data2 = ["a", "b"]@pytest.mark.parametrize("a", my_data1)
@pytest.mark.parametrize("b", my_data2)
def test_parametrize_case(a, b):print(f"测试数据为{a},{b}")
运行结果:
参数a的数据有3个,参数b的数据有2个,所以最终的用例数有3*2=6条。
============================= test session starts =============================
collecting ... collected 6 itemstest_cases07.py::test_parametrize_case[a-1] PASSED [ 16%]测试数据为1,atest_cases07.py::test_parametrize_case[a-2] PASSED [ 33%]测试数据为2,atest_cases07.py::test_parametrize_case[a-3] PASSED [ 50%]测试数据为3,atest_cases07.py::test_parametrize_case[b-1] PASSED [ 66%]测试数据为1,btest_cases07.py::test_parametrize_case[b-2] PASSED [ 83%]测试数据为2,btest_cases07.py::test_parametrize_case[b-3] PASSED [100%]测试数据为3,b============================== 6 passed in 0.04s ==============================Process finished with exit code 0
4、参数化(传入字典数据)
创建test_cases08.py文件
数据类型为字典
脚本代码:
import pytestmy_data = ({"user": "AllTests","pwd": "123456"},{"user": "TestUser","pwd": "235689"}
)@pytest.mark.parametrize("dic", my_data)
def test_parametrize_case(dic):print(f"测试数据为:\n{dic}")print(f'user:{dic["user"]}, pwd:{dic["pwd"]}')
运行结果:
============================= test session starts =============================
collecting ... collected 2 itemstest_cases08.py::test_parametrize_case[dic0] PASSED [ 50%]测试数据为:
{'user': 'AllTests', 'pwd': '123456'}
user:AllTests, pwd:123456test_cases08.py::test_parametrize_case[dic1] PASSED [100%]测试数据为:
{'user': 'TestUser', 'pwd': '235689'}
user:TestUser, pwd:235689============================== 2 passed in 0.02s ==============================Process finished with exit code 0
5、标记参数化
pytest.param 可以传三种参数:
- param values - 参数集值的变量 args,按顺序排列。
- keyword marks - marks 关键字标记,要应用于此参数集的单个标记或标记列表。
- keyword str id - 参数集的属性 id。
示例一:
创建test_cases09.py文件。
import pytest@pytest.mark.parametrize("test_input, expected", [("3+5", 8),("2+4", 6),pytest.param("6*9", 45, marks=pytest.mark.xfail),pytest.param("6*6", 50, marks=pytest.mark.skip)
])
def test_case(test_input, expected):assert eval(test_input) == expected
运行结果:
============================= test session starts =============================
collecting ... collected 4 itemstest_cases09.py::test_case[3+5-8]
test_cases09.py::test_case[2+4-6]
test_cases09.py::test_case[6*9-45]
test_cases09.py::test_case[6*6-50] =================== 2 passed, 1 skipped, 1 xfailed in 0.12s ===================
PASSED [ 25%]PASSED [ 50%]XFAIL [ 75%]
test_input = '6*9', expected = 45@pytest.mark.parametrize("test_input, expected", [("3+5", 8),("2+4", 6),pytest.param("6*9", 45, marks=pytest.mark.xfail),pytest.param("6*6", 50, marks=pytest.mark.skip)])def test_case(test_input, expected):
> assert eval(test_input) == expected
E AssertionError: assert 54 == 45
E + where 54 = eval('6*9')test_cases09.py:11: AssertionError
SKIPPED (unconditional skip) [100%]
Skipped: unconditional skipProcess finished with exit code 0
示例二:
创建test_cases10.py文件。
import pytest@pytest.mark.parametrize("test_input, expected", [pytest.param("3+5", 8, id="case1"),pytest.param("2+4", 6, id="case2"),pytest.param("6*9", 45, marks=pytest.mark.xfail, id="case3"),pytest.param("6*6", 50, marks=pytest.mark.skip, id="case4")
])
def test_case(test_input, expected):assert eval(test_input) == expected
运行结果:
============================= test session starts =============================
collecting ... collected 4 itemstest_cases10.py::test_case[case1]
test_cases10.py::test_case[case2]
test_cases10.py::test_case[case3]
test_cases10.py::test_case[case4] =================== 2 passed, 1 skipped, 1 xfailed in 0.12s ===================
PASSED [ 25%]PASSED [ 50%]XFAIL [ 75%]
test_input = '6*9', expected = 45@pytest.mark.parametrize("test_input, expected", [pytest.param("3+5", 8, id="case1"),pytest.param("2+4", 6, id="case2"),pytest.param("6*9", 45, marks=pytest.mark.xfail, id="case3"),pytest.param("6*6", 50, marks=pytest.mark.skip, id="case4")])def test_case(test_input, expected):
> assert eval(test_input) == expected
E AssertionError: assert 54 == 45
E + where 54 = eval('6*9')test_cases10.py:11: AssertionError
SKIPPED (unconditional skip) [100%]
Skipped: unconditional skipProcess finished with exit code 0
6、解决unicode编码问题
使用 @pytest.mark.parametrize 参数化的时候,加 ids 参数用例描述有中文时,在控制台输出会显示 unicode 编码问题,中文不能正常显示。
解决方法:
使用 pytest_collection_modifyitems 钩子函数,对输出的 item.name 和 item.nodeid 重新编码即可。
示例
创建test_cases11.py文件
脚本代码:
import pytestdef login(username, password):print("登入操作!!!")return {"code": 0, "msg": "success!"}my_data = [({"username": "AllTests", "password": "123456"}, "success!"),({"username": "Admin123", "password": "123456"}, "success!"),({"username": "Admin456", "password": "123456"}, "success!")
]ids = ["输入正确a账号,正确密码,登录成功","输入正确b账号,正确密码,登录成功","输入正确c账号,正确密码,登录成功",
]@pytest.mark.parametrize("input_data, expected", my_data, ids=ids)
def test_login(input_data, expected):print("test_case-----login")result = login(input_data["username"], input_data["password"])assert result["msg"] == expected
打开命令行,输入执行命令
pytest -v .\Pytest_session\fixture_params\test_cases11.py
运行结果:
控制台输出中文时显示unicode编码问题。
3、解决ids参数用例描述为中文时,控制台输出显示unicode编码问题。
在项目的根目录或与用例同级目录下,创建conftest.py文件
def pytest_collection_modifyitems(items):for item in items:item.name = item.name.encode("utf-8").decode("unicode_escape")# print(item_nodeid)item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")
重新执行用例,运行结果:
控制台输出中文时显示正常。