目录html
往期索引:http://www.javashuo.com/article/p-wpvwlyap-bn.htmlpython
在实际工做中,测试用例可能须要支持多种场景,咱们能够把和场景强相关的部分抽象成参数,经过对参数的赋值来驱动用例的执行;数据库
参数化的行为表如今不一样的层级上:api
fixture
的参数化:参考 四、fixtures:明确的、模块化的和可扩展的 -- fixture
的参数化;bash
测试用例的参数化:使用@pytest.mark.parametrize
能够在测试用例、测试类甚至测试模块中标记多个参数或fixture
的组合;app
另外,咱们也能够经过pytest_generate_tests
这个钩子方法自定义参数化的方案;模块化
@pytest.mark.parametrize
标记@pytest.mark.parametrize
的根本做用是在收集测试用例的过程当中,经过对指定参数的赋值来新增被标记对象的调用(执行);测试
首先,咱们来看一下它在源码中的定义:ui
# _pytest/python.py def parametrize(self, argnames, argvalues, indirect=False, ids=None, scope=None):
着重分析一下各个参数:this
argnames
:一个用逗号分隔的字符串,或者一个列表/元组,代表指定的参数名;
对于argnames
,实际上咱们是有一些限制的:
只能是被标记对象入参的子集:
@pytest.mark.parametrize('input, expected', [(1, 2)]) def test_sample(input): assert input + 1 == 1
test_sample
中并无声明expected
参数,若是咱们在标记中强行声明,会获得以下错误:
In test_sample: function uses no argument 'expected'
不能是被标记对象入参中,定义了默认值的参数:
@pytest.mark.parametrize('input, 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
会覆盖同名的fixture
:
@pytest.fixture() def expected(): return 1 @pytest.mark.parametrize('input, expected', [(1, 2)]) def test_sample(input, expected): assert input + 1 == expected
test_sample
标记中的expected(2)
覆盖了同名的fixture expected(1)
,因此这条用例是能够测试成功的;
argvalues
:一个可迭代对象,代表对argnames
参数的赋值,具体有如下几种状况:
若是argnames
包含多个参数,那么argvalues
的迭代返回元素必须是可度量的(即支持len()
方法),而且长度和argnames
声明参数的个数相等,因此它能够是元组/列表/集合等,代表全部入参的实参:
@pytest.mark.parametrize('input, expected', [(1, 2), [2, 3], set([3, 4])]) def test_sample(input, expected): assert input + 1 == expected
注意:考虑到集合的去重特性,咱们并不建议使用它;
若是argnames
只包含一个参数,那么argvalues
的迭代返回元素能够是具体的值:
@pytest.mark.parametrize('input', [1, 2, 3]) def test_sample(input): assert input + 1
若是你也注意到咱们以前提到,argvalues
是一个可迭代对象,那么咱们就能够实现更复杂的场景;例如:从excel
文件中读取实参:
def read_excel(): # 从数据库或者 excel 文件中读取设备的信息,这里简化为一个列表 for dev in ['dev1', 'dev2', 'dev3']: yield dev @pytest.mark.parametrize('dev', read_excel()) def test_sample(dev): assert dev
实现这个场景有多种方法,你也能够直接在一个
fixture
中去加载excel
中的数据,可是它们在测试报告中的表现会有所区别;
或许你还记得,在上一篇教程(十、skip和xfail标记 -- 结合pytest.param
方法)中,咱们使用pytest.param
为argvalues
参数赋值:
@pytest.mark.parametrize( ('n', 'expected'), [(2, 1), pytest.param(2, 1, marks=pytest.mark.xfail(), id='XPASS')]) def test_params(n, expected): assert 2 / n == expected
如今咱们来具体分析一下这个行为:
不管argvalues
中传递的是可度量对象(列表、元组等)仍是具体的值,在源码中咱们都会将其封装成一个ParameterSet
对象,它是一个具名元组(namedtuple),包含values, marks, id
三个元素:
>>> from _pytest.mark.structures import ParameterSet as PS >>> PS._make([(1, 2), [], None]) ParameterSet(values=(1, 2), marks=[], id=None)
若是直接传递一个ParameterSet
对象会发生什么呢?咱们去源码里找答案:
# _pytest/mark/structures.py class ParameterSet(namedtuple("ParameterSet", "values, marks, id")): ... @classmethod def extract_from(cls, parameterset, force_tuple=False): """ :param parameterset: a legacy style parameterset that may or may not be a tuple, and may or may not be wrapped into a mess of mark objects :param force_tuple: enforce tuple wrapping so single argument tuple values don't get decomposed and break tests """ if isinstance(parameterset, cls): return parameterset if force_tuple: return cls.param(parameterset) else: return cls(parameterset, marks=[], id=None)
能够看到若是直接传递一个ParameterSet
对象,那么返回的就是它自己(return parameterset
),因此下面例子中的两种写法是等价的:
# src/chapter-11/test_sample.py import pytest from _pytest.mark.structures import ParameterSet @pytest.mark.parametrize( 'input, expected', [(1, 2), ParameterSet(values=(1, 2), marks=[], id=None)]) def test_sample(input, expected): assert input + 1 == expected
到这里,或许你已经猜到了,pytest.param
的做用就是封装一个ParameterSet
对象;那么咱们去源码里求证一下吧!
# _pytest/mark/__init__.py def param(*values, **kw): """Specify a parameter in `pytest.mark.parametrize`_ calls or :ref:`parametrized fixtures <fixture-parametrize-marks>`. .. code-block:: python @pytest.mark.parametrize("test_input,expected", [ ("3+5", 8), pytest.param("6*9", 42, marks=pytest.mark.xfail), ]) def test_eval(test_input, expected): assert eval(test_input) == expected :param values: variable args of the values of the parameter set, in order. :keyword marks: a single mark or a list of marks to be applied to this parameter set. :keyword str id: the id to attribute to this parameter set. """ return ParameterSet.param(*values, **kw)
正如咱们所料,如今你应该更明白怎么给argvalues
传参了吧;
indirect
:argnames
的子集或者一个布尔值;将指定参数的实参经过request.param
重定向到和参数同名的fixture
中,以此知足更复杂的场景;
具体使用方法能够参考如下示例:
# src/chapter-11/test_indirect.py import pytest @pytest.fixture() def max(request): return request.param - 1 @pytest.fixture() def min(request): return request.param + 1 # 默认 indirect 为 False @pytest.mark.parametrize('min, max', [(1, 2), (3, 4)]) def test_indirect(min, max): assert min <= max # min max 对应的实参重定向到同名的 fixture 中 @pytest.mark.parametrize('min, max', [(1, 2), (3, 4)], indirect=True) def test_indirect_indirect(min, max): assert min >= max # 只将 max 对应的实参重定向到 fixture 中 @pytest.mark.parametrize('min, max', [(1, 2), (3, 4)], indirect=['max']) def test_indirect_part_indirect(min, max): assert min == max
ids
:一个可执行对象,用于生成测试ID
,或者一个列表/元组,指明全部新增用例的测试ID
;
若是使用列表/元组直接指明测试ID
,那么它的长度要等于argvalues
的长度:
@pytest.mark.parametrize('input, expected', [(1, 2), (3, 4)], ids=['first', 'second']) def test_ids_with_ids(input, expected): pass
搜集到的测试ID
以下:
collected 2 items <Module test_ids.py> <Function test_ids_with_ids[first]> <Function test_ids_with_ids[second]>
若是指定了相同的测试ID
,pytest
会在后面自动添加索引:
@pytest.mark.parametrize('input, expected', [(1, 2), (3, 4)], ids=['num', 'num']) def test_ids_with_ids(input, expected): pass
搜集到的测试ID
以下:
collected 2 items <Module test_ids.py> <Function test_ids_with_ids[num0]> <Function test_ids_with_ids[num1]>
若是在指定的测试ID
中使用了非ASCII
的值,默认显示的是字节序列:
@pytest.mark.parametrize('input, expected', [(1, 2), (3, 4)], ids=['num', '中文']) def test_ids_with_ids(input, expected): pass
搜集到的测试ID
以下:
collected 2 items <Module test_ids.py> <Function test_ids_with_ids[num]> <Function test_ids_with_ids[\u4e2d\u6587]>
能够看到咱们指望显示中文
,实际上显示的是\u4e2d\u6587
;
若是咱们想要获得指望的显示,该怎么办呢?去源码里找答案:
# _pytest/python.py def _ascii_escaped_by_config(val, config): if config is None: escape_option = False else: escape_option = config.getini( "disable_test_id_escaping_and_forfeit_all_rights_to_community_support" ) return val if escape_option else ascii_escaped(val)
咱们能够经过在pytest.ini
中使能disable_test_id_escaping_and_forfeit_all_rights_to_community_support
选项来避免这种状况:
[pytest] disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True
再次搜集到的测试ID
以下:
<Module test_ids.py> <Function test_ids_with_ids[num]> <Function test_ids_with_ids[中文]>
若是经过一个可执行对象生成测试ID
:
def idfn(val): # 将每一个 val 都加 1 return val + 1 @pytest.mark.parametrize('input, expected', [(1, 2), (3, 4)], ids=idfn) def test_ids_with_ids(input, expected): pass
搜集到的测试ID
以下:
collected 2 items <Module test_ids.py> <Function test_ids_with_ids[2-3]> <Function test_ids_with_ids[4-5]>
经过上面的例子咱们能够看到,对于一个具体的argvalues
参数(1, 2)
来讲,它被拆分为1
和2
分别传递给idfn
,并将返回值经过-
符号链接在一块儿做为一个测试ID
返回,而不是将(1, 2)
做为一个总体传入的;
下面咱们在源码中看看是如何实现的:
# _pytest/python.py def _idvalset(idx, parameterset, argnames, idfn, ids, item, config): if parameterset.id is not None: return parameterset.id if ids is None or (idx >= len(ids) or ids[idx] is None): this_id = [ _idval(val, argname, idx, idfn, item=item, config=config) for val, argname in zip(parameterset.values, argnames) ] return "-".join(this_id) else: return _ascii_escaped_by_config(ids[idx], config)
和咱们猜测的同样,先经过zip(parameterset.values, argnames)
将argnames
和argvalues
的值一一对应,再将处理过的返回值经过"-".join(this_id)
链接;
另外,若是咱们足够细心,从上面的源码中还能够看出,假设已经经过pytest.param
指定了id
属性,那么将会覆盖ids
中对应的测试ID
,咱们来证明一下:
@pytest.mark.parametrize( 'input, expected', [(1, 2), pytest.param(3, 4, id='id_via_pytest_param')], ids=['first', 'second']) def test_ids_with_ids(input, expected): pass
搜集到的测试ID
以下:
collected 2 items <Module test_ids.py> <Function test_ids_with_ids[first]> <Function test_ids_with_ids[id_via_pytest_param]>
测试ID
是id_via_pytest_param
,而不是second
;
讲了这么多ids
的用法,对咱们有什么用呢?
我以为,其最主要的做用就是更进一步的细化测试用例,区分不一样的测试场景,为有针对性的执行测试提供了一种新方法;
例如,对于如下测试用例,能够经过-k 'Window and not Non'
选项,只执行和Windows
相关的场景:
# src/chapter-11/test_ids.py import pytest @pytest.mark.parametrize('input, expected', [ pytest.param(1, 2, id='Windows'), pytest.param(3, 4, id='Windows'), pytest.param(5, 6, id='Non-Windows') ]) def test_ids_with_ids(input, expected): pass
scope
:声明argnames
中参数的做用域,并经过对应的argvalues
实例划分测试用例,进而影响到测试用例的收集顺序;
若是咱们显式的指明scope参数;例如,将参数做用域声明为模块级别:
# src/chapter-11/test_scope.py import pytest @pytest.mark.parametrize('test_input, expected', [(1, 2), (3, 4)], scope='module') def test_scope1(test_input, expected): pass @pytest.mark.parametrize('test_input, expected', [(1, 2), (3, 4)], scope='module') def test_scope2(test_input, expected): pass
搜集到的测试用例以下:
collected 4 items <Module test_scope.py> <Function test_scope1[1-2]> <Function test_scope2[1-2]> <Function test_scope1[3-4]> <Function test_scope2[3-4]>
如下是默认的收集顺序,咱们能够看到明显的差异:
collected 4 items <Module test_scope.py> <Function test_scope1[1-2]> <Function test_scope1[3-4]> <Function test_scope2[1-2]> <Function test_scope2[3-4]>
scope
未指定的状况下(或者scope=None
),当indirect
等于True
或者包含全部的argnames
参数时,做用域为全部fixture
做用域的最小范围;不然,其永远为function
;
# src/chapter-11/test_scope.py @pytest.fixture(scope='module') def test_input(request): pass @pytest.fixture(scope='module') def expected(request): pass @pytest.mark.parametrize('test_input, expected', [(1, 2), (3, 4)], indirect=True) def test_scope1(test_input, expected): pass @pytest.mark.parametrize('test_input, expected', [(1, 2), (3, 4)], indirect=True) def test_scope2(test_input, expected): pass
test_input
和expected
的做用域都是module
,因此参数的做用域也是module
,用例的收集顺序和上一节相同:
collected 4 items <Module test_scope.py> <Function test_scope1[1-2]> <Function test_scope2[1-2]> <Function test_scope1[3-4]> <Function test_scope2[3-4]>
empty_parameter_set_mark
选项默认状况下,若是@pytest.mark.parametrize
的argnames
中的参数没有接收到任何的实参的话,用例的结果将会被置为SKIPPED
;
例如,当python
版本小于3.8
时返回一个空的列表(当前Python
版本为3.7.3
):
# src/chapter-11/test_empty.py import pytest import sys def read_value(): if sys.version_info >= (3, 8): return [1, 2, 3] else: return [] @pytest.mark.parametrize('test_input', read_value()) def test_empty(test_input): assert test_input
咱们能够经过在pytest.ini
中设置empty_parameter_set_mark
选项来改变这种行为,其可能的值为:
skip
:默认值xfail
:跳过执行直接将用例标记为XFAIL
,等价于xfail(run=False)
fail_at_collect
:上报一个CollectError
异常;若是一个用例标记了多个@pytest.mark.parametrize
标记,以下所示:
# src/chapter-11/test_multi.py @pytest.mark.parametrize('test_input', [1, 2, 3]) @pytest.mark.parametrize('test_output, expected', [(1, 2), (3, 4)]) def test_multi(test_input, test_output, expected): pass
实际收集到的用例,是它们全部可能的组合:
collected 6 items <Module test_multi.py> <Function test_multi[1-2-1]> <Function test_multi[1-2-2]> <Function test_multi[1-2-3]> <Function test_multi[3-4-1]> <Function test_multi[3-4-2]> <Function test_multi[3-4-3]>
咱们能够经过对pytestmark
赋值,参数化一个测试模块:
# src/chapter-11/test_module.py import pytest pytestmark = pytest.mark.parametrize('test_input, expected', [(1, 2), (3, 4)]) def test_module(test_input, expected): assert test_input + 1 == expected
pytest_generate_tests
钩子方法pytest_generate_tests
方法在测试用例的收集过程当中被调用,它接收一个metafunc
对象,咱们能够经过其访问测试请求的上下文,更重要的是,可使用metafunc.parametrize
方法自定义参数化的行为;
咱们先看看源码中是怎么使用这个方法的:
# _pytest/python.py def pytest_generate_tests(metafunc): # those alternative spellings are common - raise a specific error to alert # the user alt_spellings = ["parameterize", "parametrise", "parameterise"] for mark_name in alt_spellings: if metafunc.definition.get_closest_marker(mark_name): msg = "{0} has '{1}' mark, spelling should be 'parametrize'" fail(msg.format(metafunc.function.__name__, mark_name), pytrace=False) for marker in metafunc.definition.iter_markers(name="parametrize"): metafunc.parametrize(*marker.args, **marker.kwargs)
首先,它检查了parametrize
的拼写错误,若是你不当心写成了["parameterize", "parametrise", "parameterise"]
中的一个,pytest
会返回一个异常,并提示正确的单词;而后,循环遍历全部的parametrize
的标记,并调用metafunc.parametrize
方法;
如今,咱们来定义一个本身的参数化方案:
在下面这个用例中,咱们检查给定的stringinput
是否只由字母组成,可是咱们并无为其打上parametrize
标记,因此stringinput
被认为是一个fixture
:
# src/chapter-11/test_strings.py def test_valid_string(stringinput): assert stringinput.isalpha()
如今,咱们指望把stringinput
当成一个普通的参数,而且从命令行赋值:
首先,咱们定义一个命令行选项:
# src/chapter-11/conftest.py def pytest_addoption(parser): parser.addoption( "--stringinput", action="append", default=[], help="list of stringinputs to pass to test functions", )
而后,咱们经过pytest_generate_tests
方法,将stringinput
的行为由fixtrue
改为parametrize
:
# src/chapter-11/conftest.py def pytest_generate_tests(metafunc): if "stringinput" in metafunc.fixturenames: metafunc.parametrize("stringinput", metafunc.config.getoption("stringinput"))
最后,咱们就能够经过--stringinput
命令行选项来为stringinput
参数赋值了:
λ pipenv run pytest -q --stringinput='hello' --stringinput='world' src/chapter-11/test_strings.py .. [100%] 2 passed in 0.02s
若是咱们不加--stringinput
选项,至关于parametrize
的argnames
中的参数没有接收到任何的实参,那么测试用例的结果将会置为SKIPPED
λ pipenv run pytest -q src/chapter-11/test_strings.py s [100%] 1 skipped in 0.02s
注意:
不论是
metafunc.parametrize
方法仍是@pytest.mark.parametrize
标记,它们的参数(argnames
)不能是重复的,不然会产生一个错误:ValueError: duplicate 'stringinput'
;