First of all, you must download and install coverage.py with pip.
The steps are:
1) First have written tests for the Python program you want to test
2) Run code coverage on the unit tests you’ve written.
3) Export the report to html for better readability and more details.
and in code:
coverage run test_something.py
coverage report -m
The code coverage can now be found in a directory htmlconv/ which is in the same directory where you run the coverage commands. Open htmlconv/index.html and see the detailed html version of the code coverage.
Note: the -m argument is to show a tab for the missing code coverage
And how it looks in action:
The nose way
1) You must have nose installed. (pip install nose)
2) Again, you must have written unit tests.
3) Run the code coverage on the unit tests. Done! All in one command 🙂
and in code:
nosetests --with-coverage --cover-html test_something.py
The code coverage can now be found in a directory cover/ which is in the same directory where you run the coverage commands. Open cover/index.html and see the detailed html version of the code coverage.
Note: Nose code coverage doesn’t include the unit test file in the code coverage. To include it add
--cover-tests to the command you execute.