Coverage.py makes it easy to see how much of your code is covered by your test suite. It can be configured to spit out reports in XML (for consumption by a continuous integration server like Jenkins), in HTML (for human viewing), or simply dumping out plain text.
Getting started with coverage and Django is easy. First make sure you have the latest version of coverage (3.5 at time of writing) installed by running pip install -U coverage
, then run your test suite and print a report:
my_project
.
This works well, but what if you want to deliver a portable test script including coverage? You won’t always know the path to the project when it is installed on other people’s computers. With a little Python sorcery, we can figure out the filepath at runtime:
How about checking coverage on multiple modules? We can do that too with a small shell script:
A script like this can be bundled with your project so everyone on your team can easily test and see the coverage. Have it output XML and it is ready for use in a continuous integration system (see coverage help
and coverage help report
for more options).
It’s worth noting that the techniques described here are not Django-specific and can be used with any Python code. Simply replace coverage run manage.py test
with your test script, eg. coverage run tests.py
.