How to omit (remove) virtual environment (venv) from python coverage unit testing?

Viewed 5613

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

My coverage is also including “venv” folder and I would like to exclude it no matter what I do even with --include or omit nothing works

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

This runs the test but still adds "venv" folder and dependencies and their % coverage

When I do

coverage run --include tests.py

To run only tests - it says

Nothing to do.

It is pretty annoying... can someone please help?

Python Coverage Report

4 Answers

The help text for the --omit option says (documentation)

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

It will not work without quoting the wildcard, as bash will expand the wildcards before handing the argument list to the coverage binary. Use single-quotes to avoid bash wildcard expansion.

To run my tests without getting coverage from any files within 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%

If you usually use plain python -m unittest to run your tests you can of course omit the test target argument as well.

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

For those who don't want to pass --omit each time when executing coverage you can define following in .coveragerc or in pyproject.toml. Example for .coveragerc:

# .coveragerc file content
[run]
omit = [
  .venv/*
  tests/*
]

Example for pyproject.toml:

# pyproject.toml file content
[tool.coverage.run]
omit = [
    "tests/*",
    ".venv/*",
]

The command:

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

omits coverage from /venv (ie: venv is off of root).

You should instead try a relative directory like:

coverage run --omit venv tests.py

Use the * for /venv/ and it will eliminate all files within your virtual environment.

coverage run tests.py && coverage report --omit=*/venv/*

Related