Fundamentals 6 min read

Master Python Code Coverage with Coverage: Step-by-Step Guide and Examples

This article explains how to measure Python code coverage using the Coverage tool, covering installation, command‑line and API usage, and provides a complete example with a simple function, unit tests, and generated HTML reports to visualize covered and missed statements.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Code Coverage with Coverage: Step-by-Step Guide and Examples

1. Code Coverage

Unit‑test code coverage measures the proportion of source code executed by the test suite, calculated as the number of executed statements divided by the total number of statements.

2. Coverage Tool

Coverage is a Python package that reports code‑coverage statistics, supports branch coverage, generates HTML reports, and can be integrated into CI pipelines such as Jenkins.

Install Coverage with pip:

# Install Coverage dependency
pip3 install coverage

Coverage provides two ways to collect data:

Coverage command‑line interface

Coverage Python API

3. Practical Example

First, create a simple function to be tested (save as main.py):

# Tested code
# main.py
def get_level(cource):
    """Return a grade based on the score.
    :param cource: score
    :return: grade string
    """
    if cource >= 90:
        return "优秀"
    elif cource >= 80:
        return "良好"
    elif cource >= 60:
        return "合格"
    elif cource >= 40:
        return "不合格"
    else:
        return "差"

Then write two unit‑test cases using the built‑in unittest framework (save as test_get_level.py):

# Unit tests
# test_get_level.py
import unittest
from main import *

class GetLevel(unittest.TestCase):
    def test_get_level1(self):
        self.assertEquals(get_level(90), "优秀")

    def test_get_level2(self):
        self.assertEquals(get_level(80), "良好")

if __name__ == '__main__':
    unittest.main(verbosity=2)

Run the tests; both cases should pass.

4. Generate Coverage Report via CLI

Collect coverage data and produce an HTML report:

# Collect coverage data
coverage run test_get_level.py
# Generate HTML report in the folder "coverage_result"
coverage html -d coverage_result

Open coverage_result/index.html in a browser. The report shows:

statements : total executable lines (excluding blanks and comments)

missing : lines not executed

coverage : percentage of covered statements

Coverage HTML report screenshot
Coverage HTML report screenshot

Clicking a source file (e.g., test_get_level.py) highlights covered and uncovered lines.

File view with coverage highlights
File view with coverage highlights

5. Generate Coverage Report via API

Using the Coverage API allows programmatic control:

# exec_api.py
import coverage
import unittest

# Start coverage collection
cov = coverage.coverage()
cov.start()

# Discover and run tests
suite = unittest.defaultTestLoader.discover("./", "test_get_level.py")
unittest.TextTestRunner().run(suite)

# Stop and save results
cov.stop()
cov.save()

# Print report to console
cov.report()
# Generate HTML report in "result_html" directory
cov.html_report(directory='result_html')

6. Conclusion

The example demonstrates how to obtain code‑coverage statistics for a simple Python function using unittest and the Coverage tool. In real projects, this technique is essential for Python, Django, or Flask web applications to ensure test quality and improve product reliability.

Illustrative image
Illustrative image
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

code coveragetestingunittestcoverage tool
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.