使用unittest和coverage.py测量每个测试的覆盖率

时间:2017-02-23 11:34:56

标签: python python-unittest coverage.py

我正在尝试测量每个测试用例的代码覆盖率(这是一个有趣的项目,我无法真正提供用例)。为此,我有我的自定义结果类(摘录):

class CoverageResult(unittest.result.TestResult):
    def __init__(self, coverage_sources=None, *args, **kwargs):
        if coverage_sources:
            self.coverage = coverage.coverage(branch=True, include=coverage_sources)
        else:
            self.coverage = None

    def startTest(self, test):
        if self.coverage:
            self.coverage.start()
        super(CoverageResult, self).startTest(test)

    def stopTest(self, test):
        if self.coverage:
            self.coverage.stop()
            self.coverage.report()
            self.coverage.erase()

        super(CoverageResult, self).stopTest(test)

这样可以正常工作,并打印出每个测试的覆盖率报告。但是,我只想保存它(稍后处理),并在测试运行结束时显示汇总报告。为此,我修改了stopTest()方法并添加了一个属性:

def stopTest(self, test):
    if self.coverage:
        self.coverage.stop()
        # self.test_data is a dict with tests as a key, and contains timing information and stuff for each test.
        self.test_data[test]['coverage'] = self.coverage.data
        # This is needed so I don’t erase the result I just saved
        self.coverage.data = coverage.CoverageData()
        self.coverage.erase()

@property
def coverage_data(self):
    for test, data in self.test_data:
        self.coverage.data.update(d['coverage'])

    return self.coverage

现在,如果我运行我的测试,最后用result.coverage_data.report()打印结果,我只会得到一个例外:

coverage.misc.CoverageException: No data to report.

我知道我可以将每个测试覆盖率数据保存到磁盘上的文件(甚至像StringIO这样的文件类对象),然后将它们合并为一个,但我怎样才能传递它到Coverage实例,以便它可以从中生成报告?

0 个答案:

没有答案