python3使用coverage做代码覆盖率

  |   0 评论   |   0 浏览

背景

python3下,如何用coverage做代码覆盖率的统计。

初体验

安装

% pip3 install coverage

查看安装成功

% coverage help
Coverage.py, version 5.1 with C extension
Measure, collect, and report on code coverage in Python programs.

usage: coverage <command> [options] [args]

Commands:
    annotate    Annotate source files with execution information.
    combine     Combine a number of data files.
    erase       Erase previously collected coverage data.
    help        Get help on using coverage.py.
    html        Create an HTML report.
    json        Create a JSON report of coverage results.
    report      Report coverage stats on modules.
    run         Run a Python program and measure code execution.
    xml         Create an XML report of coverage results.

Use "coverage help <command>" for detailed help on any command.
Full documentation is at https://coverage.readthedocs.io

编写测试代码

#!/usr/bin/python3

import subprocess


class Response:
    stdout = None
    stderr = None

    def __init__(self, stdout, stderr):
        self.stdout = stdout
        self.stderr = stderr


def run_shell(command, quiet=False, do_split=True):
    if not quiet:
        logging.info("run shell cmd: {0}".format(command))

    commands = command
    if do_split:
        commands = command.split()
    pipe = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1, text=True)
    communicate = pipe.communicate()
    response_str = Response(communicate[0], communicate[1])

    return response_str

运行单元测试

先正常运行

% python3 main_processor.py
=== now we test run_shell ===
INFO:root:run shell cmd: ls -lh
stdout:
-rw-r--r--  1 xuqian  staff   1.1K  4 21 15:22 main_processor.py

再使用单元测试覆盖率运行

% coverage run main_processor.py
=== now we test run_shell ===
INFO:root:run shell cmd: ls -lh
stdout:
-rw-r--r--  1 xuqian  staff   1.1K  4 21 15:22 main_processor.py

然后会生成一个 .coverage文件,如下:

% ls -la
-rw-r--r--   1 note  abeffect  53248  4 21 20:36 .coverage

生成 html文件

% coverage html

结果

% ls -lh
total 16
drwxr-xr-x  17 xuqian  staff   544B  4 21 20:37 htmlcov

在浏览器中查看html文件

open htmlcov/index.html

其它

  • erase - 清楚之前coverage收集的数据
  • combine - 合并coverage收集的数据

参考