How to use Coverage.py to Measure Code Coverage in Python Projects

On This Page What is Code Coverage?What is Coverage.py?March 09, 2026 · 8 min read · Testing Guide

How to use Coverage.py to Measure Code Coverage in Python Projects

Building rich software goes beyond writing code; it requires creating tested, reliable code that functions as expected. As the codebase grow, dog what works and what could go incorrect becomes dispute. While testing assist catch bug, measuring tryout effectiveness can be tricky.

This is where code coverage tools likeCoverage.pyare utile. They allow developers to see which parts of the code are examine and highlight areas for advance. With Coverage.py, you can mensurate test coverage and enhance the quality of your Python projects.

This article will guide you in habituateCoverage.pyto measure code reportage in Python projects.

What is Code Coverage?

is a metric that evaluates the extent to which your source code executes during quiz. It helps identify untested areas of a program and control the codebase is thoroughly validated.

It covers statements, branches, and functions. This help and ensures entire validation. High reportage does not undertake a bug-free covering, but it strengthens.

Also Read:

What is Coverage.py?

Coverage.pyis a creature that mensurate code coverage in Python programs. It tracks which parts of the codification are executed during testing, helping developers identify unseasoned section.

By integrating with testing frameworks like and pytest, Coverage.py provides reports in various format, including schoolbook and HTML, to visualize coverage data.

This insight aid in improving test effectiveness and overall code quality.

Also Read:

Key Features of Coverage.py

The main feature of Coverage.py are:

  • Execution Monitoring: This faculty uses tracing hooks in Python to track what portion of the code are be executed during the exam runs.
  • Analysis: It analyzes the code to determine which lines might receive been executed and helps name subdivision not covered by test.
  • Reporting: This module produces reports in respective formats, such as textbook and HTML, to visualise the data on codification reportage.
  • Integration: It supports essay framework like unit test and pytest.

Also Read:

Why is Code Coverage Measuring important in Python projects?

Code coverage in Python projects should be mensurate for various understanding:

  • : Higher codification reportage signifies proper testing with minimal chances of undetected bug reach product.
  • Risk mitigation: If the developer do not test codes, it allows focusing testing on specific critical region.
  • Code Maintenance: This aids in codification maintenance by providing insurance, allowing regressions to be ruled out while any changes are incorporated.
  • Documentation: The reports generated by code reportage tools could be used to document the areas of testing where the codification miss coverage and where more attention was necessary.

Also Read:

Installing Coverage.py

To install Coverage.py, follow these steps:

Prerequisites

Ensure Python is installed on your system. You can verify this by running the Python & # 8211; version or python3 & # 8211; edition in your terminal.
Confirm that pip, Python & # 8217; s software installer, is up to appointment.

Update it using:

python -m pip install -- upgrade pip

Installation:

Install Coverage.py using pip:

python -m pip install reporting

For enhanced performance, Coverage.py include a C extension. To ensure it & # 8217; s installed:

On Linux, you may need to install development instrument:

sudo apt-get install python3-dev gcc

After installing, verify the C extension is combat-ready:

coverage -- edition

Verification:

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

Check the installed version to confirm successful installment:

reportage –version

You can also invoke Coverage.py as a faculty:

python -m coverage -- variation

Both commands should display the version number and confirm the installation.

Also Read:

How to use Coverage.py to Measure Code Coverage

UnderstandingCoverage.pycan be done with a simple example of Python code that performs canonical addition and deduction.

Running Tests with Coverage.py

To begin, ensure you have the necessary dependencies. Open your terminal and run the following command to install reportage and pytest:

pip install coverage pytest

You & # 8217; ll want two Python file:

main.py(the code to test) andtest_main.py(the test file).

main.py

This file contains the functions add () and subtract (). These are simple part that do add-on and subtraction of two numbers.

# main.py def add (a, b): return a + b def subtract (a, b): return a - b

test_main.py

This file contains the test functions that use pytest to test the functionality of the functions in main.py.

# test_main.py from main import add, subtract def test_add (): assert add (2, 3) == 5 def test_subtract (): assert subtract (5, 3) == 2

To run the tests and measure code coverage, use coverage.py. In the terminal, navigate to the project directory and run:

reporting run -m pytest

This will run the tests from test_main.py while measuring which lines of code were extend by the tests.

Learn More:

Generate the Coverage Report

You can generate a code coverage report after escape the tests. First, run this command to generate a simple report in the terminal:

reporting report

This will demonstrate a coverage summary show which parts of your code be test. For example, the output might look like this:

This indicates that the tests continue all the codification in both main.py and test_main.py.

For a more detailed, optic reporting account, you can give an HTML report using the following command:

reporting html

This will create an htmlcov/ directory with an index.html file inside it.

Open the index.html file in your browser to see a visual representation of your code coverage, highlighting covered dark-green and uncovered red lines.

Must Read:

Integrating Coverage.py with CI/CD Pipelines

