5.pytest参数化使用
在软件测试中,经常遇到同一个用例需要输入多组不同的参数组合,进行功能覆盖测试,在自动化测试中,我们把这种叫做参数化,在pytest中使用装饰器就能完成参数化.
@pytest.mark.parametrize(argnames, argvalues) # 参数: # argnames:以逗号分隔的字符串 # argvaluse: 参数值列表,若有多个参数,一组参数以元组形式存在,包含多组参数的所有参数 # 以元组列表形式存在
一个参数
新建test_05.py
文件
import pytest @pytest.mark.parametrize("arg_1",[1,2]) def test_01(arg_1): assert 1 == arg_1 if __name__ == '__main__': pytest.main(['-s', 'test_05.py']) 运行结果: ============================= test session starts ============================= platform win32 -- Python 3.7.1, pytest-6.0.2, py-1.9.0, pluggy-0.13.1 rootdir: D:\study\auto-pytest collected 2 items test_05.py .. ============================== 2 passed in 0.07s ==============================
多个参数
修改test_05.py
import pytest values = [ (1, 1, 2), (1, 2, 4), (1, 3, 4) ] @pytest.mark.parametrize("a,b,c",values) def test_add(a,b,c): assert (a+b)==c if __name__ == '__main__': pytest.main(['-s', 'test_05.py']) 运行结果: ============================= test session starts ============================= platform win32 -- Python 3.7.1, pytest-6.0.2, py-1.9.0, pluggy-0.13.1 rootdir: D:\study\auto-pytest collected 3 items test_05.py .F. ================================== FAILURES =================================== _______________________________ test_add[1-2-4] _______________________________ a = 1, b = 2, c = 4 @pytest.mark.parametrize("a,b,c",values) def test_add(a,b,c): > assert (a+b)==c E assert (1 + 2) == 4 test_05.py:11: AssertionError =========================== short test summary info =========================== FAILED test_05.py::test_add[1-2-4] - assert (1 + 2) == 4 ========================= 1 failed, 2 passed in 0.10s =========================
结果三组参数运行用例,断言a+b=c的时候,发现1+2不等于4,报错了