Getting a Django Application to 100% Coverage

Last updated 138 days ago by Adam Johnson

django

Code coverage is a simple tool for checking which lines of your application code are run by your test suite. 100% coverage is a laudable goal, as it means every line is run at least once.

Coverage.py is the Python tool for measuring code coverage. Ned Batchelder has maintained it for an incredible 14 years!

I like adding Coverage.py to my Django projects, like fellow Django Software Foundation member Sasha Romijn.

Let’s look at how we can integrate it with a Django project, and how to get that golden 100% (even if it means ignoring some lines).

Configuring Coverage.py

Install coverage with pip install coverage. It includes a C extension for speed-up, it’s worth checking that this installs properly - see the installation docs for information.

Then set up a configuration file for your project. The default file name is .coveragerc, but since that’s a hidden file I prefer to use the option to store the configuration in setup.cfg.

This INI file was originally used only by setuptools but now many tools have the option to read their configuration from it. For Coverage.py, we put our settings there in sections prefixed with coverage:.

The Run Section

This is where we tell Coverage.py what coverage data to gather.

We tell Coverage.py which files to check with the source option. In a typical Django project this is as easy as specifying the current directory (source = .) or the app directory (source = myapp/*). Add it like so:

Read full Article