2

我有许多项目,我使用pytest.mark.xfail标记来标记失败但不应该失败的测试,以便可以在问题解决之前添加失败的测试用例。我不想跳过这些测试,因为如果我做的某件事导致它们开始通过,我想知道这一点,以便我可以删除xfail标记以避免回归。

问题是,因为xfail测试实际上一直运行到失败,所以导致失败的任何行都被计为“已覆盖”,即使它们是 no pass test 的一部分,这给了我关于我的代码实际上有多少的误导性指标测试为工作。一个最小的例子是:

包.py

def f(fail):
    if fail:
        print("This line should not be covered")
        return "wrong answer"

    return "right answer"

test_pkg.py

import pytest
from pkg import f

def test_success():
    assert f(fail=False) == "right answer"

@pytest.mark.xfail
def test_failure():
    assert f(fail=True) == "right answer"

运行python -m pytest --cov=pkg,我得到:

platform linux -- Python 3.7.1, pytest-3.10.0, py-1.7.0, pluggy-0.8.0
rootdir: /tmp/cov, inifile:
plugins: cov-2.6.0
collected 2 items

tests/test_pkg.py .x                                            [100%]

----------- coverage: platform linux, python 3.7.1-final-0 -----------
Name     Stmts   Miss  Cover
----------------------------
pkg.py       5      0   100%

如您所见,所有五行都被覆盖,但第 3 行和第 4 行仅在xfail测试期间被命中。

我现在处理这个问题的方法是设置tox运行类似的东西pytest -m "not xfail" --cov && pytest -m xfail,但是除了有点麻烦之外,那只是过滤掉带有xfail标记的东西,这意味着条件xfails 也会被过滤掉,无论是否条件满足。

有没有办法计算coveragepytest不计算失败测试的覆盖率?或者,我可以使用一种忽略测试覆盖率的机制,如果满足条件xfail,它只会忽略条件测试。xfail

4

1 回答 1

2

由于您使用的是pytest-cov插件,因此请利用它的no_cover标记。使用 注释时pytest.mark.no_cover,将关闭代码覆盖以进行测试。唯一需要实现的是将no_cover标记应用于所有标记为 的测试pytest.mark.xfail。在你的conftest.py

import pytest

def pytest_collection_modifyitems(items):
    for item in items:
        if item.get_closest_marker('xfail'):
            item.add_marker(pytest.mark.no_cover)

运行您的示例现在将产生:

$ pytest --cov=pkg -v
=================================== test session starts ===================================
platform darwin -- Python 3.7.1, pytest-3.9.1, py-1.7.0, pluggy-0.8.0
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow, inifile:
plugins: cov-2.6.0
collected 2 items

test_pkg.py::test_success PASSED                                                     [ 50%]
test_pkg.py::test_failure xfail                                                      [100%]

---------- coverage: platform darwin, python 3.7.1-final-0 -----------
Name     Stmts   Miss  Cover
----------------------------
pkg.py       5      2    60%


=========================== 1 passed, 1 xfailed in 0.04 seconds ===========================

编辑:处理xfail标记中的条件

标记参数可以通过marker.argsand访问marker.kwargs,所以如果你有一个标记

@pytest.mark.xfail(sys.platform == 'win32', reason='This fails on Windows')

访问参数

marker = item.get_closest_marker('xfail')
condition = marker.args[0]
reason = marker.kwargs['reason']

为了考虑条件标志,上面的钩子可以修改如下:

def pytest_collection_modifyitems(items):
    for item in items:
        marker = item.get_closest_marker('xfail')
        if marker and (not marker.args or marker.args[0]):
            item.add_marker(pytest.mark.no_cover)
于 2018-11-07T21:47:42.237 回答