Python testing
“Program testing can be used to show the presence of bugs, but never to show their absence!” – Edsger W. Dijkstra
Consider this file called polymultiply.py
def polymultiply(a, b): """ Remember that the multiplication operator in Python is polymorphic. So you can do both of: >>> multiply(4, 3) 12 >>> multiply('a', 3) 'aaa' """ return a * b
And also this file called test_polymultiply.py
import unittest from polymultiply import polymultiply class TestPM(unittest.TestCase): def setUp(self): pass def test_numbers_3_4(self): self.assertEqual(polymultiply(3, 4), 12) def test_strings_a_3(self): self.assertEqual(polymultiply("a", 3), "aaa") if __name__ == "__main__": unittest.main()
- We have written a function called
polymultiplythat does nothing more than Python multiplication and reminds us in the comments that*is polymorphic; we can use it on numbers and on strings. - In the second file we import the
polymultiplyfunction from thepolymultiplymodule. We also import the unittest module. We use it in two places. We useTestCaseand we usemain. - Within
TestPMwe have three definitions.setUpdoes nothing but it might be used to set up some configuration for our tests, for example by defining some values we are going to use.- Following that are two tests which use
assertEqualto assert that the results of the calls topolymultiplyshould be equal to the values given. - Other kinds of assertion are possible but we will mostly use use
assertEqual.
- The curious incantation at the end says to run the following code if the python file is loaded but not if it is imported. This means that if we run this file, the tests will be carried out but if we import it into other code, they will not.