Functions of coverage.py
Let’s discuss coverage.py and how it helps in measuring our code coverage.
We'll cover the following...
Coverage.py
is a 3rd party tool for Python that is used for measuring our code coverage.
It was originally created by Ned
Batchelder. The term “coverage” in programming circles is typically used to describe the effectiveness of our tests and how much of our code is actually covered by tests.
We can use coverage.py
with Python 2.6 up to the current version of Python 3 as well as with PyPy
.
If you don’t have coverage.py
installed, you may do so using pip:
pip3 install coverage
Examples of coverage.py
Now that we have coverage.py
installed, we need some code to use it
with. Let’s use the mymath
module that we created earlier in the
course. Here’s the code:
##mymath.pydef add(a, b):return a + bdef subtract(a, b):return a - bdef multiply(a, b):return a * bdef divide(numerator, denominator):return float(numerator) / denominatorprint(divide(34,5))print(add(4,5))print(subtract(3,4))print(multiply(3,4))
Now we need a test. Here is the code:
# test_mymath.pyimport mymathimport unittestclass 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 oneconcatenated string"""result = mymath.add('abc', 'def')self.assertEqual(result, 'abcdef')if __name__ == '__main__':unittest.main()
Testing the implementation with commands
Let’s test the below example with the commands provided in this lesson and see the ...