Test Coverage
Getting a Django Application to 100% Test Coverage
Introduction
Code coverage is a simple tool for checking which lines of our application code are run by our 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. we can integrate it with a Django project.
Configuring Coverage.py
Install coverage:
pip install coverage
Checking the installation:
coverage --version
The default configuration file name is .coveragerc
[run]
branch = True
disable_warnings = no-data-collected
omit =
# omit anything in a .local directory anywhere
*/.local/*
*/node_modules/*
# omit everything in /migrations
/migrations/*
# omit this single file
manage.py
[report]
exclude_lines =
pragma: no cover
def __repr__
if self.debug:
if settings.DEBUG
raise AssertionError
raise NotImplementedError
if 0:
if __name__ == .__main__.:
fail_under = 100
show_missing = True
skip_covered = True
ignore_errors = True
[html]
directory = coverage_html_report
There’s an integrated way of achieving this inside Django. We can patchmanage.py
to call Coverage.py’s API to measure when we run thetest
command.
#!/usr/bin/env python
"""Django's 3.0 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.save()
covered = cov.report()
if covered < 100:
sys.exit(1)
if __name__ == '__main__':
main()
Run the test:
python manage.py test
Last updated
Was this helpful?