Pytest:如何重置标记.增量对于每个新的参数化参数集

2024-10-06 07:04:56 发布

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

我的问题here是关于在接收参数化参数的类上使用增量修饰符。我描述了参数化如何使类为每个参数运行第一个函数,然后才为每个参数运行第二个函数,等等。我收到了一个answer关于如何更改函数调用顺序的命令,使其变为function1(param1)、function2(param1)、function1(param2)、function2(param2)。你知道吗

不幸的是,这并没有解决根本问题。使用答案中的代码:

# content of conftest.py
import pytest
def pytest_generate_tests(metafunc):
    idlist = []
    argvalues = []
    for scenario in metafunc.cls.scenarios:
        idlist.append(scenario[0])
        items = scenario[1].items() #pretty sure this is NOT the same "item" as in function below
        argnames = [x[0] for x in items]
        argvalues.append(([x[1] for x in items]))
    metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class")

def pytest_runtest_makereport(item, call):
    if "incremental" in item.keywords:
        if call.excinfo is not None:
            parent = item.parent
            parent._previousfailed = item

def pytest_runtest_setup(item):
    if "incremental" in item.keywords:
        previousfailed = getattr(item.parent, "_previousfailed", None)
        if previousfailed is not None:
            pytest.xfail("previous test failed (%s)" %previousfailed.name)

# content of test_scenarios.py
import pytest

scenario1 = ('basic', {'attribute': 'value'})
scenario2 = ('advanced', {'attribute': 'value2'})

@pytest.mark.incremental
class TestSampleWithScenarios(object):
    scenarios = [scenario1, scenario2]

    def test_demo1(self, attribute):
        assert attribute=="value2"

    def test_demo2(self, attribute):
        assert isinstance(attribute, str)

我得到的是:

测试1-失败

测试演示2-X失败

测试演示1-失败(应通过)

测试演示2-X失败(应通过)

这是因为pytest正在检查父级之前是否失败,而这并不取决于新一轮的参数。你知道吗

有没有办法重新设置以前失败的标记,以便增量生成所需的报告?你知道吗


Tags: intestfor参数ifpytestdefitems