如何运行 coverage.py 在一个目录上?

How to run coverage.py on a directory?

我有一个目录 tests,其中包含许多名为 test_* 的不同测试。

我试过 运行 coverage run tests 但是没用。

如何 运行 一个命令覆盖目录中的多个文件?

使用--include 仅包含特定目录中的文件。它匹配文件路径,所以它可以匹配一个子目录。

您可以使用 --source 来实现。例如:coverage run --source=tests/ <run_tests>

这是一个完整的示例,其中包含来自同一个 PWD 的所有阶段的命令。通过一个经过处理的示例,我还包括测试和覆盖前后的报告部分 运行。我 运行 以下步骤在 osx/mojave.

上运行良好
  1. Discover and run all tests in the test directory

$ python -m unittest discover <directory_name>

Or Discover and run all tests in "directory" with tests having file name pattern *_test.py

$ python -m unittest discover -s <directory> -p '*_test.py'

  1. run coverage for all modules

$ coverage run --source=./test -m unittest discover -s <directory>/

  1. get the coverage report from the same directory - no need to cd.

$ coverage report -m

Notice in above examples that the test directory doesn't have to be named "test" and same goes for the test modules.

None 这里的答案对我来说非常有用。我发现 coverage 和 pytest 工作正常:

coverage run -m pytest

这是 运行 在项目文件夹中。它能够找到名为 tests 的文件夹,以及其中的 运行 所有测试(分为多个 python 文件并有一个 __init__.py 文件)。查看报告 运行:

coverage report