首页 文章

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

提问于
浏览
2

我正在努力实现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%

但是当我将它作为“自运行”添加到测试时,它会报告前六行未被覆盖:

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行被报告为第二种情况未被覆盖?

谢谢 .

1 回答

  • 1

    好的,我找到了一个理由 .

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

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

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

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

    3.使其作为变量可通过测试:

    def test_get_local_ips_normal_case(ifaces)
        ....
    

相关问题