docs
  • Overview
  • 🐍 PYTHON
    • Type Hints
    • PEP8 Style Guide for Python Code
    • 🏡Pipenv
    • Pathlib
  • 🕸Django
    • 🗄models
      • 🎯Best Practices
      • 🚦Django Signals
    • ⚙️ settings
    • DRF
      • Serializer
      • Authentication
      • Permissions
      • Viewsets
    • Testing
      • Faker and Factory Boy
    • 🧪Test Coverage
    • 💦Python-Decouple
    • Django Tips:
    • 💾Django ORM Queryset
    • Custom Exceptions
    • Celery
    • Resources
  • Deploy
    • 🚀Django Deployment
    • 🔒Setup SSL Certificate
  • 💾Database
    • MongoDB
  • 🛠️DevOps
    • 🖥Scripting
      • A First Script
      • Loops
      • Test
      • Variables
      • External programs
      • Functions
    • Command Line Shortcuts
    • Basic Linux Commands
    • 🎛Microservices
    • 🐳Docker
      • Docker Commands
      • Docker Compose
      • Django project
    • Kubernates
  • 📝Software IDE
    • EditorConfig
    • Linters
    • VsCode
Powered by GitBook
On this page
  • Introduction
  • Configuring Coverage.py
  • Install coverage:
  • Checking the installation:

Was this helpful?

  1. 🕸Django

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
pipenv install coverage

Checking the installation:

coverage --version
python -m 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
htmlcov/
.coverage
.coverage.*
coverage.xml
*.cover

There’s an integrated way of achieving this inside Django. We can patchmanage.pyto call Coverage.py’s API to measure when we run thetestcommand.

manage.py
#!/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
PreviousFaker and Factory BoyNext💦Python-Decouple

Last updated 4 years ago

Was this helpful?

🧪