gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:33:21 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com