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()