blob: fa198c736a7fb8f19913b81f9a64b00849ed2d69 [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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013The Python unit testing framework, sometimes referred to as ``PyUnit,'' is
Fred Drakeb9ad2282001-04-07 05:41:39 +000014a 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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019\module{unittest} supports test automation, sharing of setup and shutdown
20code for tests, aggregation of tests into collections, and independence of
Fred Drakeb9ad2282001-04-07 05:41:39 +000021the 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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025To achieve this, \module{unittest} 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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000036specific response to a particular set of inputs. \module{unittest}
37provides a base class, \class{TestCase}, which may be used to create
38new test cases.
Fred Drakeb9ad2282001-04-07 05:41:39 +000039
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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000056integrating existing test code with a \module{unittest}-driven framework.
57When building test fixtures using \class{TestCase}, the \method{setUp()}
Fred Drake62a26692001-04-12 19:34:38 +000058and \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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076\class{TestResult} is provided for use as the result object.
77\module{unittest} provides the \class{TextTestRunner} as an example
78test runner which reports test results on the standard error stream by
79default. Alternate runners can be implemented for other environments
80(such as graphical environments) without any need to derive from a
81specific class.
Fred Drake62a26692001-04-12 19:34:38 +000082
Fred Drakeb9ad2282001-04-07 05:41:39 +000083
84\begin{seealso}
Fred Drakeae55d5f2003-12-31 04:34:50 +000085 \seemodule{doctest}{Another test-support module with a very
86 different flavor.}
Fred Drakeb9ad2282001-04-07 05:41:39 +000087 \seetitle[http://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
Guido van Rossumd8faa362007-04-27 19:54:29 +000094\subsection{Basic example \label{unittest-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
Fred Drakeae55d5f2003-12-31 04:34:50 +0000131A testcase is created by subclassing \class{unittest.TestCase}.
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000132The three individual tests are defined with methods whose names start with
Fred Drakeae55d5f2003-12-31 04:34:50 +0000133the letters \samp{test}. This naming convention informs the test runner
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000134about 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
Fred Drakeae55d5f2003-12-31 04:34:50 +0000147The final block shows a simple way to run the tests.
148\function{unittest.main()} provides a command line interface to the
149test script. When run from the command line, the above script
150produces an output that looks like this:
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000151
152\begin{verbatim}
153...
154----------------------------------------------------------------------
155Ran 3 tests in 0.000s
156
157OK
158\end{verbatim}
159
Fred Drakeae55d5f2003-12-31 04:34:50 +0000160Instead of \function{unittest.main()}, there are other ways to run the tests
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000161with a finer level of control, less terse output, and no requirement to be
162run from the command line. For example, the last two lines may be replaced
163with:
164
165\begin{verbatim}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000166suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
Raymond Hettinger9de3c212003-07-10 22:14:41 +0000167unittest.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
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000194\module{unittest}, test cases are represented by instances of
195\module{unittest}'s \class{TestCase} class. To make
Fred Drake0056a422001-04-12 04:50:06 +0000196your 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
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000207The simplest \class{TestCase} subclass will simply override the
Fred Drake0056a422001-04-12 04:50:06 +0000208\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):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000215 widget = Widget('The widget')
216 self.assertEqual(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
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000221\class{TestCase} base class. If the test fails, an exception will be
222raised, and \module{unittest} will identify the test case as a
223\dfn{failure}. Any other exceptions will be treated as \dfn{errors}.
224This helps you identify where the problem is: \dfn{failures} are caused by
225incorrect results - a 5 where you expected a 6. \dfn{Errors} are caused by
226incorrect code - e.g., a \exception{TypeError} caused by an incorrect
227function call.
Fred Drake0056a422001-04-12 04:50:06 +0000228
229The way to run a test case will be described later. For now, note
230that to construct an instance of such a test case, we call its
231constructor without arguments:
232
233\begin{verbatim}
234testCase = DefaultWidgetSizeTestCase()
235\end{verbatim}
236
237Now, such test cases can be numerous, and their set-up can be
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000238repetitive. In the above case, constructing a \class{Widget} in each of
Fred Drake0056a422001-04-12 04:50:06 +0000239100 Widget test case subclasses would mean unsightly duplication.
240
241Luckily, we can factor out such set-up code by implementing a method
242called \method{setUp()}, which the testing framework will
243automatically call for us when we run the test:
244
245\begin{verbatim}
246import unittest
247
248class SimpleWidgetTestCase(unittest.TestCase):
249 def setUp(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000250 self.widget = Widget('The widget')
Fred Drake0056a422001-04-12 04:50:06 +0000251
252class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
253 def runTest(self):
Fred Drake62a26692001-04-12 19:34:38 +0000254 self.failUnless(self.widget.size() == (50,50),
255 'incorrect default size')
Fred Drake0056a422001-04-12 04:50:06 +0000256
257class WidgetResizeTestCase(SimpleWidgetTestCase):
258 def runTest(self):
259 self.widget.resize(100,150)
Fred Drake62a26692001-04-12 19:34:38 +0000260 self.failUnless(self.widget.size() == (100,150),
261 'wrong size after resize')
Fred Drake0056a422001-04-12 04:50:06 +0000262\end{verbatim}
263
264If the \method{setUp()} method raises an exception while the test is
265running, the framework will consider the test to have suffered an
266error, and the \method{runTest()} method will not be executed.
267
268Similarly, we can provide a \method{tearDown()} method that tidies up
269after the \method{runTest()} method has been run:
270
271\begin{verbatim}
272import unittest
273
274class SimpleWidgetTestCase(unittest.TestCase):
275 def setUp(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000276 self.widget = Widget('The widget')
Fred Drake0056a422001-04-12 04:50:06 +0000277
278 def tearDown(self):
279 self.widget.dispose()
280 self.widget = None
281\end{verbatim}
282
283If \method{setUp()} succeeded, the \method{tearDown()} method will be
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000284run whether \method{runTest()} succeeded or not.
Fred Drake0056a422001-04-12 04:50:06 +0000285
286Such a working environment for the testing code is called a
287\dfn{fixture}.
288
289Often, many small test cases will use the same fixture. In this case,
290we would end up subclassing \class{SimpleWidgetTestCase} into many
291small one-method classes such as
292\class{DefaultWidgetSizeTestCase}. This is time-consuming and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000293
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000294discouraging, so in the same vein as JUnit, \module{unittest} provides
295a simpler mechanism:
Fred Drake0056a422001-04-12 04:50:06 +0000296
297\begin{verbatim}
298import unittest
299
300class WidgetTestCase(unittest.TestCase):
301 def setUp(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000302 self.widget = Widget('The widget')
Fred Drake0056a422001-04-12 04:50:06 +0000303
304 def tearDown(self):
305 self.widget.dispose()
306 self.widget = None
307
308 def testDefaultSize(self):
Fred Drake62a26692001-04-12 19:34:38 +0000309 self.failUnless(self.widget.size() == (50,50),
310 'incorrect default size')
Fred Drake0056a422001-04-12 04:50:06 +0000311
312 def testResize(self):
313 self.widget.resize(100,150)
Fred Drake62a26692001-04-12 19:34:38 +0000314 self.failUnless(self.widget.size() == (100,150),
315 'wrong size after resize')
Fred Drake0056a422001-04-12 04:50:06 +0000316\end{verbatim}
317
318Here we have not provided a \method{runTest()} method, but have
319instead provided two different test methods. Class instances will now
320each run one of the \method{test*()} methods, with \code{self.widget}
321created and destroyed separately for each instance. When creating an
322instance we must specify the test method it is to run. We do this by
323passing the method name in the constructor:
324
325\begin{verbatim}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000326defaultSizeTestCase = WidgetTestCase('testDefaultSize')
327resizeTestCase = WidgetTestCase('testResize')
Fred Drake0056a422001-04-12 04:50:06 +0000328\end{verbatim}
329
330Test case instances are grouped together according to the features
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000331they test. \module{unittest} provides a mechanism for this: the
332\dfn{test suite}, represented by \module{unittest}'s \class{TestSuite}
333class:
Fred Drake0056a422001-04-12 04:50:06 +0000334
335\begin{verbatim}
336widgetTestSuite = unittest.TestSuite()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000337widgetTestSuite.addTest(WidgetTestCase('testDefaultSize'))
338widgetTestSuite.addTest(WidgetTestCase('testResize'))
Fred Drake0056a422001-04-12 04:50:06 +0000339\end{verbatim}
340
341For the ease of running tests, as we will see later, it is a good
342idea to provide in each test module a callable object that returns a
343pre-built test suite:
344
345\begin{verbatim}
346def suite():
347 suite = unittest.TestSuite()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000348 suite.addTest(WidgetTestCase('testDefaultSize'))
349 suite.addTest(WidgetTestCase('testResize'))
Fred Drake0056a422001-04-12 04:50:06 +0000350 return suite
351\end{verbatim}
352
353or even:
354
355\begin{verbatim}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000356def suite():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000357 tests = ['testDefaultSize', 'testResize']
Fred Drake0056a422001-04-12 04:50:06 +0000358
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000359 return unittest.TestSuite(map(WidgetTestCase, tests))
360\end{verbatim}
Fred Drake0056a422001-04-12 04:50:06 +0000361
362Since it is a common pattern to create a \class{TestCase} subclass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000363with many similarly named test functions, \module{unittest} provides a
364\class{TestLoader} class that can be used to automate the process of
365creating a test suite and populating it with individual tests.
366For example,
Fred Drake0056a422001-04-12 04:50:06 +0000367
368\begin{verbatim}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000369suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
Fred Drake0056a422001-04-12 04:50:06 +0000370\end{verbatim}
371
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000372will create a test suite that will run
373\code{WidgetTestCase.testDefaultSize()} and \code{WidgetTestCase.testResize}.
374\class{TestLoader} uses the \code{'test'} method name prefix to identify
375test methods automatically.
376
377Note that the order in which the various test cases will be run is
378determined by sorting the test function names with the built-in
379\function{cmp()} function.
Fred Drake0056a422001-04-12 04:50:06 +0000380
381Often it is desirable to group suites of test cases together, so as to
382run tests for the whole system at once. This is easy, since
383\class{TestSuite} instances can be added to a \class{TestSuite} just
384as \class{TestCase} instances can be added to a \class{TestSuite}:
385
386\begin{verbatim}
387suite1 = module1.TheTestSuite()
388suite2 = module2.TheTestSuite()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000389alltests = unittest.TestSuite([suite1, suite2])
Fred Drake0056a422001-04-12 04:50:06 +0000390\end{verbatim}
391
392You can place the definitions of test cases and test suites in the
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +0000393same modules as the code they are to test (such as \file{widget.py}),
Fred Drake0056a422001-04-12 04:50:06 +0000394but there are several advantages to placing the test code in a
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000395separate module, such as \file{test_widget.py}:
Fred Drake0056a422001-04-12 04:50:06 +0000396
397\begin{itemize}
398 \item The test module can be run standalone from the command line.
399 \item The test code can more easily be separated from shipped code.
Michael W. Hudsonaab02602003-02-10 19:21:16 +0000400 \item There is less temptation to change test code to fit the code
Fred Drake0056a422001-04-12 04:50:06 +0000401 it tests without a good reason.
402 \item Test code should be modified much less frequently than the
403 code it tests.
404 \item Tested code can be refactored more easily.
405 \item Tests for modules written in C must be in separate modules
406 anyway, so why not be consistent?
407 \item If the testing strategy changes, there is no need to change
408 the source code.
409\end{itemize}
410
Fred Drakeb9ad2282001-04-07 05:41:39 +0000411
412\subsection{Re-using old test code
413 \label{legacy-unit-tests}}
414
415Some users will find that they have existing test code that they would
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000416like to run from \module{unittest}, without converting every old test
417function to a \class{TestCase} subclass.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000418
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000419For this reason, \module{unittest} provides a \class{FunctionTestCase}
420class. This subclass of \class{TestCase} can be used to wrap an existing
421test function. Set-up and tear-down functions can also be provided.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000422
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
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000439called as part of the test case's operation, they can also be provided
440like so:
Fred Drakeb9ad2282001-04-07 05:41:39 +0000441
442\begin{verbatim}
443testcase = unittest.FunctionTestCase(testSomething,
444 setUp=makeSomethingDB,
445 tearDown=deleteSomethingDB)
446\end{verbatim}
447
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000448To make migrating existing test suites easier, \module{unittest}
449supports tests raising \exception{AssertionError} to indicate test failure.
450However, it is recommended that you use the explicit
451\method{TestCase.fail*()} and \method{TestCase.assert*()} methods instead,
452as future versions of \module{unittest} may treat \exception{AssertionError}
453differently.
454
455\note{Even though \class{FunctionTestCase} can be used to quickly convert
456an existing test base over to a \module{unittest}-based system, this
457approach is not recommended. Taking the time to set up proper
458\class{TestCase} subclasses will make future test refactorings infinitely
459easier.}
460
Fred Drake0056a422001-04-12 04:50:06 +0000461
462
Fred Drakeb9ad2282001-04-07 05:41:39 +0000463\subsection{Classes and functions
464 \label{unittest-contents}}
465
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466\begin{classdesc}{TestCase}{\optional{methodName}}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000467 Instances of the \class{TestCase} class represent the smallest
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000468 testable units in the \module{unittest} universe. This class is
469 intended to be used as a base class, with specific tests being
470 implemented by concrete subclasses. This class implements the
471 interface needed by the test runner to allow it to drive the
472 test, and methods that the test code can use to check for and
473 report various kinds of failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000474
475 Each instance of \class{TestCase} will run a single test method:
476 the method named \var{methodName}. If you remember, we had an
477 earlier example that went something like this:
478
479 \begin{verbatim}
480 def suite():
481 suite = unittest.TestSuite()
482 suite.addTest(WidgetTestCase('testDefaultSize'))
483 suite.addTest(WidgetTestCase('testResize'))
484 return suite
485 \end{verbatim}
486
487 Here, we create two instances of \class{WidgetTestCase}, each of
488 which runs a single test.
489
490 \var{methodName} defaults to \code{'runTest'}.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000491\end{classdesc}
492
493\begin{classdesc}{FunctionTestCase}{testFunc\optional{,
Fred Drake62a26692001-04-12 19:34:38 +0000494 setUp\optional{, tearDown\optional{, description}}}}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000495 This class implements the portion of the \class{TestCase} interface
496 which allows the test runner to drive the test, but does not provide
497 the methods which test code can use to check and report errors.
498 This is used to create test cases using legacy test code, allowing
499 it to be integrated into a \refmodule{unittest}-based test
500 framework.
501\end{classdesc}
502
Fred Drake29be7012001-04-10 22:25:06 +0000503\begin{classdesc}{TestSuite}{\optional{tests}}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000504 This class represents an aggregation of individual tests cases and
505 test suites. The class presents the interface needed by the test
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506 runner to allow it to be run as any other test case. Running a
507 \class{TestSuite} instance is the same as iterating over the suite,
508 running each test individually.
509
510 If \var{tests} is given, it must be an iterable of individual test cases or
511 other test suites that will be used to build the suite initially.
512 Additional methods are provided to add test cases and suites to the
513 collection later on.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000514\end{classdesc}
515
516\begin{classdesc}{TestLoader}{}
Fred Drake29be7012001-04-10 22:25:06 +0000517 This class is responsible for loading tests according to various
518 criteria and returning them wrapped in a \class{TestSuite}.
519 It can load all tests within a given module or \class{TestCase}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000520 subclass.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000521\end{classdesc}
522
Thomas Wouters89f507f2006-12-13 04:49:30 +0000523\begin{classdesc}{TestResult}{}
524 This class is used to compile information about which tests have succeeded
525 and which have failed.
526\end{classdesc}
527
Fred Drake62a26692001-04-12 19:34:38 +0000528\begin{datadesc}{defaultTestLoader}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000529 Instance of the \class{TestLoader} class intended to be shared. If no
Fred Drake62a26692001-04-12 19:34:38 +0000530 customization of the \class{TestLoader} is needed, this instance can
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000531 be used instead of repeatedly creating new instances.
Fred Drake62a26692001-04-12 19:34:38 +0000532\end{datadesc}
533
Fred Drakeb9ad2282001-04-07 05:41:39 +0000534\begin{classdesc}{TextTestRunner}{\optional{stream\optional{,
535 descriptions\optional{, verbosity}}}}
Fred Drake29be7012001-04-10 22:25:06 +0000536 A basic test runner implementation which prints results on standard
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000537 error. It has a few configurable parameters, but is essentially
Fred Drake29be7012001-04-10 22:25:06 +0000538 very simple. Graphical applications which run test suites should
539 provide alternate implementations.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000540\end{classdesc}
541
542\begin{funcdesc}{main}{\optional{module\optional{,
543 defaultTest\optional{, argv\optional{,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000544 testRunner\optional{, testLoader}}}}}}
Fred Drake0056a422001-04-12 04:50:06 +0000545 A command-line program that runs a set of tests; this is primarily
546 for making test modules conveniently executable. The simplest use
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000547 for this function is to include the following line at the end of a
548 test script:
Fred Drakeb9ad2282001-04-07 05:41:39 +0000549
550\begin{verbatim}
551if __name__ == '__main__':
552 unittest.main()
553\end{verbatim}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000554
555 The \var{testRunner} argument can either be a test runner class or
556 an already created instance of it.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000557\end{funcdesc}
558
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000559In some cases, the existing tests may have been written using the
Fred Drakeae55d5f2003-12-31 04:34:50 +0000560\refmodule{doctest} module. If so, that module provides a
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +0000561\class{DocTestSuite} class that can automatically build
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000562\class{unittest.TestSuite} instances from the existing
563\module{doctest}-based tests.
Raymond Hettingerd21fd7b2003-09-16 22:04:31 +0000564\versionadded{2.3}
565
Fred Drakeb9ad2282001-04-07 05:41:39 +0000566
567\subsection{TestCase Objects
568 \label{testcase-objects}}
569
Fred Drake29be7012001-04-10 22:25:06 +0000570Each \class{TestCase} instance represents a single test, but each
571concrete subclass may be used to define multiple tests --- the
572concrete class represents a single test fixture. The fixture is
573created and cleaned up for each test case.
574
575\class{TestCase} instances provide three groups of methods: one group
576used to run the test, another used by the test implementation to
577check conditions and report failures, and some inquiry methods
578allowing information about the test itself to be gathered.
579
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000580Methods in the first group (running the test) are:
Fred Drake29be7012001-04-10 22:25:06 +0000581
582\begin{methoddesc}[TestCase]{setUp}{}
583 Method called to prepare the test fixture. This is called
584 immediately before calling the test method; any exception raised by
585 this method will be considered an error rather than a test failure.
586 The default implementation does nothing.
587\end{methoddesc}
588
Fred Drake29be7012001-04-10 22:25:06 +0000589\begin{methoddesc}[TestCase]{tearDown}{}
590 Method called immediately after the test method has been called and
591 the result recorded. This is called even if the test method raised
592 an exception, so the implementation in subclasses may need to be
593 particularly careful about checking internal state. Any exception
594 raised by this method will be considered an error rather than a test
Fred Drake62a26692001-04-12 19:34:38 +0000595 failure. This method will only be called if the \method{setUp()}
596 succeeds, regardless of the outcome of the test method.
597 The default implementation does nothing.
598\end{methoddesc}
599
600\begin{methoddesc}[TestCase]{run}{\optional{result}}
601 Run the test, collecting the result into the test result object
Fred Drakeae55d5f2003-12-31 04:34:50 +0000602 passed as \var{result}. If \var{result} is omitted or \constant{None},
Thomas Wouters89f507f2006-12-13 04:49:30 +0000603 a temporary result object is created (by calling the
604 \method{defaultTestCase()} method) and used; this result object is not
605 returned to \method{run()}'s caller.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000606
607 The same effect may be had by simply calling the \class{TestCase}
608 instance.
Fred Drake29be7012001-04-10 22:25:06 +0000609\end{methoddesc}
610
611\begin{methoddesc}[TestCase]{debug}{}
612 Run the test without collecting the result. This allows exceptions
Raymond Hettinger68804312005-01-01 00:28:46 +0000613 raised by the test to be propagated to the caller, and can be used
Fred Drake29be7012001-04-10 22:25:06 +0000614 to support running tests under a debugger.
615\end{methoddesc}
616
617
Fred Drake0056a422001-04-12 04:50:06 +0000618The test code can use any of the following methods to check for and
Fred Drake62a26692001-04-12 19:34:38 +0000619report failures.
Fred Drake29be7012001-04-10 22:25:06 +0000620
Fred Drake62a26692001-04-12 19:34:38 +0000621\begin{methoddesc}[TestCase]{assert_}{expr\optional{, msg}}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000622\methodline[TestCase]{failUnless}{expr\optional{, msg}}
Fred Drake62a26692001-04-12 19:34:38 +0000623 Signal a test failure if \var{expr} is false; the explanation for
624 the error will be \var{msg} if given, otherwise it will be
Fred Drakeae55d5f2003-12-31 04:34:50 +0000625 \constant{None}.
Fred Drake29be7012001-04-10 22:25:06 +0000626\end{methoddesc}
627
Fred Drake62a26692001-04-12 19:34:38 +0000628\begin{methoddesc}[TestCase]{assertEqual}{first, second\optional{, msg}}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000629\methodline[TestCase]{failUnlessEqual}{first, second\optional{, msg}}
Fred Drake29be7012001-04-10 22:25:06 +0000630 Test that \var{first} and \var{second} are equal. If the values do
631 not compare equal, the test will fail with the explanation given by
Fred Drakeae55d5f2003-12-31 04:34:50 +0000632 \var{msg}, or \constant{None}. Note that using \method{failUnlessEqual()}
Fred Drake29be7012001-04-10 22:25:06 +0000633 improves upon doing the comparison as the first parameter to
Fred Drake62a26692001-04-12 19:34:38 +0000634 \method{failUnless()}: the default value for \var{msg} can be
Fred Drake29be7012001-04-10 22:25:06 +0000635 computed to include representations of both \var{first} and
636 \var{second}.
637\end{methoddesc}
638
Fred Drake62a26692001-04-12 19:34:38 +0000639\begin{methoddesc}[TestCase]{assertNotEqual}{first, second\optional{, msg}}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000640\methodline[TestCase]{failIfEqual}{first, second\optional{, msg}}
Fred Drake29be7012001-04-10 22:25:06 +0000641 Test that \var{first} and \var{second} are not equal. If the values
642 do compare equal, the test will fail with the explanation given by
Fred Drakeae55d5f2003-12-31 04:34:50 +0000643 \var{msg}, or \constant{None}. Note that using \method{failIfEqual()}
Fred Drake29be7012001-04-10 22:25:06 +0000644 improves upon doing the comparison as the first parameter to
645 \method{failUnless()} is that the default value for \var{msg} can be
646 computed to include representations of both \var{first} and
647 \var{second}.
648\end{methoddesc}
649
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000650\begin{methoddesc}[TestCase]{assertAlmostEqual}{first, second\optional{,
651 places\optional{, msg}}}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000652\methodline[TestCase]{failUnlessAlmostEqual}{first, second\optional{,
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000653 places\optional{, msg}}}
654 Test that \var{first} and \var{second} are approximately equal
655 by computing the difference, rounding to the given number of \var{places},
656 and comparing to zero. Note that comparing a given number of decimal places
657 is not the same as comparing a given number of significant digits.
658 If the values do not compare equal, the test will fail with the explanation
Fred Drakeae55d5f2003-12-31 04:34:50 +0000659 given by \var{msg}, or \constant{None}.
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000660\end{methoddesc}
661
662\begin{methoddesc}[TestCase]{assertNotAlmostEqual}{first, second\optional{,
663 places\optional{, msg}}}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000664\methodline[TestCase]{failIfAlmostEqual}{first, second\optional{,
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000665 places\optional{, msg}}}
666 Test that \var{first} and \var{second} are not approximately equal
667 by computing the difference, rounding to the given number of \var{places},
668 and comparing to zero. Note that comparing a given number of decimal places
669 is not the same as comparing a given number of significant digits.
670 If the values do not compare equal, the test will fail with the explanation
Fred Drakeae55d5f2003-12-31 04:34:50 +0000671 given by \var{msg}, or \constant{None}.
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000672\end{methoddesc}
673
Fred Drake62a26692001-04-12 19:34:38 +0000674\begin{methoddesc}[TestCase]{assertRaises}{exception, callable, \moreargs}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000675\methodline[TestCase]{failUnlessRaises}{exception, callable, \moreargs}
Fred Drake62a26692001-04-12 19:34:38 +0000676 Test that an exception is raised when \var{callable} is called with
677 any positional or keyword arguments that are also passed to
678 \method{assertRaises()}. The test passes if \var{exception} is
679 raised, is an error if another exception is raised, or fails if no
680 exception is raised. To catch any of a group of exceptions, a tuple
681 containing the exception classes may be passed as \var{exception}.
682\end{methoddesc}
683
Fred Drake29be7012001-04-10 22:25:06 +0000684\begin{methoddesc}[TestCase]{failIf}{expr\optional{, msg}}
Fred Drake0056a422001-04-12 04:50:06 +0000685 The inverse of the \method{failUnless()} method is the
Fred Drake62a26692001-04-12 19:34:38 +0000686 \method{failIf()} method. This signals a test failure if \var{expr}
Fred Drakeae55d5f2003-12-31 04:34:50 +0000687 is true, with \var{msg} or \constant{None} for the error message.
Fred Drake29be7012001-04-10 22:25:06 +0000688\end{methoddesc}
689
690\begin{methoddesc}[TestCase]{fail}{\optional{msg}}
Fred Drake62a26692001-04-12 19:34:38 +0000691 Signals a test failure unconditionally, with \var{msg} or
Fred Drakeae55d5f2003-12-31 04:34:50 +0000692 \constant{None} for the error message.
Fred Drake29be7012001-04-10 22:25:06 +0000693\end{methoddesc}
694
Fred Drake62a26692001-04-12 19:34:38 +0000695\begin{memberdesc}[TestCase]{failureException}
696 This class attribute gives the exception raised by the
697 \method{test()} method. If a test framework needs to use a
698 specialized exception, possibly to carry additional information, it
699 must subclass this exception in order to ``play fair'' with the
700 framework. The initial value of this attribute is
701 \exception{AssertionError}.
702\end{memberdesc}
703
Fred Drake29be7012001-04-10 22:25:06 +0000704
705Testing frameworks can use the following methods to collect
706information on the test:
707
708\begin{methoddesc}[TestCase]{countTestCases}{}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000709 Return the number of tests represented by this test object. For
710 \class{TestCase} instances, this will always be \code{1}.
Fred Drake29be7012001-04-10 22:25:06 +0000711\end{methoddesc}
712
713\begin{methoddesc}[TestCase]{defaultTestResult}{}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000714 Return an instance of the test result class that should be used
715 for this test case class (if no other result instance is provided
716 to the \method{run()} method).
717
718 For \class{TestCase} instances, this will always be an instance of
719 \class{TestResult}; subclasses of \class{TestCase} should
720 override this as necessary.
Fred Drake29be7012001-04-10 22:25:06 +0000721\end{methoddesc}
722
723\begin{methoddesc}[TestCase]{id}{}
724 Return a string identifying the specific test case. This is usually
725 the full name of the test method, including the module and class
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000726 name.
Fred Drake29be7012001-04-10 22:25:06 +0000727\end{methoddesc}
728
729\begin{methoddesc}[TestCase]{shortDescription}{}
Fred Drakeae55d5f2003-12-31 04:34:50 +0000730 Returns a one-line description of the test, or \constant{None} if no
Fred Drake29be7012001-04-10 22:25:06 +0000731 description has been provided. The default implementation of this
732 method returns the first line of the test method's docstring, if
Fred Drakeae55d5f2003-12-31 04:34:50 +0000733 available, or \constant{None}.
Fred Drake29be7012001-04-10 22:25:06 +0000734\end{methoddesc}
735
Fred Drakeb9ad2282001-04-07 05:41:39 +0000736
737\subsection{TestSuite Objects
738 \label{testsuite-objects}}
739
740\class{TestSuite} objects behave much like \class{TestCase} objects,
741except they do not actually implement a test. Instead, they are used
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000742to aggregate tests into groups of tests that should be run together.
743Some additional methods are available to add tests to \class{TestSuite}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000744instances:
745
746\begin{methoddesc}[TestSuite]{addTest}{test}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000747 Add a \class{TestCase} or \class{TestSuite} to the suite.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000748\end{methoddesc}
749
750\begin{methoddesc}[TestSuite]{addTests}{tests}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000751 Add all the tests from an iterable of \class{TestCase} and
Fred Drakeb9ad2282001-04-07 05:41:39 +0000752 \class{TestSuite} instances to this test suite.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000753
754 This is equivalent to iterating over \var{tests}, calling
755 \method{addTest()} for each element.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000756\end{methoddesc}
757
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000758\class{TestSuite} shares the following methods with \class{TestCase}:
Fred Drake4d17b302001-09-06 15:51:56 +0000759
760\begin{methoddesc}[TestSuite]{run}{result}
761 Run the tests associated with this suite, collecting the result into
762 the test result object passed as \var{result}. Note that unlike
763 \method{TestCase.run()}, \method{TestSuite.run()} requires the
764 result object to be passed in.
765\end{methoddesc}
766
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000767\begin{methoddesc}[TestSuite]{debug}{}
768 Run the tests associated with this suite without collecting the result.
769 This allows exceptions raised by the test to be propagated to the caller
770 and can be used to support running tests under a debugger.
771\end{methoddesc}
772
773\begin{methoddesc}[TestSuite]{countTestCases}{}
774 Return the number of tests represented by this test object, including
775 all individual tests and sub-suites.
776\end{methoddesc}
777
Fred Drake4d17b302001-09-06 15:51:56 +0000778In the typical usage of a \class{TestSuite} object, the \method{run()}
779method is invoked by a \class{TestRunner} rather than by the end-user
780test harness.
781
Fred Drakeb9ad2282001-04-07 05:41:39 +0000782
783\subsection{TestResult Objects
784 \label{testresult-objects}}
785
786A \class{TestResult} object stores the results of a set of tests. The
787\class{TestCase} and \class{TestSuite} classes ensure that results are
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000788properly recorded; test authors do not need to worry about recording the
Fred Drakeb9ad2282001-04-07 05:41:39 +0000789outcome of tests.
790
791Testing frameworks built on top of \refmodule{unittest} may want
792access to the \class{TestResult} object generated by running a set of
793tests for reporting purposes; a \class{TestResult} instance is
794returned by the \method{TestRunner.run()} method for this purpose.
795
Fred Drakeb9ad2282001-04-07 05:41:39 +0000796\class{TestResult} instances have the following attributes that will
797be of interest when inspecting the results of running a set of tests:
798
799\begin{memberdesc}[TestResult]{errors}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000800 A list containing 2-tuples of \class{TestCase} instances and
Thomas Wouters89f507f2006-12-13 04:49:30 +0000801 strings holding formatted tracebacks. Each tuple represents a test which
802 raised an unexpected exception.
Fred Drakec4126172002-07-02 22:46:42 +0000803 \versionchanged[Contains formatted tracebacks instead of
804 \function{sys.exc_info()} results]{2.2}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000805\end{memberdesc}
806
807\begin{memberdesc}[TestResult]{failures}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000808 A list containing 2-tuples of \class{TestCase} instances and strings
809 holding formatted tracebacks. Each tuple represents a test where a failure
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000810 was explicitly signalled using the \method{TestCase.fail*()} or
811 \method{TestCase.assert*()} methods.
Fred Drakec4126172002-07-02 22:46:42 +0000812 \versionchanged[Contains formatted tracebacks instead of
813 \function{sys.exc_info()} results]{2.2}
Fred Drakeb9ad2282001-04-07 05:41:39 +0000814\end{memberdesc}
815
816\begin{memberdesc}[TestResult]{testsRun}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000817 The total number of tests run so far.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000818\end{memberdesc}
819
820\begin{methoddesc}[TestResult]{wasSuccessful}{}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000821 Returns \constant{True} if all tests run so far have passed,
822 otherwise returns \constant{False}.
823\end{methoddesc}
824
825\begin{methoddesc}[TestResult]{stop}{}
826 This method can be called to signal that the set of tests being run
827 should be aborted by setting the \class{TestResult}'s \code{shouldStop}
828 attribute to \constant{True}. \class{TestRunner} objects should respect
829 this flag and return without running any additional tests.
830
831 For example, this feature is used by the \class{TextTestRunner} class
832 to stop the test framework when the user signals an interrupt from
833 the keyboard. Interactive tools which provide \class{TestRunner}
834 implementations can use this in a similar manner.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000835\end{methoddesc}
836
837
838The following methods of the \class{TestResult} class are used to
Martin v. Löwis7bdc4842003-09-20 11:09:28 +0000839maintain the internal data structures, and may be extended in
Fred Drakeb9ad2282001-04-07 05:41:39 +0000840subclasses to support additional reporting requirements. This is
Fred Drake8ee679f2001-07-14 02:50:55 +0000841particularly useful in building tools which support interactive
Fred Drakeb9ad2282001-04-07 05:41:39 +0000842reporting while tests are being run.
843
844\begin{methoddesc}[TestResult]{startTest}{test}
845 Called when the test case \var{test} is about to be run.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000846
847 The default implementation simply increments the instance's
848 \code{testsRun} counter.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000849\end{methoddesc}
850
851\begin{methoddesc}[TestResult]{stopTest}{test}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000852 Called after the test case \var{test} has been executed, regardless
Fred Drakeb9ad2282001-04-07 05:41:39 +0000853 of the outcome.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000854
855 The default implementation does nothing.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000856\end{methoddesc}
857
858\begin{methoddesc}[TestResult]{addError}{test, err}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000859 Called when the test case \var{test} raises an unexpected exception
860 \var{err} is a tuple of the form returned by \function{sys.exc_info()}:
861 \code{(\var{type}, \var{value}, \var{traceback})}.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000862
863 The default implementation appends \code{(\var{test}, \var{err})} to
864 the instance's \code{errors} attribute.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000865\end{methoddesc}
866
867\begin{methoddesc}[TestResult]{addFailure}{test, err}
Fred Drake62a26692001-04-12 19:34:38 +0000868 Called when the test case \var{test} signals a failure.
Fred Drake0056a422001-04-12 04:50:06 +0000869 \var{err} is a tuple of the form returned by
870 \function{sys.exc_info()}: \code{(\var{type}, \var{value},
871 \var{traceback})}.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000872
873 The default implementation appends \code{(\var{test}, \var{err})} to
874 the instance's \code{failures} attribute.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000875\end{methoddesc}
876
877\begin{methoddesc}[TestResult]{addSuccess}{test}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000878 Called when the test case \var{test} succeeds.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000879
880 The default implementation does nothing.
Fred Drakeb9ad2282001-04-07 05:41:39 +0000881\end{methoddesc}
882
883
Fred Drake62a26692001-04-12 19:34:38 +0000884
885\subsection{TestLoader Objects
886 \label{testloader-objects}}
887
888The \class{TestLoader} class is used to create test suites from
889classes and modules. Normally, there is no need to create an instance
890of this class; the \refmodule{unittest} module provides an instance
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000891that can be shared as \code{unittest.defaultTestLoader}.
892Using a subclass or instance, however, allows customization of some
Fred Drake62a26692001-04-12 19:34:38 +0000893configurable properties.
894
895\class{TestLoader} objects have the following methods:
896
897\begin{methoddesc}[TestLoader]{loadTestsFromTestCase}{testCaseClass}
898 Return a suite of all tests cases contained in the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000899 \class{TestCase}-derived \class{testCaseClass}.
Fred Drake62a26692001-04-12 19:34:38 +0000900\end{methoddesc}
901
902\begin{methoddesc}[TestLoader]{loadTestsFromModule}{module}
903 Return a suite of all tests cases contained in the given module.
904 This method searches \var{module} for classes derived from
905 \class{TestCase} and creates an instance of the class for each test
906 method defined for the class.
907
Fred Drake0aa811c2001-10-20 04:24:09 +0000908 \warning{While using a hierarchy of
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000909 \class{TestCase}-derived classes can be convenient in sharing
Fred Drake62a26692001-04-12 19:34:38 +0000910 fixtures and helper functions, defining test methods on base classes
911 that are not intended to be instantiated directly does not play well
912 with this method. Doing so, however, can be useful when the
Fred Drake0aa811c2001-10-20 04:24:09 +0000913 fixtures are different and defined in subclasses.}
Fred Drake62a26692001-04-12 19:34:38 +0000914\end{methoddesc}
915
916\begin{methoddesc}[TestLoader]{loadTestsFromName}{name\optional{, module}}
917 Return a suite of all tests cases given a string specifier.
918
Fred Drake4d17b302001-09-06 15:51:56 +0000919 The specifier \var{name} is a ``dotted name'' that may resolve
Thomas Wouters89f507f2006-12-13 04:49:30 +0000920 either to a module, a test case class, a test method within a test
921 case class, a \class{TestSuite} instance, or a callable object which
922 returns a \class{TestCase} or \class{TestSuite} instance. These checks
923 are applied in the order listed here; that is, a method on a possible
924 test case class will be picked up as ``a test method within a test
925 case class'', rather than ``a callable object''.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000926
927 For example, if you have a module \module{SampleTests} containing a
928 \class{TestCase}-derived class \class{SampleTestCase} with three test
929 methods (\method{test_one()}, \method{test_two()}, and
930 \method{test_three()}), the specifier \code{'SampleTests.SampleTestCase'}
931 would cause this method to return a suite which will run all three test
932 methods. Using the specifier \code{'SampleTests.SampleTestCase.test_two'}
933 would cause it to return a test suite which will run only the
Fred Drake4d17b302001-09-06 15:51:56 +0000934 \method{test_two()} test method. The specifier can refer to modules
935 and packages which have not been imported; they will be imported as
936 a side-effect.
Fred Drake62a26692001-04-12 19:34:38 +0000937
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000938 The method optionally resolves \var{name} relative to the given
939 \var{module}.
Fred Drake62a26692001-04-12 19:34:38 +0000940\end{methoddesc}
941
942\begin{methoddesc}[TestLoader]{loadTestsFromNames}{names\optional{, module}}
943 Similar to \method{loadTestsFromName()}, but takes a sequence of
944 names rather than a single name. The return value is a test suite
945 which supports all the tests defined for each name.
946\end{methoddesc}
947
948\begin{methoddesc}[TestLoader]{getTestCaseNames}{testCaseClass}
949 Return a sorted sequence of method names found within
Thomas Wouters89f507f2006-12-13 04:49:30 +0000950 \var{testCaseClass}; this should be a subclass of \class{TestCase}.
Fred Drake62a26692001-04-12 19:34:38 +0000951\end{methoddesc}
952
953
954The following attributes of a \class{TestLoader} can be configured
955either by subclassing or assignment on an instance:
956
957\begin{memberdesc}[TestLoader]{testMethodPrefix}
958 String giving the prefix of method names which will be interpreted
959 as test methods. The default value is \code{'test'}.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000960
961 This affects \method{getTestCaseNames()} and all the
962 \method{loadTestsFrom*()} methods.
Fred Drake62a26692001-04-12 19:34:38 +0000963\end{memberdesc}
964
965\begin{memberdesc}[TestLoader]{sortTestMethodsUsing}
966 Function to be used to compare method names when sorting them in
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000967 \method{getTestCaseNames()} and all the \method{loadTestsFrom*()} methods.
968 The default value is the built-in \function{cmp()} function; the attribute
969 can also be set to \constant{None} to disable the sort.
Fred Drake62a26692001-04-12 19:34:38 +0000970\end{memberdesc}
971
972\begin{memberdesc}[TestLoader]{suiteClass}
973 Callable object that constructs a test suite from a list of tests.
974 No methods on the resulting object are needed. The default value is
975 the \class{TestSuite} class.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000976
977 This affects all the \method{loadTestsFrom*()} methods.
Fred Drake62a26692001-04-12 19:34:38 +0000978\end{memberdesc}