When you are developing a large project, it is possible to accidentally forget some parts of the code that need to be tested. Coverage.py is a python tool to help you with this.
Installation
Use pip or easy_install as you like
pip install coverage
Starting and uninstalling
To run in a Django project, use the command:
overage run --source='.' manage.py test the-app-you-want-to-test
This command will fill in ".coverage" which is located in COVERAGE_FILE and then you can see the results or report. If you need to delete the received data, use the command:
coverage erase
For one file
If you only want to test Python code, then you need to do:
coverage run your_program.py arg1 arg2 arg3
There are several additional options that you can look at
link
.
You can learn about templates
in the plugins section
.
View result
If you want to display results on the command line:
coverage report
For clearer and more convenient reports:
coverage html
To know exactly what part of your code is covered by tests, use the following command:
coverage annotate -d directory-where-to-put-annotated-files
The program will generate the same source code file with additional syntax:
- A line with ">" means that it has been executed.
- A line starting with "!" means that it was not executed.
- A line starting with "-" means that the line has been excluded from the coverage statistics.
Good level of coverage
Good coverage is usually 90%. However, if the result is 100%, this may be a bad signal, since it may be a matter of coverage, and not the quality of the tests.
A few tips:
- Be careful with the quality of your tests.
- Don't slow down your developer speeds for the sake of coverage.
- Use coverage to find unverified code and decide if it deserves coverage.
Exclude code
Sometimes we need to exclude some code that doesn't need coverage. There are several options:
- Specifying files to exclude and skip in .coveragerc.
- Writing in one line of the comment block.
# pragma: no cover
For example, if you want to exclude generated code from coverage because it must be supported by the generation tool:
def generated_code(): # pragma: no cover do_something()
More info at Coverage.py documentation.