使覆盖率只计算成功的测试,而忽略xfailing测试



我有很多项目,在这些项目中,我使用pytest.mark.xfail标记来标记失败的测试,但不应该失败,这样就可以在解决问题之前添加失败的测试用例。我不想跳过这些测试,因为如果我所做的事情导致它们开始通过,我希望被告知这一点,这样我就可以删除xfail标记以避免倒退。

问题是,因为xfail测试实际上一直运行到失败,所以导致失败的任何行都被视为"覆盖",,即使它们是不通过测试的一部分,这给了我关于我的代码实际测试为有效的误导性指标。一个最小的例子是:

pkg.py

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

测试_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标记的东西,这意味着无论是否满足条件,条件xfail也会被过滤掉。

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

由于您使用的是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.argsmarker.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)

最新更新