Basic Use of unittest - sc15000/python-testing-cookbook GitHub Wiki

We'll dive right in. In order to get the most commonly used Python testing framework running in its most basic form, we need to:

  1. import the unittest module into our test script file, as this contains the test execution engine and the test case base class.
  2. prefix each test method with test, thereby allowing unittest to automatically discover the test(s).
  3. run the unittest executor (main())

Additionally, for readibility, it is convention to:

  1. name the test case class as for the DUT but appended with Test.

###Summary Example

import unittest # 1
...
DUTClass(object):
   ...
DUTClassTest(unittest.TestCase) # 4

   def test_high_values(self): # 2
      ...
   def test_low_values(self): # 2
      ...

if __name__ == "__main__"
   unittest.main() # 3

Full Example

See Basic unittest example

Key Notes

  • Provided are assertEquals, assertTrue, assertFalse, assertRaises.
  • Some are more useful than others. assertEquals, for example, will at least report the compared values on failure, whereas assertTrue will literally tell you that True != False, which is pretty pointless.
  • When comparing anything but Python's basic built-ins (lists, integers, strings, dictionaries), you'll need to define the object's __cmp__() method.