Skip to content

Code Coverage in Testing

Getting an idea of much code your test covers varies in how complex your code is. I have found coverage.py from Ned Batchelder to be a great tool.

The usage confused me slightly for a while, so I thought I`d share with you how I used it.

First step was to created my Python test. I created mine using the standard unittest framework in Python. I then ran ‘coverage -e -x test_mytest_file.py’ which executes the test.

To extract the coverage of the test run ‘coverage -b -i -d htmlcov ../module_being_tested.py’. This creates a directory of HTML output containing an index.html. Open this in your browser and you will be able to see the overall percentage of covered code. On this page is a list of the modules you tested. Clicking on a module highlights in red the statements not covered by your test.