使用 pytest-cov 缺少 class 声明的测试覆盖率

Missing test coverage for class declaration with pytest-cov

我正在努力实现 100% 的覆盖率。

我有文件 (app/ifaces.py):

import netifaces

class NoIPException(Exception):
    pass

def get_local_ips():
    ...(code here)

我有测试:

import pytest
import mock
import netifaces

from app import ifaces

def test_get_local_ips_normal_case():
....

当我运行手动测试时:

py.test -v --cov app --cov-report term-missing

它报告 100% 的代码覆盖率: app/ifaces 16 0 100%

但是当我将它作为 'self-run' 添加到测试中时,它报告前六行未被覆盖:

if __name__ == "__main__":
    import sys
    pytest.main("-v %s --cov app/ifaces.py --cov-report term-missing" % sys.argv[0])

报告:

Name           Stmts   Miss  Cover   Missing
--------------------------------------------
app/ifaces        16      4    75%   1-6

如何添加自运行 测试以获得与手动py.test 执行相同的结果?结果之间有什么区别?为什么 app/ifaces.py 中的 6 行被报告为未包含在第二种情况中?

谢谢。

好的,我找到原因了。

当从测试本身调用 pytest 时,所有导入都已完成,因此,它们不计入已覆盖。

为了覆盖它们,需要在 pytest-cov 执行期间导入它们。

我的解决方案是使用 pytest fixtures 进行导入: 1. 从测试程序的顶部删除 "from app import ifaces"。 2. 添加夹具:

 @pytest.fixture
 def ifaces():
     from app import ifaces
     return ifaces

3.Make 它可以作为变量通过测试:

def test_get_local_ips_normal_case(ifaces)
    ....