Unit Testing in Python – Part 2 – Coverage

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.

coverage html

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:

2018-03-05 20_17_46-Coverage report

When I click on apiwrapper.py I can see the lines I missed:

2018-03-05 20_17_09-Coverage for apiwrapper.py_ 90%

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s