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:
- import the
unittestmodule into our test script file, as this contains the test execution engine and the test case base class. - prefix each test method with
test, thereby allowing unittest to automatically discover the test(s). - run the
unittestexecutor (main())
Additionally, for readibility, it is convention to:
- 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
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, whereasassertTruewill literally tell you thatTrue != 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.