blob: 6c8769d67aae0fe58edb78704986a3cfac800e7e [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
Johannes Gijsberseaaa7712004-11-07 16:02:07 +000038cases. You may provide your own implementation that does not subclass
39from \class{TestCase}, of course.
Fred Drakeb9ad2282001-04-07 05:41:39 +000040
41\term{test suite}
42A \dfn{test suite} is a collection of test cases, test suites, or
43both. It is used to aggregate tests that should be executed
44together.
45
46\term{test runner}
47A \dfn{test runner} is a component which orchestrates the execution of
48tests and provides the outcome to the user. The runner may use a
49graphical interface, a textual interface, or return a special value to
50indicate the results of executing the tests.
51\end{definitions}
52
53
Fred Drake62a26692001-04-12 19:34:38 +000054The test case and test fixture concepts are supported through the
55\class{TestCase} and \class{FunctionTestCase} classes; the former
Just van Rossumedd179e2002-12-15 13:14:22 +000056should be used when creating new tests, and the latter can be used when
Fred Drake62a26692001-04-12 19:34:38 +000057integrating existing test code with a PyUnit-driven framework. When
58building test fixtures using \class{TestCase}, the \method{setUp()}
59and \method{tearDown()} methods can be overridden to provide
60initialization and cleanup for the fixture. With
61\class{FunctionTestCase}, existing functions can be passed to the
62constructor for these purposes. When the test is run, the
63fixture initialization is run first; if it succeeds, the cleanup
64method is run after the test has been executed, regardless of the
65outcome of the test. Each instance of the \class{TestCase} will only
66be used to run a single test method, so a new fixture is created for
67each test.
68
69Test suites are implemented by the \class{TestSuite} class. This
70class allows individual tests and test suites to be aggregated; when
71the suite is executed, all tests added directly to the suite and in
72``child'' test suites are run.
73
74A test runner is an object that provides a single method,
75\method{run()}, which accepts a \class{TestCase} or \class{TestSuite}
76object as a parameter, and returns a result object. The class
77\class{TestResult} is provided for use as the result object. PyUnit
78provide the \class{TextTestRunner} as an example test runner which
79reports test results on the standard error stream by default.
80Alternate runners can be implemented for other environments (such as
81graphical environments) without any need to derive from a specific
82class.
83
Fred Drakeb9ad2282001-04-07 05:41:39 +000084
85\begin{seealso}
Fred Drakeae55d5f2003-12-31 04:34:50 +000086 \seemodule{doctest}{Another test-support module with a very
87 different flavor.}
Fred Drakeb9ad2282001-04-07 05:41:39 +000088 \seetitle[http://pyunit.sourceforge.net/]{PyUnit Web Site}{The
89 source for further information on PyUnit.}
90 \seetitle[http://www.XProgramming.com/testfram.htm]{Simple Smalltalk
91 Testing: With Patterns}{Kent Beck's original paper on
92 testing frameworks using the pattern shared by
93 \module{unittest}.}
94\end{seealso}
95
96
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +000097\subsection{Basic example \label{minimal-example}}
Raymond Hettinger9de3c212003-07-10 22:14:41 +000098
99The \module{unittest} module provides a rich set of tools for
100constructing and running tests. This section demonstrates that a
101small subset of the tools suffice to meet the needs of most users.
102
103Here is a short script to test three functions from the
104\refmodule{random} module:
105
106\begin{verbatim}
107import random
108import unittest
109
110class TestSequenceFunctions(unittest.TestCase):
111
112 def setUp(self):
113 self.seq = range(10)
114
115 def testshuffle(self):
116 # make sure the shuffled sequence does not lose any elements
117 random.shuffle(self.seq)
118 self.seq.sort()
119 self.assertEqual(self.seq, range(10))
120
121 def testchoice(self):
122 element = random.choice(self.seq)
123 self.assert_(element in self.seq)
124
125 def testsample(self):
126 self.assertRaises(ValueError, random.sample, self.seq, 20)
127 for element in random.sample(self.seq, 5):
128 self.assert_(element in self.seq)
129
130if __name__ == '__main__':
131 unittest.main()
132\end{verbatim}
133
Fred Drakeae55d5f2003-12-31 04:34:50 +0000134A testcase is created by subclassing \class{unittest.TestCase}.
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000135The three individual tests are defined with methods whose names start with
Fred Drakeae55d5f2003-12-31 04:34:50 +0000136the letters \samp{test}. This naming convention informs the test runner
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000137about which methods represent tests.
138
139The crux of each test is a call to \method{assertEqual()} to
140check for an expected result; \method{assert_()} to verify a condition;
141or \method{assertRaises()} to verify that an expected exception gets
142raised. These methods are used instead of the \keyword{assert} statement
143so the test runner can accumulate all test results and produce a report.
144
145When a \method{setUp()} method is defined, the test runner will run that
146method prior to each test. Likewise, if a \method{tearDown()} method is
147defined, the test runner will invoke that method after each test. In the
148example, \method{setUp()} was used to create a fresh sequence for each test.
149
Fred Drakeae55d5f2003-12-31 04:34:50 +0000150The final block shows a simple way to run the tests.
151\function{unittest.main()} provides a command line interface to the
152test script. When run from the command line, the above script
153produces an output that looks like this:
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000154
155\begin{verbatim}
156...
157----------------------------------------------------------------------
158Ran 3 tests in 0.000s
159
160OK
161\end{verbatim}
162
Fred Drakeae55d5f2003-12-31 04:34:50 +0000163Instead of \function{unittest.main()}, there are other ways to run the tests
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000164with a finer level of control, less terse output, and no requirement to be
165run from the command line. For example, the last two lines may be replaced
166with:
167
168\begin{verbatim}
Fred Drakeae55d5f2003-12-31 04:34:50 +0000169suite = unittest.makeSuite(TestSequenceFunctions)
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000170unittest.TextTestRunner(verbosity=2).run(suite)
171\end{verbatim}
172
173Running the revised script from the interpreter or another script
174produces the following output:
175
176\begin{verbatim}
177testchoice (__main__.TestSequenceFunctions) ... ok
178testsample (__main__.TestSequenceFunctions) ... ok
179testshuffle (__main__.TestSequenceFunctions) ... ok
180
181----------------------------------------------------------------------
182Ran 3 tests in 0.110s
183
184OK
185\end{verbatim}
186
187The above examples show the most commonly used \module{unittest} features
188which are sufficient to meet many everyday testing needs. The remainder
189of the documentation explores the full feature set from first principles.
190
191
Fred Drakeb9ad2282001-04-07 05:41:39 +0000192\subsection{Organizing test code
193 \label{organizing-tests}}
194
Fred Drake0056a422001-04-12 04:50:06 +0000195The basic building blocks of unit testing are \dfn{test cases} ---
196single scenarios that must be set up and checked for correctness. In
197PyUnit, test cases are represented by instances of the
198\class{TestCase} class in the \refmodule{unittest} module. To make
199your own test cases you must write subclasses of \class{TestCase}, or
200use \class{FunctionTestCase}.
201
202An instance of a \class{TestCase}-derived class is an object that can
203completely run a single test method, together with optional set-up
204and tidy-up code.
205
206The testing code of a \class{TestCase} instance should be entirely
207self contained, such that it can be run either in isolation or in
208arbitrary combination with any number of other test cases.
209
210The simplest test case subclass will simply override the
211\method{runTest()} method in order to perform specific testing code:
212
213\begin{verbatim}
214import unittest
215
216class DefaultWidgetSizeTestCase(unittest.TestCase):
217 def runTest(self):
218 widget = Widget("The widget")
Fred Drake62a26692001-04-12 19:34:38 +0000219 self.failUnless(widget.size() == (50,50), 'incorrect default size')
Fred Drake0056a422001-04-12 04:50:06 +0000220\end{verbatim}
221
Fred Drake62a26692001-04-12 19:34:38 +0000222Note that in order to test something, we use the one of the
223\method{assert*()} or \method{fail*()} methods provided by the
224\class{TestCase} base class. If the test fails when the test case
225runs, an exception will be raised, and the testing framework will
226identify the test case as a \dfn{failure}. Other exceptions that do
227not arise from checks made through the \method{assert*()} and
228\method{fail*()} methods are identified by the testing framework as
229dfn{errors}.
Fred Drake0056a422001-04-12 04:50:06 +0000230
231The way to run a test case will be described later. For now, note
232that to construct an instance of such a test case, we call its
233constructor without arguments:
234
235\begin{verbatim}
236testCase = DefaultWidgetSizeTestCase()
237\end{verbatim}
238
239Now, such test cases can be numerous, and their set-up can be
240repetitive. In the above case, constructing a ``Widget'' in each of
241100 Widget test case subclasses would mean unsightly duplication.
242
243Luckily, we can factor out such set-up code by implementing a method
244called \method{setUp()}, which the testing framework will
245automatically call for us when we run the test:
246
247\begin{verbatim}
248import unittest
249
250class SimpleWidgetTestCase(unittest.TestCase):
251 def setUp(self):
252 self.widget = Widget("The widget")
253
254class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
255 def runTest(self):
Fred Drake62a26692001-04-12 19:34:38 +0000256 self.failUnless(self.widget.size() == (50,50),
257 'incorrect default size')
Fred Drake0056a422001-04-12 04:50:06 +0000258
259class WidgetResizeTestCase(SimpleWidgetTestCase):
260 def runTest(self):
261 self.widget.resize(100,150)
Fred Drake62a26692001-04-12 19:34:38 +0000262 self.failUnless(self.widget.size() == (100,150),
263 'wrong size after resize')
Fred Drake0056a422001-04-12 04:50:06 +0000264\end{verbatim}
265
266If the \method{setUp()} method raises an exception while the test is
267running, the framework will consider the test to have suffered an
268error, and the \method{runTest()} method will not be executed.
269
270Similarly, we can provide a \method{tearDown()} method that tidies up
271after the \method{runTest()} method has been run:
272
273\begin{verbatim}
274import unittest
275
276class SimpleWidgetTestCase(unittest.TestCase):
277 def setUp(self):
278 self.widget = Widget("The widget")
279
280 def tearDown(self):
281 self.widget.dispose()
282 self.widget = None
283\end{verbatim}
284
285If \method{setUp()} succeeded, the \method{tearDown()} method will be
286run regardless of whether or not \method{runTest()} succeeded.
287
288Such a working environment for the testing code is called a
289\dfn{fixture}.
290
291Often, many small test cases will use the same fixture. In this case,
292we would end up subclassing \class{SimpleWidgetTestCase} into many
293small one-method classes such as
294\class{DefaultWidgetSizeTestCase}. This is time-consuming and
295discouraging, so in the same vein as JUnit, PyUnit provides a simpler
296mechanism:
297
298\begin{verbatim}
299import unittest
300
301class WidgetTestCase(unittest.TestCase):
302 def setUp(self):
303 self.widget = Widget("The widget")
304
305 def tearDown(self):
306 self.widget.dispose()
307 self.widget = None
308
309 def testDefaultSize(self):
Fred Drake62a26692001-04-12 19:34:38 +0000310 self.failUnless(self.widget.size() == (50,50),
311 'incorrect default size')
Fred Drake0056a422001-04-12 04:50:06 +0000312
313 def testResize(self):
314 self.widget.resize(100,150)
Fred Drake62a26692001-04-12 19:34:38 +0000315 self.failUnless(self.widget.size() == (100,150),
316 'wrong size after resize')
Fred Drake0056a422001-04-12 04:50:06 +0000317\end{verbatim}
318
319Here we have not provided a \method{runTest()} method, but have
320instead provided two different test methods. Class instances will now
321each run one of the \method{test*()} methods, with \code{self.widget}
322created and destroyed separately for each instance. When creating an
323instance we must specify the test method it is to run. We do this by
324passing the method name in the constructor:
325
326\begin{verbatim}
327defaultSizeTestCase = WidgetTestCase("testDefaultSize")
328resizeTestCase = WidgetTestCase("testResize")
329\end{verbatim}
330
331Test case instances are grouped together according to the features
332they test. PyUnit provides a mechanism for this: the \class{test
333suite}, represented by the class \class{TestSuite} in the
334\refmodule{unittest} module:
335
336\begin{verbatim}
337widgetTestSuite = unittest.TestSuite()
338widgetTestSuite.addTest(WidgetTestCase("testDefaultSize"))
339widgetTestSuite.addTest(WidgetTestCase("testResize"))
340\end{verbatim}
341
342For the ease of running tests, as we will see later, it is a good
343idea to provide in each test module a callable object that returns a
344pre-built test suite:
345
346\begin{verbatim}
347def suite():
348 suite = unittest.TestSuite()
349 suite.addTest(WidgetTestCase("testDefaultSize"))
350 suite.addTest(WidgetTestCase("testResize"))
351 return suite
352\end{verbatim}
353
354or even:
355
356\begin{verbatim}
357class WidgetTestSuite(unittest.TestSuite):
358 def __init__(self):
359 unittest.TestSuite.__init__(self,map(WidgetTestCase,
360 ("testDefaultSize",
361 "testResize")))
362\end{verbatim}
363
364(The latter is admittedly not for the faint-hearted!)
365
366Since it is a common pattern to create a \class{TestCase} subclass
367with many similarly named test functions, there is a convenience
Fred Drakeae55d5f2003-12-31 04:34:50 +0000368function called \function{makeSuite()} that constructs a test suite
369that comprises all of the test cases in a test case class:
Fred Drake0056a422001-04-12 04:50:06 +0000370
371\begin{verbatim}
Fred Drakeae55d5f2003-12-31 04:34:50 +0000372suite = unittest.makeSuite(WidgetTestCase)
Fred Drake0056a422001-04-12 04:50:06 +0000373\end{verbatim}
374
375Note that when using the \function{makeSuite()} function, the order in
376which the various test cases will be run by the test suite is the
377order determined by sorting the test function names using the
378\function{cmp()} built-in function.
379
380Often it is desirable to group suites of test cases together, so as to
381run tests for the whole system at once. This is easy, since
382\class{TestSuite} instances can be added to a \class{TestSuite} just
383as \class{TestCase} instances can be added to a \class{TestSuite}:
384
385\begin{verbatim}
386suite1 = module1.TheTestSuite()
387suite2 = module2.TheTestSuite()
388alltests = unittest.TestSuite((suite1, suite2))
389\end{verbatim}
390
391You can place the definitions of test cases and test suites in the
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +0000392same modules as the code they are to test (such as \file{widget.py}),
Fred Drake0056a422001-04-12 04:50:06 +0000393but there are several advantages to placing the test code in a
394separate module, such as \file{widgettests.py}:
395
396\begin{itemize}
397 \item The test module can be run standalone from the command line.
398 \item The test code can more easily be separated from shipped code.
Michael W. Hudsonaab02602003-02-10 19:21:16 +0000399 \item There is less temptation to change test code to fit the code
Fred Drake0056a422001-04-12 04:50:06 +0000400 it tests without a good reason.
401 \item Test code should be modified much less frequently than the
402 code it tests.
403 \item Tested code can be refactored more easily.
404 \item Tests for modules written in C must be in separate modules
405 anyway, so why not be consistent?
406 \item If the testing strategy changes, there is no need to change
407 the source code.
408\end{itemize}
409
Fred Drakeb9ad2282001-04-07 05:41:39 +0000410
411\subsection{Re-using old test code
412 \label{legacy-unit-tests}}
413
414Some users will find that they have existing test code that they would
415like to run from PyUnit, without converting every old test function to
416a \class{TestCase} subclass.
417
418For this reason, PyUnit provides a \class{FunctionTestCase} class.
419This subclass of \class{TestCase} can be used to wrap an existing test
420function. Set-up and tear-down functions can also optionally be
421wrapped.
422
423Given the following test function:
424
425\begin{verbatim}
426def testSomething():
427 something = makeSomething()
428 assert something.name is not None
429 # ...
430\end{verbatim}
431
432one can create an equivalent test case instance as follows:
433
434\begin{verbatim}
435testcase = unittest.FunctionTestCase(testSomething)
436\end{verbatim}
437
438If there are additional set-up and tear-down methods that should be
439called as part of the test case's operation, they can also be provided:
440
441\begin{verbatim}
442testcase = unittest.FunctionTestCase(testSomething,
443 setUp=makeSomethingDB,
444 tearDown=deleteSomethingDB)
445\end{verbatim}
446
Fred Drake0aa811c2001-10-20 04:24:09 +0000447\note{PyUnit supports the use of \exception{AssertionError}
Fred Drake0056a422001-04-12 04:50:06 +0000448as an indicator of test failure, but does not recommend it. Future
Fred Drake0aa811c2001-10-20 04:24:09 +0000449versions may treat \exception{AssertionError} differently.}
Fred Drake0056a422001-04-12 04:50:06 +0000450
451
Fred Drakeb9ad2282001-04-07 05:41:39 +0000452\subsection{Classes and functions
453 \label{unittest-contents}}
454
455\begin{classdesc}{TestCase}{}
456 Instances of the \class{TestCase} class represent the smallest
457 testable units in a set of tests. This class is intended to be used
458 as a base class, with specific tests being implemented by concrete
459 subclasses. This class implements the interface needed by the test
460 runner to allow it to drive the test, and methods that the test code
461 can use to check for and report various kinds of failures.
462\end{classdesc}
463
464\begin{classdesc}{FunctionTestCase}{testFunc\optional{,
Fred Drake62a26692001-04-12 19:34:38 +0000465 setUp\optional{, tearDown\optional{, description}}}}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000466 This class implements the portion of the \class{TestCase} interface
467 which allows the test runner to drive the test, but does not provide
468 the methods which test code can use to check and report errors.
469 This is used to create test cases using legacy test code, allowing
470 it to be integrated into a \refmodule{unittest}-based test
471 framework.
472\end{classdesc}
473
Fred Drake29be7012001-04-10 22:25:06 +0000474\begin{classdesc}{TestSuite}{\optional{tests}}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000475 This class represents an aggregation of individual tests cases and
476 test suites. The class presents the interface needed by the test
477 runner to allow it to be run as any other test case, but all the
478 contained tests and test suites are executed. Additional methods
Fred Drake29be7012001-04-10 22:25:06 +0000479 are provided to add test cases and suites to the aggregation. If
480 \var{tests} is given, it must be a sequence of individual tests that
481 will be added to the suite.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000482\end{classdesc}
483
484\begin{classdesc}{TestLoader}{}
Fred Drake29be7012001-04-10 22:25:06 +0000485 This class is responsible for loading tests according to various
486 criteria and returning them wrapped in a \class{TestSuite}.
487 It can load all tests within a given module or \class{TestCase}
488 class. When loading from a module, it considers all
489 \class{TestCase}-derived classes. For each such class, it creates
490 an instance for each method with a name beginning with the string
491 \samp{test}.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000492\end{classdesc}
493
Fred Drake62a26692001-04-12 19:34:38 +0000494\begin{datadesc}{defaultTestLoader}
495 Instance of the \class{TestLoader} class which can be shared. If no
496 customization of the \class{TestLoader} is needed, this instance can
497 always be used instead of creating new instances.
498\end{datadesc}
499
Fred Drakeb9ad2282001-04-07 05:41:39 +0000500\begin{classdesc}{TextTestRunner}{\optional{stream\optional{,
501 descriptions\optional{, verbosity}}}}
Fred Drake29be7012001-04-10 22:25:06 +0000502 A basic test runner implementation which prints results on standard
503 output. It has a few configurable parameters, but is essentially
504 very simple. Graphical applications which run test suites should
505 provide alternate implementations.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000506\end{classdesc}
507
508\begin{funcdesc}{main}{\optional{module\optional{,
509 defaultTest\optional{, argv\optional{,
510 testRunner\optional{, testRunner}}}}}}
Fred Drake0056a422001-04-12 04:50:06 +0000511 A command-line program that runs a set of tests; this is primarily
512 for making test modules conveniently executable. The simplest use
513 for this function is:
Fred Drakeb9ad2282001-04-07 05:41:39 +0000514
515\begin{verbatim}
516if __name__ == '__main__':
517 unittest.main()
518\end{verbatim}
519\end{funcdesc}
520
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +0000521In some cases, the existing tests may have be written using the
Fred Drakeae55d5f2003-12-31 04:34:50 +0000522\refmodule{doctest} module. If so, that module provides a
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +0000523\class{DocTestSuite} class that can automatically build
524\class{unittest.TestSuite} instances from the existing test code.
525\versionadded{2.3}
526
Fred Drakeb9ad2282001-04-07 05:41:39 +0000527
528\subsection{TestCase Objects
529 \label{testcase-objects}}
530
Fred Drake29be7012001-04-10 22:25:06 +0000531Each \class{TestCase} instance represents a single test, but each
532concrete subclass may be used to define multiple tests --- the
533concrete class represents a single test fixture. The fixture is
534created and cleaned up for each test case.
535
536\class{TestCase} instances provide three groups of methods: one group
537used to run the test, another used by the test implementation to
538check conditions and report failures, and some inquiry methods
539allowing information about the test itself to be gathered.
540
541Methods in the first group are:
542
543\begin{methoddesc}[TestCase]{setUp}{}
544 Method called to prepare the test fixture. This is called
545 immediately before calling the test method; any exception raised by
546 this method will be considered an error rather than a test failure.
547 The default implementation does nothing.
548\end{methoddesc}
549
Fred Drake29be7012001-04-10 22:25:06 +0000550\begin{methoddesc}[TestCase]{tearDown}{}
551 Method called immediately after the test method has been called and
552 the result recorded. This is called even if the test method raised
553 an exception, so the implementation in subclasses may need to be
554 particularly careful about checking internal state. Any exception
555 raised by this method will be considered an error rather than a test
Fred Drake62a26692001-04-12 19:34:38 +0000556 failure. This method will only be called if the \method{setUp()}
557 succeeds, regardless of the outcome of the test method.
558 The default implementation does nothing.
559\end{methoddesc}
560
561\begin{methoddesc}[TestCase]{run}{\optional{result}}
562 Run the test, collecting the result into the test result object
Fred Drakeae55d5f2003-12-31 04:34:50 +0000563 passed as \var{result}. If \var{result} is omitted or \constant{None},
Fred Drake62a26692001-04-12 19:34:38 +0000564 a temporary result object is created and used, but is not made
565 available to the caller. This is equivalent to simply calling the
566 \class{TestCase} instance.
Fred Drake29be7012001-04-10 22:25:06 +0000567\end{methoddesc}
568
569\begin{methoddesc}[TestCase]{debug}{}
570 Run the test without collecting the result. This allows exceptions
Raymond Hettinger68804312005-01-01 00:28:46 +0000571 raised by the test to be propagated to the caller, and can be used
Fred Drake29be7012001-04-10 22:25:06 +0000572 to support running tests under a debugger.
573\end{methoddesc}
574
575
Fred Drake0056a422001-04-12 04:50:06 +0000576The test code can use any of the following methods to check for and
Fred Drake62a26692001-04-12 19:34:38 +0000577report failures.
Fred Drake29be7012001-04-10 22:25:06 +0000578
Fred Drake62a26692001-04-12 19:34:38 +0000579\begin{methoddesc}[TestCase]{assert_}{expr\optional{, msg}}
580\methodline{failUnless}{expr\optional{, msg}}
581 Signal a test failure if \var{expr} is false; the explanation for
582 the error will be \var{msg} if given, otherwise it will be
Fred Drakeae55d5f2003-12-31 04:34:50 +0000583 \constant{None}.
Fred Drake29be7012001-04-10 22:25:06 +0000584\end{methoddesc}
585
Fred Drake62a26692001-04-12 19:34:38 +0000586\begin{methoddesc}[TestCase]{assertEqual}{first, second\optional{, msg}}
587\methodline{failUnlessEqual}{first, second\optional{, msg}}
Fred Drake29be7012001-04-10 22:25:06 +0000588 Test that \var{first} and \var{second} are equal. If the values do
589 not compare equal, the test will fail with the explanation given by
Fred Drakeae55d5f2003-12-31 04:34:50 +0000590 \var{msg}, or \constant{None}. Note that using \method{failUnlessEqual()}
Fred Drake29be7012001-04-10 22:25:06 +0000591 improves upon doing the comparison as the first parameter to
Fred Drake62a26692001-04-12 19:34:38 +0000592 \method{failUnless()}: the default value for \var{msg} can be
Fred Drake29be7012001-04-10 22:25:06 +0000593 computed to include representations of both \var{first} and
594 \var{second}.
595\end{methoddesc}
596
Fred Drake62a26692001-04-12 19:34:38 +0000597\begin{methoddesc}[TestCase]{assertNotEqual}{first, second\optional{, msg}}
598\methodline{failIfEqual}{first, second\optional{, msg}}
Fred Drake29be7012001-04-10 22:25:06 +0000599 Test that \var{first} and \var{second} are not equal. If the values
600 do compare equal, the test will fail with the explanation given by
Fred Drakeae55d5f2003-12-31 04:34:50 +0000601 \var{msg}, or \constant{None}. Note that using \method{failIfEqual()}
Fred Drake29be7012001-04-10 22:25:06 +0000602 improves upon doing the comparison as the first parameter to
603 \method{failUnless()} is that the default value for \var{msg} can be
604 computed to include representations of both \var{first} and
605 \var{second}.
606\end{methoddesc}
607
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000608\begin{methoddesc}[TestCase]{assertAlmostEqual}{first, second\optional{,
609 places\optional{, msg}}}
610\methodline{failUnlessAlmostEqual}{first, second\optional{,
611 places\optional{, msg}}}
612 Test that \var{first} and \var{second} are approximately equal
613 by computing the difference, rounding to the given number of \var{places},
614 and comparing to zero. Note that comparing a given number of decimal places
615 is not the same as comparing a given number of significant digits.
616 If the values do not compare equal, the test will fail with the explanation
Fred Drakeae55d5f2003-12-31 04:34:50 +0000617 given by \var{msg}, or \constant{None}.
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000618\end{methoddesc}
619
620\begin{methoddesc}[TestCase]{assertNotAlmostEqual}{first, second\optional{,
621 places\optional{, msg}}}
622\methodline{failIfAlmostEqual}{first, second\optional{,
623 places\optional{, msg}}}
624 Test that \var{first} and \var{second} are not approximately equal
625 by computing the difference, rounding to the given number of \var{places},
626 and comparing to zero. Note that comparing a given number of decimal places
627 is not the same as comparing a given number of significant digits.
628 If the values do not compare equal, the test will fail with the explanation
Fred Drakeae55d5f2003-12-31 04:34:50 +0000629 given by \var{msg}, or \constant{None}.
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000630\end{methoddesc}
631
Fred Drake62a26692001-04-12 19:34:38 +0000632\begin{methoddesc}[TestCase]{assertRaises}{exception, callable, \moreargs}
633\methodline{failUnlessRaises}{exception, callable, \moreargs}
634 Test that an exception is raised when \var{callable} is called with
635 any positional or keyword arguments that are also passed to
636 \method{assertRaises()}. The test passes if \var{exception} is
637 raised, is an error if another exception is raised, or fails if no
638 exception is raised. To catch any of a group of exceptions, a tuple
639 containing the exception classes may be passed as \var{exception}.
640\end{methoddesc}
641
Fred Drake29be7012001-04-10 22:25:06 +0000642\begin{methoddesc}[TestCase]{failIf}{expr\optional{, msg}}
Fred Drake0056a422001-04-12 04:50:06 +0000643 The inverse of the \method{failUnless()} method is the
Fred Drake62a26692001-04-12 19:34:38 +0000644 \method{failIf()} method. This signals a test failure if \var{expr}
Fred Drakeae55d5f2003-12-31 04:34:50 +0000645 is true, with \var{msg} or \constant{None} for the error message.
Fred Drake29be7012001-04-10 22:25:06 +0000646\end{methoddesc}
647
648\begin{methoddesc}[TestCase]{fail}{\optional{msg}}
Fred Drake62a26692001-04-12 19:34:38 +0000649 Signals a test failure unconditionally, with \var{msg} or
Fred Drakeae55d5f2003-12-31 04:34:50 +0000650 \constant{None} for the error message.
Fred Drake29be7012001-04-10 22:25:06 +0000651\end{methoddesc}
652
Fred Drake62a26692001-04-12 19:34:38 +0000653\begin{memberdesc}[TestCase]{failureException}
654 This class attribute gives the exception raised by the
655 \method{test()} method. If a test framework needs to use a
656 specialized exception, possibly to carry additional information, it
657 must subclass this exception in order to ``play fair'' with the
658 framework. The initial value of this attribute is
659 \exception{AssertionError}.
660\end{memberdesc}
661
Fred Drake29be7012001-04-10 22:25:06 +0000662
663Testing frameworks can use the following methods to collect
664information on the test:
665
666\begin{methoddesc}[TestCase]{countTestCases}{}
667 Return the number of tests represented by the this test object. For
668 \class{TestCase} instances, this will always be \code{1}, but this
669 method is also implemented by the \class{TestSuite} class, which can
670 return larger values.
671\end{methoddesc}
672
673\begin{methoddesc}[TestCase]{defaultTestResult}{}
674 Return the default type of test result object to be used to run this
675 test.
676\end{methoddesc}
677
678\begin{methoddesc}[TestCase]{id}{}
679 Return a string identifying the specific test case. This is usually
680 the full name of the test method, including the module and class
681 names.
682\end{methoddesc}
683
684\begin{methoddesc}[TestCase]{shortDescription}{}
Fred Drakeae55d5f2003-12-31 04:34:50 +0000685 Returns a one-line description of the test, or \constant{None} if no
Fred Drake29be7012001-04-10 22:25:06 +0000686 description has been provided. The default implementation of this
687 method returns the first line of the test method's docstring, if
Fred Drakeae55d5f2003-12-31 04:34:50 +0000688 available, or \constant{None}.
Fred Drake29be7012001-04-10 22:25:06 +0000689\end{methoddesc}
690
Fred Drakeb9ad2282001-04-07 05:41:39 +0000691
692\subsection{TestSuite Objects
693 \label{testsuite-objects}}
694
695\class{TestSuite} objects behave much like \class{TestCase} objects,
696except they do not actually implement a test. Instead, they are used
697to aggregate tests into groups that should be run together. Some
698additional methods are available to add tests to \class{TestSuite}
699instances:
700
701\begin{methoddesc}[TestSuite]{addTest}{test}
702 Add a \class{TestCase} or \class{TestSuite} to the set of tests that
703 make up the suite.
704\end{methoddesc}
705
706\begin{methoddesc}[TestSuite]{addTests}{tests}
707 Add all the tests from a sequence of \class{TestCase} and
708 \class{TestSuite} instances to this test suite.
709\end{methoddesc}
710
Fred Drake4d17b302001-09-06 15:51:56 +0000711The \method{run()} method is also slightly different:
712
713\begin{methoddesc}[TestSuite]{run}{result}
714 Run the tests associated with this suite, collecting the result into
715 the test result object passed as \var{result}. Note that unlike
716 \method{TestCase.run()}, \method{TestSuite.run()} requires the
717 result object to be passed in.
718\end{methoddesc}
719
720In the typical usage of a \class{TestSuite} object, the \method{run()}
721method is invoked by a \class{TestRunner} rather than by the end-user
722test harness.
723
Fred Drakeb9ad2282001-04-07 05:41:39 +0000724
725\subsection{TestResult Objects
726 \label{testresult-objects}}
727
728A \class{TestResult} object stores the results of a set of tests. The
729\class{TestCase} and \class{TestSuite} classes ensure that results are
730properly stored; test authors do not need to worry about recording the
731outcome of tests.
732
733Testing frameworks built on top of \refmodule{unittest} may want
734access to the \class{TestResult} object generated by running a set of
735tests for reporting purposes; a \class{TestResult} instance is
736returned by the \method{TestRunner.run()} method for this purpose.
737
738Each instance holds the total number of tests run, and collections of
739failures and errors that occurred among those test runs. The
740collections contain tuples of \code{(\var{testcase},
Fred Drake387c8b52002-07-02 22:34:44 +0000741\var{traceback})}, where \var{traceback} is a string containing a
742formatted version of the traceback for the exception.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000743
744\class{TestResult} instances have the following attributes that will
745be of interest when inspecting the results of running a set of tests:
746
747\begin{memberdesc}[TestResult]{errors}
748 A list containing pairs of \class{TestCase} instances and the
Fred Drake387c8b52002-07-02 22:34:44 +0000749 formatted tracebacks for tests which raised an exception but did not
750 signal a test failure.
Fred Drakec4126172002-07-02 22:46:42 +0000751 \versionchanged[Contains formatted tracebacks instead of
752 \function{sys.exc_info()} results]{2.2}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000753\end{memberdesc}
754
755\begin{memberdesc}[TestResult]{failures}
756 A list containing pairs of \class{TestCase} instances and the
Fred Drake387c8b52002-07-02 22:34:44 +0000757 formatted tracebacks for tests which signalled a failure in the code
758 under test.
Fred Drakec4126172002-07-02 22:46:42 +0000759 \versionchanged[Contains formatted tracebacks instead of
760 \function{sys.exc_info()} results]{2.2}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000761\end{memberdesc}
762
763\begin{memberdesc}[TestResult]{testsRun}
764 The number of tests which have been started.
765\end{memberdesc}
766
767\begin{methoddesc}[TestResult]{wasSuccessful}{}
768 Returns true if all tests run so far have passed, otherwise returns
769 false.
770\end{methoddesc}
771
772
773The following methods of the \class{TestResult} class are used to
Martin v. Löwis7bdc4842003-09-20 11:09:28 +0000774maintain the internal data structures, and may be extended in
Fred Drakeb9ad2282001-04-07 05:41:39 +0000775subclasses to support additional reporting requirements. This is
Fred Drake8ee679f2001-07-14 02:50:55 +0000776particularly useful in building tools which support interactive
Fred Drakeb9ad2282001-04-07 05:41:39 +0000777reporting while tests are being run.
778
779\begin{methoddesc}[TestResult]{startTest}{test}
780 Called when the test case \var{test} is about to be run.
781\end{methoddesc}
782
783\begin{methoddesc}[TestResult]{stopTest}{test}
784 Called when the test case \var{test} has been executed, regardless
785 of the outcome.
786\end{methoddesc}
787
788\begin{methoddesc}[TestResult]{addError}{test, err}
Fred Drake62a26692001-04-12 19:34:38 +0000789 Called when the test case \var{test} raises an exception without
790 signalling a test failure. \var{err} is a tuple of the form
791 returned by \function{sys.exc_info()}: \code{(\var{type},
792 \var{value}, \var{traceback})}.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000793\end{methoddesc}
794
795\begin{methoddesc}[TestResult]{addFailure}{test, err}
Fred Drake62a26692001-04-12 19:34:38 +0000796 Called when the test case \var{test} signals a failure.
Fred Drake0056a422001-04-12 04:50:06 +0000797 \var{err} is a tuple of the form returned by
798 \function{sys.exc_info()}: \code{(\var{type}, \var{value},
799 \var{traceback})}.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000800\end{methoddesc}
801
802\begin{methoddesc}[TestResult]{addSuccess}{test}
803 This method is called for a test that does not fail; \var{test} is
804 the test case object.
805\end{methoddesc}
806
807
808One additional method is available for \class{TestResult} objects:
809
810\begin{methoddesc}[TestResult]{stop}{}
811 This method can be called to signal that the set of tests being run
812 should be aborted. Once this has been called, the
813 \class{TestRunner} object return to its caller without running any
814 additional tests. This is used by the \class{TextTestRunner} class
815 to stop the test framework when the user signals an interrupt from
Fred Drake8ee679f2001-07-14 02:50:55 +0000816 the keyboard. Interactive tools which provide runners can use this
817 in a similar manner.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000818\end{methoddesc}
Fred Drake62a26692001-04-12 19:34:38 +0000819
820
821\subsection{TestLoader Objects
822 \label{testloader-objects}}
823
824The \class{TestLoader} class is used to create test suites from
825classes and modules. Normally, there is no need to create an instance
826of this class; the \refmodule{unittest} module provides an instance
827that can be shared as the \code{defaultTestLoader} module attribute.
828Using a subclass or instance would allow customization of some
829configurable properties.
830
831\class{TestLoader} objects have the following methods:
832
833\begin{methoddesc}[TestLoader]{loadTestsFromTestCase}{testCaseClass}
834 Return a suite of all tests cases contained in the
835 \class{TestCase}-derived class \class{testCaseClass}.
836\end{methoddesc}
837
838\begin{methoddesc}[TestLoader]{loadTestsFromModule}{module}
839 Return a suite of all tests cases contained in the given module.
840 This method searches \var{module} for classes derived from
841 \class{TestCase} and creates an instance of the class for each test
842 method defined for the class.
843
Fred Drake0aa811c2001-10-20 04:24:09 +0000844 \warning{While using a hierarchy of
Fred Drake62a26692001-04-12 19:34:38 +0000845 \class{Testcase}-derived classes can be convenient in sharing
846 fixtures and helper functions, defining test methods on base classes
847 that are not intended to be instantiated directly does not play well
848 with this method. Doing so, however, can be useful when the
Fred Drake0aa811c2001-10-20 04:24:09 +0000849 fixtures are different and defined in subclasses.}
Fred Drake62a26692001-04-12 19:34:38 +0000850\end{methoddesc}
851
852\begin{methoddesc}[TestLoader]{loadTestsFromName}{name\optional{, module}}
853 Return a suite of all tests cases given a string specifier.
854
Fred Drake4d17b302001-09-06 15:51:56 +0000855 The specifier \var{name} is a ``dotted name'' that may resolve
856 either to a module, a test case class, a test method within a test
857 case class, or a callable object which returns a \class{TestCase} or
858 \class{TestSuite} instance. For example, if you have a module
859 \module{SampleTests} containing a \class{TestCase}-derived class
860 \class{SampleTestCase} with three test methods (\method{test_one()},
861 \method{test_two()}, and \method{test_three()}), the specifier
862 \code{'SampleTests.SampleTestCase'} would cause this method to
863 return a suite which will run all three test methods. Using the
864 specifier \code{'SampleTests.SampleTestCase.test_two'} would cause
865 it to return a test suite which will run only the
866 \method{test_two()} test method. The specifier can refer to modules
867 and packages which have not been imported; they will be imported as
868 a side-effect.
Fred Drake62a26692001-04-12 19:34:38 +0000869
870 The method optionally resolves \var{name} relative to a given module.
871\end{methoddesc}
872
873\begin{methoddesc}[TestLoader]{loadTestsFromNames}{names\optional{, module}}
874 Similar to \method{loadTestsFromName()}, but takes a sequence of
875 names rather than a single name. The return value is a test suite
876 which supports all the tests defined for each name.
877\end{methoddesc}
878
879\begin{methoddesc}[TestLoader]{getTestCaseNames}{testCaseClass}
880 Return a sorted sequence of method names found within
881 \var{testCaseClass}.
882\end{methoddesc}
883
884
885The following attributes of a \class{TestLoader} can be configured
886either by subclassing or assignment on an instance:
887
888\begin{memberdesc}[TestLoader]{testMethodPrefix}
889 String giving the prefix of method names which will be interpreted
890 as test methods. The default value is \code{'test'}.
891\end{memberdesc}
892
893\begin{memberdesc}[TestLoader]{sortTestMethodsUsing}
894 Function to be used to compare method names when sorting them in
895 \method{getTestCaseNames()}. The default value is the built-in
Fred Drakeae55d5f2003-12-31 04:34:50 +0000896 \function{cmp()} function; it can be set to \constant{None} to disable
Fred Drake62a26692001-04-12 19:34:38 +0000897 the sort.
898\end{memberdesc}
899
900\begin{memberdesc}[TestLoader]{suiteClass}
901 Callable object that constructs a test suite from a list of tests.
902 No methods on the resulting object are needed. The default value is
903 the \class{TestSuite} class.
904\end{memberdesc}