Integrating Coverage.py into your line automatically mensurate test coverage with every commit, cater continuous feedback on the effectiveness of your tests.

This integration is essential for maintaining high and ascertain that new changes don ’ t reduce overall tryout reporting.

To integrate Coverage.py into your pipeline, follow these general steps:

  • Choose a CI/CD Platform: Popular CI/CD services like GitHub Actions, GitLab CI,, Travis CI, and proffer easy integration with testing tools like pytest and Coverage.py. Choose a program establish on your labor ’ s needs.
  • Create a CI/CD Configuration File: Each CI/CD platform requires a configuration file that defines the stairs to run tests and gather code coverage. For case, in GitHub Actions, you would create a .github/workflows directory and a YAML file specifying the steps to install addiction, run tests, and generate the coverage report.
  • Install Coverage.py: You need to ensure that Coverage.py is installed in your CI pipeline. You can do this by including it in the dependencies subdivision of your configuration file or by running pip install reportage during the grapevine setup.
  • Run Tests with Coverage: To cumulate coverage data, the pipeline should run your test suite (typically pytest) with Coverage.py. The command reportage run -m pytest can run tests with coverage measurement.
  • Generate Coverage Reports: Coverage.py can generate coverage study once the tests are accomplished. These story can be yield to the terminal (using reporting report), or you can generate an HTML report using coverage html. The HTML study is useful for visually reviewing the areas of the code that are well-tested and those that postulate more tests.
  • Store and Display Coverage Data: After running the exam and generating the coverage report, store the report as an artefact. Most CI/CD platforms, like GitHub Actions, allow you to upload the coverage report as an artefact, making it available for download or review.
  • Display Code Coverage Badge: Many CI/CD services, like Codecov and Coveralls, allow displaying a badge that shows your current code coverage percentage. You can add this badge to your repository & # 8217; s README file to provide an at-a-glance view of your test reportage.

Also Read:

Best Practices for Code Coverage in Python

The following tips can assist you improve code coverage in Python:

  • Strive for high (e.g., 80-90 %), but remember that 100 % coverage does not guarantee the calibre of your tests. Focus on meaningful trial for critical code paths.
  • Ensure your tests continue edge cases, error handling, and exceptional weather to control that your code behaves as expected under respective scenarios.
  • Regularly generate and review coverage reports to identify untried areas of your codebase and improve tryout coverage where necessary.
  • Skip tests for simple or trivial code (e.g., setters and getters, boilerplate code) unless it is required for logic or integrating.
  • Prioritise tests that cover your application & # 8217; s core business logic, as these are more likely to affect functionality and user experience.
  • Test the integration points with external libraries to ensure they work aright in your environment.
  • If parts of the codebase are untested, consider refactoring them to improve testability and add examination for the newly refactored code.
  • Run tests across various environments, constellation, or operating systems to see the application act in all scenarios.
  • Integrate code coverage tool with your CI/CD pipelines to track coverage on every commit and get issues early.
  • While code reportage is a helpful metric, don & # 8217; t trust on it alone to assess the quality of your examination. Focus on test quality and relevance rather than just achieving high reportage percentage.

Also Read:

Test on Existent Devices with BrowserStack

BrowserStackis a cloud-based examination platform that allows you to run and on real devices and browsers. It allow you examine your Python covering on without place up your gimmick farm.

Here & # 8217; s how you can use BrowserStack for testing your Python projects:

  • Access : BrowserStack render access to a wide range of real devices, including smartphones, pad, and desktop devices. This is crucial for testing and see your covering works seamlessly across different devices and.
  • Run Automated Tests: You can integrate BrowserStack with your tools like pytest or Selenium. This integration allow you to run your machine-driven trial on existent device, insure your application behaves correctly in different surroundings.
  • Live and Interactive Testing: In addition to automated testing, BrowserStack volunteer live testing capableness where you can manually quiz your Python application on existent devices. This characteristic helps identify UI/UX topic, performance constriction, and device-specific bugs.
  • : You can test your Python application across various browser like Chrome, Firefox, Safari, and Edge to ensure compatibility and consistent performance.
  • Integrate with CI/CD: BrowserStack back consolidation with CI/CD tools to run tests on existent devices as part of your build line. This consolidation control that your application is thoroughly tested with each deployment.
  • Generate Test Reports: BrowserStack allows you to render detailed test study for automated and manual tests. These study include logs, screenshots, and video recordings, making analyse and debug issues easier.

Talk to an Expert

Conclusion

Measuring codification coverage in Python projects with Coverage.py is essential for maintaining high-quality code. By tracking which constituent of your code are tested, Coverage.py helps identify spread and meliorate tryout coverage.

Integrating it into CI/CD pipelines secure uninterrupted testing with each commit. Good practices include aiming for eminent but realistic coverage, centre on critical codification paths, and habituate reportage report to guide exam improvements.

Tools like BrowserStack further enhance testing by enable real-device testing, ensuring your Python application performs well across respective environment.

Tags
52,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free