How to Improve Code Quality in Python Projects with Unit Test Coverage
Ensuring code quality is a crucial aspect of software development, and one effective way to achieve it is by adding unit test coverage to your Python projects. Code coverage helps you identify areas in your codebase that are untested, reducing the likelihood of bugs and improving overall software reliability. In this guide, we’ll explore how to add unit test coverage to your Python projects using the pytest-cov library.
Libraries
When it comes to collecting code coverage in Python, you have a couple of options. The raw library for collecting code coverage is coverage.py. However, if you’re already using pytest, a popular testing framework for Python, you can leverage the pytest-cov plugin, which integrates seamlessly with pytest and simplifies the process.
Installation of pytest-cov
Before we dive into collecting code coverage, make sure you have pytest
installed. You can install pytest-cov
and pytest
using pip
as follows:
Install with pip
pip install pytest-cov
Install with requirements.txt If you prefer to manage your project’s dependencies with a requirements file, add the following dev requirement:
pytest-cov == 4.0.0
Run unit tests
Now that you have pytest-cov
installed, running your unit tests with code coverage is a breeze. Use the following command to a generate code coverage report:
python3 -m pytest -v --cov=my_code_under_test --cov-report html
And will produce stdout summary:
-------------------- coverage: ... ---------------------
Name Stmts Miss Cover
----------------------------------------
my_code_under_test/__init__ 2 0 100%
my_code_under_test/myproj 257 13 94%
my_code_under_test/feature4286 94 7 92%
----------------------------------------
TOTAL 353 20 94%
This summary provides an overview of code coverage for different parts of your project, helping you identify areas that may need more testing.
Ignore test files
In some cases, your test code may show up in the coverage report, which is not what you want. To exclude test files from the coverage report, follow these steps:
- Create a file named
.coveragerc
in the root of your project directory. - In the
.coveragerc
file, add the following statement to omit your test code:[run] omit = src/test/ src/perf_test/
By specifying the paths to omit, you ensure that only your production code is considered for coverage analysis.
Conclusion
In conclusion, adding unit test coverage to your Python projects using pytest-cov is a valuable practice to enhance code quality and identify untested code. By following the steps outlined in this guide, you can systematically improve your project’s reliability and maintainability.