The unittest module provides a rich set of tools for constructing and running tests. This section demonstrates that a small subset of the tools suffice to meet the needs of most users.
Here is a short script to test three functions from the random module:
import random import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def testshuffle(self): # make sure the shuffled sequence does not lose any elements random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, range(10)) def testchoice(self): element = random.choice(self.seq) self.assert_(element in self.seq) def testsample(self): self.assertRaises(ValueError, random.sample, self.seq, 20) for element in random.sample(self.seq, 5): self.assert_(element in self.seq) if __name__ == '__main__': unittest.main()
A testcase is created by subclassing unittest.TestCase
.
The three individual tests are defined with methods whose names start with
the letters test
. This naming convention informs the test runner
about which methods represent tests.
The crux of each test is a call to assertEqual() to check for an expected result; assert_() to verify a condition; or assertRaises() to verify that an expected exception gets raised. These methods are used instead of the assert statement so the test runner can accumulate all test results and produce a report.
When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each test. In the example, setUp() was used to create a fresh sequence for each test.
The final block shows a simple way to run the tests. unittest.main()
provides a command line interface to the test script. When run from the
command line, the above script produces an output that looks like this:
... ---------------------------------------------------------------------- Ran 3 tests in 0.000s OK
Instead of unittest.main()
, there are other ways to run the tests
with a finer level of control, less terse output, and no requirement to be
run from the command line. For example, the last two lines may be replaced
with:
suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestSequenceFunctions)) unittest.TextTestRunner(verbosity=2).run(suite)
Running the revised script from the interpreter or another script produces the following output:
testchoice (__main__.TestSequenceFunctions) ... ok testsample (__main__.TestSequenceFunctions) ... ok testshuffle (__main__.TestSequenceFunctions) ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.110s OK
The above examples show the most commonly used unittest features which are sufficient to meet many everyday testing needs. The remainder of the documentation explores the full feature set from first principles.
See About this document... for information on suggesting changes.