Getting a Django Application to 100% Test Coverage

Underneath the coverage

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:

[coverage:run]
source = .

(Remove the coverage: if you’re using .coveragerc.).

An issue I’ve seen on a Django project is Coverage.py finding Python files from a nested node_modules. It seems Python is so great even JavaScript projects have a hard time resisting it! We can tell coverage to ignore these files by adding omit = */node_modules/*.

When you come to a fork in the road, take it.

Yogi Berra

An extra I like to add is branch coverage. This ensures that your code runs through both the True and False paths of each conditional statement. You can set this up by adding branch = True in your run section.

As an example, take this code:

def frobnicate(widget):
    if is_red(widget):
        paint(widget, blue)
    flim_flam(widget)

With branch coverage off, we can get away with tests that pass in a red widget. Really, we should be testing with both red and non-red widgets. Branch coverage enforces this, by counting both paths from the if.

The Report Section

This is where we tell Coverage.py how to report the coverage data back to us.

I like to add three settings here.

  1. fail_under = 100 requires us to reach that sweet 100% goal to pass. If we’re under our target, the report command fails.
  2. show_missing = True adds a column to the report with a summary of which lines (and branches) the tests missed. This makes it easy to go from a failure to fixing it, rather than using the HTML report.
  3. skip_covered = True avoids outputting file names with 100% coverage. This makes the report a lot shorter, especially if you have a lot of files and are getting to 100% coverage.

Add them like so:

[coverage:report]
fail_under = 100
show_missing = True
skip_covered = True

(Again, remove the coverage: prefix if you’re using .coveragerc.)

Template Coverage

Your Django project probably has a lot of template code. It’s a great idea to test its coverage too. This can help you find blocks or whole template files that the tests didn’t run.

Lucky for us, the primary plugin listed on the Coverage.py plugins page is the Django template plugin.

See the django_coverage_plugin PyPI page for its installation instructions. It just needs a pip install and activation in [coverage:run].

Git Ignore

If your project is using Git, you’ll want to ignore the files that Coverage.py generates. GitHub’s default Python .gitignore already ignores Coverage’s file. If your project isn’t using this, add these lines in your .gitignore:

htmlcov/
.coverage
.coverage.*
coverage.xml
*.cover

Using Coverage in Tests

This bit depends on how you run your tests. I prefer using pytest with pytest-django. However many, projects use the default Django test runner, so I’ll describe that first.

With Django’s Test Runner

If you’re using manage.py test, you need to change the way you run it. You need to wrap it with three coverage commands like so:

$ coverage erase  # Remove any coverage data from previous runs
$ coverage run manage.py test  # Run the full test suite
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.............................................................................
----------------------------------------------------------------------
Ran 77 tests in 0.741s

OK
Destroying test database for alias 'default'...
$ coverage report  # Report on which files are covered
Name                     Stmts   Miss Branch BrPart  Cover   Missing
--------------------------------------------------------------------
settings/dev.py              2      2      0      0     0%   4-6
testapp/models.py            1      1      0      0     0%   5
testapp/test_api.py        400      2      0      0    99%   366, 375
testapp/test_models.py       6      4      0      0    33%   5-8
urls.py                      9      0      2      1    91%   16->exit
--------------------------------------------------------------------
TOTAL                      811      9      4      1    99%

15 files skipped due to complete coverage.

99% - looks like I have a little bit of work to do on my test application!

Having to run three commands sucks. That’s three times as many commands as before!

We could wrap the tests with a shell script. You could add a shell script with this code:

#!/bin/sh
set -e  # Configure shell so that if one command fails, it exits
coverage erase
coverage run manage.py test
coverage report

Update (2020-01-06): Previously the below section recommended a custom test management command. However, since this will only be run after some imports, it's not possible to record 100% coverage this way. Thanks to Hervé Le Roy for reporting this.

However, there’s a more integrated way of achieving this inside Django. We can patch manage.py to call Coverage.py’s API to measure when we run the test command. Here’s how, based on the default manage.py in Django 3.0:

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproj.settings")

    # MyProject Customization: run coverage.py around tests automatically
    try:
        command = sys.argv[1]
    except IndexError:
        command = "help"

    running_tests = command == "test"
    if running_tests:
        from coverage import Coverage

        cov = Coverage()
        cov.erase()
        cov.start()

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

    if running_tests:
        cov.stop()
        cov = Coverage()
        cov.save()
        covered = cov.report()
        if covered < 100:
            raise SystemExit(1)


if __name__ == "__main__":
    main()

Notes:

  1. The two customizations are the blocks before and after the execute_from_command_line block, guarded with if running_tests:.

  2. You need to add manage.py to omit in the configuration file, since it runs before coverage starts. For example:

    [coverage:run]
    omit =
       */node_modules/*
       manage.py
    

    (It's fine, and good, to put them on multiple lines. Ignore the furious red from my blog's syntax highlighter.)

  3. The .report() method doesn’t exit for us like the commandline method does. Instead we do our own test on the returned covered amount. This means we can remove fail_under from the [coverage:report] section in our configuration file.

Run the tests again and you'll see it in use:

$ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.............................................................................
----------------------------------------------------------------------
Ran 77 tests in 0.741s

OK
Destroying test database for alias 'default'...
Name                     Stmts   Miss Branch BrPart  Cover   Missing
--------------------------------------------------------------------
settings/dev.py              2      2      0      0     0%   4-6
testapp/models.py            1      1      0      0     0%   5
testapp/test_api.py        400      2      0      0    99%   366, 375
testapp/test_models.py       6      4      0      0    33%   5-8
urls.py                      9      0      2      1    91%   16->exit
--------------------------------------------------------------------
TOTAL                      811      9      4      1    99%

15 files skipped due to complete coverage.

Yay!

(Okay, it’s still 99%. Spoiler: I’m actually not going to fix that in this post because I’m lazy.)

With pytest

It’s less work to set up Coverage testing in the magical land of pytest. Simply install the pytest-cov plugin and follow its configuration guide.

The plugin will ignore the [coverage:report] section and source setting in the configuration, in favour of its own pytest arguments. We can set these in our pytest configuration’s addopts setting. For example in our pytest.ini we might have:

[pytest]
DJANGO_SETTINGS_MODULE = settings.test
addopts = --cov=.
          --cov-report term-missing:skip-covered
          --cov-fail-under 100

(Ignore the angry red from my blog’s syntax highlighter.)

Run pytest again and you’ll see the coverage report at the end of the pytest report:

$ pytest
============================= test session starts ==============================
platform darwin -- Python 3.7.3, pytest-4.4.1, py-1.8.0, pluggy-0.9.0
Django settings: settings.test (from ini file)
rootdir: /.../tests, inifile: setup.cfg
plugins: django-3.4.8, cov-2.6.1
collected 78 items

testapp/test_api.py .............................                        [ 37%]
testapp/test_builtins.py ..................                              [ 60%]
testapp/test_checks.py ..                                                [ 62%]
testapp/test_commands.py ..........                                      [ 75%]
testapp/test_manager.py .....                                            [ 82%]
testapp/test_models.py .                                                 [ 83%]
testapp/test_template_tags.py ..........                                 [ 96%]
testapp/test_testutils.py ...                                            [100%]

=============================== warnings summary ===============================
...

-- Docs: https://docs.pytest.org/en/latest/warnings.html

---------- coverage: platform darwin, python 3.7.3-final-0 -----------
Name                                  Stmts   Miss Branch BrPart  Cover   Missing
---------------------------------------------------------------------------------
testapp/management/commands/test.py       4      4      0      0     0%   1-7
testapp/test_api.py                     400      2      0      0    99%   366, 375
testapp/test_models.py                    6      2      0      0    67%   7-8
---------------------------------------------------------------------------------
TOTAL                                   773      8      2      0    99%

11 files skipped due to complete coverage.

FAIL Required test coverage of 100% not reached. Total coverage: 98.97%
=================== 78 passed, 383 warnings in 1.19 seconds ====================

Hooray!

(Yup, still 99%.)

Browsing the Coverage HTML Report

The terminal report is great but it can be hard to join this data back with your code. Looking at uncovered lines requires:

  1. Remembering the file name and line numbers from the terminal report
  2. Opening the file in your text editor
  3. Navigating to those lines
  4. Repeat for each set of lines in each file

This gets tiring quickly!

Coverage.py has a very useful feature to automate this merging, the HTML report.

After running coverage run, the coverage data is stored in the .coverage file. Run this command to generate an HTML report from this file:

$ coverage html

This creates a folder called htmlcov. Open up htmlcov/index.html and you’ll see something like this:

Coverage.py HTML report index

Click on an individual file to see line by line coverage information:

Coverage.py HTML report file

The highlighted red lines are not covered and need work.

Django itself uses this on its Jenkins test server. See the “HTML Coverage Report” on the djangoci.com project django-coverage.

Django coverage

With PyCharm

Coverage.py is built-in to this editor, in the “Run <name> with coverage” feature.

This is great for individual development but less so for a team as other developers may not use PyCharm. Also it won’t be automatically run in your tests or your Continuous Integration pipeline.

See more in this Jetbrains feature spotlight blog post.

Is 100% (Branch) Coverage Too Much?

Some advocate for 100% branch coverage on every project. Others are skeptical, and even believe it to be a waste of time.

For examples of this debate, see this Stack Overflow question and this one.

Like most things, it depends.

First, it depends on your project’s maturity. If you’re writing an MVP and moving fast with few tests, coverage will definitely slow you down. But if your project is supporting anything of value, it’s an investment for quality.

Second, it depends on your tests. If your tests are low quality, Coverage won’t magically improve them. That said, it can be a tool to help you work towards smaller, better targeted tests.

100% coverage certainly does not mean your tests cover all scenarios. Indeed, it’s impossible to cover all scenarios, due to the combinatorial explosion from multiplying branches. (See all-pairs testing for one way of tackling this explosion.)

Third, it depends on your code. Certain types of code are harder to test, for example branches dealing with concurrent conditions.

IF YOU’RE HAVING CONCURRENCY PROBLEMS I FEEL BAD FOR YOU SON

99 AIN’T GOT I BUT PROBLEMS CONCURRENCY ONE

—[@quinnypig on Twitter](https://twitter.com/QuinnyPig/status/1110567694837800961)

Some tools, such as unittest.mock, help us reach those hard branches. However, it might be a lot of work to cover them all, taking time away from other means of verification.

Fourth, it depends on your other tooling. If you have good code review, quality tests, fast deploys, and detailed monitoring, you already have many defences against bugs. Perhaps 100% coverage won’t add much, but normally these areas are all a bit lacking or not possible. For example, if you’re working a solo project, you don’t have code review, so 100% coverage can be a great boon.

To conclude, I think that coverage is a great addition to any project, but it shouldn’t be the only priority. A pragmatic balance is to set up Coverage for 100% branch coverage, but to be unafraid of adding # pragma: no cover. These comments may be ugly, but at least they mark untested sections intentionally. If no cover code crashes in production, you should be less surprised.

Also, review these comments periodically with a simple search. You might learn more and change your mind about how easy it is to test those sections.

Fin

Go forth and cover your tests!

If you used this post to improve your test suite, I’d love to hear your story. Tell me via Twitter or email - contact details are on the front page.

—Adam

Thanks to Aidas Bendoraitis for reviewing this post.

Ship it

Newly updated: my book Boost Your Django DX now covers Django 5.0 and Python 3.12.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: