Coverage.py is a tool for measuring code coverage of Python programs. It monitors the program, noting which parts of the code were executed, and then analyzes the source to identify code that could have been executed but was not.
Coverage measurement is often used to measure the effectiveness of testing. It can show which parts of the code the tests are executing, and which parts are not.
install coverage.py
$ python3 -m pip install coverage
run test
Used to run the test suite and collect data.
coverage run
If the test runner command starts with "python", simply replace the initials "python" with "coverage run".
python something.py
becomecoverage run something.py
python -m amodule
becomecoverage run -m amodule
if used
If you normally use:
$ pytest arg1 arg2 arg3
Tests can be run under coverage using:
$ coverage run -m pytest arg1 arg2 arg3
specified range
To restrict coverage measurement to code in the current directory, and to find files that are not executed at all, add the parameter to your coverage command line.
--source=.
coverage run --source=dir1,dir2 my_program.py arg1 arg2 coverage run --source=dir1,dir2 -m packagename.modulename arg1 arg2
branch coverage
coverage collects line coverage by default. If you want to collect branch coverage, you can use the parameter --branch
You can see that the views file has 12 branches, with a coverage rate of 95%.
output test report
coverage report
This flag also shows the line numbers of missing statements:-m
$ coverage report -m
coverage report -m filename filename
Only specified files can be collected.
Output html test report
coverage html