Python 使用pytest cov的类声明缺少测试覆盖率
我正在努力实现100%的覆盖率 我有一个文件(app/ifaces.py): 我有一个测试:Python 使用pytest cov的类声明缺少测试覆盖率,python,unit-testing,code-coverage,pytest,Python,Unit Testing,Code Coverage,Pytest,我正在努力实现100%的覆盖率 我有一个文件(app/ifaces.py): 我有一个测试: import pytest import mock import netifaces from app import ifaces def test_get_local_ips_normal_case(): .... 当我手动运行测试时: py.test-v--cov应用程序--cov报告术语缺失 它报告了100%的代码覆盖率: app/ifaces 16 0 100% 但当我将其作为“自运行”添
import pytest
import mock
import netifaces
from app import ifaces
def test_get_local_ips_normal_case():
....
当我手动运行测试时:
py.test-v--cov应用程序--cov报告术语缺失
它报告了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行被报告为第二种情况下未涵盖
谢谢。好的,我找到了一个理由
当从测试本身调用pytest时,所有导入都已完成,因此,它们不被视为已覆盖
为了覆盖它,需要在pytest cov执行期间导入它们
我的解决方案是使用pytest装置进行导入:
1.从测试程序顶部删除“从应用程序导入ifaces”。
2.添加固定装置:
@pytest.fixture
def ifaces():
from app import ifaces
return ifaces
3.使其作为变量通过试验:
def test_get_local_ips_normal_case(ifaces)
....
def test_get_local_ips_normal_case(ifaces)
....