参数化测试
向函数传值并检验输出结果是软件测试常用手段,但是对大部分功能测试而言,仅仅使用一组数据是无法充分测试函数功能的,参数化测试允许传递多组数据,一旦发现测试失败,pytest会及时报告
@pytest.mark.parametrize装饰器
@pytest.mark.parametrize(argnames, argvalues)达到批量传送参数的目的
argnames:是一个字符串,是参数的名字,如果有多个参数时,用逗号分隔
argvalues:是一个列表(或者元祖),是具体的要传入的数据
一个简单的parametrize例子
import pytest
def inc(x):
return x+1
@pytest.mark.parametrize("test_input,expected",[(3,4),(4,5),(5,6)])
def test_inc(test_input,expected):
assert inc(test_input)==expected
运行结果:
collected 3 items
test_markparam.py::test_inc[3-4] PASSED
test_markparam.py::test_inc[4-5] PASSED
test_markparam.py::test_inc[5-6] PASSED
pytest.mark.parametrize和pytest.fixture
pytest.fixture也可以提供测试数据,使用fixture需要定一个fixture,并且传入参数params,还需要使用request.param取出参数,比较麻烦,不如pytest.mark.parametrize方便
@pytest.fixture(params=[(3,4),(4,5),(5,7)])
def test_input(request):
return request.param
def test_inc_2(test_input):
assert inc(test_input[0])==test_input[1]
运行结果:
test_markparam.py::test_inc_2[test_input0] PASSED
test_markparam.py::test_inc_2[test_input1] PASSED
test_markparam.py::test_inc_2[test_input2] FAILED