在 pytest 单元测试和定制内联测试中使用覆盖率和 codecov.io

Using coverage and codecov.io with both pytest unit tests and bespoke inline tests

我的 Python 项目的代码库包含大量测试。这些测试足够广泛和广泛,我称之为“稳健”。我想知道它们到底有多健壮,所以我设置了 the coverage.py tool, and a codecov.io account.

该项目有两种类型的测试:

  1. 一套单元测试,从一开始到 运行 使用 pytest 编写 - 即没有遗留的基于 unittest 的测试,并且 pytest固定装置和挂钩的杠杆作用很大。
  2. 每个模块的内联测试功能套件,用 a simple bespoke test runner 编写。这些看起来都像这样:
# -*- coding: utf-8 -*-
import sys # …etc

# «module code»

def test():
    
    from clu.testing.utils import inline
    
    @inline.precheck
    def show_some_initial_values():
        """ Precheck function description """
        # «pre-check code»
    
    @inline
    def test_one():
        """ Test one’s description """
        # «test code»
    
    @inline
    def test_two():
        """ Test two’s description """
        # «test code»
    
    @inline.diagnostic
    def show_some_final_values():
        """ Diagnostic function description """
        # «post-run diagnostic code»
    
    return inline.test(100) # runs test functions 100 times;
                            # prechecks and diagnostics run once

if __name__ == '__main__':
    sys.exit(test())

…他们输出这样的报告:

… 内联测试可以 运行 基于每个模块,直接来自编辑器。它们也可以通过 a nox setup that collects and runs all modules that define inline tests.

全部 运行

所以现在,关于 coverage.py 和 codecov.io – 将 pytest 套件与这些工具集成起来非常容易。我对现成的 .coveragerc 文件进行了一些调整,安装了 pytest codecov.io 插件,仅此而已——这些测试将它们的覆盖率报告给 codecov.io很好。

我的问题是,如何集成内联测试的覆盖率报告?

Coverage.py 对测试一无所知。它所做的只是告诉您代码的哪些部分被某个程序运行。通常该程序是测试 运行ner,但 coverage.py 不关心。

如果您 运行 现在使用 python mytestrunner.py 进行测试,请将命令更改为 coverage run mytestrunner.py,您将获得数据。