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

标签 python unit-testing code-coverage pytest

我正在努力实现 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% 的代码覆盖率: 应用程序/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 fixtures 进行导入: 1. 从测试程序的顶部删除“from app import ifaces”。 2. 添加 fixture :

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

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

def test_get_local_ips_normal_case(ifaces)
    ....

关于python - 使用 pytest-cov 的类声明缺少测试覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34882426/

相关文章:

unit-testing - 如何使Resharper在方法名称中但在测试中仅允许下划线?

c# - DotCover 不覆盖引用的 DLL

python - pyconfig.h - 无法打开包含文件 : 'io.h' : No such file or directory

python - psycopg2 在 executemany 语句中插入表名

python - 在没有循环的情况下在 numpy 中计算 xi-xj 矩阵(通过 api 调用)

Python Pandas groupby 或滚动多年平均汇总统计

python - Django @override_settings 不允许字典?

java - 在 adobe cq6 实例中使用放心框架运行单元测试用例

node.js - 如何使用 expresso 显示代码覆盖率输出?

ant - JaCoCo 报告看起来正确,但无法查看源代码