blob: 5350edc2d7b0869e6196dc24f759e1eafe744311 [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 Hettinger9de3c212003-07-10 22:14:41 +000094\subsection{Minimal example \label{minimal-example}}
95
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
390same modules as the code they are to test (e.g.\ \file{widget.py}),
391but 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
519
520\subsection{TestCase Objects
521 \label{testcase-objects}}
522
Fred Drake29be7012001-04-10 22:25:06 +0000523Each \class{TestCase} instance represents a single test, but each
524concrete subclass may be used to define multiple tests --- the
525concrete class represents a single test fixture. The fixture is
526created and cleaned up for each test case.
527
528\class{TestCase} instances provide three groups of methods: one group
529used to run the test, another used by the test implementation to
530check conditions and report failures, and some inquiry methods
531allowing information about the test itself to be gathered.
532
533Methods in the first group are:
534
535\begin{methoddesc}[TestCase]{setUp}{}
536 Method called to prepare the test fixture. This is called
537 immediately before calling the test method; any exception raised by
538 this method will be considered an error rather than a test failure.
539 The default implementation does nothing.
540\end{methoddesc}
541
Fred Drake29be7012001-04-10 22:25:06 +0000542\begin{methoddesc}[TestCase]{tearDown}{}
543 Method called immediately after the test method has been called and
544 the result recorded. This is called even if the test method raised
545 an exception, so the implementation in subclasses may need to be
546 particularly careful about checking internal state. Any exception
547 raised by this method will be considered an error rather than a test
Fred Drake62a26692001-04-12 19:34:38 +0000548 failure. This method will only be called if the \method{setUp()}
549 succeeds, regardless of the outcome of the test method.
550 The default implementation does nothing.
551\end{methoddesc}
552
553\begin{methoddesc}[TestCase]{run}{\optional{result}}
554 Run the test, collecting the result into the test result object
555 passed as \var{result}. If \var{result} is omitted or \code{None},
556 a temporary result object is created and used, but is not made
557 available to the caller. This is equivalent to simply calling the
558 \class{TestCase} instance.
Fred Drake29be7012001-04-10 22:25:06 +0000559\end{methoddesc}
560
561\begin{methoddesc}[TestCase]{debug}{}
562 Run the test without collecting the result. This allows exceptions
563 raised by the test to be propogated to the caller, and can be used
564 to support running tests under a debugger.
565\end{methoddesc}
566
567
Fred Drake0056a422001-04-12 04:50:06 +0000568The test code can use any of the following methods to check for and
Fred Drake62a26692001-04-12 19:34:38 +0000569report failures.
Fred Drake29be7012001-04-10 22:25:06 +0000570
Fred Drake62a26692001-04-12 19:34:38 +0000571\begin{methoddesc}[TestCase]{assert_}{expr\optional{, msg}}
572\methodline{failUnless}{expr\optional{, msg}}
573 Signal a test failure if \var{expr} is false; the explanation for
574 the error will be \var{msg} if given, otherwise it will be
575 \code{None}.
Fred Drake29be7012001-04-10 22:25:06 +0000576\end{methoddesc}
577
Fred Drake62a26692001-04-12 19:34:38 +0000578\begin{methoddesc}[TestCase]{assertEqual}{first, second\optional{, msg}}
579\methodline{failUnlessEqual}{first, second\optional{, msg}}
Fred Drake29be7012001-04-10 22:25:06 +0000580 Test that \var{first} and \var{second} are equal. If the values do
581 not compare equal, the test will fail with the explanation given by
Fred Drake0056a422001-04-12 04:50:06 +0000582 \var{msg}, or \code{None}. Note that using \method{failUnlessEqual()}
Fred Drake29be7012001-04-10 22:25:06 +0000583 improves upon doing the comparison as the first parameter to
Fred Drake62a26692001-04-12 19:34:38 +0000584 \method{failUnless()}: the default value for \var{msg} can be
Fred Drake29be7012001-04-10 22:25:06 +0000585 computed to include representations of both \var{first} and
586 \var{second}.
587\end{methoddesc}
588
Fred Drake62a26692001-04-12 19:34:38 +0000589\begin{methoddesc}[TestCase]{assertNotEqual}{first, second\optional{, msg}}
590\methodline{failIfEqual}{first, second\optional{, msg}}
Fred Drake29be7012001-04-10 22:25:06 +0000591 Test that \var{first} and \var{second} are not equal. If the values
592 do compare equal, the test will fail with the explanation given by
Fred Drake0056a422001-04-12 04:50:06 +0000593 \var{msg}, or \code{None}. Note that using \method{failIfEqual()}
Fred Drake29be7012001-04-10 22:25:06 +0000594 improves upon doing the comparison as the first parameter to
595 \method{failUnless()} is that the default value for \var{msg} can be
596 computed to include representations of both \var{first} and
597 \var{second}.
598\end{methoddesc}
599
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000600\begin{methoddesc}[TestCase]{assertAlmostEqual}{first, second\optional{,
601 places\optional{, msg}}}
602\methodline{failUnlessAlmostEqual}{first, second\optional{,
603 places\optional{, msg}}}
604 Test that \var{first} and \var{second} are approximately equal
605 by computing the difference, rounding to the given number of \var{places},
606 and comparing to zero. Note that comparing a given number of decimal places
607 is not the same as comparing a given number of significant digits.
608 If the values do not compare equal, the test will fail with the explanation
609 given by \var{msg}, or \code{None}.
610\end{methoddesc}
611
612\begin{methoddesc}[TestCase]{assertNotAlmostEqual}{first, second\optional{,
613 places\optional{, msg}}}
614\methodline{failIfAlmostEqual}{first, second\optional{,
615 places\optional{, msg}}}
616 Test that \var{first} and \var{second} are not approximately equal
617 by computing the difference, rounding to the given number of \var{places},
618 and comparing to zero. Note that comparing a given number of decimal places
619 is not the same as comparing a given number of significant digits.
620 If the values do not compare equal, the test will fail with the explanation
621 given by \var{msg}, or \code{None}.
622\end{methoddesc}
623
Fred Drake62a26692001-04-12 19:34:38 +0000624\begin{methoddesc}[TestCase]{assertRaises}{exception, callable, \moreargs}
625\methodline{failUnlessRaises}{exception, callable, \moreargs}
626 Test that an exception is raised when \var{callable} is called with
627 any positional or keyword arguments that are also passed to
628 \method{assertRaises()}. The test passes if \var{exception} is
629 raised, is an error if another exception is raised, or fails if no
630 exception is raised. To catch any of a group of exceptions, a tuple
631 containing the exception classes may be passed as \var{exception}.
632\end{methoddesc}
633
Fred Drake29be7012001-04-10 22:25:06 +0000634\begin{methoddesc}[TestCase]{failIf}{expr\optional{, msg}}
Fred Drake0056a422001-04-12 04:50:06 +0000635 The inverse of the \method{failUnless()} method is the
Fred Drake62a26692001-04-12 19:34:38 +0000636 \method{failIf()} method. This signals a test failure if \var{expr}
637 is true, with \var{msg} or \code{None} for the error message.
Fred Drake29be7012001-04-10 22:25:06 +0000638\end{methoddesc}
639
640\begin{methoddesc}[TestCase]{fail}{\optional{msg}}
Fred Drake62a26692001-04-12 19:34:38 +0000641 Signals a test failure unconditionally, with \var{msg} or
642 \code{None} for the error message.
Fred Drake29be7012001-04-10 22:25:06 +0000643\end{methoddesc}
644
Fred Drake62a26692001-04-12 19:34:38 +0000645\begin{memberdesc}[TestCase]{failureException}
646 This class attribute gives the exception raised by the
647 \method{test()} method. If a test framework needs to use a
648 specialized exception, possibly to carry additional information, it
649 must subclass this exception in order to ``play fair'' with the
650 framework. The initial value of this attribute is
651 \exception{AssertionError}.
652\end{memberdesc}
653
Fred Drake29be7012001-04-10 22:25:06 +0000654
655Testing frameworks can use the following methods to collect
656information on the test:
657
658\begin{methoddesc}[TestCase]{countTestCases}{}
659 Return the number of tests represented by the this test object. For
660 \class{TestCase} instances, this will always be \code{1}, but this
661 method is also implemented by the \class{TestSuite} class, which can
662 return larger values.
663\end{methoddesc}
664
665\begin{methoddesc}[TestCase]{defaultTestResult}{}
666 Return the default type of test result object to be used to run this
667 test.
668\end{methoddesc}
669
670\begin{methoddesc}[TestCase]{id}{}
671 Return a string identifying the specific test case. This is usually
672 the full name of the test method, including the module and class
673 names.
674\end{methoddesc}
675
676\begin{methoddesc}[TestCase]{shortDescription}{}
677 Returns a one-line description of the test, or \code{None} if no
678 description has been provided. The default implementation of this
679 method returns the first line of the test method's docstring, if
680 available, or \code{None}.
681\end{methoddesc}
682
Fred Drakeb9ad2282001-04-07 05:41:39 +0000683
684\subsection{TestSuite Objects
685 \label{testsuite-objects}}
686
687\class{TestSuite} objects behave much like \class{TestCase} objects,
688except they do not actually implement a test. Instead, they are used
689to aggregate tests into groups that should be run together. Some
690additional methods are available to add tests to \class{TestSuite}
691instances:
692
693\begin{methoddesc}[TestSuite]{addTest}{test}
694 Add a \class{TestCase} or \class{TestSuite} to the set of tests that
695 make up the suite.
696\end{methoddesc}
697
698\begin{methoddesc}[TestSuite]{addTests}{tests}
699 Add all the tests from a sequence of \class{TestCase} and
700 \class{TestSuite} instances to this test suite.
701\end{methoddesc}
702
Fred Drake4d17b302001-09-06 15:51:56 +0000703The \method{run()} method is also slightly different:
704
705\begin{methoddesc}[TestSuite]{run}{result}
706 Run the tests associated with this suite, collecting the result into
707 the test result object passed as \var{result}. Note that unlike
708 \method{TestCase.run()}, \method{TestSuite.run()} requires the
709 result object to be passed in.
710\end{methoddesc}
711
712In the typical usage of a \class{TestSuite} object, the \method{run()}
713method is invoked by a \class{TestRunner} rather than by the end-user
714test harness.
715
Fred Drakeb9ad2282001-04-07 05:41:39 +0000716
717\subsection{TestResult Objects
718 \label{testresult-objects}}
719
720A \class{TestResult} object stores the results of a set of tests. The
721\class{TestCase} and \class{TestSuite} classes ensure that results are
722properly stored; test authors do not need to worry about recording the
723outcome of tests.
724
725Testing frameworks built on top of \refmodule{unittest} may want
726access to the \class{TestResult} object generated by running a set of
727tests for reporting purposes; a \class{TestResult} instance is
728returned by the \method{TestRunner.run()} method for this purpose.
729
730Each instance holds the total number of tests run, and collections of
731failures and errors that occurred among those test runs. The
732collections contain tuples of \code{(\var{testcase},
Fred Drake387c8b52002-07-02 22:34:44 +0000733\var{traceback})}, where \var{traceback} is a string containing a
734formatted version of the traceback for the exception.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000735
736\class{TestResult} instances have the following attributes that will
737be of interest when inspecting the results of running a set of tests:
738
739\begin{memberdesc}[TestResult]{errors}
740 A list containing pairs of \class{TestCase} instances and the
Fred Drake387c8b52002-07-02 22:34:44 +0000741 formatted tracebacks for tests which raised an exception but did not
742 signal a test failure.
Fred Drakec4126172002-07-02 22:46:42 +0000743 \versionchanged[Contains formatted tracebacks instead of
744 \function{sys.exc_info()} results]{2.2}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000745\end{memberdesc}
746
747\begin{memberdesc}[TestResult]{failures}
748 A list containing pairs of \class{TestCase} instances and the
Fred Drake387c8b52002-07-02 22:34:44 +0000749 formatted tracebacks for tests which signalled a failure in the code
750 under test.
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]{testsRun}
756 The number of tests which have been started.
757\end{memberdesc}
758
759\begin{methoddesc}[TestResult]{wasSuccessful}{}
760 Returns true if all tests run so far have passed, otherwise returns
761 false.
762\end{methoddesc}
763
764
765The following methods of the \class{TestResult} class are used to
766maintain the internal data structures, and mmay be extended in
767subclasses to support additional reporting requirements. This is
Fred Drake8ee679f2001-07-14 02:50:55 +0000768particularly useful in building tools which support interactive
Fred Drakeb9ad2282001-04-07 05:41:39 +0000769reporting while tests are being run.
770
771\begin{methoddesc}[TestResult]{startTest}{test}
772 Called when the test case \var{test} is about to be run.
773\end{methoddesc}
774
775\begin{methoddesc}[TestResult]{stopTest}{test}
776 Called when the test case \var{test} has been executed, regardless
777 of the outcome.
778\end{methoddesc}
779
780\begin{methoddesc}[TestResult]{addError}{test, err}
Fred Drake62a26692001-04-12 19:34:38 +0000781 Called when the test case \var{test} raises an exception without
782 signalling a test failure. \var{err} is a tuple of the form
783 returned by \function{sys.exc_info()}: \code{(\var{type},
784 \var{value}, \var{traceback})}.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000785\end{methoddesc}
786
787\begin{methoddesc}[TestResult]{addFailure}{test, err}
Fred Drake62a26692001-04-12 19:34:38 +0000788 Called when the test case \var{test} signals a failure.
Fred Drake0056a422001-04-12 04:50:06 +0000789 \var{err} is a tuple of the form returned by
790 \function{sys.exc_info()}: \code{(\var{type}, \var{value},
791 \var{traceback})}.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000792\end{methoddesc}
793
794\begin{methoddesc}[TestResult]{addSuccess}{test}
795 This method is called for a test that does not fail; \var{test} is
796 the test case object.
797\end{methoddesc}
798
799
800One additional method is available for \class{TestResult} objects:
801
802\begin{methoddesc}[TestResult]{stop}{}
803 This method can be called to signal that the set of tests being run
804 should be aborted. Once this has been called, the
805 \class{TestRunner} object return to its caller without running any
806 additional tests. This is used by the \class{TextTestRunner} class
807 to stop the test framework when the user signals an interrupt from
Fred Drake8ee679f2001-07-14 02:50:55 +0000808 the keyboard. Interactive tools which provide runners can use this
809 in a similar manner.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000810\end{methoddesc}
Fred Drake62a26692001-04-12 19:34:38 +0000811
812
813\subsection{TestLoader Objects
814 \label{testloader-objects}}
815
816The \class{TestLoader} class is used to create test suites from
817classes and modules. Normally, there is no need to create an instance
818of this class; the \refmodule{unittest} module provides an instance
819that can be shared as the \code{defaultTestLoader} module attribute.
820Using a subclass or instance would allow customization of some
821configurable properties.
822
823\class{TestLoader} objects have the following methods:
824
825\begin{methoddesc}[TestLoader]{loadTestsFromTestCase}{testCaseClass}
826 Return a suite of all tests cases contained in the
827 \class{TestCase}-derived class \class{testCaseClass}.
828\end{methoddesc}
829
830\begin{methoddesc}[TestLoader]{loadTestsFromModule}{module}
831 Return a suite of all tests cases contained in the given module.
832 This method searches \var{module} for classes derived from
833 \class{TestCase} and creates an instance of the class for each test
834 method defined for the class.
835
Fred Drake0aa811c2001-10-20 04:24:09 +0000836 \warning{While using a hierarchy of
Fred Drake62a26692001-04-12 19:34:38 +0000837 \class{Testcase}-derived classes can be convenient in sharing
838 fixtures and helper functions, defining test methods on base classes
839 that are not intended to be instantiated directly does not play well
840 with this method. Doing so, however, can be useful when the
Fred Drake0aa811c2001-10-20 04:24:09 +0000841 fixtures are different and defined in subclasses.}
Fred Drake62a26692001-04-12 19:34:38 +0000842\end{methoddesc}
843
844\begin{methoddesc}[TestLoader]{loadTestsFromName}{name\optional{, module}}
845 Return a suite of all tests cases given a string specifier.
846
Fred Drake4d17b302001-09-06 15:51:56 +0000847 The specifier \var{name} is a ``dotted name'' that may resolve
848 either to a module, a test case class, a test method within a test
849 case class, or a callable object which returns a \class{TestCase} or
850 \class{TestSuite} instance. For example, if you have a module
851 \module{SampleTests} containing a \class{TestCase}-derived class
852 \class{SampleTestCase} with three test methods (\method{test_one()},
853 \method{test_two()}, and \method{test_three()}), the specifier
854 \code{'SampleTests.SampleTestCase'} would cause this method to
855 return a suite which will run all three test methods. Using the
856 specifier \code{'SampleTests.SampleTestCase.test_two'} would cause
857 it to return a test suite which will run only the
858 \method{test_two()} test method. The specifier can refer to modules
859 and packages which have not been imported; they will be imported as
860 a side-effect.
Fred Drake62a26692001-04-12 19:34:38 +0000861
862 The method optionally resolves \var{name} relative to a given module.
863\end{methoddesc}
864
865\begin{methoddesc}[TestLoader]{loadTestsFromNames}{names\optional{, module}}
866 Similar to \method{loadTestsFromName()}, but takes a sequence of
867 names rather than a single name. The return value is a test suite
868 which supports all the tests defined for each name.
869\end{methoddesc}
870
871\begin{methoddesc}[TestLoader]{getTestCaseNames}{testCaseClass}
872 Return a sorted sequence of method names found within
873 \var{testCaseClass}.
874\end{methoddesc}
875
876
877The following attributes of a \class{TestLoader} can be configured
878either by subclassing or assignment on an instance:
879
880\begin{memberdesc}[TestLoader]{testMethodPrefix}
881 String giving the prefix of method names which will be interpreted
882 as test methods. The default value is \code{'test'}.
883\end{memberdesc}
884
885\begin{memberdesc}[TestLoader]{sortTestMethodsUsing}
886 Function to be used to compare method names when sorting them in
887 \method{getTestCaseNames()}. The default value is the built-in
888 \function{cmp()} function; it can be set to \code{None} to disable
889 the sort.
890\end{memberdesc}
891
892\begin{memberdesc}[TestLoader]{suiteClass}
893 Callable object that constructs a test suite from a list of tests.
894 No methods on the resulting object are needed. The default value is
895 the \class{TestSuite} class.
896\end{memberdesc}
Fred Drake387c8b52002-07-02 22:34:44 +0000897
898
899\subsection{Getting Extended Error Information
900 \label{unittest-error-info}}
901
902Some applications can make use of more error information (for example,
903an integrated development environment, or IDE). Such an application
904can retrieve supplemental information about errors and failures by
905using an alternate \class{TestResult} implementation, and extending
906the \method{defaultTestResult()} method of the \class{TestCase} class
907to provide it.
908
909Here is a brief example of a \class{TestResult} subclass which stores
910the actual exception and traceback objects. (Be aware that storing
911traceback objects can cause a great deal of memory not to be reclaimed
912when it otherwise would be, which can have effects that affect the
913behavior of the tests.)
914
915\begin{verbatim}
916import unittest
917
918class MyTestCase(unittest.TestCase):
919 def defaultTestResult(self):
920 return MyTestResult()
921
922class MyTestResult(unittest.TestResult):
923 def __init__(self):
924 self.errors_tb = []
925 self.failures_tb = []
926
927 def addError(self, test, err):
928 self.errors_tb.append((test, err))
929 unittest.TestResult.addError(self, test, err)
930
931 def addFailure(self, test, err):
932 self.failures_tb.append((test, err))
933 unittest.TestResult.addFailure(self, test, err)
934\end{verbatim}
935
936Tests written using \class{MyTestCase} as the base class, instead of
937\class{TestCase}, will allow tools to extract additional information
938from the results object.