Geo*_*lin 5 python unit-testing code-coverage pytest
我正在努力实现 100% 的覆盖率。
我有文件(app/ifaces.py):
import netifaces
class NoIPException(Exception):
pass
def get_local_ips():
...(code here)
Run Code Online (Sandbox Code Playgroud)
我有测试:
import pytest
import mock
import netifaces
from app import ifaces
def test_get_local_ips_normal_case():
....
Run Code Online (Sandbox Code Playgroud)
当我手动运行测试时:
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])
Run Code Online (Sandbox Code Playgroud)
报告:
Name Stmts Miss Cover Missing
--------------------------------------------
app/ifaces 16 4 75% 1-6
Run Code Online (Sandbox Code Playgroud)
如何添加自运行测试以获得与手动 py.test 执行相同的结果?结果之间有什么区别?为什么 app/ifaces.py 中的 6 行被报告为在第二种情况下未涵盖?
谢谢。
好吧,我找到了原因。
当从 test 本身调用 pytest 时,所有导入都已完成,因此,它们不被算作覆盖范围。
为了覆盖它们,需要在 pytest-cov 执行期间导入它们。
我的解决方案是使用 pytest 装置进行导入: 1. 从测试程序顶部删除“from app import ifaces”。2. 添加夹具:
@pytest.fixture
def ifaces():
from app import ifaces
return ifaces
Run Code Online (Sandbox Code Playgroud)
3.使其可作为变量传递给测试:
def test_get_local_ips_normal_case(ifaces)
....
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1376 次 |
| 最近记录: |