首页 > 解决方案 > 编写单元测试以检查python中的代码覆盖率

问题描述

我需要在 python 中使用 unittest 编写测试,当覆盖率小于 50% 时会失败。如:

class ExampleTest(unittest.TestCase):

def setUp(self):
    cov = coverage.Coverage()
    cov.load()
    with open(os.devnull, "w") as f:
        self.total = cov.report(file=f)

def test_compare_values(self):
    self.assertGreaterEqual(self.total, 20)

但是当测试运行时,文件覆盖率被锁定并且无法打开。

如何解决这个问题?

标签: pythonpython-unittestcoverage.py

解决方案


不要尝试从测试中读取覆盖率数据。而是使用--fail-under=50覆盖率报告命令上的选项。


推荐阅读