An Intro to coverage.py
Mike Driscoll explains the code coverage tool coverage.py, how to use it, and provides some simple demos.
Join the DZone community and get the full member experience.Join For Free
coverage.py is a 3rd party tool for python that is used for measuring your code coverage. it was originally created by ned batchelder. the term “coverage” in programming circles is typically used to describe the effectiveness of your tests and how much of your code is actually covered by tests. you can use coverage.py with python 2.6 up to the current version of python 3 as well as with pypy.
pip install coverage
now that we have coverage.py installed, we need some code to use it with. let’s create a module that we’ll call mymath.py here’s the code:
def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def divide(numerator, denominator): return float(numerator) / denominator
now we need a test. let’s create one that tests the add function. let’s give our test the following name: test_mymath.py . go ahead and save it in the same location as you did for the previous module. then add the following code to our test:
# test_mymath.py import mymath import unittest class testadd(unittest.testcase): """ test the add function from the mymath library """ def test_add_integers(self): """ test that the addition of two integers returns the correct total """ result = mymath.add(1, 2) self.assertequal(result, 3) def test_add_floats(self): """ test that the addition of two floats returns the correct result """ result = mymath.add(10.5, 2) self.assertequal(result, 12.5) def test_add_strings(self): """ test the addition of two strings returns the two string as one concatenated string """ result = mymath.add('abc', 'def') self.assertequal(result, 'abcdef') if __name__ == '__main__': unittest.main()
now that we have all the pieces, we can run coverage.py using the test. open up a terminal and navigate to the folder that contains the mymath module and the test code we wrote. now we can call coverage.py like this:
coverage run test_mymath.py
note that we need to call run to get coverage.py to run the module. if your module accepts arguments, you can pass those in as you normally would. when you do this, you will see the test’s output as if you ran it yourself. you will also find a new file in the directory that is called .coverage (note the period at the beginning). to get information out of this file, you will need to run the following command:
coverage report -m
executing this command will result in the following output:
name stmts miss cover missing ---------------------------------------------- mymath.py 9 3 67% 9, 13, 17 test_mymath.py 14 0 100% ---------------------------------------------- total
the -m flag tells coverage.py that you want it to include the missing column in the output. if you omit the -m , then you’ll only get the first four columns. what you see here is that coverage ran the test code and determined that i have only 67% of the mymath module covered by my unit test. the “missing” column tells me what lines of code still need coverage. if you look at the lines coverage.py points out, you will quickly see that my test code doesn’t test the subtract , multiply or divide functions.
before we try to add more test coverage, let’s learn how to make coverage.py produce an html report. to do this, all you need to do is run the following command:
this command will create a folder named htmlcov that contains various files. navigate into that folder and try opening index.html in your browser of choice. on my machine, it loaded a page like this:
you can actually click on the modules listed to load up an annotated web page that shows you what parts of the code are not covered. since the mymath.py module obviously isn’t covered very well, let’s click on that one. you should end up seeing something like the following:
this screenshot clearly shows what parts of the code were not covered in our original unit test. now that we know definitively what’s missing in our test coverage, let’s add a unit test for our subtract function and see how that changes things!
open up your copy of test_mymath.py and add the following class to it:
class testsubtract(unittest.testcase): """ test the subtract function from the mymath library """ def test_subtract_integers(self): """ test that subtracting integers returns the correct result """ result = mymath.subtract(10, 8) self.assertequal(result, 2)
now we need to re-run coverage against the updated test. all you need to do is rerun this command: coverage run test_mymath.py . the output will show that four tests have passed successfully. now rerun coverage html and reopen the “index.html” file. you should now see the that we’re at 78% coverage:
this is an 11% improvement! let’s go ahead and add a simple test for the multiply and divide functions and see if we can hit 100% coverage!
class testmultiply(unittest.testcase): """ test the multiply function from the mymath library """ def test_subtract_integers(self): """ test that multiplying integers returns the correct result """ result = mymath.multiply(5, 50) self.assertequal(result, 250) class testdivide(unittest.testcase): """ test the divide function from the mymath library """ def test_divide_by_zero(self): """ test that multiplying integers returns the correct result """ with self.assertraises(zerodivisionerror): result = mymath.divide(8, 0)
now you can re-run the same commands as before and reload the “index.html” file. when you do, you should see something like the following:
as you can see, we have hit full test coverage! of course, full coverage in this case means that each function is exercised by our test suite. the problem with this is that we have three times the number of tests for the addition function versus the others, but coverage.py doesn’t give us any kind of data about that. however it will give us a good idea of basic coverage even if it can’t tell us if we’ve tested every possible argument permutation imaginable.
i just wanted to mention a few other features of coverage.py without going into a lot of detail. first, coverage.py supports configuration files. the configuration file format is your classic “.ini” file with sections demarcated by the fact that they are surrounded with square braces (i.e. [my_section]). you can add comments to the config file using the following # or ; (semi-colon).
coverage.py also allows you to specify what source files you want it to analyze via the configuration file we mentioned previously. once you have the configuration set up the way you want it, then you can run coverage.py. it also supports a “–source” command-line switch. finally you can use the “–include” and “–omit” switches to include a list of file name patterns or exclude them. these switches have matching configuration values that you can add to your configuration file too.
the last item that i want to mention is that coverage.py supports plugins. you can write your own or download and install someone else’s plugin to enhance coverage.py.
you now know the basics of coverage.py and what this special package is useful for. coverage.py allows you to check your tests and find holes in your test coverage. if you aren’t sure you’ve got your code tested properly, this package will help you ascertain where the holes are if they exist. of course, you are still responsible for writing good tests. if your tests aren’t valid but they pass anyway, coverage.py won’t help you.
Published at DZone with permission of Mike Driscoll, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.