Pytest五(参数化parametrize)
一、parametrizing
pytest.mark.parametrize装饰器可以实现测试用例参数化。
import pytest
@pytest.mark.parametrize("imput_num,expc_num",
[ ("3+5", 8),
("2+4", 6),
("6 * 9", 42),
("6 * 7", 42),
])
def test_check(imput_num, expc_num):
assert eval(imput_num) == expc_num
if __name__ == "__main__":
pytest.main(["-s", "test_17.py"])
示例:

2、可以标记单个测试实例在参数化,例如使用内置的mark.xfail
import pytest
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
pytest.param("6 * 9", 42, marks=pytest.mark.xfail),
])
def test_eval(test_input, expected):
print("-------开始用例------")
assert eval(test_input) == expected
if __name__ == "__main__":
pytest.main(["-s", "test_18.py"])

标记为失败的用例就不运行了,直接跳过显示xfailed
二、参数组合
1、获得多个参数化参数的所有组合,可以堆叠参数化装饰器
import pytest
@pytest.mark.parametrize("x", [0, 1])
@pytest.mark.parametrize("y", [2, 3])
def test_foo(x, y):
print("测试数据组合:x->%s, y->%s" % (x, y))
if __name__ == "__main__":
pytest.main(["-s", "test_19.py"])


浙公网安备 33010602011771号