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()
  1. We have written a function called polymultiply that does nothing more than Python multiplication and reminds us in the comments that * is polymorphic; we can use it on numbers and on strings.
  2. In the second file we import the polymultiply function from the polymultiply module. We also import the unittest module. We use it in two places. We use TestCase and we use main.
  3. Within TestPM we have three definitions.
    • setUp does 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 assertEqual to assert that the results of the calls to polymultiply should be equal to the values given.
    • Other kinds of assertion are possible but we will mostly use use assertEqual.
  4. 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.

Author: Breanndán Ó Nualláin <o@uva.nl>

Date: 2025-02-10 Mon 14:45