Skip to content

Instantly share code, notes, and snippets.

@uuklanger
Last active November 12, 2019 21:11
Show Gist options
  • Save uuklanger/b4073f40f92cdafae52e69adbe849a8d to your computer and use it in GitHub Desktop.
Save uuklanger/b4073f40f92cdafae52e69adbe849a8d to your computer and use it in GitHub Desktop.
HOWTO - Run Coverage for All Code with Unittests

Overview

Within most IDEs you can run "coverage" on your code which tells you how much of your unittests cover the code you have written. If you want to run this kind of coverage from the command line (terminal) for a Python project there are just a few simple steps to follow.

This can be tried directly by cloning this project and running the following.

Assumptions

  • Python 3.7+
  • macOS, linux, or even Windows 10 (WSL preferred).
  • The project you are working with is structured similar to the example referenced.

Install

Coverage is available via pip and can be installed via the following...

% pip3 install --user coverage
% python3 -m coverage --version

This can also be installed via venv if you want it to exist for only a one project.

Execution

The following shows the different ways to run your tests with or without coverage.

Running all Unittests

From the project root directory, running the following command will launch all the unittests within the project.

% python3 -m unittest discover

Running Main Application with Coverage

The following will run coveage on the main application of the project. Then you can run a report based on the coverage results.

% python3 -m coverage run word_search.py data/sample/star_trek_word_search.csv
% python3 -m coverage report

Running Unittests with Coverage

The following will run coveage on all code based on unittests of the project. Then you can run a report based on the coverage results.

% python3 -m coverage run -m unittest discover
% python3 -m coverage report

Coverage

There a ton of different things you can do to control the output so check the coveage docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment