Python 5.pytest 参数化使用

Maple · 2020年12月27日 · 974 次阅读

在软件测试中,经常遇到同一个用例需要输入多组不同的参数组合,进行功能覆盖测试,在自动化测试中,我们把这种叫做参数化,在 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,报错了

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册