如何将一些生成的测试标记为xfail / skip?

时间:2012-09-11 07:29:43

标签: python testing pytest

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

e.g。

# 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

1 个答案:

答案 0 :(得分:3)

当然,您可以使用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__xfail调用;它使用提供给param的{​​{1}}来决定是否进行测试。

Funcarg工厂更常用于生成在收集时创建昂贵的参数,但应用标记也是完全支持的用法。