欧洲站vat激活,logo 在线生成,焦作维科网站建设公司,白城整站优化1. pytest.mark.parametrize标记 1.1. empty_parameter_set_mark选项1.2. 多个标记组合1.3. 标记测试模块 2. pytest_generate_tests钩子方法
在实际工作中#xff0c;测试用例可能需要支持多种场景#xff0c;我们可以把和场景强相关的部分抽象成参数#xff0c;通过对参数…1. pytest.mark.parametrize标记 1.1. empty_parameter_set_mark选项1.2. 多个标记组合1.3. 标记测试模块 2. pytest_generate_tests钩子方法
在实际工作中测试用例可能需要支持多种场景我们可以把和场景强相关的部分抽象成参数通过对参数的赋值来驱动用例的执行
参数化的行为表现在不同的层级上 fixture的参数化参考 4、fixtures明确的、模块化的和可扩展的 – fixture的参数化 测试用例的参数化使用pytest.mark.parametrize可以在测试用例、测试类甚至测试模块中标记多个参数或fixture的组合
另外我们也可以通过pytest_generate_tests这个钩子方法自定义参数化的方案
1. pytest.mark.parametrize标记
pytest.mark.parametrize的根本作用是在收集测试用例的过程中通过对指定参数的赋值来新增被标记对象的调用执行
首先我们来看一下它在源码中的定义
# _pytest/python.pydef parametrize(self, argnames, argvalues, indirectFalse, idsNone, scopeNone):着重分析一下各个参数 argnames一个用逗号分隔的字符串或者一个列表/元组表明指定的参数名 对于argnames实际上我们是有一些限制的 只能是被标记对象入参的子集 pytest.mark.parametrize(input, expected, [(1, 2)])
def test_sample(input):assert input 1 1test_sample中并没有声明expected参数如果我们在标记中强行声明会得到如下错误 In test_sample: function uses no argument expected不能是被标记对象入参中定义了默认值的参数 pytest.mark.parametrize(input, expected, [(1, 2)])
def test_sample(input, expected2):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 1pytest.mark.parametrize(input, expected, [(1, 2)])
def test_sample(input, expected):assert input 1 expected
test_sample标记中的expected2覆盖了同名的fixture expected1所以这条用例是可以测试成功的这里可以参考[4、fixtures明确的、模块化的和可扩展的 -- 在用例参数中覆写fixture](4、fixtures明确的、模块化的和可扩展的.md#163-在用例参数中覆写fixture)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 devpytest.mark.parametrize(dev, read_excel())
def test_sample(dev):assert dev实现这个场景有多种方法你也可以直接在一个fixture中去加载excel中的数据但是它们在测试报告中的表现会有所区别或许你还记得在上一篇教程10、skip和xfail标记 – 结合pytest.param方法中我们使用pytest.param为argvalues参数赋值 pytest.mark.parametrize((n, expected),[(2, 1),pytest.param(2, 1, markspytest.mark.xfail(), idXPASS)])
def test_params(n, expected):assert 2 / n expected现在我们来具体分析一下这个行为 无论argvalues中传递的是可度量对象列表、元组等还是具体的值在源码中我们都会将其封装成一个ParameterSet对象它是一个具名元组namedtuple包含values, marks, id三个元素 from _pytest.mark.structures import ParameterSet as PSPS._make([(1, 2), [], None])
ParameterSet(values(1, 2), marks[], idNone)如果直接传递一个ParameterSet对象会发生什么呢我们去源码里找答案 # _pytest/mark/structures.pyclass ParameterSet(namedtuple(ParameterSet, values, marks, id)):...classmethoddef extract_from(cls, parameterset, force_tupleFalse)::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 valuesdont get decomposed and break testsif isinstance(parameterset, cls):return parametersetif force_tuple:return cls.param(parameterset)else:return cls(parameterset, marks[], idNone)可以看到如果直接传递一个ParameterSet对象那么返回的就是它本身return parameterset所以下面例子中的两种写法是等价的 # src/chapter-11/test_sample.pyimport pytestfrom _pytest.mark.structures import ParameterSetpytest.mark.parametrize(input, expected,[(1, 2), ParameterSet(values(1, 2), marks[], idNone)])
def test_sample(input, expected):assert input 1 expected到这里或许你已经猜到了pytest.param的作用就是封装一个ParameterSet对象那么我们去源码里求证一下吧 # _pytest/mark/__init__.pydef param(*values, **kw):Specify a parameter in pytest.mark.parametrize_ calls or:ref:parametrized fixtures fixture-parametrize-marks... code-block:: pythonpytest.mark.parametrize(test_input,expected, [(35, 8),pytest.param(6*9, 42, markspytest.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传参了吧 indirectargnames的子集或者一个布尔值将指定参数的实参通过request.param重定向到和参数同名的fixture中以此满足更复杂的场景 具体使用方法可以参考以下示例 # src/chapter-11/test_indirect.pyimport pytestpytest.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)], indirectTrue) 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.pyFunction test_ids_with_ids[first]Function test_ids_with_ids[second]如果指定了相同的测试IDpytest会在后面自动添加索引 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.pyFunction 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.pyFunction test_ids_with_ids[num]Function test_ids_with_ids[\u4e2d\u6587]可以看到我们期望显示中文实际上显示的是\u4e2d\u6587 如果我们想要得到期望的显示该怎么办呢去源码里找答案 # _pytest/python.pydef _ascii_escaped_by_config(val, config):if config is None:escape_option Falseelse: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.pyFunction test_ids_with_ids[num]Function test_ids_with_ids[中文]如果通过一个可执行对象生成测试ID def idfn(val):# 将每个 val 都加 1return val 1pytest.mark.parametrize(input, expected, [(1, 2), (3, 4)], idsidfn)
def test_ids_with_ids(input, expected):pass
搜集到的测试ID如下bash
collected 2 items
Module test_ids.pyFunction test_ids_with_ids[2-3]Function test_ids_with_ids[4-5]
通过上面的例子我们可以看到对于一个具体的argvalues参数(1, 2)来说它被拆分为1和2分别传递给idfn并将返回值通过-符号连接在一起作为一个测试ID返回而不是将(1, 2)作为一个整体传入的下面我们在源码中看看是如何实现的python
# _pytest/python.pydef _idvalset(idx, parameterset, argnames, idfn, ids, item, config):if parameterset.id is not None:return parameterset.idif ids is None or (idx len(ids) or ids[idx] is None):this_id [_idval(val, argname, idx, idfn, itemitem, configconfig)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我们来证实一下python
pytest.mark.parametrize(input, expected,[(1, 2), pytest.param(3, 4, idid_via_pytest_param)],ids[first, second])
def test_ids_with_ids(input, expected):pass
搜集到的测试ID如下bash
collected 2 items
Module test_ids.pyFunction 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.pyimport pytestpytest.mark.parametrize(input, expected, [pytest.param(1, 2, idWindows),pytest.param(3, 4, idWindows),pytest.param(5, 6, idNon-Windows)
])
def test_ids_with_ids(input, expected):passscope声明argnames中参数的作用域并通过对应的argvalues实例划分测试用例进而影响到测试用例的收集顺序 如果我们显式的指明scope参数例如将参数作用域声明为模块级别 # src/chapter-11/test_scope.pyimport pytestpytest.mark.parametrize(test_input, expected, [(1, 2), (3, 4)], scopemodule)
def test_scope1(test_input, expected):passpytest.mark.parametrize(test_input, expected, [(1, 2), (3, 4)], scopemodule)
def test_scope2(test_input, expected):pass
搜集到的测试用例如下bash
collected 4 items
Module test_scope.pyFunction test_scope1[1-2]Function test_scope2[1-2]Function test_scope1[3-4]Function test_scope2[3-4]
以下是默认的收集顺序我们可以看到明显的差别bash
collected 4 items
Module test_scope.pyFunction test_scope1[1-2]Function test_scope1[3-4]Function test_scope2[1-2]Function test_scope2[3-4]scope未指定的情况下或者scopeNone当indirect等于True或者包含所有的argnames参数时作用域为所有fixture作用域的最小范围否则其永远为function # src/chapter-11/test_scope.pypytest.fixture(scopemodule)
def test_input(request):passpytest.fixture(scopemodule)
def expected(request):passpytest.mark.parametrize(test_input, expected, [(1, 2), (3, 4)],indirectTrue)
def test_scope1(test_input, expected):passpytest.mark.parametrize(test_input, expected, [(1, 2), (3, 4)],indirectTrue)
def test_scope2(test_input, expected):passtest_input和expected的作用域都是module所以参数的作用域也是module用例的收集顺序和上一节相同 collected 4 items
Module test_scope.pyFunction test_scope1[1-2]Function test_scope2[1-2]Function test_scope1[3-4]Function test_scope2[3-4]1.1. empty_parameter_set_mark选项
默认情况下如果pytest.mark.parametrize的argnames中的参数没有接收到任何的实参的话用例的结果将会被置为SKIPPED
例如当python版本小于3.8时返回一个空的列表当前Python版本为3.7.3
# src/chapter-11/test_empty.pyimport pytest
import sysdef 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(runFalse)fail_at_collect上报一个CollectError异常
1.2. 多个标记组合
如果一个用例标记了多个pytest.mark.parametrize标记如下所示
# src/chapter-11/test_multi.pypytest.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.pyFunction 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]1.3. 标记测试模块
我们可以通过对pytestmark赋值参数化一个测试模块
# src/chapter-11/test_module.pyimport pytestpytestmark pytest.mark.parametrize(test_input, expected, [(1, 2), (3, 4)])def test_module(test_input, expected):assert test_input 1 expected2. pytest_generate_tests钩子方法
pytest_generate_tests方法在测试用例的收集过程中被调用它接收一个metafunc对象我们可以通过其访问测试请求的上下文更重要的是可以使用metafunc.parametrize方法自定义参数化的行为
我们先看看源码中是怎么使用这个方法的
# _pytest/python.pydef pytest_generate_tests(metafunc):# those alternative spellings are common - raise a specific error to alert# the useralt_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 parametrizefail(msg.format(metafunc.function.__name__, mark_name), pytraceFalse)for marker in metafunc.definition.iter_markers(nameparametrize):metafunc.parametrize(*marker.args, **marker.kwargs)首先它检查了parametrize的拼写错误如果你不小心写成了[parameterize, parametrise, parameterise]中的一个pytest会返回一个异常并提示正确的单词然后循环遍历所有的parametrize的标记并调用metafunc.parametrize方法
现在我们来定义一个自己的参数化方案
在下面这个用例中我们检查给定的stringinput是否只由字母组成但是我们并没有为其打上parametrize标记所以stringinput被认为是一个fixture
# src/chapter-11/test_strings.pydef test_valid_string(stringinput):assert stringinput.isalpha()现在我们期望把stringinput当成一个普通的参数并且从命令行赋值
首先我们定义一个命令行选项
# src/chapter-11/conftest.pydef pytest_addoption(parser):parser.addoption(--stringinput,actionappend,default[],helplist of stringinputs to pass to test functions,)然后我们通过pytest_generate_tests方法将stringinput的行为由fixtrue改成parametrize
# src/chapter-11/conftest.pydef pytest_generate_tests(metafunc):if stringinput in metafunc.fixturenames:metafunc.parametrize(stringinput, metafunc.config.getoption(stringinput))最后我们就可以通过--stringinput命令行选项来为stringinput参数赋值了
λ pytest -q --stringinputhello --stringinputworld src/chapter-11/test_strings.py
.. [100%]
2 passed in 0.02s如果我们不加--stringinput选项相当于parametrize的argnames中的参数没有接收到任何的实参那么测试用例的结果将会置为SKIPPED
λ pytest -q src/chapter-11/test_strings.py
s [100%]
1 skipped in 0.02s注意 不管是metafunc.parametrize方法还是pytest.mark.parametrize标记它们的参数argnames不能是重复的否则会产生一个错误ValueError: duplicate stringinput