实际测试过程中,测试用例可能需要支持多种场景,可以把场景强相关的部分抽象为参数,通过对参数赋值来驱动用例的执行。参数化对的行为表现在不同的层级上:
#_pytest/python.py
def parametrize(self, argnames, argvalues, indirect=False, ids = None,scope = None)
参数分析如下:
argnames:一个逗号分隔的字符串或者一个元组、列表,表明指定对的参数名。对于argnames,还是有一些限制:
只能是被标记对象入参的子集
@pytest.mark.parametrize('input, expected', [(1,2)])
def test_sample(input):
assert input + 1 =1
不能是被标记对象入参中,定义了默认值的参数:
@pytest.mark.parametrize('innput, expected' , [(1,2)])
def test_sample(input, expected = 2)
assert input + 1 == expected
虽然test_sample
声明了expected
参数,但是也赋予了一个默认值,如果我们在标记中强行声明,会得到错误:
In test_sample: function already takes an argument 'expected' with a default value
import pytest
@pytest.fixture()
def excepted():
return 1
@pytest.mark.parametrize('input, excepted', [(1,2)])
def test_sample(input , excepted):
assert input + 1 == excepted
测试结果:
D:\pytest\exercise\chapter11>pytest test_mark.py
================================================================= test session starts ==================================================================
platform win32 -- Python 3.8.5, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: D:\pytest\exercise\chapter11
plugins: allure-pytest-2.8.36
collected 1 item
test_mark.py . [100%]
================================================================== 1 passed in 0.04s ===================================================================
test_sample标记中对的excepted(2)覆盖了同名对的fixture excepted(1),所以测试用例通过。
@pytest.mark.parametrize('input,excepted',[(1,2),[2,3]],set([3,4]))
def test_sample(input,excepted):
assert input + 1 == excepted
测试结果:
D:\pytest\exercise\chapter11>pytest test_mark.py
================================================================= test session starts ==================================================================
platform win32 -- Python 3.8.5, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: D:\pytest\exercise\chapter11
plugins: allure-pytest-2.8.36
collected 0 items / 1 error
======================================================================== ERRORS ============================