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.
pip install coverage
Python code
22 linesimport 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
.
----------------------------------------------------------------------
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
- Use coverage run -m unittest from the command line instead of embedding in code
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.