对于py.test,我经常生成一些测试用例可能会失败的测试如何将它们标记为xfail如果我将@py.test.mark.xfail放在测试函数上,则意味着它的所有实例都是xfail如果我在测试中做了py.test.xfail(),它实际上会失败,而不仅仅是将其标记为xfail。我可以用metafunc添加这个标记吗?
例如

# code - function with a bug :)

def evenHigherThanSquare(n):
    return n**2


# test file

def pytest_generate_tests(metafunc):
    data = [
        (2, 4),
        (3, 10), # should be xfail
        (4, 16),
        (5, 26), # should be xfail
        ]
    for input, expected in data:
        if metafunc.function is test_evenHigherThanSquare:
            metafunc.addcall(funcargs=dict(input=input, expected=expected))


def test_evenHigherThanSquare(input, expected):
    assert evenHigherThanSquare(input) == expected

最佳答案

当然,您可以使用funcarg factoryapply an xfail marker(since 1.3.2)

def pytest_generate_tests(metafunc):
    data = [
        # input # output # is expected to fail?
        (2, 4, False),
        (3, 10, True),
        (4, 16, False),
        (5, 26, True),
        ]
    for input, expected, xfail in data:
        if metafunc.function is test_evenHigherThanSquare:
            metafunc.addcall(funcargs=dict(input=input, expected=expected),
                             param=xfail)


def pytest_funcarg__xfail(request):
    if request.param:
        request.applymarker(py.test.mark.xfail)


def test_evenHigherThanSquare(input, expected, xfail):
    assert evenHigherThanSquare(input) == expected

在这里,我们使用未使用的xfail参数来触发对每个测试项的test_evenHigherThanSquare调用;它使用提供给pytest_funcarg__xfailparam来决定是否发送测试。
Funcarg工厂更常用于生成在收集时创建代价高昂的参数,但应用标记也是完全受支持的用法。

07-24 17:58