This is the second part in a larger series about unit testing in Python. If you missed the first one, you can find it here. This time I’ll be exploring how to see the code coverage of my test.
It’s all well and good to have tests written and passing, but it’d be nice to see how much of my code is being executed by those tests. To achieve this I’m going to use the coverage package. I’ll continue to use the same python example from Part 1 (GitHub).
I will be using the coverage cli (installed via `pip install coverage`). To generate the coverage reports I run two commands.
coverage run --branch apiwrapper_test.py
This first command creates a .coverage file which isn’t very human-readable. I like to pass the `–branch` parameter so that I can see which parts of my conditionals are being executed. If you have multiple test files you will need to run the command multiple times with the `-a` option to append to the existing results.
This second command converts the .coverage file into an nice html page that I can use to visualize the quality of my tests. I can now point my browser at the index.html in the `htmlcov` folder and see a nice summary of all packages tested:
When I click on apiwrapper.py I can see the lines I missed:
Here you can see that I missed a case where the request was successful and returned a 201. I can simply add that test, rerun my two commands and refresh this page to see that I’ve addressed the issue.
I hope you enjoyed this look at Python’s code coverage capabilities. Join me next time as I explore how Visual Studio Code makes very easy to run Python unit tests.