blob: 05617c2aa47bbd9fd3f01e7e7eb722e67b26911b [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}
85 \seetitle[http://pyunit.sourceforge.net/]{PyUnit Web Site}{The
86 source for further information on PyUnit.}
87 \seetitle[http://www.XProgramming.com/testfram.htm]{Simple Smalltalk
88 Testing: With Patterns}{Kent Beck's original paper on
89 testing frameworks using the pattern shared by
90 \module{unittest}.}
91\end{seealso}
92
93
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +000094\subsection{Basic example \label{minimal-example}}
Raymond Hettinger9de3c212003-07-10 22:14:41 +000095
96The \module{unittest} module provides a rich set of tools for
97constructing and running tests. This section demonstrates that a
98small subset of the tools suffice to meet the needs of most users.
99
100Here is a short script to test three functions from the
101\refmodule{random} module:
102
103\begin{verbatim}
104import random
105import unittest
106
107class TestSequenceFunctions(unittest.TestCase):
108
109 def setUp(self):
110 self.seq = range(10)
111
112 def testshuffle(self):
113 # make sure the shuffled sequence does not lose any elements
114 random.shuffle(self.seq)
115 self.seq.sort()
116 self.assertEqual(self.seq, range(10))
117
118 def testchoice(self):
119 element = random.choice(self.seq)
120 self.assert_(element in self.seq)
121
122 def testsample(self):
123 self.assertRaises(ValueError, random.sample, self.seq, 20)
124 for element in random.sample(self.seq, 5):
125 self.assert_(element in self.seq)
126
127if __name__ == '__main__':
128 unittest.main()
129\end{verbatim}
130
131A testcase is created by subclassing \code{unittest.TestCase}.
132The three individual tests are defined with methods whose names start with
133the letters \code{test}. This naming convention informs the test runner
134about which methods represent tests.
135
136The crux of each test is a call to \method{assertEqual()} to
137check for an expected result; \method{assert_()} to verify a condition;
138or \method{assertRaises()} to verify that an expected exception gets
139raised. These methods are used instead of the \keyword{assert} statement
140so the test runner can accumulate all test results and produce a report.
141
142When a \method{setUp()} method is defined, the test runner will run that
143method prior to each test. Likewise, if a \method{tearDown()} method is
144defined, the test runner will invoke that method after each test. In the
145example, \method{setUp()} was used to create a fresh sequence for each test.
146
147The final block shows a simple way to run the tests. \code{unittest.main()}
148provides a command line interface to the test script. When run from the
149command line, the above script produces an output that looks like this:
150
151\begin{verbatim}
152...
153----------------------------------------------------------------------
154Ran 3 tests in 0.000s
155
156OK
157\end{verbatim}
158
159Instead of \code{unittest.main()}, there are other ways to run the tests
160with a finer level of control, less terse output, and no requirement to be
161run from the command line. For example, the last two lines may be replaced
162with:
163
164\begin{verbatim}
165suite = unittest.TestSuite()
166suite.addTest(unittest.makeSuite(TestSequenceFunctions))
167unittest.TextTestRunner(verbosity=2).run(suite)
168\end{verbatim}
169
170Running the revised script from the interpreter or another script
171produces the following output:
172
173\begin{verbatim}
174testchoice (__main__.TestSequenceFunctions) ... ok
175testsample (__main__.TestSequenceFunctions) ... ok
176testshuffle (__main__.TestSequenceFunctions) ... ok
177
178----------------------------------------------------------------------
179Ran 3 tests in 0.110s
180
181OK
182\end{verbatim}
183
184The above examples show the most commonly used \module{unittest} features
185which are sufficient to meet many everyday testing needs. The remainder
186of the documentation explores the full feature set from first principles.
187
188
Fred Drakeb9ad2282001-04-07 05:41:39 +0000189\subsection{Organizing test code
190 \label{organizing-tests}}
191
Fred Drake0056a422001-04-12 04:50:06 +0000192The basic building blocks of unit testing are \dfn{test cases} ---
193single scenarios that must be set up and checked for correctness. In
194PyUnit, test cases are represented by instances of the
195\class{TestCase} class in the \refmodule{unittest} module. To make
196your own test cases you must write subclasses of \class{TestCase}, or
197use \class{FunctionTestCase}.
198
199An instance of a \class{TestCase}-derived class is an object that can
200completely run a single test method, together with optional set-up
201and tidy-up code.
202
203The testing code of a \class{TestCase} instance should be entirely
204self contained, such that it can be run either in isolation or in
205arbitrary combination with any number of other test cases.
206
207The simplest test case subclass will simply override the
208\method{runTest()} method in order to perform specific testing code:
209
210\begin{verbatim}
211import unittest
212
213class DefaultWidgetSizeTestCase(unittest.TestCase):
214 def runTest(self):
215 widget = Widget("The widget")
Fred Drake62a26692001-04-12 19:34:38 +0000216 self.failUnless(widget.size() == (50,50), 'incorrect default size')
Fred Drake0056a422001-04-12 04:50:06 +0000217\end{verbatim}
218
Fred Drake62a26692001-04-12 19:34:38 +0000219Note that in order to test something, we use the one of the
220\method{assert*()} or \method{fail*()} methods provided by the
221\class{TestCase} base class. If the test fails when the test case
222runs, an exception will be raised, and the testing framework will
223identify the test case as a \dfn{failure}. Other exceptions that do
224not arise from checks made through the \method{assert*()} and
225\method{fail*()} methods are identified by the testing framework as
226dfn{errors}.
Fred Drake0056a422001-04-12 04:50:06 +0000227
228The way to run a test case will be described later. For now, note
229that to construct an instance of such a test case, we call its
230constructor without arguments:
231
232\begin{verbatim}
233testCase = DefaultWidgetSizeTestCase()
234\end{verbatim}
235
236Now, such test cases can be numerous, and their set-up can be
237repetitive. In the above case, constructing a ``Widget'' in each of
238100 Widget test case subclasses would mean unsightly duplication.
239
240Luckily, we can factor out such set-up code by implementing a method
241called \method{setUp()}, which the testing framework will
242automatically call for us when we run the test:
243
244\begin{verbatim}
245import unittest
246
247class SimpleWidgetTestCase(unittest.TestCase):
248 def setUp(self):
249 self.widget = Widget("The widget")
250
251class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
252 def runTest(self):
Fred Drake62a26692001-04-12 19:34:38 +0000253 self.failUnless(self.widget.size() == (50,50),
254 'incorrect default size')
Fred Drake0056a422001-04-12 04:50:06 +0000255
256class WidgetResizeTestCase(SimpleWidgetTestCase):
257 def runTest(self):
258 self.widget.resize(100,150)
Fred Drake62a26692001-04-12 19:34:38 +0000259 self.failUnless(self.widget.size() == (100,150),
260 'wrong size after resize')
Fred Drake0056a422001-04-12 04:50:06 +0000261\end{verbatim}
262
263If the \method{setUp()} method raises an exception while the test is
264running, the framework will consider the test to have suffered an
265error, and the \method{runTest()} method will not be executed.
266
267Similarly, we can provide a \method{tearDown()} method that tidies up
268after the \method{runTest()} method has been run:
269
270\begin{verbatim}
271import unittest
272
273class SimpleWidgetTestCase(unittest.TestCase):
274 def setUp(self):
275 self.widget = Widget("The widget")
276
277 def tearDown(self):
278 self.widget.dispose()
279 self.widget = None
280\end{verbatim}
281
282If \method{setUp()} succeeded, the \method{tearDown()} method will be
283run regardless of whether or not \method{runTest()} succeeded.
284
285Such a working environment for the testing code is called a
286\dfn{fixture}.
287
288Often, many small test cases will use the same fixture. In this case,
289we would end up subclassing \class{SimpleWidgetTestCase} into many
290small one-method classes such as
291\class{DefaultWidgetSizeTestCase}. This is time-consuming and
292discouraging, so in the same vein as JUnit, PyUnit provides a simpler
293mechanism:
294
295\begin{verbatim}
296import unittest
297
298class WidgetTestCase(unittest.TestCase):
299 def setUp(self):
300 self.widget = Widget("The widget")
301
302 def tearDown(self):
303 self.widget.dispose()
304 self.widget = None
305
306 def testDefaultSize(self):
Fred Drake62a26692001-04-12 19:34:38 +0000307 self.failUnless(self.widget.size() == (50,50),
308 'incorrect default size')
Fred Drake0056a422001-04-12 04:50:06 +0000309
310 def testResize(self):
311 self.widget.resize(100,150)
Fred Drake62a26692001-04-12 19:34:38 +0000312 self.failUnless(self.widget.size() == (100,150),
313 'wrong size after resize')
Fred Drake0056a422001-04-12 04:50:06 +0000314\end{verbatim}
315
316Here we have not provided a \method{runTest()} method, but have
317instead provided two different test methods. Class instances will now
318each run one of the \method{test*()} methods, with \code{self.widget}
319created and destroyed separately for each instance. When creating an
320instance we must specify the test method it is to run. We do this by
321passing the method name in the constructor:
322
323\begin{verbatim}
324defaultSizeTestCase = WidgetTestCase("testDefaultSize")
325resizeTestCase = WidgetTestCase("testResize")
326\end{verbatim}
327
328Test case instances are grouped together according to the features
329they test. PyUnit provides a mechanism for this: the \class{test
330suite}, represented by the class \class{TestSuite} in the
331\refmodule{unittest} module:
332
333\begin{verbatim}
334widgetTestSuite = unittest.TestSuite()
335widgetTestSuite.addTest(WidgetTestCase("testDefaultSize"))
336widgetTestSuite.addTest(WidgetTestCase("testResize"))
337\end{verbatim}
338
339For the ease of running tests, as we will see later, it is a good
340idea to provide in each test module a callable object that returns a
341pre-built test suite:
342
343\begin{verbatim}
344def suite():
345 suite = unittest.TestSuite()
346 suite.addTest(WidgetTestCase("testDefaultSize"))
347 suite.addTest(WidgetTestCase("testResize"))
348 return suite
349\end{verbatim}
350
351or even:
352
353\begin{verbatim}
354class WidgetTestSuite(unittest.TestSuite):
355 def __init__(self):
356 unittest.TestSuite.__init__(self,map(WidgetTestCase,
357 ("testDefaultSize",
358 "testResize")))
359\end{verbatim}
360
361(The latter is admittedly not for the faint-hearted!)
362
363Since it is a common pattern to create a \class{TestCase} subclass
364with many similarly named test functions, there is a convenience
365function called \function{makeSuite()} provided in the
366\refmodule{unittest} module that constructs a test suite that
367comprises all of the test cases in a test case class:
368
369\begin{verbatim}
370suite = unittest.makeSuite(WidgetTestCase,'test')
371\end{verbatim}
372
373Note that when using the \function{makeSuite()} function, the order in
374which the various test cases will be run by the test suite is the
375order determined by sorting the test function names using the
376\function{cmp()} built-in function.
377
378Often it is desirable to group suites of test cases together, so as to
379run tests for the whole system at once. This is easy, since
380\class{TestSuite} instances can be added to a \class{TestSuite} just
381as \class{TestCase} instances can be added to a \class{TestSuite}:
382
383\begin{verbatim}
384suite1 = module1.TheTestSuite()
385suite2 = module2.TheTestSuite()
386alltests = unittest.TestSuite((suite1, suite2))
387\end{verbatim}
388
389You can place the definitions of test cases and test suites in the
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +0000390same modules as the code they are to test (such as \file{widget.py}),
Fred Drake0056a422001-04-12 04:50:06 +0000391but there are several advantages to placing the test code in a
392separate module, such as \file{widgettests.py}:
393
394\begin{itemize}
395 \item The test module can be run standalone from the command line.
396 \item The test code can more easily be separated from shipped code.
Michael W. Hudsonaab02602003-02-10 19:21:16 +0000397 \item There is less temptation to change test code to fit the code
Fred Drake0056a422001-04-12 04:50:06 +0000398 it tests without a good reason.
399 \item Test code should be modified much less frequently than the
400 code it tests.
401 \item Tested code can be refactored more easily.
402 \item Tests for modules written in C must be in separate modules
403 anyway, so why not be consistent?
404 \item If the testing strategy changes, there is no need to change
405 the source code.
406\end{itemize}
407
Fred Drakeb9ad2282001-04-07 05:41:39 +0000408
409\subsection{Re-using old test code
410 \label{legacy-unit-tests}}
411
412Some users will find that they have existing test code that they would
413like to run from PyUnit, without converting every old test function to
414a \class{TestCase} subclass.
415
416For this reason, PyUnit provides a \class{FunctionTestCase} class.
417This subclass of \class{TestCase} can be used to wrap an existing test
418function. Set-up and tear-down functions can also optionally be
419wrapped.
420
421Given the following test function:
422
423\begin{verbatim}
424def testSomething():
425 something = makeSomething()
426 assert something.name is not None
427 # ...
428\end{verbatim}
429
430one can create an equivalent test case instance as follows:
431
432\begin{verbatim}
433testcase = unittest.FunctionTestCase(testSomething)
434\end{verbatim}
435
436If there are additional set-up and tear-down methods that should be
437called as part of the test case's operation, they can also be provided:
438
439\begin{verbatim}
440testcase = unittest.FunctionTestCase(testSomething,
441 setUp=makeSomethingDB,
442 tearDown=deleteSomethingDB)
443\end{verbatim}
444
Fred Drake0aa811c2001-10-20 04:24:09 +0000445\note{PyUnit supports the use of \exception{AssertionError}
Fred Drake0056a422001-04-12 04:50:06 +0000446as an indicator of test failure, but does not recommend it. Future
Fred Drake0aa811c2001-10-20 04:24:09 +0000447versions may treat \exception{AssertionError} differently.}
Fred Drake0056a422001-04-12 04:50:06 +0000448
449
Fred Drakeb9ad2282001-04-07 05:41:39 +0000450\subsection{Classes and functions
451 \label{unittest-contents}}
452
453\begin{classdesc}{TestCase}{}
454 Instances of the \class{TestCase} class represent the smallest
455 testable units in a set of tests. This class is intended to be used
456 as a base class, with specific tests being implemented by concrete
457 subclasses. This class implements the interface needed by the test
458 runner to allow it to drive the test, and methods that the test code
459 can use to check for and report various kinds of failures.
460\end{classdesc}
461
462\begin{classdesc}{FunctionTestCase}{testFunc\optional{,
Fred Drake62a26692001-04-12 19:34:38 +0000463 setUp\optional{, tearDown\optional{, description}}}}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000464 This class implements the portion of the \class{TestCase} interface
465 which allows the test runner to drive the test, but does not provide
466 the methods which test code can use to check and report errors.
467 This is used to create test cases using legacy test code, allowing
468 it to be integrated into a \refmodule{unittest}-based test
469 framework.
470\end{classdesc}
471
Fred Drake29be7012001-04-10 22:25:06 +0000472\begin{classdesc}{TestSuite}{\optional{tests}}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000473 This class represents an aggregation of individual tests cases and
474 test suites. The class presents the interface needed by the test
475 runner to allow it to be run as any other test case, but all the
476 contained tests and test suites are executed. Additional methods
Fred Drake29be7012001-04-10 22:25:06 +0000477 are provided to add test cases and suites to the aggregation. If
478 \var{tests} is given, it must be a sequence of individual tests that
479 will be added to the suite.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000480\end{classdesc}
481
482\begin{classdesc}{TestLoader}{}
Fred Drake29be7012001-04-10 22:25:06 +0000483 This class is responsible for loading tests according to various
484 criteria and returning them wrapped in a \class{TestSuite}.
485 It can load all tests within a given module or \class{TestCase}
486 class. When loading from a module, it considers all
487 \class{TestCase}-derived classes. For each such class, it creates
488 an instance for each method with a name beginning with the string
489 \samp{test}.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000490\end{classdesc}
491
Fred Drake62a26692001-04-12 19:34:38 +0000492\begin{datadesc}{defaultTestLoader}
493 Instance of the \class{TestLoader} class which can be shared. If no
494 customization of the \class{TestLoader} is needed, this instance can
495 always be used instead of creating new instances.
496\end{datadesc}
497
Fred Drakeb9ad2282001-04-07 05:41:39 +0000498\begin{classdesc}{TextTestRunner}{\optional{stream\optional{,
499 descriptions\optional{, verbosity}}}}
Fred Drake29be7012001-04-10 22:25:06 +0000500 A basic test runner implementation which prints results on standard
501 output. It has a few configurable parameters, but is essentially
502 very simple. Graphical applications which run test suites should
503 provide alternate implementations.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000504\end{classdesc}
505
506\begin{funcdesc}{main}{\optional{module\optional{,
507 defaultTest\optional{, argv\optional{,
508 testRunner\optional{, testRunner}}}}}}
Fred Drake0056a422001-04-12 04:50:06 +0000509 A command-line program that runs a set of tests; this is primarily
510 for making test modules conveniently executable. The simplest use
511 for this function is:
Fred Drakeb9ad2282001-04-07 05:41:39 +0000512
513\begin{verbatim}
514if __name__ == '__main__':
515 unittest.main()
516\end{verbatim}
517\end{funcdesc}
518
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +0000519In some cases, the existing tests may have be written using the
520\module{doctest} module. If so, that module provides a
521\class{DocTestSuite} class that can automatically build
522\class{unittest.TestSuite} instances from the existing test code.
523\versionadded{2.3}
524
Fred Drakeb9ad2282001-04-07 05:41:39 +0000525
526\subsection{TestCase Objects
527 \label{testcase-objects}}
528
Fred Drake29be7012001-04-10 22:25:06 +0000529Each \class{TestCase} instance represents a single test, but each
530concrete subclass may be used to define multiple tests --- the
531concrete class represents a single test fixture. The fixture is
532created and cleaned up for each test case.
533
534\class{TestCase} instances provide three groups of methods: one group
535used to run the test, another used by the test implementation to
536check conditions and report failures, and some inquiry methods
537allowing information about the test itself to be gathered.
538
539Methods in the first group are:
540
541\begin{methoddesc}[TestCase]{setUp}{}
542 Method called to prepare the test fixture. This is called
543 immediately before calling the test method; any exception raised by
544 this method will be considered an error rather than a test failure.
545 The default implementation does nothing.
546\end{methoddesc}
547
Fred Drake29be7012001-04-10 22:25:06 +0000548\begin{methoddesc}[TestCase]{tearDown}{}
549 Method called immediately after the test method has been called and
550 the result recorded. This is called even if the test method raised
551 an exception, so the implementation in subclasses may need to be
552 particularly careful about checking internal state. Any exception
553 raised by this method will be considered an error rather than a test
Fred Drake62a26692001-04-12 19:34:38 +0000554 failure. This method will only be called if the \method{setUp()}
555 succeeds, regardless of the outcome of the test method.
556 The default implementation does nothing.
557\end{methoddesc}
558
559\begin{methoddesc}[TestCase]{run}{\optional{result}}
560 Run the test, collecting the result into the test result object
561 passed as \var{result}. If \var{result} is omitted or \code{None},
562 a temporary result object is created and used, but is not made
563 available to the caller. This is equivalent to simply calling the
564 \class{TestCase} instance.
Fred Drake29be7012001-04-10 22:25:06 +0000565\end{methoddesc}
566
567\begin{methoddesc}[TestCase]{debug}{}
568 Run the test without collecting the result. This allows exceptions
569 raised by the test to be propogated to the caller, and can be used
570 to support running tests under a debugger.
571\end{methoddesc}
572
573
Fred Drake0056a422001-04-12 04:50:06 +0000574The test code can use any of the following methods to check for and
Fred Drake62a26692001-04-12 19:34:38 +0000575report failures.
Fred Drake29be7012001-04-10 22:25:06 +0000576
Fred Drake62a26692001-04-12 19:34:38 +0000577\begin{methoddesc}[TestCase]{assert_}{expr\optional{, msg}}
578\methodline{failUnless}{expr\optional{, msg}}
579 Signal a test failure if \var{expr} is false; the explanation for
580 the error will be \var{msg} if given, otherwise it will be
581 \code{None}.
Fred Drake29be7012001-04-10 22:25:06 +0000582\end{methoddesc}
583
Fred Drake62a26692001-04-12 19:34:38 +0000584\begin{methoddesc}[TestCase]{assertEqual}{first, second\optional{, msg}}
585\methodline{failUnlessEqual}{first, second\optional{, msg}}
Fred Drake29be7012001-04-10 22:25:06 +0000586 Test that \var{first} and \var{second} are equal. If the values do
587 not compare equal, the test will fail with the explanation given by
Fred Drake0056a422001-04-12 04:50:06 +0000588 \var{msg}, or \code{None}. Note that using \method{failUnlessEqual()}
Fred Drake29be7012001-04-10 22:25:06 +0000589 improves upon doing the comparison as the first parameter to
Fred Drake62a26692001-04-12 19:34:38 +0000590 \method{failUnless()}: the default value for \var{msg} can be
Fred Drake29be7012001-04-10 22:25:06 +0000591 computed to include representations of both \var{first} and
592 \var{second}.
593\end{methoddesc}
594
Fred Drake62a26692001-04-12 19:34:38 +0000595\begin{methoddesc}[TestCase]{assertNotEqual}{first, second\optional{, msg}}
596\methodline{failIfEqual}{first, second\optional{, msg}}
Fred Drake29be7012001-04-10 22:25:06 +0000597 Test that \var{first} and \var{second} are not equal. If the values
598 do compare equal, the test will fail with the explanation given by
Fred Drake0056a422001-04-12 04:50:06 +0000599 \var{msg}, or \code{None}. Note that using \method{failIfEqual()}
Fred Drake29be7012001-04-10 22:25:06 +0000600 improves upon doing the comparison as the first parameter to
601 \method{failUnless()} is that the default value for \var{msg} can be
602 computed to include representations of both \var{first} and
603 \var{second}.
604\end{methoddesc}
605
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000606\begin{methoddesc}[TestCase]{assertAlmostEqual}{first, second\optional{,
607 places\optional{, msg}}}
608\methodline{failUnlessAlmostEqual}{first, second\optional{,
609 places\optional{, msg}}}
610 Test that \var{first} and \var{second} are approximately equal
611 by computing the difference, rounding to the given number of \var{places},
612 and comparing to zero. Note that comparing a given number of decimal places
613 is not the same as comparing a given number of significant digits.
614 If the values do not compare equal, the test will fail with the explanation
615 given by \var{msg}, or \code{None}.
616\end{methoddesc}
617
618\begin{methoddesc}[TestCase]{assertNotAlmostEqual}{first, second\optional{,
619 places\optional{, msg}}}
620\methodline{failIfAlmostEqual}{first, second\optional{,
621 places\optional{, msg}}}
622 Test that \var{first} and \var{second} are not approximately equal
623 by computing the difference, rounding to the given number of \var{places},
624 and comparing to zero. Note that comparing a given number of decimal places
625 is not the same as comparing a given number of significant digits.
626 If the values do not compare equal, the test will fail with the explanation
627 given by \var{msg}, or \code{None}.
628\end{methoddesc}
629
Fred Drake62a26692001-04-12 19:34:38 +0000630\begin{methoddesc}[TestCase]{assertRaises}{exception, callable, \moreargs}
631\methodline{failUnlessRaises}{exception, callable, \moreargs}
632 Test that an exception is raised when \var{callable} is called with
633 any positional or keyword arguments that are also passed to
634 \method{assertRaises()}. The test passes if \var{exception} is
635 raised, is an error if another exception is raised, or fails if no
636 exception is raised. To catch any of a group of exceptions, a tuple
637 containing the exception classes may be passed as \var{exception}.
638\end{methoddesc}
639
Fred Drake29be7012001-04-10 22:25:06 +0000640\begin{methoddesc}[TestCase]{failIf}{expr\optional{, msg}}
Fred Drake0056a422001-04-12 04:50:06 +0000641 The inverse of the \method{failUnless()} method is the
Fred Drake62a26692001-04-12 19:34:38 +0000642 \method{failIf()} method. This signals a test failure if \var{expr}
643 is true, with \var{msg} or \code{None} for the error message.
Fred Drake29be7012001-04-10 22:25:06 +0000644\end{methoddesc}
645
646\begin{methoddesc}[TestCase]{fail}{\optional{msg}}
Fred Drake62a26692001-04-12 19:34:38 +0000647 Signals a test failure unconditionally, with \var{msg} or
648 \code{None} for the error message.
Fred Drake29be7012001-04-10 22:25:06 +0000649\end{methoddesc}
650
Fred Drake62a26692001-04-12 19:34:38 +0000651\begin{memberdesc}[TestCase]{failureException}
652 This class attribute gives the exception raised by the
653 \method{test()} method. If a test framework needs to use a
654 specialized exception, possibly to carry additional information, it
655 must subclass this exception in order to ``play fair'' with the
656 framework. The initial value of this attribute is
657 \exception{AssertionError}.
658\end{memberdesc}
659
Fred Drake29be7012001-04-10 22:25:06 +0000660
661Testing frameworks can use the following methods to collect
662information on the test:
663
664\begin{methoddesc}[TestCase]{countTestCases}{}
665 Return the number of tests represented by the this test object. For
666 \class{TestCase} instances, this will always be \code{1}, but this
667 method is also implemented by the \class{TestSuite} class, which can
668 return larger values.
669\end{methoddesc}
670
671\begin{methoddesc}[TestCase]{defaultTestResult}{}
672 Return the default type of test result object to be used to run this
673 test.
674\end{methoddesc}
675
676\begin{methoddesc}[TestCase]{id}{}
677 Return a string identifying the specific test case. This is usually
678 the full name of the test method, including the module and class
679 names.
680\end{methoddesc}
681
682\begin{methoddesc}[TestCase]{shortDescription}{}
683 Returns a one-line description of the test, or \code{None} if no
684 description has been provided. The default implementation of this
685 method returns the first line of the test method's docstring, if
686 available, or \code{None}.
687\end{methoddesc}
688
Fred Drakeb9ad2282001-04-07 05:41:39 +0000689
690\subsection{TestSuite Objects
691 \label{testsuite-objects}}
692
693\class{TestSuite} objects behave much like \class{TestCase} objects,
694except they do not actually implement a test. Instead, they are used
695to aggregate tests into groups that should be run together. Some
696additional methods are available to add tests to \class{TestSuite}
697instances:
698
699\begin{methoddesc}[TestSuite]{addTest}{test}
700 Add a \class{TestCase} or \class{TestSuite} to the set of tests that
701 make up the suite.
702\end{methoddesc}
703
704\begin{methoddesc}[TestSuite]{addTests}{tests}
705 Add all the tests from a sequence of \class{TestCase} and
706 \class{TestSuite} instances to this test suite.
707\end{methoddesc}
708
Fred Drake4d17b302001-09-06 15:51:56 +0000709The \method{run()} method is also slightly different:
710
711\begin{methoddesc}[TestSuite]{run}{result}
712 Run the tests associated with this suite, collecting the result into
713 the test result object passed as \var{result}. Note that unlike
714 \method{TestCase.run()}, \method{TestSuite.run()} requires the
715 result object to be passed in.
716\end{methoddesc}
717
718In the typical usage of a \class{TestSuite} object, the \method{run()}
719method is invoked by a \class{TestRunner} rather than by the end-user
720test harness.
721
Fred Drakeb9ad2282001-04-07 05:41:39 +0000722
723\subsection{TestResult Objects
724 \label{testresult-objects}}
725
726A \class{TestResult} object stores the results of a set of tests. The
727\class{TestCase} and \class{TestSuite} classes ensure that results are
728properly stored; test authors do not need to worry about recording the
729outcome of tests.
730
731Testing frameworks built on top of \refmodule{unittest} may want
732access to the \class{TestResult} object generated by running a set of
733tests for reporting purposes; a \class{TestResult} instance is
734returned by the \method{TestRunner.run()} method for this purpose.
735
736Each instance holds the total number of tests run, and collections of
737failures and errors that occurred among those test runs. The
738collections contain tuples of \code{(\var{testcase},
Fred Drake387c8b52002-07-02 22:34:44 +0000739\var{traceback})}, where \var{traceback} is a string containing a
740formatted version of the traceback for the exception.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000741
742\class{TestResult} instances have the following attributes that will
743be of interest when inspecting the results of running a set of tests:
744
745\begin{memberdesc}[TestResult]{errors}
746 A list containing pairs of \class{TestCase} instances and the
Fred Drake387c8b52002-07-02 22:34:44 +0000747 formatted tracebacks for tests which raised an exception but did not
748 signal a test failure.
Fred Drakec4126172002-07-02 22:46:42 +0000749 \versionchanged[Contains formatted tracebacks instead of
750 \function{sys.exc_info()} results]{2.2}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000751\end{memberdesc}
752
753\begin{memberdesc}[TestResult]{failures}
754 A list containing pairs of \class{TestCase} instances and the
Fred Drake387c8b52002-07-02 22:34:44 +0000755 formatted tracebacks for tests which signalled a failure in the code
756 under test.
Fred Drakec4126172002-07-02 22:46:42 +0000757 \versionchanged[Contains formatted tracebacks instead of
758 \function{sys.exc_info()} results]{2.2}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000759\end{memberdesc}
760
761\begin{memberdesc}[TestResult]{testsRun}
762 The number of tests which have been started.
763\end{memberdesc}
764
765\begin{methoddesc}[TestResult]{wasSuccessful}{}
766 Returns true if all tests run so far have passed, otherwise returns
767 false.
768\end{methoddesc}
769
770
771The following methods of the \class{TestResult} class are used to
Martin v. Löwis7bdc4842003-09-20 11:09:28 +0000772maintain the internal data structures, and may be extended in
Fred Drakeb9ad2282001-04-07 05:41:39 +0000773subclasses to support additional reporting requirements. This is
Fred Drake8ee679f2001-07-14 02:50:55 +0000774particularly useful in building tools which support interactive
Fred Drakeb9ad2282001-04-07 05:41:39 +0000775reporting while tests are being run.
776
777\begin{methoddesc}[TestResult]{startTest}{test}
778 Called when the test case \var{test} is about to be run.
779\end{methoddesc}
780
781\begin{methoddesc}[TestResult]{stopTest}{test}
782 Called when the test case \var{test} has been executed, regardless
783 of the outcome.
784\end{methoddesc}
785
786\begin{methoddesc}[TestResult]{addError}{test, err}
Fred Drake62a26692001-04-12 19:34:38 +0000787 Called when the test case \var{test} raises an exception without
788 signalling a test failure. \var{err} is a tuple of the form
789 returned by \function{sys.exc_info()}: \code{(\var{type},
790 \var{value}, \var{traceback})}.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000791\end{methoddesc}
792
793\begin{methoddesc}[TestResult]{addFailure}{test, err}
Fred Drake62a26692001-04-12 19:34:38 +0000794 Called when the test case \var{test} signals a failure.
Fred Drake0056a422001-04-12 04:50:06 +0000795 \var{err} is a tuple of the form returned by
796 \function{sys.exc_info()}: \code{(\var{type}, \var{value},
797 \var{traceback})}.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000798\end{methoddesc}
799
800\begin{methoddesc}[TestResult]{addSuccess}{test}
801 This method is called for a test that does not fail; \var{test} is
802 the test case object.
803\end{methoddesc}
804
805
806One additional method is available for \class{TestResult} objects:
807
808\begin{methoddesc}[TestResult]{stop}{}
809 This method can be called to signal that the set of tests being run
810 should be aborted. Once this has been called, the
811 \class{TestRunner} object return to its caller without running any
812 additional tests. This is used by the \class{TextTestRunner} class
813 to stop the test framework when the user signals an interrupt from
Fred Drake8ee679f2001-07-14 02:50:55 +0000814 the keyboard. Interactive tools which provide runners can use this
815 in a similar manner.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000816\end{methoddesc}
Fred Drake62a26692001-04-12 19:34:38 +0000817
818
819\subsection{TestLoader Objects
820 \label{testloader-objects}}
821
822The \class{TestLoader} class is used to create test suites from
823classes and modules. Normally, there is no need to create an instance
824of this class; the \refmodule{unittest} module provides an instance
825that can be shared as the \code{defaultTestLoader} module attribute.
826Using a subclass or instance would allow customization of some
827configurable properties.
828
829\class{TestLoader} objects have the following methods:
830
831\begin{methoddesc}[TestLoader]{loadTestsFromTestCase}{testCaseClass}
832 Return a suite of all tests cases contained in the
833 \class{TestCase}-derived class \class{testCaseClass}.
834\end{methoddesc}
835
836\begin{methoddesc}[TestLoader]{loadTestsFromModule}{module}
837 Return a suite of all tests cases contained in the given module.
838 This method searches \var{module} for classes derived from
839 \class{TestCase} and creates an instance of the class for each test
840 method defined for the class.
841
Fred Drake0aa811c2001-10-20 04:24:09 +0000842 \warning{While using a hierarchy of
Fred Drake62a26692001-04-12 19:34:38 +0000843 \class{Testcase}-derived classes can be convenient in sharing
844 fixtures and helper functions, defining test methods on base classes
845 that are not intended to be instantiated directly does not play well
846 with this method. Doing so, however, can be useful when the
Fred Drake0aa811c2001-10-20 04:24:09 +0000847 fixtures are different and defined in subclasses.}
Fred Drake62a26692001-04-12 19:34:38 +0000848\end{methoddesc}
849
850\begin{methoddesc}[TestLoader]{loadTestsFromName}{name\optional{, module}}
851 Return a suite of all tests cases given a string specifier.
852
Fred Drake4d17b302001-09-06 15:51:56 +0000853 The specifier \var{name} is a ``dotted name'' that may resolve
854 either to a module, a test case class, a test method within a test
855 case class, or a callable object which returns a \class{TestCase} or
856 \class{TestSuite} instance. For example, if you have a module
857 \module{SampleTests} containing a \class{TestCase}-derived class
858 \class{SampleTestCase} with three test methods (\method{test_one()},
859 \method{test_two()}, and \method{test_three()}), the specifier
860 \code{'SampleTests.SampleTestCase'} would cause this method to
861 return a suite which will run all three test methods. Using the
862 specifier \code{'SampleTests.SampleTestCase.test_two'} would cause
863 it to return a test suite which will run only the
864 \method{test_two()} test method. The specifier can refer to modules
865 and packages which have not been imported; they will be imported as
866 a side-effect.
Fred Drake62a26692001-04-12 19:34:38 +0000867
868 The method optionally resolves \var{name} relative to a given module.
869\end{methoddesc}
870
871\begin{methoddesc}[TestLoader]{loadTestsFromNames}{names\optional{, module}}
872 Similar to \method{loadTestsFromName()}, but takes a sequence of
873 names rather than a single name. The return value is a test suite
874 which supports all the tests defined for each name.
875\end{methoddesc}
876
877\begin{methoddesc}[TestLoader]{getTestCaseNames}{testCaseClass}
878 Return a sorted sequence of method names found within
879 \var{testCaseClass}.
880\end{methoddesc}
881
882
883The following attributes of a \class{TestLoader} can be configured
884either by subclassing or assignment on an instance:
885
886\begin{memberdesc}[TestLoader]{testMethodPrefix}
887 String giving the prefix of method names which will be interpreted
888 as test methods. The default value is \code{'test'}.
889\end{memberdesc}
890
891\begin{memberdesc}[TestLoader]{sortTestMethodsUsing}
892 Function to be used to compare method names when sorting them in
893 \method{getTestCaseNames()}. The default value is the built-in
894 \function{cmp()} function; it can be set to \code{None} to disable
895 the sort.
896\end{memberdesc}
897
898\begin{memberdesc}[TestLoader]{suiteClass}
899 Callable object that constructs a test suite from a list of tests.
900 No methods on the resulting object are needed. The default value is
901 the \class{TestSuite} class.
902\end{memberdesc}
Fred Drake387c8b52002-07-02 22:34:44 +0000903
904
905\subsection{Getting Extended Error Information
906 \label{unittest-error-info}}
907
908Some applications can make use of more error information (for example,
909an integrated development environment, or IDE). Such an application
910can retrieve supplemental information about errors and failures by
911using an alternate \class{TestResult} implementation, and extending
912the \method{defaultTestResult()} method of the \class{TestCase} class
913to provide it.
914
915Here is a brief example of a \class{TestResult} subclass which stores
916the actual exception and traceback objects. (Be aware that storing
917traceback objects can cause a great deal of memory not to be reclaimed
918when it otherwise would be, which can have effects that affect the
919behavior of the tests.)
920
921\begin{verbatim}
922import unittest
923
924class MyTestCase(unittest.TestCase):
925 def defaultTestResult(self):
926 return MyTestResult()
927
928class MyTestResult(unittest.TestResult):
929 def __init__(self):
930 self.errors_tb = []
931 self.failures_tb = []
932
933 def addError(self, test, err):
934 self.errors_tb.append((test, err))
935 unittest.TestResult.addError(self, test, err)
936
937 def addFailure(self, test, err):
938 self.failures_tb.append((test, err))
939 unittest.TestResult.addFailure(self, test, err)
940\end{verbatim}
941
942Tests written using \class{MyTestCase} as the base class, instead of
943\class{TestCase}, will allow tools to extract additional information
944from the results object.