首页 > 解决方案 > 如何从 python 覆盖单元测试中省略(删除)虚拟环境(venv)?

问题描述

https://coverage.readthedocs.io/en/coverage-4.5.1a/source.html#source

我的覆盖范围还包括“venv”文件夹,无论我做什么,我都想排除它,即使使用 --include 或 omit nothing works

coverage run --omit /venv/* tests.py

这会运行测试,但仍会添加“venv”文件夹和依赖项及其覆盖率

当我做

coverage run --include tests.py

只运行测试 - 它说

Nothing to do.

这很烦人......有人可以帮忙吗?

Python 覆盖率报告

标签: pythonpython-3.xunit-testingcoverage.pypython-venv

解决方案


--omit选项的帮助文本说(文档

--omit=PAT1,PAT2,...  Omit files whose paths match one of these patterns.
                      Accepts shell-style wildcards, which must be quoted.

如果不引用通配符,它​​将无法工作,因为 bash 在将参数列表传递给覆盖二进制文件之前会扩展通配符。使用单引号来避免 bash 通配符扩展。

要运行我的测试而不从venv/*中的任何文件获得覆盖:

$ coverage run --omit 'venv/*' -m unittest tests/*.py && coverage report -m
........
----------------------------------------------------------------------
Ran 8 tests in 0.023s

OK
Name                      Stmts   Miss  Cover   Missing
-------------------------------------------------------
ruterstop.py                 84      8    90%   177, 188, 191-197, 207
tests/test_ruterstop.py     108      0   100%
-------------------------------------------------------
TOTAL                       192      8    96%

如果你通常使用 plainpython -m unittest来运行你的测试,你当然也可以省略 test target 参数。

$ coverage run --omit 'venv/*' -m unittest
$ coverage report -m

推荐阅读