43

Should I care how my tests cover the external libraries I'm using in my project ?

The py.test --cov displays how all files are covered, including ones in my virtualenv directory. How can I make the output show only the coverage of the modules I've written ?

David Ben Ari
  • 2,259
  • 3
  • 21
  • 40

5 Answers5

61

In the root of your project, create file .coveragerc containing:

[run]
omit = path_to_libs_to_omit/*

Depending on your setup, you might need to add --cov-config=path/to/.coveragerc as option to the py.test command.

There are more options you can use to configure coverage.

cacti5
  • 2,006
  • 2
  • 25
  • 33
sashk
  • 3,946
  • 2
  • 33
  • 41
  • 11
    worth mentioning that you can have multiple paths by using a comma separated list ```[run] omit = path_to_libs_to_omit/**,path_to_other_libs_to_omit/** ``` – Clintm Sep 24 '20 at 16:58
  • you can also define multiple paths for `omit` as one path per line (great if you have a lot to exclude). – mlen108 Jul 16 '21 at 09:28
  • 1
    Alternately, add an entry to your tox.ini `[coverage:run] omit = path_to_libs_to_omit/*` as documented at https://coverage.readthedocs.io/en/latest/config.html – chrisinmtown Jan 14 '22 at 16:28
30

You should add your module's name to the --cov command line option, for example form pytest-cov documentation:

py.test --cov=myproj tests/

This restrict the coverage to the module myproj and all its sub-modules.

alexamici
  • 754
  • 5
  • 10
20

@alexamici answer is the correct one for virtualenvs, but for completeness, adding pyproject.toml (suggested config file for python projects) set up:

[tool.coverage.run]
omit = [
    "file/to/exclude.py",
    "other/file.py",
    "some/path/*"
    ]
Michał Zawadzki
  • 695
  • 6
  • 14
3

one-liner,

echo -e "[run]\nomit = venv/*" > .coveragerc && pytest -v --cov

Pretty handy if you use this in CI or if you don't want to add .coveragerc to your git repo just because of 'venv'.

Jinesi Yelizati
  • 271
  • 1
  • 7
2

This is how I managed to do it: pytest.py

[pytest]
python_files = tests.py test_*.py *_tests.py
addopts = -v -p no:warnings --nomigrations --cov=. --no-cov-on-fail

coveragerc

[run]
omit = venv/*
gildniy
  • 3,528
  • 1
  • 33
  • 23