blob: e739a85f6a4a6bd7885e3ddeaf4575346f83aa02 [file] [log] [blame]
Fred Drakeb9ad2282001-04-07 05:41:39 +00001\section{\module{unittest} ---
2 Unit testing framework}
3
4\declaremodule{standard}{unittest}
Fred Drake62a26692001-04-12 19:34:38 +00005\modulesynopsis{Unit testing framework for Python.}
Fred Drakeb9ad2282001-04-07 05:41:39 +00006\moduleauthor{Steve Purcell}{stephen\textunderscore{}purcell@yahoo.com}
7\sectionauthor{Steve Purcell}{stephen\textunderscore{}purcell@yahoo.com}
8\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
Raymond Hettinger9de3c212003-07-10 22:14:41 +00009\sectionauthor{Raymond Hettinger}{python@rcn.com}
Fred Drakeb9ad2282001-04-07 05:41:39 +000010
Fred Drake5430f4e2002-10-10 16:16:25 +000011\versionadded{2.1}
Fred Drakeb9ad2282001-04-07 05:41:39 +000012
13The Python unit testing framework, often referred to as ``PyUnit,'' is
14a Python language version of JUnit, by Kent Beck and Erich Gamma.
15JUnit is, in turn, a Java version of Kent's Smalltalk testing
16framework. Each is the de facto standard unit testing framework for
17its respective language.
18
19PyUnit supports test automation, sharing of setup and shutdown code
20for tests, aggregation of tests into collections, and independence of
21the tests from the reporting framework. The \module{unittest} module
22provides classes that make it easy to support these qualities for a
23set of tests.
24
Fred Drake62a26692001-04-12 19:34:38 +000025To achieve this, PyUnit supports some important concepts:
Fred Drakeb9ad2282001-04-07 05:41:39 +000026
27\begin{definitions}
Fred Drake29be7012001-04-10 22:25:06 +000028\term{test fixture}
29A \dfn{test fixture} represents the preparation needed to perform one
30or more tests, and any associate cleanup actions. This may involve,
31for example, creating temporary or proxy databases, directories, or
32starting a server process.
33
Fred Drakeb9ad2282001-04-07 05:41:39 +000034\term{test case}
35A \dfn{test case} is the smallest unit of testing. It checks for a
36specific response to a particular set of inputs. PyUnit provides a
37base class, \class{TestCase}, which may be used to create new test
38cases.
39
40\term{test suite}
41A \dfn{test suite} is a collection of test cases, test suites, or
42both. It is used to aggregate tests that should be executed
43together.
44
45\term{test runner}
46A \dfn{test runner} is a component which orchestrates the execution of
47tests and provides the outcome to the user. The runner may use a
48graphical interface, a textual interface, or return a special value to
49indicate the results of executing the tests.
50\end{definitions}
51
52
Fred Drake62a26692001-04-12 19:34:38 +000053The test case and test fixture concepts are supported through the
54\class{TestCase} and \class{FunctionTestCase} classes; the former
Just van Rossumedd179e2002-12-15 13:14:22 +000055should be used when creating new tests, and the latter can be used when
Fred Drake62a26692001-04-12 19:34:38 +000056integrating existing test code with a PyUnit-driven framework. When
57building test fixtures using \class{TestCase}, the \method{setUp()}
58and \method{tearDown()} methods can be overridden to provide
59initialization and cleanup for the fixture. With
60\class{FunctionTestCase}, existing functions can be passed to the
61constructor for these purposes. When the test is run, the
62fixture initialization is run first; if it succeeds, the cleanup
63method is run after the test has been executed, regardless of the
64outcome of the test. Each instance of the \class{TestCase} will only
65be used to run a single test method, so a new fixture is created for
66each test.
67
68Test suites are implemented by the \class{TestSuite} class. This
69class allows individual tests and test suites to be aggregated; when
70the suite is executed, all tests added directly to the suite and in
71``child'' test suites are run.
72
73A test runner is an object that provides a single method,
74\method{run()}, which accepts a \class{TestCase} or \class{TestSuite}
75object as a parameter, and returns a result object. The class
76\class{TestResult} is provided for use as the result object. PyUnit
77provide the \class{TextTestRunner} as an example test runner which
78reports test results on the standard error stream by default.
79Alternate runners can be implemented for other environments (such as
80graphical environments) without any need to derive from a specific
81class.
82
Fred Drakeb9ad2282001-04-07 05:41:39 +000083
84\begin{seealso}
Fred Drakeae55d5f2003-12-31 04:34:50 +000085 \seemodule{doctest}{Another test-support module with a very
86 different flavor.}
Fred Drakeb9ad2282001-04-07 05:41:39 +000087 \seetitle[http://pyunit.sourceforge.net/]{PyUnit Web Site}{The
88 source for further information on PyUnit.}
89 \seetitle[http://www.XProgramming.com/testfram.htm]{Simple Smalltalk
90 Testing: With Patterns}{Kent Beck's original paper on
91 testing frameworks using the pattern shared by
92 \module{unittest}.}
93\end{seealso}
94
95
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +000096\subsection{Basic example \label{minimal-example}}
Raymond Hettinger9de3c212003-07-10 22:14:41 +000097
98The \module{unittest} module provides a rich set of tools for
99constructing and running tests. This section demonstrates that a
100small subset of the tools suffice to meet the needs of most users.
101
102Here is a short script to test three functions from the
103\refmodule{random} module:
104
105\begin{verbatim}
106import random
107import unittest
108
109class TestSequenceFunctions(unittest.TestCase):
110
111 def setUp(self):
112 self.seq = range(10)
113
114 def testshuffle(self):
115 # make sure the shuffled sequence does not lose any elements
116 random.shuffle(self.seq)
117 self.seq.sort()
118 self.assertEqual(self.seq, range(10))
119
120 def testchoice(self):
121 element = random.choice(self.seq)
122 self.assert_(element in self.seq)
123
124 def testsample(self):
125 self.assertRaises(ValueError, random.sample, self.seq, 20)
126 for element in random.sample(self.seq, 5):
127 self.assert_(element in self.seq)
128
129if __name__ == '__main__':
130 unittest.main()
131\end{verbatim}
132
Fred Drakeae55d5f2003-12-31 04:34:50 +0000133A testcase is created by subclassing \class{unittest.TestCase}.
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000134The three individual tests are defined with methods whose names start with
Fred Drakeae55d5f2003-12-31 04:34:50 +0000135the letters \samp{test}. This naming convention informs the test runner
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000136about which methods represent tests.
137
138The crux of each test is a call to \method{assertEqual()} to
139check for an expected result; \method{assert_()} to verify a condition;
140or \method{assertRaises()} to verify that an expected exception gets
141raised. These methods are used instead of the \keyword{assert} statement
142so the test runner can accumulate all test results and produce a report.
143
144When a \method{setUp()} method is defined, the test runner will run that
145method prior to each test. Likewise, if a \method{tearDown()} method is
146defined, the test runner will invoke that method after each test. In the
147example, \method{setUp()} was used to create a fresh sequence for each test.
148
Fred Drakeae55d5f2003-12-31 04:34:50 +0000149The final block shows a simple way to run the tests.
150\function{unittest.main()} provides a command line interface to the
151test script. When run from the command line, the above script
152produces an output that looks like this:
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000153
154\begin{verbatim}
155...
156----------------------------------------------------------------------
157Ran 3 tests in 0.000s
158
159OK
160\end{verbatim}
161
Fred Drakeae55d5f2003-12-31 04:34:50 +0000162Instead of \function{unittest.main()}, there are other ways to run the tests
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000163with a finer level of control, less terse output, and no requirement to be
164run from the command line. For example, the last two lines may be replaced
165with:
166
167\begin{verbatim}
Fred Drakeae55d5f2003-12-31 04:34:50 +0000168suite = unittest.makeSuite(TestSequenceFunctions)
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000169unittest.TextTestRunner(verbosity=2).run(suite)
170\end{verbatim}
171
172Running the revised script from the interpreter or another script
173produces the following output:
174
175\begin{verbatim}
176testchoice (__main__.TestSequenceFunctions) ... ok
177testsample (__main__.TestSequenceFunctions) ... ok
178testshuffle (__main__.TestSequenceFunctions) ... ok
179
180----------------------------------------------------------------------
181Ran 3 tests in 0.110s
182
183OK
184\end{verbatim}
185
186The above examples show the most commonly used \module{unittest} features
187which are sufficient to meet many everyday testing needs. The remainder
188of the documentation explores the full feature set from first principles.
189
190
Fred Drakeb9ad2282001-04-07 05:41:39 +0000191\subsection{Organizing test code
192 \label{organizing-tests}}
193
Fred Drake0056a422001-04-12 04:50:06 +0000194The basic building blocks of unit testing are \dfn{test cases} ---
195single scenarios that must be set up and checked for correctness. In
196PyUnit, test cases are represented by instances of the
197\class{TestCase} class in the \refmodule{unittest} module. To make
198your own test cases you must write subclasses of \class{TestCase}, or
199use \class{FunctionTestCase}.
200
201An instance of a \class{TestCase}-derived class is an object that can
202completely run a single test method, together with optional set-up
203and tidy-up code.
204
205The testing code of a \class{TestCase} instance should be entirely
206self contained, such that it can be run either in isolation or in
207arbitrary combination with any number of other test cases.
208
209The simplest test case subclass will simply override the
210\method{runTest()} method in order to perform specific testing code:
211
212\begin{verbatim}
213import unittest
214
215class DefaultWidgetSizeTestCase(unittest.TestCase):
216 def runTest(self):
217 widget = Widget("The widget")
Fred Drake62a26692001-04-12 19:34:38 +0000218 self.failUnless(widget.size() == (50,50), 'incorrect default size')
Fred Drake0056a422001-04-12 04:50:06 +0000219\end{verbatim}
220
Fred Drake62a26692001-04-12 19:34:38 +0000221Note that in order to test something, we use the one of the
222\method{assert*()} or \method{fail*()} methods provided by the
223\class{TestCase} base class. If the test fails when the test case
224runs, an exception will be raised, and the testing framework will
225identify the test case as a \dfn{failure}. Other exceptions that do
226not arise from checks made through the \method{assert*()} and
227\method{fail*()} methods are identified by the testing framework as
228dfn{errors}.
Fred Drake0056a422001-04-12 04:50:06 +0000229
230The way to run a test case will be described later. For now, note
231that to construct an instance of such a test case, we call its
232constructor without arguments:
233
234\begin{verbatim}
235testCase = DefaultWidgetSizeTestCase()
236\end{verbatim}
237
238Now, such test cases can be numerous, and their set-up can be
239repetitive. In the above case, constructing a ``Widget'' in each of
240100 Widget test case subclasses would mean unsightly duplication.
241
242Luckily, we can factor out such set-up code by implementing a method
243called \method{setUp()}, which the testing framework will
244automatically call for us when we run the test:
245
246\begin{verbatim}
247import unittest
248
249class SimpleWidgetTestCase(unittest.TestCase):
250 def setUp(self):
251 self.widget = Widget("The widget")
252
253class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
254 def runTest(self):
Fred Drake62a26692001-04-12 19:34:38 +0000255 self.failUnless(self.widget.size() == (50,50),
256 'incorrect default size')
Fred Drake0056a422001-04-12 04:50:06 +0000257
258class WidgetResizeTestCase(SimpleWidgetTestCase):
259 def runTest(self):
260 self.widget.resize(100,150)
Fred Drake62a26692001-04-12 19:34:38 +0000261 self.failUnless(self.widget.size() == (100,150),
262 'wrong size after resize')
Fred Drake0056a422001-04-12 04:50:06 +0000263\end{verbatim}
264
265If the \method{setUp()} method raises an exception while the test is
266running, the framework will consider the test to have suffered an
267error, and the \method{runTest()} method will not be executed.
268
269Similarly, we can provide a \method{tearDown()} method that tidies up
270after the \method{runTest()} method has been run:
271
272\begin{verbatim}
273import unittest
274
275class SimpleWidgetTestCase(unittest.TestCase):
276 def setUp(self):
277 self.widget = Widget("The widget")
278
279 def tearDown(self):
280 self.widget.dispose()
281 self.widget = None
282\end{verbatim}
283
284If \method{setUp()} succeeded, the \method{tearDown()} method will be
285run regardless of whether or not \method{runTest()} succeeded.
286
287Such a working environment for the testing code is called a
288\dfn{fixture}.
289
290Often, many small test cases will use the same fixture. In this case,
291we would end up subclassing \class{SimpleWidgetTestCase} into many
292small one-method classes such as
293\class{DefaultWidgetSizeTestCase}. This is time-consuming and
294discouraging, so in the same vein as JUnit, PyUnit provides a simpler
295mechanism:
296
297\begin{verbatim}
298import unittest
299
300class WidgetTestCase(unittest.TestCase):
301 def setUp(self):
302 self.widget = Widget("The widget")
303
304 def tearDown(self):
305 self.widget.dispose()
306 self.widget = None
307
308 def testDefaultSize(self):
Fred Drake62a26692001-04-12 19:34:38 +0000309 self.failUnless(self.widget.size() == (50,50),
310 'incorrect default size')
Fred Drake0056a422001-04-12 04:50:06 +0000311
312 def testResize(self):
313 self.widget.resize(100,150)
Fred Drake62a26692001-04-12 19:34:38 +0000314 self.failUnless(self.widget.size() == (100,150),
315 'wrong size after resize')
Fred Drake0056a422001-04-12 04:50:06 +0000316\end{verbatim}
317
318Here we have not provided a \method{runTest()} method, but have
319instead provided two different test methods. Class instances will now
320each run one of the \method{test*()} methods, with \code{self.widget}
321created and destroyed separately for each instance. When creating an
322instance we must specify the test method it is to run. We do this by
323passing the method name in the constructor:
324
325\begin{verbatim}
326defaultSizeTestCase = WidgetTestCase("testDefaultSize")
327resizeTestCase = WidgetTestCase("testResize")
328\end{verbatim}
329
330Test case instances are grouped together according to the features
331they test. PyUnit provides a mechanism for this: the \class{test
332suite}, represented by the class \class{TestSuite} in the
333\refmodule{unittest} module:
334
335\begin{verbatim}
336widgetTestSuite = unittest.TestSuite()
337widgetTestSuite.addTest(WidgetTestCase("testDefaultSize"))
338widgetTestSuite.addTest(WidgetTestCase("testResize"))
339\end{verbatim}
340
341For the ease of running tests, as we will see later, it is a good
342idea to provide in each test module a callable object that returns a
343pre-built test suite:
344
345\begin{verbatim}
346def suite():
347 suite = unittest.TestSuite()
348 suite.addTest(WidgetTestCase("testDefaultSize"))
349 suite.addTest(WidgetTestCase("testResize"))
350 return suite
351\end{verbatim}
352
353or even:
354
355\begin{verbatim}
356class WidgetTestSuite(unittest.TestSuite):
357 def __init__(self):
358 unittest.TestSuite.__init__(self,map(WidgetTestCase,
359 ("testDefaultSize",
360 "testResize")))
361\end{verbatim}
362
363(The latter is admittedly not for the faint-hearted!)
364
365Since it is a common pattern to create a \class{TestCase} subclass
366with many similarly named test functions, there is a convenience
Fred Drakeae55d5f2003-12-31 04:34:50 +0000367function called \function{makeSuite()} that constructs a test suite
368that comprises all of the test cases in a test case class:
Fred Drake0056a422001-04-12 04:50:06 +0000369
370\begin{verbatim}
Fred Drakeae55d5f2003-12-31 04:34:50 +0000371suite = unittest.makeSuite(WidgetTestCase)
Fred Drake0056a422001-04-12 04:50:06 +0000372\end{verbatim}
373
374Note that when using the \function{makeSuite()} function, the order in
375which the various test cases will be run by the test suite is the
376order determined by sorting the test function names using the
377\function{cmp()} built-in function.
378
379Often it is desirable to group suites of test cases together, so as to
380run tests for the whole system at once. This is easy, since
381\class{TestSuite} instances can be added to a \class{TestSuite} just
382as \class{TestCase} instances can be added to a \class{TestSuite}:
383
384\begin{verbatim}
385suite1 = module1.TheTestSuite()
386suite2 = module2.TheTestSuite()
387alltests = unittest.TestSuite((suite1, suite2))
388\end{verbatim}
389
390You can place the definitions of test cases and test suites in the
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +0000391same modules as the code they are to test (such as \file{widget.py}),
Fred Drake0056a422001-04-12 04:50:06 +0000392but there are several advantages to placing the test code in a
393separate module, such as \file{widgettests.py}:
394
395\begin{itemize}
396 \item The test module can be run standalone from the command line.
397 \item The test code can more easily be separated from shipped code.
Michael W. Hudsonaab02602003-02-10 19:21:16 +0000398 \item There is less temptation to change test code to fit the code
Fred Drake0056a422001-04-12 04:50:06 +0000399 it tests without a good reason.
400 \item Test code should be modified much less frequently than the
401 code it tests.
402 \item Tested code can be refactored more easily.
403 \item Tests for modules written in C must be in separate modules
404 anyway, so why not be consistent?
405 \item If the testing strategy changes, there is no need to change
406 the source code.
407\end{itemize}
408
Fred Drakeb9ad2282001-04-07 05:41:39 +0000409
410\subsection{Re-using old test code
411 \label{legacy-unit-tests}}
412
413Some users will find that they have existing test code that they would
414like to run from PyUnit, without converting every old test function to
415a \class{TestCase} subclass.
416
417For this reason, PyUnit provides a \class{FunctionTestCase} class.
418This subclass of \class{TestCase} can be used to wrap an existing test
419function. Set-up and tear-down functions can also optionally be
420wrapped.
421
422Given the following test function:
423
424\begin{verbatim}
425def testSomething():
426 something = makeSomething()
427 assert something.name is not None
428 # ...
429\end{verbatim}
430
431one can create an equivalent test case instance as follows:
432
433\begin{verbatim}
434testcase = unittest.FunctionTestCase(testSomething)
435\end{verbatim}
436
437If there are additional set-up and tear-down methods that should be
438called as part of the test case's operation, they can also be provided:
439
440\begin{verbatim}
441testcase = unittest.FunctionTestCase(testSomething,
442 setUp=makeSomethingDB,
443 tearDown=deleteSomethingDB)
444\end{verbatim}
445
Fred Drake0aa811c2001-10-20 04:24:09 +0000446\note{PyUnit supports the use of \exception{AssertionError}
Fred Drake0056a422001-04-12 04:50:06 +0000447as an indicator of test failure, but does not recommend it. Future
Fred Drake0aa811c2001-10-20 04:24:09 +0000448versions may treat \exception{AssertionError} differently.}
Fred Drake0056a422001-04-12 04:50:06 +0000449
450
Fred Drakeb9ad2282001-04-07 05:41:39 +0000451\subsection{Classes and functions
452 \label{unittest-contents}}
453
454\begin{classdesc}{TestCase}{}
455 Instances of the \class{TestCase} class represent the smallest
456 testable units in a set of tests. This class is intended to be used
457 as a base class, with specific tests being implemented by concrete
458 subclasses. This class implements the interface needed by the test
459 runner to allow it to drive the test, and methods that the test code
460 can use to check for and report various kinds of failures.
461\end{classdesc}
462
463\begin{classdesc}{FunctionTestCase}{testFunc\optional{,
Fred Drake62a26692001-04-12 19:34:38 +0000464 setUp\optional{, tearDown\optional{, description}}}}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000465 This class implements the portion of the \class{TestCase} interface
466 which allows the test runner to drive the test, but does not provide
467 the methods which test code can use to check and report errors.
468 This is used to create test cases using legacy test code, allowing
469 it to be integrated into a \refmodule{unittest}-based test
470 framework.
471\end{classdesc}
472
Fred Drake29be7012001-04-10 22:25:06 +0000473\begin{classdesc}{TestSuite}{\optional{tests}}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000474 This class represents an aggregation of individual tests cases and
475 test suites. The class presents the interface needed by the test
476 runner to allow it to be run as any other test case, but all the
477 contained tests and test suites are executed. Additional methods
Fred Drake29be7012001-04-10 22:25:06 +0000478 are provided to add test cases and suites to the aggregation. If
479 \var{tests} is given, it must be a sequence of individual tests that
480 will be added to the suite.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000481\end{classdesc}
482
483\begin{classdesc}{TestLoader}{}
Fred Drake29be7012001-04-10 22:25:06 +0000484 This class is responsible for loading tests according to various
485 criteria and returning them wrapped in a \class{TestSuite}.
486 It can load all tests within a given module or \class{TestCase}
487 class. When loading from a module, it considers all
488 \class{TestCase}-derived classes. For each such class, it creates
489 an instance for each method with a name beginning with the string
490 \samp{test}.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000491\end{classdesc}
492
Fred Drake62a26692001-04-12 19:34:38 +0000493\begin{datadesc}{defaultTestLoader}
494 Instance of the \class{TestLoader} class which can be shared. If no
495 customization of the \class{TestLoader} is needed, this instance can
496 always be used instead of creating new instances.
497\end{datadesc}
498
Fred Drakeb9ad2282001-04-07 05:41:39 +0000499\begin{classdesc}{TextTestRunner}{\optional{stream\optional{,
500 descriptions\optional{, verbosity}}}}
Fred Drake29be7012001-04-10 22:25:06 +0000501 A basic test runner implementation which prints results on standard
502 output. It has a few configurable parameters, but is essentially
503 very simple. Graphical applications which run test suites should
504 provide alternate implementations.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000505\end{classdesc}
506
507\begin{funcdesc}{main}{\optional{module\optional{,
508 defaultTest\optional{, argv\optional{,
509 testRunner\optional{, testRunner}}}}}}
Fred Drake0056a422001-04-12 04:50:06 +0000510 A command-line program that runs a set of tests; this is primarily
511 for making test modules conveniently executable. The simplest use
512 for this function is:
Fred Drakeb9ad2282001-04-07 05:41:39 +0000513
514\begin{verbatim}
515if __name__ == '__main__':
516 unittest.main()
517\end{verbatim}
518\end{funcdesc}
519
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +0000520In some cases, the existing tests may have be written using the
Fred Drakeae55d5f2003-12-31 04:34:50 +0000521\refmodule{doctest} module. If so, that module provides a
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +0000522\class{DocTestSuite} class that can automatically build
523\class{unittest.TestSuite} instances from the existing test code.
524\versionadded{2.3}
525
Fred Drakeb9ad2282001-04-07 05:41:39 +0000526
527\subsection{TestCase Objects
528 \label{testcase-objects}}
529
Fred Drake29be7012001-04-10 22:25:06 +0000530Each \class{TestCase} instance represents a single test, but each
531concrete subclass may be used to define multiple tests --- the
532concrete class represents a single test fixture. The fixture is
533created and cleaned up for each test case.
534
535\class{TestCase} instances provide three groups of methods: one group
536used to run the test, another used by the test implementation to
537check conditions and report failures, and some inquiry methods
538allowing information about the test itself to be gathered.
539
540Methods in the first group are:
541
542\begin{methoddesc}[TestCase]{setUp}{}
543 Method called to prepare the test fixture. This is called
544 immediately before calling the test method; any exception raised by
545 this method will be considered an error rather than a test failure.
546 The default implementation does nothing.
547\end{methoddesc}
548
Fred Drake29be7012001-04-10 22:25:06 +0000549\begin{methoddesc}[TestCase]{tearDown}{}
550 Method called immediately after the test method has been called and
551 the result recorded. This is called even if the test method raised
552 an exception, so the implementation in subclasses may need to be
553 particularly careful about checking internal state. Any exception
554 raised by this method will be considered an error rather than a test
Fred Drake62a26692001-04-12 19:34:38 +0000555 failure. This method will only be called if the \method{setUp()}
556 succeeds, regardless of the outcome of the test method.
557 The default implementation does nothing.
558\end{methoddesc}
559
560\begin{methoddesc}[TestCase]{run}{\optional{result}}
561 Run the test, collecting the result into the test result object
Fred Drakeae55d5f2003-12-31 04:34:50 +0000562 passed as \var{result}. If \var{result} is omitted or \constant{None},
Fred Drake62a26692001-04-12 19:34:38 +0000563 a temporary result object is created and used, but is not made
564 available to the caller. This is equivalent to simply calling the
565 \class{TestCase} instance.
Fred Drake29be7012001-04-10 22:25:06 +0000566\end{methoddesc}
567
568\begin{methoddesc}[TestCase]{debug}{}
569 Run the test without collecting the result. This allows exceptions
570 raised by the test to be propogated to the caller, and can be used
571 to support running tests under a debugger.
572\end{methoddesc}
573
574
Fred Drake0056a422001-04-12 04:50:06 +0000575The test code can use any of the following methods to check for and
Fred Drake62a26692001-04-12 19:34:38 +0000576report failures.
Fred Drake29be7012001-04-10 22:25:06 +0000577
Fred Drake62a26692001-04-12 19:34:38 +0000578\begin{methoddesc}[TestCase]{assert_}{expr\optional{, msg}}
579\methodline{failUnless}{expr\optional{, msg}}
580 Signal a test failure if \var{expr} is false; the explanation for
581 the error will be \var{msg} if given, otherwise it will be
Fred Drakeae55d5f2003-12-31 04:34:50 +0000582 \constant{None}.
Fred Drake29be7012001-04-10 22:25:06 +0000583\end{methoddesc}
584
Fred Drake62a26692001-04-12 19:34:38 +0000585\begin{methoddesc}[TestCase]{assertEqual}{first, second\optional{, msg}}
586\methodline{failUnlessEqual}{first, second\optional{, msg}}
Fred Drake29be7012001-04-10 22:25:06 +0000587 Test that \var{first} and \var{second} are equal. If the values do
588 not compare equal, the test will fail with the explanation given by
Fred Drakeae55d5f2003-12-31 04:34:50 +0000589 \var{msg}, or \constant{None}. Note that using \method{failUnlessEqual()}
Fred Drake29be7012001-04-10 22:25:06 +0000590 improves upon doing the comparison as the first parameter to
Fred Drake62a26692001-04-12 19:34:38 +0000591 \method{failUnless()}: the default value for \var{msg} can be
Fred Drake29be7012001-04-10 22:25:06 +0000592 computed to include representations of both \var{first} and
593 \var{second}.
594\end{methoddesc}
595
Fred Drake62a26692001-04-12 19:34:38 +0000596\begin{methoddesc}[TestCase]{assertNotEqual}{first, second\optional{, msg}}
597\methodline{failIfEqual}{first, second\optional{, msg}}
Fred Drake29be7012001-04-10 22:25:06 +0000598 Test that \var{first} and \var{second} are not equal. If the values
599 do compare equal, the test will fail with the explanation given by
Fred Drakeae55d5f2003-12-31 04:34:50 +0000600 \var{msg}, or \constant{None}. Note that using \method{failIfEqual()}
Fred Drake29be7012001-04-10 22:25:06 +0000601 improves upon doing the comparison as the first parameter to
602 \method{failUnless()} is that the default value for \var{msg} can be
603 computed to include representations of both \var{first} and
604 \var{second}.
605\end{methoddesc}
606
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000607\begin{methoddesc}[TestCase]{assertAlmostEqual}{first, second\optional{,
608 places\optional{, msg}}}
609\methodline{failUnlessAlmostEqual}{first, second\optional{,
610 places\optional{, msg}}}
611 Test that \var{first} and \var{second} are approximately equal
612 by computing the difference, rounding to the given number of \var{places},
613 and comparing to zero. Note that comparing a given number of decimal places
614 is not the same as comparing a given number of significant digits.
615 If the values do not compare equal, the test will fail with the explanation
Fred Drakeae55d5f2003-12-31 04:34:50 +0000616 given by \var{msg}, or \constant{None}.
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000617\end{methoddesc}
618
619\begin{methoddesc}[TestCase]{assertNotAlmostEqual}{first, second\optional{,
620 places\optional{, msg}}}
621\methodline{failIfAlmostEqual}{first, second\optional{,
622 places\optional{, msg}}}
623 Test that \var{first} and \var{second} are not approximately equal
624 by computing the difference, rounding to the given number of \var{places},
625 and comparing to zero. Note that comparing a given number of decimal places
626 is not the same as comparing a given number of significant digits.
627 If the values do not compare equal, the test will fail with the explanation
Fred Drakeae55d5f2003-12-31 04:34:50 +0000628 given by \var{msg}, or \constant{None}.
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000629\end{methoddesc}
630
Fred Drake62a26692001-04-12 19:34:38 +0000631\begin{methoddesc}[TestCase]{assertRaises}{exception, callable, \moreargs}
632\methodline{failUnlessRaises}{exception, callable, \moreargs}
633 Test that an exception is raised when \var{callable} is called with
634 any positional or keyword arguments that are also passed to
635 \method{assertRaises()}. The test passes if \var{exception} is
636 raised, is an error if another exception is raised, or fails if no
637 exception is raised. To catch any of a group of exceptions, a tuple
638 containing the exception classes may be passed as \var{exception}.
639\end{methoddesc}
640
Fred Drake29be7012001-04-10 22:25:06 +0000641\begin{methoddesc}[TestCase]{failIf}{expr\optional{, msg}}
Fred Drake0056a422001-04-12 04:50:06 +0000642 The inverse of the \method{failUnless()} method is the
Fred Drake62a26692001-04-12 19:34:38 +0000643 \method{failIf()} method. This signals a test failure if \var{expr}
Fred Drakeae55d5f2003-12-31 04:34:50 +0000644 is true, with \var{msg} or \constant{None} for the error message.
Fred Drake29be7012001-04-10 22:25:06 +0000645\end{methoddesc}
646
647\begin{methoddesc}[TestCase]{fail}{\optional{msg}}
Fred Drake62a26692001-04-12 19:34:38 +0000648 Signals a test failure unconditionally, with \var{msg} or
Fred Drakeae55d5f2003-12-31 04:34:50 +0000649 \constant{None} for the error message.
Fred Drake29be7012001-04-10 22:25:06 +0000650\end{methoddesc}
651
Fred Drake62a26692001-04-12 19:34:38 +0000652\begin{memberdesc}[TestCase]{failureException}
653 This class attribute gives the exception raised by the
654 \method{test()} method. If a test framework needs to use a
655 specialized exception, possibly to carry additional information, it
656 must subclass this exception in order to ``play fair'' with the
657 framework. The initial value of this attribute is
658 \exception{AssertionError}.
659\end{memberdesc}
660
Fred Drake29be7012001-04-10 22:25:06 +0000661
662Testing frameworks can use the following methods to collect
663information on the test:
664
665\begin{methoddesc}[TestCase]{countTestCases}{}
666 Return the number of tests represented by the this test object. For
667 \class{TestCase} instances, this will always be \code{1}, but this
668 method is also implemented by the \class{TestSuite} class, which can
669 return larger values.
670\end{methoddesc}
671
672\begin{methoddesc}[TestCase]{defaultTestResult}{}
673 Return the default type of test result object to be used to run this
674 test.
675\end{methoddesc}
676
677\begin{methoddesc}[TestCase]{id}{}
678 Return a string identifying the specific test case. This is usually
679 the full name of the test method, including the module and class
680 names.
681\end{methoddesc}
682
683\begin{methoddesc}[TestCase]{shortDescription}{}
Fred Drakeae55d5f2003-12-31 04:34:50 +0000684 Returns a one-line description of the test, or \constant{None} if no
Fred Drake29be7012001-04-10 22:25:06 +0000685 description has been provided. The default implementation of this
686 method returns the first line of the test method's docstring, if
Fred Drakeae55d5f2003-12-31 04:34:50 +0000687 available, or \constant{None}.
Fred Drake29be7012001-04-10 22:25:06 +0000688\end{methoddesc}
689
Fred Drakeb9ad2282001-04-07 05:41:39 +0000690
691\subsection{TestSuite Objects
692 \label{testsuite-objects}}
693
694\class{TestSuite} objects behave much like \class{TestCase} objects,
695except they do not actually implement a test. Instead, they are used
696to aggregate tests into groups that should be run together. Some
697additional methods are available to add tests to \class{TestSuite}
698instances:
699
700\begin{methoddesc}[TestSuite]{addTest}{test}
701 Add a \class{TestCase} or \class{TestSuite} to the set of tests that
702 make up the suite.
703\end{methoddesc}
704
705\begin{methoddesc}[TestSuite]{addTests}{tests}
706 Add all the tests from a sequence of \class{TestCase} and
707 \class{TestSuite} instances to this test suite.
708\end{methoddesc}
709
Fred Drake4d17b302001-09-06 15:51:56 +0000710The \method{run()} method is also slightly different:
711
712\begin{methoddesc}[TestSuite]{run}{result}
713 Run the tests associated with this suite, collecting the result into
714 the test result object passed as \var{result}. Note that unlike
715 \method{TestCase.run()}, \method{TestSuite.run()} requires the
716 result object to be passed in.
717\end{methoddesc}
718
719In the typical usage of a \class{TestSuite} object, the \method{run()}
720method is invoked by a \class{TestRunner} rather than by the end-user
721test harness.
722
Fred Drakeb9ad2282001-04-07 05:41:39 +0000723
724\subsection{TestResult Objects
725 \label{testresult-objects}}
726
727A \class{TestResult} object stores the results of a set of tests. The
728\class{TestCase} and \class{TestSuite} classes ensure that results are
729properly stored; test authors do not need to worry about recording the
730outcome of tests.
731
732Testing frameworks built on top of \refmodule{unittest} may want
733access to the \class{TestResult} object generated by running a set of
734tests for reporting purposes; a \class{TestResult} instance is
735returned by the \method{TestRunner.run()} method for this purpose.
736
737Each instance holds the total number of tests run, and collections of
738failures and errors that occurred among those test runs. The
739collections contain tuples of \code{(\var{testcase},
Fred Drake387c8b52002-07-02 22:34:44 +0000740\var{traceback})}, where \var{traceback} is a string containing a
741formatted version of the traceback for the exception.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000742
743\class{TestResult} instances have the following attributes that will
744be of interest when inspecting the results of running a set of tests:
745
746\begin{memberdesc}[TestResult]{errors}
747 A list containing pairs of \class{TestCase} instances and the
Fred Drake387c8b52002-07-02 22:34:44 +0000748 formatted tracebacks for tests which raised an exception but did not
749 signal a test failure.
Fred Drakec4126172002-07-02 22:46:42 +0000750 \versionchanged[Contains formatted tracebacks instead of
751 \function{sys.exc_info()} results]{2.2}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000752\end{memberdesc}
753
754\begin{memberdesc}[TestResult]{failures}
755 A list containing pairs of \class{TestCase} instances and the
Fred Drake387c8b52002-07-02 22:34:44 +0000756 formatted tracebacks for tests which signalled a failure in the code
757 under test.
Fred Drakec4126172002-07-02 22:46:42 +0000758 \versionchanged[Contains formatted tracebacks instead of
759 \function{sys.exc_info()} results]{2.2}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000760\end{memberdesc}
761
762\begin{memberdesc}[TestResult]{testsRun}
763 The number of tests which have been started.
764\end{memberdesc}
765
766\begin{methoddesc}[TestResult]{wasSuccessful}{}
767 Returns true if all tests run so far have passed, otherwise returns
768 false.
769\end{methoddesc}
770
771
772The following methods of the \class{TestResult} class are used to
Martin v. Löwis7bdc4842003-09-20 11:09:28 +0000773maintain the internal data structures, and may be extended in
Fred Drakeb9ad2282001-04-07 05:41:39 +0000774subclasses to support additional reporting requirements. This is
Fred Drake8ee679f2001-07-14 02:50:55 +0000775particularly useful in building tools which support interactive
Fred Drakeb9ad2282001-04-07 05:41:39 +0000776reporting while tests are being run.
777
778\begin{methoddesc}[TestResult]{startTest}{test}
779 Called when the test case \var{test} is about to be run.
780\end{methoddesc}
781
782\begin{methoddesc}[TestResult]{stopTest}{test}
783 Called when the test case \var{test} has been executed, regardless
784 of the outcome.
785\end{methoddesc}
786
787\begin{methoddesc}[TestResult]{addError}{test, err}
Fred Drake62a26692001-04-12 19:34:38 +0000788 Called when the test case \var{test} raises an exception without
789 signalling a test failure. \var{err} is a tuple of the form
790 returned by \function{sys.exc_info()}: \code{(\var{type},
791 \var{value}, \var{traceback})}.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000792\end{methoddesc}
793
794\begin{methoddesc}[TestResult]{addFailure}{test, err}
Fred Drake62a26692001-04-12 19:34:38 +0000795 Called when the test case \var{test} signals a failure.
Fred Drake0056a422001-04-12 04:50:06 +0000796 \var{err} is a tuple of the form returned by
797 \function{sys.exc_info()}: \code{(\var{type}, \var{value},
798 \var{traceback})}.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000799\end{methoddesc}
800
801\begin{methoddesc}[TestResult]{addSuccess}{test}
802 This method is called for a test that does not fail; \var{test} is
803 the test case object.
804\end{methoddesc}
805
806
807One additional method is available for \class{TestResult} objects:
808
809\begin{methoddesc}[TestResult]{stop}{}
810 This method can be called to signal that the set of tests being run
811 should be aborted. Once this has been called, the
812 \class{TestRunner} object return to its caller without running any
813 additional tests. This is used by the \class{TextTestRunner} class
814 to stop the test framework when the user signals an interrupt from
Fred Drake8ee679f2001-07-14 02:50:55 +0000815 the keyboard. Interactive tools which provide runners can use this
816 in a similar manner.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000817\end{methoddesc}
Fred Drake62a26692001-04-12 19:34:38 +0000818
819
820\subsection{TestLoader Objects
821 \label{testloader-objects}}
822
823The \class{TestLoader} class is used to create test suites from
824classes and modules. Normally, there is no need to create an instance
825of this class; the \refmodule{unittest} module provides an instance
826that can be shared as the \code{defaultTestLoader} module attribute.
827Using a subclass or instance would allow customization of some
828configurable properties.
829
830\class{TestLoader} objects have the following methods:
831
832\begin{methoddesc}[TestLoader]{loadTestsFromTestCase}{testCaseClass}
833 Return a suite of all tests cases contained in the
834 \class{TestCase}-derived class \class{testCaseClass}.
835\end{methoddesc}
836
837\begin{methoddesc}[TestLoader]{loadTestsFromModule}{module}
838 Return a suite of all tests cases contained in the given module.
839 This method searches \var{module} for classes derived from
840 \class{TestCase} and creates an instance of the class for each test
841 method defined for the class.
842
Fred Drake0aa811c2001-10-20 04:24:09 +0000843 \warning{While using a hierarchy of
Fred Drake62a26692001-04-12 19:34:38 +0000844 \class{Testcase}-derived classes can be convenient in sharing
845 fixtures and helper functions, defining test methods on base classes
846 that are not intended to be instantiated directly does not play well
847 with this method. Doing so, however, can be useful when the
Fred Drake0aa811c2001-10-20 04:24:09 +0000848 fixtures are different and defined in subclasses.}
Fred Drake62a26692001-04-12 19:34:38 +0000849\end{methoddesc}
850
851\begin{methoddesc}[TestLoader]{loadTestsFromName}{name\optional{, module}}
852 Return a suite of all tests cases given a string specifier.
853
Fred Drake4d17b302001-09-06 15:51:56 +0000854 The specifier \var{name} is a ``dotted name'' that may resolve
855 either to a module, a test case class, a test method within a test
856 case class, or a callable object which returns a \class{TestCase} or
857 \class{TestSuite} instance. For example, if you have a module
858 \module{SampleTests} containing a \class{TestCase}-derived class
859 \class{SampleTestCase} with three test methods (\method{test_one()},
860 \method{test_two()}, and \method{test_three()}), the specifier
861 \code{'SampleTests.SampleTestCase'} would cause this method to
862 return a suite which will run all three test methods. Using the
863 specifier \code{'SampleTests.SampleTestCase.test_two'} would cause
864 it to return a test suite which will run only the
865 \method{test_two()} test method. The specifier can refer to modules
866 and packages which have not been imported; they will be imported as
867 a side-effect.
Fred Drake62a26692001-04-12 19:34:38 +0000868
869 The method optionally resolves \var{name} relative to a given module.
870\end{methoddesc}
871
872\begin{methoddesc}[TestLoader]{loadTestsFromNames}{names\optional{, module}}
873 Similar to \method{loadTestsFromName()}, but takes a sequence of
874 names rather than a single name. The return value is a test suite
875 which supports all the tests defined for each name.
876\end{methoddesc}
877
878\begin{methoddesc}[TestLoader]{getTestCaseNames}{testCaseClass}
879 Return a sorted sequence of method names found within
880 \var{testCaseClass}.
881\end{methoddesc}
882
883
884The following attributes of a \class{TestLoader} can be configured
885either by subclassing or assignment on an instance:
886
887\begin{memberdesc}[TestLoader]{testMethodPrefix}
888 String giving the prefix of method names which will be interpreted
889 as test methods. The default value is \code{'test'}.
890\end{memberdesc}
891
892\begin{memberdesc}[TestLoader]{sortTestMethodsUsing}
893 Function to be used to compare method names when sorting them in
894 \method{getTestCaseNames()}. The default value is the built-in
Fred Drakeae55d5f2003-12-31 04:34:50 +0000895 \function{cmp()} function; it can be set to \constant{None} to disable
Fred Drake62a26692001-04-12 19:34:38 +0000896 the sort.
897\end{memberdesc}
898
899\begin{memberdesc}[TestLoader]{suiteClass}
900 Callable object that constructs a test suite from a list of tests.
901 No methods on the resulting object are needed. The default value is
902 the \class{TestSuite} class.
903\end{memberdesc}