blob: b1315c0e7d94065bcdaf5a4f79c3ed83227a5e61 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`unittest` --- Unit testing framework
3==========================================
4
5.. module:: unittest
6 :synopsis: Unit testing framework for Python.
7.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
9.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
10.. sectionauthor:: Raymond Hettinger <python@rcn.com>
11
12
Georg Brandl116aa622007-08-15 14:28:22 +000013The Python unit testing framework, sometimes referred to as "PyUnit," is a
14Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
15turn, a Java version of Kent's Smalltalk testing framework. Each is the de
16facto standard unit testing framework for its respective language.
17
18:mod:`unittest` supports test automation, sharing of setup and shutdown code for
19tests, aggregation of tests into collections, and independence of the tests from
20the reporting framework. The :mod:`unittest` module provides classes that make
21it easy to support these qualities for a set of tests.
22
23To achieve this, :mod:`unittest` supports some important concepts:
24
25test fixture
26 A :dfn:`test fixture` represents the preparation needed to perform one or more
27 tests, and any associate cleanup actions. This may involve, for example,
28 creating temporary or proxy databases, directories, or starting a server
29 process.
30
31test case
32 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
33 response to a particular set of inputs. :mod:`unittest` provides a base class,
34 :class:`TestCase`, which may be used to create new test cases.
35
36test suite
37 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
38 used to aggregate tests that should be executed together.
39
40test runner
41 A :dfn:`test runner` is a component which orchestrates the execution of tests
42 and provides the outcome to the user. The runner may use a graphical interface,
43 a textual interface, or return a special value to indicate the results of
44 executing the tests.
45
46The test case and test fixture concepts are supported through the
47:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
48used when creating new tests, and the latter can be used when integrating
49existing test code with a :mod:`unittest`\ -driven framework. When building test
50fixtures using :class:`TestCase`, the :meth:`setUp` and :meth:`tearDown` methods
51can be overridden to provide initialization and cleanup for the fixture. With
52:class:`FunctionTestCase`, existing functions can be passed to the constructor
53for these purposes. When the test is run, the fixture initialization is run
54first; if it succeeds, the cleanup method is run after the test has been
55executed, regardless of the outcome of the test. Each instance of the
56:class:`TestCase` will only be used to run a single test method, so a new
57fixture is created for each test.
58
59Test suites are implemented by the :class:`TestSuite` class. This class allows
60individual tests and test suites to be aggregated; when the suite is executed,
61all tests added directly to the suite and in "child" test suites are run.
62
63A test runner is an object that provides a single method, :meth:`run`, which
64accepts a :class:`TestCase` or :class:`TestSuite` object as a parameter, and
65returns a result object. The class :class:`TestResult` is provided for use as
66the result object. :mod:`unittest` provides the :class:`TextTestRunner` as an
67example test runner which reports test results on the standard error stream by
68default. Alternate runners can be implemented for other environments (such as
69graphical environments) without any need to derive from a specific class.
70
71
72.. seealso::
73
74 Module :mod:`doctest`
75 Another test-support module with a very different flavor.
76
77 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
78 Kent Beck's original paper on testing frameworks using the pattern shared by
79 :mod:`unittest`.
80
81
82.. _unittest-minimal-example:
83
84Basic example
85-------------
86
87The :mod:`unittest` module provides a rich set of tools for constructing and
88running tests. This section demonstrates that a small subset of the tools
89suffice to meet the needs of most users.
90
91Here is a short script to test three functions from the :mod:`random` module::
92
93 import random
94 import unittest
95
96 class TestSequenceFunctions(unittest.TestCase):
97
98 def setUp(self):
99 self.seq = range(10)
100
101 def testshuffle(self):
102 # make sure the shuffled sequence does not lose any elements
103 random.shuffle(self.seq)
104 self.seq.sort()
105 self.assertEqual(self.seq, range(10))
106
107 def testchoice(self):
108 element = random.choice(self.seq)
109 self.assert_(element in self.seq)
110
111 def testsample(self):
112 self.assertRaises(ValueError, random.sample, self.seq, 20)
113 for element in random.sample(self.seq, 5):
114 self.assert_(element in self.seq)
115
116 if __name__ == '__main__':
117 unittest.main()
118
119A testcase is created by subclassing :class:`unittest.TestCase`. The three
120individual tests are defined with methods whose names start with the letters
121``test``. This naming convention informs the test runner about which methods
122represent tests.
123
124The crux of each test is a call to :meth:`assertEqual` to check for an expected
125result; :meth:`assert_` to verify a condition; or :meth:`assertRaises` to verify
126that an expected exception gets raised. These methods are used instead of the
127:keyword:`assert` statement so the test runner can accumulate all test results
128and produce a report.
129
130When a :meth:`setUp` method is defined, the test runner will run that method
131prior to each test. Likewise, if a :meth:`tearDown` method is defined, the test
132runner will invoke that method after each test. In the example, :meth:`setUp`
133was used to create a fresh sequence for each test.
134
135The final block shows a simple way to run the tests. :func:`unittest.main`
136provides a command line interface to the test script. When run from the command
137line, the above script produces an output that looks like this::
138
139 ...
140 ----------------------------------------------------------------------
141 Ran 3 tests in 0.000s
142
143 OK
144
145Instead of :func:`unittest.main`, there are other ways to run the tests with a
146finer level of control, less terse output, and no requirement to be run from the
147command line. For example, the last two lines may be replaced with::
148
149 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
150 unittest.TextTestRunner(verbosity=2).run(suite)
151
152Running the revised script from the interpreter or another script produces the
153following output::
154
155 testchoice (__main__.TestSequenceFunctions) ... ok
156 testsample (__main__.TestSequenceFunctions) ... ok
157 testshuffle (__main__.TestSequenceFunctions) ... ok
158
159 ----------------------------------------------------------------------
160 Ran 3 tests in 0.110s
161
162 OK
163
164The above examples show the most commonly used :mod:`unittest` features which
165are sufficient to meet many everyday testing needs. The remainder of the
166documentation explores the full feature set from first principles.
167
168
169.. _organizing-tests:
170
171Organizing test code
172--------------------
173
174The basic building blocks of unit testing are :dfn:`test cases` --- single
175scenarios that must be set up and checked for correctness. In :mod:`unittest`,
176test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
177class. To make your own test cases you must write subclasses of
178:class:`TestCase`, or use :class:`FunctionTestCase`.
179
180An instance of a :class:`TestCase`\ -derived class is an object that can
181completely run a single test method, together with optional set-up and tidy-up
182code.
183
184The testing code of a :class:`TestCase` instance should be entirely self
185contained, such that it can be run either in isolation or in arbitrary
186combination with any number of other test cases.
187
188The simplest :class:`TestCase` subclass will simply override the :meth:`runTest`
189method in order to perform specific testing code::
190
191 import unittest
192
193 class DefaultWidgetSizeTestCase(unittest.TestCase):
194 def runTest(self):
195 widget = Widget('The widget')
196 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
197
198Note that in order to test something, we use the one of the :meth:`assert\*` or
199:meth:`fail\*` methods provided by the :class:`TestCase` base class. If the
200test fails, an exception will be raised, and :mod:`unittest` will identify the
201test case as a :dfn:`failure`. Any other exceptions will be treated as
202:dfn:`errors`. This helps you identify where the problem is: :dfn:`failures` are
203caused by incorrect results - a 5 where you expected a 6. :dfn:`Errors` are
204caused by incorrect code - e.g., a :exc:`TypeError` caused by an incorrect
205function call.
206
207The way to run a test case will be described later. For now, note that to
208construct an instance of such a test case, we call its constructor without
209arguments::
210
211 testCase = DefaultWidgetSizeTestCase()
212
213Now, such test cases can be numerous, and their set-up can be repetitive. In
214the above case, constructing a :class:`Widget` in each of 100 Widget test case
215subclasses would mean unsightly duplication.
216
217Luckily, we can factor out such set-up code by implementing a method called
218:meth:`setUp`, which the testing framework will automatically call for us when
219we run the test::
220
221 import unittest
222
223 class SimpleWidgetTestCase(unittest.TestCase):
224 def setUp(self):
225 self.widget = Widget('The widget')
226
227 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
228 def runTest(self):
229 self.failUnless(self.widget.size() == (50,50),
230 'incorrect default size')
231
232 class WidgetResizeTestCase(SimpleWidgetTestCase):
233 def runTest(self):
234 self.widget.resize(100,150)
235 self.failUnless(self.widget.size() == (100,150),
236 'wrong size after resize')
237
238If the :meth:`setUp` method raises an exception while the test is running, the
239framework will consider the test to have suffered an error, and the
240:meth:`runTest` method will not be executed.
241
242Similarly, we can provide a :meth:`tearDown` method that tidies up after the
243:meth:`runTest` method has been run::
244
245 import unittest
246
247 class SimpleWidgetTestCase(unittest.TestCase):
248 def setUp(self):
249 self.widget = Widget('The widget')
250
251 def tearDown(self):
252 self.widget.dispose()
253 self.widget = None
254
255If :meth:`setUp` succeeded, the :meth:`tearDown` method will be run whether
256:meth:`runTest` succeeded or not.
257
258Such a working environment for the testing code is called a :dfn:`fixture`.
259
260Often, many small test cases will use the same fixture. In this case, we would
261end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
262classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
263
264discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
265mechanism::
266
267 import unittest
268
269 class WidgetTestCase(unittest.TestCase):
270 def setUp(self):
271 self.widget = Widget('The widget')
272
273 def tearDown(self):
274 self.widget.dispose()
275 self.widget = None
276
277 def testDefaultSize(self):
278 self.failUnless(self.widget.size() == (50,50),
279 'incorrect default size')
280
281 def testResize(self):
282 self.widget.resize(100,150)
283 self.failUnless(self.widget.size() == (100,150),
284 'wrong size after resize')
285
286Here we have not provided a :meth:`runTest` method, but have instead provided
287two different test methods. Class instances will now each run one of the
288:meth:`test\*` methods, with ``self.widget`` created and destroyed separately
289for each instance. When creating an instance we must specify the test method it
290is to run. We do this by passing the method name in the constructor::
291
292 defaultSizeTestCase = WidgetTestCase('testDefaultSize')
293 resizeTestCase = WidgetTestCase('testResize')
294
295Test case instances are grouped together according to the features they test.
296:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
297represented by :mod:`unittest`'s :class:`TestSuite` class::
298
299 widgetTestSuite = unittest.TestSuite()
300 widgetTestSuite.addTest(WidgetTestCase('testDefaultSize'))
301 widgetTestSuite.addTest(WidgetTestCase('testResize'))
302
303For the ease of running tests, as we will see later, it is a good idea to
304provide in each test module a callable object that returns a pre-built test
305suite::
306
307 def suite():
308 suite = unittest.TestSuite()
309 suite.addTest(WidgetTestCase('testDefaultSize'))
310 suite.addTest(WidgetTestCase('testResize'))
311 return suite
312
313or even::
314
315 def suite():
316 tests = ['testDefaultSize', 'testResize']
317
318 return unittest.TestSuite(map(WidgetTestCase, tests))
319
320Since it is a common pattern to create a :class:`TestCase` subclass with many
321similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
322class that can be used to automate the process of creating a test suite and
323populating it with individual tests. For example, ::
324
325 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
326
327will create a test suite that will run ``WidgetTestCase.testDefaultSize()`` and
328``WidgetTestCase.testResize``. :class:`TestLoader` uses the ``'test'`` method
329name prefix to identify test methods automatically.
330
331Note that the order in which the various test cases will be run is determined by
332sorting the test function names with the built-in :func:`cmp` function.
333
334Often it is desirable to group suites of test cases together, so as to run tests
335for the whole system at once. This is easy, since :class:`TestSuite` instances
336can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
337added to a :class:`TestSuite`::
338
339 suite1 = module1.TheTestSuite()
340 suite2 = module2.TheTestSuite()
341 alltests = unittest.TestSuite([suite1, suite2])
342
343You can place the definitions of test cases and test suites in the same modules
344as the code they are to test (such as :file:`widget.py`), but there are several
345advantages to placing the test code in a separate module, such as
346:file:`test_widget.py`:
347
348* The test module can be run standalone from the command line.
349
350* The test code can more easily be separated from shipped code.
351
352* There is less temptation to change test code to fit the code it tests without
353 a good reason.
354
355* Test code should be modified much less frequently than the code it tests.
356
357* Tested code can be refactored more easily.
358
359* Tests for modules written in C must be in separate modules anyway, so why not
360 be consistent?
361
362* If the testing strategy changes, there is no need to change the source code.
363
364
365.. _legacy-unit-tests:
366
367Re-using old test code
368----------------------
369
370Some users will find that they have existing test code that they would like to
371run from :mod:`unittest`, without converting every old test function to a
372:class:`TestCase` subclass.
373
374For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
375This subclass of :class:`TestCase` can be used to wrap an existing test
376function. Set-up and tear-down functions can also be provided.
377
378Given the following test function::
379
380 def testSomething():
381 something = makeSomething()
382 assert something.name is not None
383 # ...
384
385one can create an equivalent test case instance as follows::
386
387 testcase = unittest.FunctionTestCase(testSomething)
388
389If there are additional set-up and tear-down methods that should be called as
390part of the test case's operation, they can also be provided like so::
391
392 testcase = unittest.FunctionTestCase(testSomething,
393 setUp=makeSomethingDB,
394 tearDown=deleteSomethingDB)
395
396To make migrating existing test suites easier, :mod:`unittest` supports tests
397raising :exc:`AssertionError` to indicate test failure. However, it is
398recommended that you use the explicit :meth:`TestCase.fail\*` and
399:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
400may treat :exc:`AssertionError` differently.
401
402.. note::
403
404 Even though :class:`FunctionTestCase` can be used to quickly convert an existing
405 test base over to a :mod:`unittest`\ -based system, this approach is not
406 recommended. Taking the time to set up proper :class:`TestCase` subclasses will
407 make future test refactorings infinitely easier.
408
409
410.. _unittest-contents:
411
412Classes and functions
413---------------------
414
415
416.. class:: TestCase([methodName])
417
418 Instances of the :class:`TestCase` class represent the smallest testable units
419 in the :mod:`unittest` universe. This class is intended to be used as a base
420 class, with specific tests being implemented by concrete subclasses. This class
421 implements the interface needed by the test runner to allow it to drive the
422 test, and methods that the test code can use to check for and report various
423 kinds of failure.
424
425 Each instance of :class:`TestCase` will run a single test method: the method
426 named *methodName*. If you remember, we had an earlier example that went
427 something like this::
428
429 def suite():
430 suite = unittest.TestSuite()
431 suite.addTest(WidgetTestCase('testDefaultSize'))
432 suite.addTest(WidgetTestCase('testResize'))
433 return suite
434
435 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
436 single test.
437
438 *methodName* defaults to ``'runTest'``.
439
440
441.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
442
443 This class implements the portion of the :class:`TestCase` interface which
444 allows the test runner to drive the test, but does not provide the methods which
445 test code can use to check and report errors. This is used to create test cases
446 using legacy test code, allowing it to be integrated into a :mod:`unittest`\
447 -based test framework.
448
449
450.. class:: TestSuite([tests])
451
452 This class represents an aggregation of individual tests cases and test suites.
453 The class presents the interface needed by the test runner to allow it to be run
454 as any other test case. Running a :class:`TestSuite` instance is the same as
455 iterating over the suite, running each test individually.
456
457 If *tests* is given, it must be an iterable of individual test cases or other
458 test suites that will be used to build the suite initially. Additional methods
459 are provided to add test cases and suites to the collection later on.
460
461
462.. class:: TestLoader()
463
464 This class is responsible for loading tests according to various criteria and
465 returning them wrapped in a :class:`TestSuite`. It can load all tests within a
466 given module or :class:`TestCase` subclass.
467
468
469.. class:: TestResult()
470
471 This class is used to compile information about which tests have succeeded and
472 which have failed.
473
474
475.. data:: defaultTestLoader
476
477 Instance of the :class:`TestLoader` class intended to be shared. If no
478 customization of the :class:`TestLoader` is needed, this instance can be used
479 instead of repeatedly creating new instances.
480
481
482.. class:: TextTestRunner([stream[, descriptions[, verbosity]]])
483
484 A basic test runner implementation which prints results on standard error. It
485 has a few configurable parameters, but is essentially very simple. Graphical
486 applications which run test suites should provide alternate implementations.
487
488
489.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader]]]]])
490
491 A command-line program that runs a set of tests; this is primarily for making
492 test modules conveniently executable. The simplest use for this function is to
493 include the following line at the end of a test script::
494
495 if __name__ == '__main__':
496 unittest.main()
497
498 The *testRunner* argument can either be a test runner class or an already
499 created instance of it.
500
501In some cases, the existing tests may have been written using the :mod:`doctest`
502module. If so, that module provides a :class:`DocTestSuite` class that can
503automatically build :class:`unittest.TestSuite` instances from the existing
504:mod:`doctest`\ -based tests.
505
Georg Brandl116aa622007-08-15 14:28:22 +0000506
507.. _testcase-objects:
508
509TestCase Objects
510----------------
511
512Each :class:`TestCase` instance represents a single test, but each concrete
513subclass may be used to define multiple tests --- the concrete class represents
514a single test fixture. The fixture is created and cleaned up for each test
515case.
516
517:class:`TestCase` instances provide three groups of methods: one group used to
518run the test, another used by the test implementation to check conditions and
519report failures, and some inquiry methods allowing information about the test
520itself to be gathered.
521
522Methods in the first group (running the test) are:
523
524
525.. method:: TestCase.setUp()
526
527 Method called to prepare the test fixture. This is called immediately before
528 calling the test method; any exception raised by this method will be considered
529 an error rather than a test failure. The default implementation does nothing.
530
531
532.. method:: TestCase.tearDown()
533
534 Method called immediately after the test method has been called and the result
535 recorded. This is called even if the test method raised an exception, so the
536 implementation in subclasses may need to be particularly careful about checking
537 internal state. Any exception raised by this method will be considered an error
538 rather than a test failure. This method will only be called if the
539 :meth:`setUp` succeeds, regardless of the outcome of the test method. The
540 default implementation does nothing.
541
542
543.. method:: TestCase.run([result])
544
545 Run the test, collecting the result into the test result object passed as
546 *result*. If *result* is omitted or :const:`None`, a temporary result object is
547 created (by calling the :meth:`defaultTestCase` method) and used; this result
548 object is not returned to :meth:`run`'s caller.
549
550 The same effect may be had by simply calling the :class:`TestCase` instance.
551
552
553.. method:: TestCase.debug()
554
555 Run the test without collecting the result. This allows exceptions raised by
556 the test to be propagated to the caller, and can be used to support running
557 tests under a debugger.
558
559The test code can use any of the following methods to check for and report
560failures.
561
562
563.. method:: TestCase.assert_(expr[, msg])
564 TestCase.failUnless(expr[, msg])
565
566 Signal a test failure if *expr* is false; the explanation for the error will be
567 *msg* if given, otherwise it will be :const:`None`.
568
569
570.. method:: TestCase.assertEqual(first, second[, msg])
571 TestCase.failUnlessEqual(first, second[, msg])
572
573 Test that *first* and *second* are equal. If the values do not compare equal,
574 the test will fail with the explanation given by *msg*, or :const:`None`. Note
575 that using :meth:`failUnlessEqual` improves upon doing the comparison as the
576 first parameter to :meth:`failUnless`: the default value for *msg* can be
577 computed to include representations of both *first* and *second*.
578
579
580.. method:: TestCase.assertNotEqual(first, second[, msg])
581 TestCase.failIfEqual(first, second[, msg])
582
583 Test that *first* and *second* are not equal. If the values do compare equal,
584 the test will fail with the explanation given by *msg*, or :const:`None`. Note
585 that using :meth:`failIfEqual` improves upon doing the comparison as the first
586 parameter to :meth:`failUnless` is that the default value for *msg* can be
587 computed to include representations of both *first* and *second*.
588
589
590.. method:: TestCase.assertAlmostEqual(first, second[, places[, msg]])
591 TestCase.failUnlessAlmostEqual(first, second[, places[, msg]])
592
593 Test that *first* and *second* are approximately equal by computing the
594 difference, rounding to the given number of *places*, and comparing to zero.
595 Note that comparing a given number of decimal places is not the same as
596 comparing a given number of significant digits. If the values do not compare
597 equal, the test will fail with the explanation given by *msg*, or :const:`None`.
598
599
600.. method:: TestCase.assertNotAlmostEqual(first, second[, places[, msg]])
601 TestCase.failIfAlmostEqual(first, second[, places[, msg]])
602
603 Test that *first* and *second* are not approximately equal by computing the
604 difference, rounding to the given number of *places*, and comparing to zero.
605 Note that comparing a given number of decimal places is not the same as
606 comparing a given number of significant digits. If the values do not compare
607 equal, the test will fail with the explanation given by *msg*, or :const:`None`.
608
609
610.. method:: TestCase.assertRaises(exception, callable, ...)
611 TestCase.failUnlessRaises(exception, callable, ...)
612
613 Test that an exception is raised when *callable* is called with any positional
614 or keyword arguments that are also passed to :meth:`assertRaises`. The test
615 passes if *exception* is raised, is an error if another exception is raised, or
616 fails if no exception is raised. To catch any of a group of exceptions, a tuple
617 containing the exception classes may be passed as *exception*.
618
619
620.. method:: TestCase.failIf(expr[, msg])
621
622 The inverse of the :meth:`failUnless` method is the :meth:`failIf` method. This
623 signals a test failure if *expr* is true, with *msg* or :const:`None` for the
624 error message.
625
626
627.. method:: TestCase.fail([msg])
628
629 Signals a test failure unconditionally, with *msg* or :const:`None` for the
630 error message.
631
632
633.. attribute:: TestCase.failureException
634
635 This class attribute gives the exception raised by the :meth:`test` method. If
636 a test framework needs to use a specialized exception, possibly to carry
637 additional information, it must subclass this exception in order to "play fair"
638 with the framework. The initial value of this attribute is
639 :exc:`AssertionError`.
640
641Testing frameworks can use the following methods to collect information on the
642test:
643
644
645.. method:: TestCase.countTestCases()
646
647 Return the number of tests represented by this test object. For
648 :class:`TestCase` instances, this will always be ``1``.
649
650
651.. method:: TestCase.defaultTestResult()
652
653 Return an instance of the test result class that should be used for this test
654 case class (if no other result instance is provided to the :meth:`run` method).
655
656 For :class:`TestCase` instances, this will always be an instance of
657 :class:`TestResult`; subclasses of :class:`TestCase` should override this as
658 necessary.
659
660
661.. method:: TestCase.id()
662
663 Return a string identifying the specific test case. This is usually the full
664 name of the test method, including the module and class name.
665
666
667.. method:: TestCase.shortDescription()
668
669 Returns a one-line description of the test, or :const:`None` if no description
670 has been provided. The default implementation of this method returns the first
671 line of the test method's docstring, if available, or :const:`None`.
672
673
674.. _testsuite-objects:
675
676TestSuite Objects
677-----------------
678
679:class:`TestSuite` objects behave much like :class:`TestCase` objects, except
680they do not actually implement a test. Instead, they are used to aggregate
681tests into groups of tests that should be run together. Some additional methods
682are available to add tests to :class:`TestSuite` instances:
683
684
685.. method:: TestSuite.addTest(test)
686
687 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
688
689
690.. method:: TestSuite.addTests(tests)
691
692 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
693 instances to this test suite.
694
695 This is equivalent to iterating over *tests*, calling :meth:`addTest` for each
696 element.
697
698:class:`TestSuite` shares the following methods with :class:`TestCase`:
699
700
701.. method:: TestSuite.run(result)
702
703 Run the tests associated with this suite, collecting the result into the test
704 result object passed as *result*. Note that unlike :meth:`TestCase.run`,
705 :meth:`TestSuite.run` requires the result object to be passed in.
706
707
708.. method:: TestSuite.debug()
709
710 Run the tests associated with this suite without collecting the result. This
711 allows exceptions raised by the test to be propagated to the caller and can be
712 used to support running tests under a debugger.
713
714
715.. method:: TestSuite.countTestCases()
716
717 Return the number of tests represented by this test object, including all
718 individual tests and sub-suites.
719
720In the typical usage of a :class:`TestSuite` object, the :meth:`run` method is
721invoked by a :class:`TestRunner` rather than by the end-user test harness.
722
723
724.. _testresult-objects:
725
726TestResult Objects
727------------------
728
729A :class:`TestResult` object stores the results of a set of tests. The
730:class:`TestCase` and :class:`TestSuite` classes ensure that results are
731properly recorded; test authors do not need to worry about recording the outcome
732of tests.
733
734Testing frameworks built on top of :mod:`unittest` may want access to the
735:class:`TestResult` object generated by running a set of tests for reporting
736purposes; a :class:`TestResult` instance is returned by the
737:meth:`TestRunner.run` method for this purpose.
738
739:class:`TestResult` instances have the following attributes that will be of
740interest when inspecting the results of running a set of tests:
741
742
743.. attribute:: TestResult.errors
744
745 A list containing 2-tuples of :class:`TestCase` instances and strings holding
746 formatted tracebacks. Each tuple represents a test which raised an unexpected
747 exception.
748
Georg Brandl116aa622007-08-15 14:28:22 +0000749
750.. attribute:: TestResult.failures
751
752 A list containing 2-tuples of :class:`TestCase` instances and strings holding
753 formatted tracebacks. Each tuple represents a test where a failure was
754 explicitly signalled using the :meth:`TestCase.fail\*` or
755 :meth:`TestCase.assert\*` methods.
756
Georg Brandl116aa622007-08-15 14:28:22 +0000757
758.. attribute:: TestResult.testsRun
759
760 The total number of tests run so far.
761
762
763.. method:: TestResult.wasSuccessful()
764
765 Returns :const:`True` if all tests run so far have passed, otherwise returns
766 :const:`False`.
767
768
769.. method:: TestResult.stop()
770
771 This method can be called to signal that the set of tests being run should be
772 aborted by setting the :class:`TestResult`'s ``shouldStop`` attribute to
773 :const:`True`. :class:`TestRunner` objects should respect this flag and return
774 without running any additional tests.
775
776 For example, this feature is used by the :class:`TextTestRunner` class to stop
777 the test framework when the user signals an interrupt from the keyboard.
778 Interactive tools which provide :class:`TestRunner` implementations can use this
779 in a similar manner.
780
781The following methods of the :class:`TestResult` class are used to maintain the
782internal data structures, and may be extended in subclasses to support
783additional reporting requirements. This is particularly useful in building
784tools which support interactive reporting while tests are being run.
785
786
787.. method:: TestResult.startTest(test)
788
789 Called when the test case *test* is about to be run.
790
791 The default implementation simply increments the instance's ``testsRun``
792 counter.
793
794
795.. method:: TestResult.stopTest(test)
796
797 Called after the test case *test* has been executed, regardless of the outcome.
798
799 The default implementation does nothing.
800
801
802.. method:: TestResult.addError(test, err)
803
804 Called when the test case *test* raises an unexpected exception *err* is a tuple
805 of the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
806
807 The default implementation appends ``(test, err)`` to the instance's ``errors``
808 attribute.
809
810
811.. method:: TestResult.addFailure(test, err)
812
813 Called when the test case *test* signals a failure. *err* is a tuple of the form
814 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
815
816 The default implementation appends ``(test, err)`` to the instance's
817 ``failures`` attribute.
818
819
820.. method:: TestResult.addSuccess(test)
821
822 Called when the test case *test* succeeds.
823
824 The default implementation does nothing.
825
826
827.. _testloader-objects:
828
829TestLoader Objects
830------------------
831
832The :class:`TestLoader` class is used to create test suites from classes and
833modules. Normally, there is no need to create an instance of this class; the
834:mod:`unittest` module provides an instance that can be shared as
835``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
836customization of some configurable properties.
837
838:class:`TestLoader` objects have the following methods:
839
840
841.. method:: TestLoader.loadTestsFromTestCase(testCaseClass)
842
843 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
844 :class:`testCaseClass`.
845
846
847.. method:: TestLoader.loadTestsFromModule(module)
848
849 Return a suite of all tests cases contained in the given module. This method
850 searches *module* for classes derived from :class:`TestCase` and creates an
851 instance of the class for each test method defined for the class.
852
853 .. warning::
854
855 While using a hierarchy of :class:`TestCase`\ -derived classes can be convenient
856 in sharing fixtures and helper functions, defining test methods on base classes
857 that are not intended to be instantiated directly does not play well with this
858 method. Doing so, however, can be useful when the fixtures are different and
859 defined in subclasses.
860
861
862.. method:: TestLoader.loadTestsFromName(name[, module])
863
864 Return a suite of all tests cases given a string specifier.
865
866 The specifier *name* is a "dotted name" that may resolve either to a module, a
867 test case class, a test method within a test case class, a :class:`TestSuite`
868 instance, or a callable object which returns a :class:`TestCase` or
869 :class:`TestSuite` instance. These checks are applied in the order listed here;
870 that is, a method on a possible test case class will be picked up as "a test
871 method within a test case class", rather than "a callable object".
872
873 For example, if you have a module :mod:`SampleTests` containing a
874 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
875 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
876 specifier ``'SampleTests.SampleTestCase'`` would cause this method to return a
877 suite which will run all three test methods. Using the specifier
878 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test suite
879 which will run only the :meth:`test_two` test method. The specifier can refer
880 to modules and packages which have not been imported; they will be imported as a
881 side-effect.
882
883 The method optionally resolves *name* relative to the given *module*.
884
885
886.. method:: TestLoader.loadTestsFromNames(names[, module])
887
888 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather than
889 a single name. The return value is a test suite which supports all the tests
890 defined for each name.
891
892
893.. method:: TestLoader.getTestCaseNames(testCaseClass)
894
895 Return a sorted sequence of method names found within *testCaseClass*; this
896 should be a subclass of :class:`TestCase`.
897
898The following attributes of a :class:`TestLoader` can be configured either by
899subclassing or assignment on an instance:
900
901
902.. attribute:: TestLoader.testMethodPrefix
903
904 String giving the prefix of method names which will be interpreted as test
905 methods. The default value is ``'test'``.
906
907 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
908 methods.
909
910
911.. attribute:: TestLoader.sortTestMethodsUsing
912
913 Function to be used to compare method names when sorting them in
914 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
915 default value is the built-in :func:`cmp` function; the attribute can also be
916 set to :const:`None` to disable the sort.
917
918
919.. attribute:: TestLoader.suiteClass
920
921 Callable object that constructs a test suite from a list of tests. No methods on
922 the resulting object are needed. The default value is the :class:`TestSuite`
923 class.
924
925 This affects all the :meth:`loadTestsFrom\*` methods.
926