How to Run Coverage Report and Generate HTML in Python

Use the coverage module to measure test coverage, save the report, and generate an HTML report in Python.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 12 views 0 copies

Requires third-party packages — install first
pip install coverage

Python code

22 lines
Python 3.9+
import coverage
import unittest


def add(a, b):
    return a + b


class TestAdd(unittest.TestCase):
    def test_add_positive(self):
        self.assertEqual(add(2, 3), 5)


if __name__ == "__main__":
    cov = coverage.Coverage(source=["__main__"])
    cov.start()
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestAdd)
    unittest.TextTestRunner().run(suite)
    cov.stop()
    cov.save()
    cov.html_report(directory="htmlcov")
    print(cov.report())

Output

stdout
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Name          Stmts   Miss  Cover
---------------------------------
__main__          2      0   100%

How it works

This script uses the coverage module to track executed lines while running tests with unittest. cov.start() begins recording, and cov.stop() ends it before saving results with cov.save(). cov.html_report(directory="htmlcov") generates an HTML report in the specified folder. The cov.report() call prints a concise terminal summary showing statement counts, missed lines, and coverage percentage. Keeping source scoped to __main__ focuses coverage on your code rather than library internals.

Common mistakes

  • Forgetting to call cov.save() before generating the report, losing data
  • Not scoping source to your code with source=["__main__"], including stdlib modules
  • Calling cov.stop() inside a test method instead of after all tests run

Variations

  1. Use coverage run -m unittest from the command line instead of embedding in code
  2. Generate a Cobertura XML with cov.xml_report() for CI integration

Real-world use cases

  • CI pipelines that fail when coverage drops below a threshold after running unit tests.
  • Local development to identify untested code paths before committing changes.
  • Privacy-focused companies that keep coverage reports inside their intranet via generated HTML.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Modern tooling

Related tutorials and quizzes for this topic.