有没有可能从 Coverage.py 报告中排除测试目录?

我还是个新手,只会玩 Python 单元测试,尤其是 Coverage.py。是否希望覆盖率报告包括实际测试文件的覆盖率?

下面是我的 HTML 报告作为一个例子的屏幕截图。

您可以看到报告包括 tests/test_credit_card。起初,我试图从报告中省略 tests/目录,像这样:

coverage html --omit=tests/ -d tests/coverage

我尝试了几种不同的命令,但我可以 没有为我的生活得到测试/排除。在接受失败后,我开始怀疑是否可能的测试文件是 假设包括在报告中。

有人能解释一下吗?

49857 次浏览

coverage html --omit="*/test*" -d tests/coverage

Create .coveragerc file in your project root folder, and include the following:

[run]
omit = *tests*

You can also explicitly specify which directory has the code you want coverage on instead of saying which things to omit. In a .coveragerc file, if the directory of interest is called demo, this looks like

[run]
source = demo

Leaving this here in case if any Django developer needs a .coveragerc for their project.

[run]
source = .
omit = ./venv/*,*tests*,*apps.py,*manage.py,*__init__.py,*migrations*,*asgi*,*wsgi*,*admin.py,*urls.py


[report]
omit = ./venv/*,*tests*,*apps.py,*manage.py,*__init__.py,*migrations*,*asgi*,*wsgi*,*admin.py,*urls.py

Create a file named .coveragerc on your projects root directory, paste the above code and then just run the command:

coverage run manage.py test

In addition, if you want the tests to execute faster run this command instead.

coverage run manage.py test --keepdb --parallel

This will preserve the test DB and will run the tests in parallel.

You can specify the directories you want to exclude by creating a .coveragerc in the project root.

It supports wildcards (which you can use to exclude virtual environment) and comments (very useful for effective tracking).

The below code block shows how omit can be used (taken from the latest documentation) with multiple files and directories.

[run]
omit =
# omit anything in a .local directory anywhere
*/.local/*
# omit everything in /usr
/usr/*
# omit this single file
utils/tirefire.py

In your case, you could have the following in your .coveragerc:

[run]
omit =
# ignore all test cases in tests/
tests/*

For your question on coverage reports, you can think about testing and coverage in the following manner:

  • When you run pytest or unittest, all the test cases for your source code are executed

  • When you run coverage, it shows the part of the source code that isn't being used.

  • When you run pytest with coverage (something like pytest -v --cov), it runs all test cases and shows the part of the source code that isn't being used.

Extra:

  • You can also specify the location of your HTML report in the configuration file like:
[html]
directory = tests/coverage/html_report/

This is going to create html, js, css, etc. inside tests/coverage/html_report/ everytime you run coverage or pytest -v --cov