python-pytest学习(六)-参数化

一、前言

  pytest.mark.parameterize装饰器可以实现测试用例参数化。

二、parametrizing

  1.这里是一个实现检查一定的输入和期望输出测试功能的典型例子

import pytest

@pytest.mark.parametrize("test_input,expected",
                         [("3+5",8),
                          ("2+4",6),
                          ("6*9",42),
                          ])
def test_eval(test_input,expected):
    assert eval(test_input) == expected

if __name__=="__main__":
    pytest.main(["-s","test_param1.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_param1.py"])

运行结果:

标记为失败的用例就不运行了,直接跳过显示xfailed

  3.参数组合

(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.mark(["-s","test_param2.py"])

运行结果:

 这将运行测试,参数设置为x=0/y=2,x=1/y=2,x=0/y=3,x=1/y=3组合参数。

参考文章:https://www.jianshu.com/p/983412a7c2ae

原文地址:https://www.cnblogs.com/zhaocbbb/p/12829508.html