Coverage.py

Coverage.py is a tool for measuring code coverage of Python programs. Itmonitors your program, noting which parts of the code have been executed, thenanalyzes the source to identify code that could have been executed but was not.

Coverage measurement is typically used to gauge the effectiveness of tests. Itcan show which parts of your code are being exercised by tests, and which arenot.

The latest version is coverage.py 4.3.3, released January 17th 2017. Itis supported on:

  • Python versions 2.6, 2.7, 3.3, 3.4, 3.5, and 3.6.
  • PyPy2 5.6 and PyPy3 5.5.
  • Jython 2.7.1, though only for running code, not reporting.

Quick start

Getting started is easy:

  1. Install coverage.py from thecoverage.py page on the Python Package Index,or by using “pip install coverage”. For a few more details, seeInstallation.

  2. Usecoveragerun to run your program and gather data:

    $ coverage run my_program.py arg1 arg2blah blah ..your program's output.. blah blah
  3. Usecoveragereport to report on the results:

    $ coverage report -mName                      Stmts   Miss  Cover   Missing-------------------------------------------------------my_program.py                20      4    80%   33-35, 39my_other_module.py           56      6    89%   17-23-------------------------------------------------------TOTAL                        76     10    87%
  4. For a nicer presentation, usecoveragehtml to get annotated HTMLlistings detailing missed lines:

    $ coverage html

    Then visit htmlcov/index.html in your browser, to see areport like this.

Using coverage.py

There are a few different ways to use coverage.py. The simplest is thecommand line, which lets you run your program and see the results.If you need more control over how your project is measured, you can use theAPI.

Some test runners provide coverage integration to make it easy to usecoverage.py while running tests. For example,pytest has thepytest-covplugin.

You can fine-tune coverage.py’s view of your code by directing it to ignoreparts that you know aren’t interesting. SeeSpecifying source files andExcluding code from coverage.pyfor details.

Getting help

If theFAQ doesn’t answer your question, you can discusscoverage.py or get help using it on theTesting In Python mailing list.

Bug reports are gladly accepted at theBitbucket issue tracker.Bitbucket also hosts thecode repository. There is amirrored repo onGitHub.

I can be reached in a number of ways. I’m happy to answer questions aboutusing coverage.py.