- Install the Coverage tool
easy_install coverage
or
pip install coverage
Copy the code
- Here’s an example of how to use the Coverage tool
Project directory
- Generate a coverage report for the specified test case module
cd tests
coverage run test_ascheduler.py
Copy the code
Paste_Image.png
A new. Coverage file is added, which records coverage data for the module corresponding to test_ascheduler.py unit test script.
The default coverage data is recorded in the. Coverage file. You can also specify the name of the file to save before running, and change the name of the file to store the coverage report by setting the environment variable COVERAGE_FILE.
- You can use the following command to view test case coverage:
coverage report
Copy the code
- Generate multiple test case module reports
There are multiple test case modules starting with test_ under the Tests directory. If you run coverage run separately, the.coverage will be overwritten by the later results. You can save multiple test case coverage reports by executing the following command:
coverage run -p test_ascheduler.py
coverage run -p test_calendar.py
coverage run -p test_cmd.py
coverage run -p test_cmd2.py
coverage run -p test_rsync.py
Copy the code
- Merge multiple test case coverage reports
coverage combine
Copy the code
Merged into a. Coverage file:
Paste_Image.png
- View lines of code not covered by the test case
coverage report -m
Copy the code
The Missing column represents lines of code not covered by the test case
- Test case modules are not shown in the test coverage report
In the above test case report, there are many test case modules with their own coverage. In fact, we only want to see the test coverage of the functional modules. We can execute the following command:
coverage report --omit="test_*.py"
Copy the code
Or specify filtering at execution time, ignoring all Python files that match the test_*.py schema
coverage run --omit="test_*.py" test_ascheduler.py
coverage report
Copy the code
Alternatively, filter rules can be set through the configuration file. Coveragerc:
touch .coveragerc
Copy the code
vim .coveragerc
[run]
omit =
test_*.py
*/utils/__init__.py
*/utils/errors.py
Copy the code
General test case coverage does not require statistics on the test case modules themselves, filtering out test_*. Py modules, and __init__.py and errors.py files generally do not require test case coverage.
coverage run test_ascheduler.py
coverage report
Copy the code
Paste_Image.png
- If you want to know more detailed coverage of use, access to the official document: coverage. Readthedocs. IO/en/latest/I…