5

使用 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
4

2 回答 2

4

当然,您可以使用funcarg 工厂应用 xfail 标记 (从 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提供的内容metafunc.addcall来决定是否使测试失败。

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

于 2012-09-11T11:10:32.423 回答
0

这是另一种方式:

def evenHigherThanSquare(n):
    return n ** 2


# test file

def pytest_generate_tests(metafunc):
    data = [
        pytest.param(2, 4, marks=[]),
        pytest.param(3, 10, marks=[pytest.mark.xfail]),
        pytest.param(4, 16, marks=[]),
        pytest.param(5, 26, marks=[pytest.mark.xfail]),
    ]
    if metafunc.function is test_evenHigherThanSquare:
        metafunc.parametrize("input, expected", data)


def test_evenHigherThanSquare(input, expected):
    assert evenHigherThanSquare(input) == expected
于 2022-02-22T10:19:14.770 回答