Testing coverage
Test Coverage
Use coverage run to run your test suite and gather data. However you normally run your test suite, you can run your test runner under coverage. If your test runner command starts with “python”, just replace the initial “python” with “coverage run”.
Pytest
If you usually use:
then you can run your tests under coverage with:Unittest
Change “python” to “coverage run”, so this:
To limit coverage measurement to code in the current directory, and also find files that weren’t executed at all, add the --source=. argument to your coverage command line.
Report
Use coverage report to report on the results:
coverage report -m
Name Stmts Miss Cover Missing
-------------------------------------------------------
my_program.py 20 4 80% 33-35, 39
my_other_module.py 56 6 89% 17-23
-------------------------------------------------------
TOTAL 76 10 87%
For a nicer presentation, use coverage html to get annotated HTML listings detailing missed lines:
Coverage measurement is typically used to measure the effectiveness of tests. It can show which parts of your code are being processed by tests and which are not.
You can use the сoverage.py tool for measuring code coverage. It monitors your program, recording which code parts have been executed, then analyzes the code that could have been executed but was not.
To run coverage measurement:
use the coverage run command to run your test and collect the data. However, you normally run your test, you can run your test runner under coverage. If normally your test execution command starts with the python, you replace the initial python with the coverage run — coverage run -m pytest, then use the coverage report to report on the results:
$ coverage report
Name Stmts Miss Cover Missing
-----------------------------------------------------------
main.py 7 3 57% 8-10
test_main.py 6 0 100%
-----------------------------------------------------------
TOTAL 13 3 77%
for PyCharm Pro, click the Run with Coverage button on the main toolbar. This will launch the selected run/debug configuration:
![[coverage_button.png.webp]]