在pytest parametriz中标记输入

2024-06-01 12:47:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个测试,我想作为两个不同测试套件的一部分运行,这些测试套件具有基于测试套件的不同参数输入。测试套件用pytest标记进行标识。在

有没有一种方法可以标记参数化条目,以便它们只在特定的测试套件中运行?在

我想做的是:

@pytest.mark.suiteA # include the test in Suite A
@pytest.mark.suiteB # include the test in Suite B
@pytest.mark.parametrize("inputParameter", [
                              (10),                    # use this input for Suites A and B
                              pytest.mark.suiteB(12)]) # only use this input for Suite B
def test_printInputParameter(inputParameter):
    print inputParameter

像这样运行代码并不能产生我想要的结果——两个输入都用于两个套件。在

我已经看到pytest将允许使用xfail或在parametrize中跳过(请参见http://pytest.org/latest/skipping.html上的“skip/xfail with parametrize”),如果有一种方法可以编写一个只有在运行suiteb时才计算为true的条件语句,那么这也可以满足我的需要。在

提前谢谢你的帮助。在


Tags: the方法in标记test参数include套件
2条回答

似乎您可以使用skipif mark来完成此操作,如http://pytest.org/latest/skipping.html#skip-xfail-with-parametrize(您所指的)中所述。您需要做的就是有一个方法来知道您的代码是在suiteA还是suiteB中运行,因为suiteASuiteB标记起作用了,您可能已经有了。因此,在这个例子中,让我们在sys模块上设置一个(丑陋的)helper属性,类似于检测代码是否在下面运行py.测试公司名称:

# E.g. in conftest.py; in real life the value probably comes from a
# command line option added by pytest_addoption()
def pytest_configure(config):
    sys._my_test_suite = 'A'  # or 'B'

# The actual test can now use this in skipif
@pytest.mark.suiteA # include the test in Suite A
@pytest.mark.suiteB # include the test in Suite B
@pytest.mark.parametrize(
    "inputParameter",
    [(10), pytest.mark.skipif(sys._my_test_suite == 'A', reason='suite A only')(12)])])
def test_printInputParameter(inputParameter):
    print inputParameter

是的,在sys模块上设置一个属性是一个丑陋的黑客行为,但对于这种情况来说,这是一个简单的解决方案。在

你已经和@suiteX.pytest公司使所有参数化测试都具有该标记,因此实际上,您已经标记了所有测试,而只在参数列表中应用标记:

import pytest

mark = pytest.mark

@mark.parametrize("inputParameter", [
    mark.suiteA(10),
    mark.suiteB(12),
])
def test_printInputParameter(inputParameter):
    print inputParameter

然后在cli上使用-m(mark)选择要筛选的测试:

^{pr2}$

相关问题 更多 >