blob: e1d416d607a07a5e5929b94037167a842364ea66 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`unittest` --- Unit testing framework
2==========================================
3
4.. module:: unittest
5 :synopsis: Unit testing framework for Python.
6.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
7.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9.. sectionauthor:: Raymond Hettinger <python@rcn.com>
10
11
12.. versionadded:: 2.1
Benjamin Peterson692428e2009-03-23 21:50:21 +000013
Benjamin Peterson99721e02009-03-23 23:10:14 +000014.. versionchanged:: 2.7
15 Added test :ref:`skipping and expected failures <unittest-skipping>`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000016
17The Python unit testing framework, sometimes referred to as "PyUnit," is a
18Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
19turn, a Java version of Kent's Smalltalk testing framework. Each is the de
20facto standard unit testing framework for its respective language.
21
22:mod:`unittest` supports test automation, sharing of setup and shutdown code for
23tests, aggregation of tests into collections, and independence of the tests from
24the reporting framework. The :mod:`unittest` module provides classes that make
25it easy to support these qualities for a set of tests.
26
27To achieve this, :mod:`unittest` supports some important concepts:
28
29test fixture
30 A :dfn:`test fixture` represents the preparation needed to perform one or more
31 tests, and any associate cleanup actions. This may involve, for example,
32 creating temporary or proxy databases, directories, or starting a server
33 process.
34
35test case
36 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
37 response to a particular set of inputs. :mod:`unittest` provides a base class,
38 :class:`TestCase`, which may be used to create new test cases.
39
40test suite
41 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
42 used to aggregate tests that should be executed together.
43
44test runner
45 A :dfn:`test runner` is a component which orchestrates the execution of tests
46 and provides the outcome to the user. The runner may use a graphical interface,
47 a textual interface, or return a special value to indicate the results of
48 executing the tests.
49
50The test case and test fixture concepts are supported through the
51:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
52used when creating new tests, and the latter can be used when integrating
53existing test code with a :mod:`unittest`\ -driven framework. When building test
Benjamin Peterson99721e02009-03-23 23:10:14 +000054fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
55:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
56and cleanup for the fixture. With :class:`FunctionTestCase`, existing functions
57can be passed to the constructor for these purposes. When the test is run, the
58fixture initialization is run first; if it succeeds, the cleanup method is run
59after the test has been executed, regardless of the outcome of the test. Each
60instance of the :class:`TestCase` will only be used to run a single test method,
61so a new fixture is created for each test.
Georg Brandl8ec7f652007-08-15 14:28:01 +000062
63Test suites are implemented by the :class:`TestSuite` class. This class allows
64individual tests and test suites to be aggregated; when the suite is executed,
Benjamin Peterson692428e2009-03-23 21:50:21 +000065all tests added directly to the suite and in "child" test suites are run. A
66:class:`ClassTestSuite` contains the test cases of a class.
Georg Brandl8ec7f652007-08-15 14:28:01 +000067
Benjamin Peterson99721e02009-03-23 23:10:14 +000068A test runner is an object that provides a single method,
69:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
70object as a parameter, and returns a result object. The class
71:class:`TestResult` is provided for use as the result object. :mod:`unittest`
72provides the :class:`TextTestRunner` as an example test runner which reports
73test results on the standard error stream by default. Alternate runners can be
74implemented for other environments (such as graphical environments) without any
75need to derive from a specific class.
Georg Brandl8ec7f652007-08-15 14:28:01 +000076
77
78.. seealso::
79
80 Module :mod:`doctest`
81 Another test-support module with a very different flavor.
82
83 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
84 Kent Beck's original paper on testing frameworks using the pattern shared by
85 :mod:`unittest`.
86
Raymond Hettinger21b617b2009-03-24 00:17:11 +000087 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
88 Third-party unittest frameworks with a lighter-weight syntax
89 for writing tests. For example, ``assert func(10) == 42``.
90
91 `python-mock <http://python-mock.sourceforge.net/>`_ and `minimock <http://blog.ianbicking.org/minimock.html>`_
92 Tools for creating mock test objects (objects simulating external resources).
Georg Brandl8ec7f652007-08-15 14:28:01 +000093
94.. _unittest-minimal-example:
95
96Basic example
97-------------
98
99The :mod:`unittest` module provides a rich set of tools for constructing and
100running tests. This section demonstrates that a small subset of the tools
101suffice to meet the needs of most users.
102
103Here is a short script to test three functions from the :mod:`random` module::
104
105 import random
106 import unittest
107
108 class TestSequenceFunctions(unittest.TestCase):
109
110 def setUp(self):
111 self.seq = range(10)
112
Benjamin Peterson99721e02009-03-23 23:10:14 +0000113 def test_shuffle(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000114 # make sure the shuffled sequence does not lose any elements
115 random.shuffle(self.seq)
116 self.seq.sort()
117 self.assertEqual(self.seq, range(10))
118
Benjamin Peterson99721e02009-03-23 23:10:14 +0000119 def test_choice(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000120 element = random.choice(self.seq)
121 self.assert_(element in self.seq)
122
Benjamin Peterson99721e02009-03-23 23:10:14 +0000123 def test_sample(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000124 self.assertRaises(ValueError, random.sample, self.seq, 20)
125 for element in random.sample(self.seq, 5):
126 self.assert_(element in self.seq)
127
128 if __name__ == '__main__':
129 unittest.main()
130
Benjamin Peterson99721e02009-03-23 23:10:14 +0000131A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl8ec7f652007-08-15 14:28:01 +0000132individual tests are defined with methods whose names start with the letters
133``test``. This naming convention informs the test runner about which methods
134represent tests.
135
Benjamin Peterson99721e02009-03-23 23:10:14 +0000136The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
137expected result; :meth:`~TestCase.assert_` to verify a condition; or
138:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
139These methods are used instead of the :keyword:`assert` statement so the test
140runner can accumulate all test results and produce a report.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000141
Benjamin Peterson99721e02009-03-23 23:10:14 +0000142When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
143method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
144defined, the test runner will invoke that method after each test. In the
145example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
146test.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000147
148The final block shows a simple way to run the tests. :func:`unittest.main`
149provides a command line interface to the test script. When run from the command
150line, the above script produces an output that looks like this::
151
152 ...
153 ----------------------------------------------------------------------
154 Ran 3 tests in 0.000s
155
156 OK
157
158Instead of :func:`unittest.main`, there are other ways to run the tests with a
159finer level of control, less terse output, and no requirement to be run from the
160command line. For example, the last two lines may be replaced with::
161
162 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
163 unittest.TextTestRunner(verbosity=2).run(suite)
164
165Running the revised script from the interpreter or another script produces the
166following output::
167
168 testchoice (__main__.TestSequenceFunctions) ... ok
169 testsample (__main__.TestSequenceFunctions) ... ok
170 testshuffle (__main__.TestSequenceFunctions) ... ok
171
172 ----------------------------------------------------------------------
173 Ran 3 tests in 0.110s
174
175 OK
176
177The above examples show the most commonly used :mod:`unittest` features which
178are sufficient to meet many everyday testing needs. The remainder of the
179documentation explores the full feature set from first principles.
180
181
182.. _organizing-tests:
183
184Organizing test code
185--------------------
186
187The basic building blocks of unit testing are :dfn:`test cases` --- single
188scenarios that must be set up and checked for correctness. In :mod:`unittest`,
189test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
190class. To make your own test cases you must write subclasses of
191:class:`TestCase`, or use :class:`FunctionTestCase`.
192
193An instance of a :class:`TestCase`\ -derived class is an object that can
194completely run a single test method, together with optional set-up and tidy-up
195code.
196
197The testing code of a :class:`TestCase` instance should be entirely self
198contained, such that it can be run either in isolation or in arbitrary
199combination with any number of other test cases.
200
Benjamin Peterson99721e02009-03-23 23:10:14 +0000201The simplest :class:`TestCase` subclass will simply override the
202:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000203
204 import unittest
205
206 class DefaultWidgetSizeTestCase(unittest.TestCase):
207 def runTest(self):
208 widget = Widget('The widget')
209 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
210
Gregory P. Smith28399852009-03-31 16:54:10 +0000211Note that in order to test something, we use the one of the :meth:`assert\*`
212methods provided by the :class:`TestCase` base class. If the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000213test fails, an exception will be raised, and :mod:`unittest` will identify the
214test case as a :dfn:`failure`. Any other exceptions will be treated as
215:dfn:`errors`. This helps you identify where the problem is: :dfn:`failures` are
216caused by incorrect results - a 5 where you expected a 6. :dfn:`Errors` are
217caused by incorrect code - e.g., a :exc:`TypeError` caused by an incorrect
218function call.
219
220The way to run a test case will be described later. For now, note that to
221construct an instance of such a test case, we call its constructor without
222arguments::
223
224 testCase = DefaultWidgetSizeTestCase()
225
226Now, such test cases can be numerous, and their set-up can be repetitive. In
227the above case, constructing a :class:`Widget` in each of 100 Widget test case
228subclasses would mean unsightly duplication.
229
230Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson99721e02009-03-23 23:10:14 +0000231:meth:`~TestCase.setUp`, which the testing framework will automatically call for
232us when we run the test::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000233
234 import unittest
235
236 class SimpleWidgetTestCase(unittest.TestCase):
237 def setUp(self):
238 self.widget = Widget('The widget')
239
240 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
241 def runTest(self):
Gregory P. Smith28399852009-03-31 16:54:10 +0000242 self.assertTrue(self.widget.size() == (50,50),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000243 'incorrect default size')
244
245 class WidgetResizeTestCase(SimpleWidgetTestCase):
246 def runTest(self):
247 self.widget.resize(100,150)
Gregory P. Smith28399852009-03-31 16:54:10 +0000248 self.assertTrue(self.widget.size() == (100,150),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000249 'wrong size after resize')
250
Benjamin Peterson99721e02009-03-23 23:10:14 +0000251If the :meth:`~TestCase.setUp` method raises an exception while the test is
252running, the framework will consider the test to have suffered an error, and the
253:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000254
Benjamin Peterson99721e02009-03-23 23:10:14 +0000255Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
256after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000257
258 import unittest
259
260 class SimpleWidgetTestCase(unittest.TestCase):
261 def setUp(self):
262 self.widget = Widget('The widget')
263
264 def tearDown(self):
265 self.widget.dispose()
266 self.widget = None
267
Benjamin Peterson99721e02009-03-23 23:10:14 +0000268If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
269be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000270
271Such a working environment for the testing code is called a :dfn:`fixture`.
272
273Often, many small test cases will use the same fixture. In this case, we would
274end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
275classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000276discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
277mechanism::
278
279 import unittest
280
281 class WidgetTestCase(unittest.TestCase):
282 def setUp(self):
283 self.widget = Widget('The widget')
284
285 def tearDown(self):
286 self.widget.dispose()
287 self.widget = None
288
289 def testDefaultSize(self):
Gregory P. Smith28399852009-03-31 16:54:10 +0000290 self.assertTrue(self.widget.size() == (50,50),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000291 'incorrect default size')
292
293 def testResize(self):
294 self.widget.resize(100,150)
Gregory P. Smith28399852009-03-31 16:54:10 +0000295 self.assertTrue(self.widget.size() == (100,150),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000296 'wrong size after resize')
297
Benjamin Peterson99721e02009-03-23 23:10:14 +0000298Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
299provided two different test methods. Class instances will now each run one of
300the :meth:`test\*` methods, with ``self.widget`` created and destroyed
301separately for each instance. When creating an instance we must specify the
302test method it is to run. We do this by passing the method name in the
303constructor::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000304
305 defaultSizeTestCase = WidgetTestCase('testDefaultSize')
306 resizeTestCase = WidgetTestCase('testResize')
307
308Test case instances are grouped together according to the features they test.
309:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
310represented by :mod:`unittest`'s :class:`TestSuite` class::
311
312 widgetTestSuite = unittest.TestSuite()
313 widgetTestSuite.addTest(WidgetTestCase('testDefaultSize'))
314 widgetTestSuite.addTest(WidgetTestCase('testResize'))
315
316For the ease of running tests, as we will see later, it is a good idea to
317provide in each test module a callable object that returns a pre-built test
318suite::
319
320 def suite():
321 suite = unittest.TestSuite()
322 suite.addTest(WidgetTestCase('testDefaultSize'))
323 suite.addTest(WidgetTestCase('testResize'))
324 return suite
325
326or even::
327
328 def suite():
329 tests = ['testDefaultSize', 'testResize']
330
331 return unittest.TestSuite(map(WidgetTestCase, tests))
332
333Since it is a common pattern to create a :class:`TestCase` subclass with many
334similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
335class that can be used to automate the process of creating a test suite and
336populating it with individual tests. For example, ::
337
338 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
339
340will create a test suite that will run ``WidgetTestCase.testDefaultSize()`` and
341``WidgetTestCase.testResize``. :class:`TestLoader` uses the ``'test'`` method
342name prefix to identify test methods automatically.
343
344Note that the order in which the various test cases will be run is determined by
345sorting the test function names with the built-in :func:`cmp` function.
346
347Often it is desirable to group suites of test cases together, so as to run tests
348for the whole system at once. This is easy, since :class:`TestSuite` instances
349can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
350added to a :class:`TestSuite`::
351
352 suite1 = module1.TheTestSuite()
353 suite2 = module2.TheTestSuite()
354 alltests = unittest.TestSuite([suite1, suite2])
355
356You can place the definitions of test cases and test suites in the same modules
357as the code they are to test (such as :file:`widget.py`), but there are several
358advantages to placing the test code in a separate module, such as
359:file:`test_widget.py`:
360
361* The test module can be run standalone from the command line.
362
363* The test code can more easily be separated from shipped code.
364
365* There is less temptation to change test code to fit the code it tests without
366 a good reason.
367
368* Test code should be modified much less frequently than the code it tests.
369
370* Tested code can be refactored more easily.
371
372* Tests for modules written in C must be in separate modules anyway, so why not
373 be consistent?
374
375* If the testing strategy changes, there is no need to change the source code.
376
377
378.. _legacy-unit-tests:
379
380Re-using old test code
381----------------------
382
383Some users will find that they have existing test code that they would like to
384run from :mod:`unittest`, without converting every old test function to a
385:class:`TestCase` subclass.
386
387For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
388This subclass of :class:`TestCase` can be used to wrap an existing test
389function. Set-up and tear-down functions can also be provided.
390
391Given the following test function::
392
393 def testSomething():
394 something = makeSomething()
395 assert something.name is not None
396 # ...
397
398one can create an equivalent test case instance as follows::
399
400 testcase = unittest.FunctionTestCase(testSomething)
401
402If there are additional set-up and tear-down methods that should be called as
403part of the test case's operation, they can also be provided like so::
404
405 testcase = unittest.FunctionTestCase(testSomething,
406 setUp=makeSomethingDB,
407 tearDown=deleteSomethingDB)
408
409To make migrating existing test suites easier, :mod:`unittest` supports tests
410raising :exc:`AssertionError` to indicate test failure. However, it is
411recommended that you use the explicit :meth:`TestCase.fail\*` and
412:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
413may treat :exc:`AssertionError` differently.
414
415.. note::
416
417 Even though :class:`FunctionTestCase` can be used to quickly convert an existing
418 test base over to a :mod:`unittest`\ -based system, this approach is not
419 recommended. Taking the time to set up proper :class:`TestCase` subclasses will
420 make future test refactorings infinitely easier.
421
Benjamin Peterson99721e02009-03-23 23:10:14 +0000422In some cases, the existing tests may have been written using the :mod:`doctest`
423module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
424automatically build :class:`unittest.TestSuite` instances from the existing
425:mod:`doctest`\ -based tests.
426
Georg Brandl8ec7f652007-08-15 14:28:01 +0000427
Benjamin Peterson692428e2009-03-23 21:50:21 +0000428.. _unittest-skipping:
429
430Skipping tests and expected failures
431------------------------------------
432
433Unittest supports skipping individual test methods and even whole classes of
434tests. In addition, it supports marking a test as a "expected failure," a test
435that is broken and will fail, but shouldn't be counted as a failure on a
436:class:`TestResult`.
437
438Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
439or one of its conditional variants.
440
441Basic skipping looks like this: ::
442
443 class MyTestCase(unittest.TestCase):
444
445 @unittest.skip("demonstrating skipping")
446 def test_nothing(self):
447 self.fail("shouldn't happen")
448
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000449 @unittest.skipIf(mylib.__version__ < (1, 3), "not supported in this library version")
450 def test_format(self):
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000451 # Tests that work for only a certain version of the library.
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000452 pass
453
454 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
455 def test_windows_support(self):
456 # windows specific testing code
457 pass
458
Benjamin Peterson692428e2009-03-23 21:50:21 +0000459This is the output of running the example above in verbose mode: ::
460
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000461 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000462 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000463 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000464
465 ----------------------------------------------------------------------
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000466 Ran 3 tests in 0.005s
467
468 OK (skipped=3)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000469
470Classes can be skipped just like methods: ::
471
472 @skip("showing class skipping")
473 class MySkippedTestCase(unittest.TestCase):
474 def test_not_run(self):
475 pass
476
Benjamin Peterson31b78062009-03-23 23:13:36 +0000477:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
478that needs to be set up is not available.
479
Benjamin Peterson692428e2009-03-23 21:50:21 +0000480Expected failures use the :func:`expectedFailure` decorator. ::
481
482 class ExpectedFailureTestCase(unittest.TestCase):
483 @unittest.expectedFailure
484 def test_fail(self):
485 self.assertEqual(1, 0, "broken")
486
487It's easy to roll your own skipping decorators by making a decorator that calls
488:func:`skip` on the test when it wants it to be skipped. This decorator skips
489the test unless the passed object has a certain attribute: ::
490
491 def skipUnlessHasattr(obj, attr):
492 if hasattr(obj, attr):
493 return lambda func: func
494 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
495
496The following decorators implement test skipping and expected failures:
497
498.. function:: skip(reason)
499
500 Unconditionally skip the decorated test. *reason* should describe why the
501 test is being skipped.
502
503.. function:: skipIf(condition, reason)
504
505 Skip the decorated test if *condition* is true.
506
507.. function:: skipUnless(condition, reason)
508
509 Skip the decoratored test unless *condition* is true.
510
511.. function:: expectedFailure
512
513 Mark the test as an expected failure. If the test fails when run, the test
514 is not counted as a failure.
515
516
Georg Brandl8ec7f652007-08-15 14:28:01 +0000517.. _unittest-contents:
518
519Classes and functions
520---------------------
521
Benjamin Peterson99721e02009-03-23 23:10:14 +0000522This section describes in depth the API of :mod:`unittest`.
523
524
525.. _testcase-objects:
526
527Test cases
528~~~~~~~~~~
Georg Brandl8ec7f652007-08-15 14:28:01 +0000529
530.. class:: TestCase([methodName])
531
532 Instances of the :class:`TestCase` class represent the smallest testable units
533 in the :mod:`unittest` universe. This class is intended to be used as a base
534 class, with specific tests being implemented by concrete subclasses. This class
535 implements the interface needed by the test runner to allow it to drive the
536 test, and methods that the test code can use to check for and report various
537 kinds of failure.
538
539 Each instance of :class:`TestCase` will run a single test method: the method
540 named *methodName*. If you remember, we had an earlier example that went
541 something like this::
542
543 def suite():
544 suite = unittest.TestSuite()
545 suite.addTest(WidgetTestCase('testDefaultSize'))
546 suite.addTest(WidgetTestCase('testResize'))
547 return suite
548
549 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
550 single test.
551
Benjamin Peterson99721e02009-03-23 23:10:14 +0000552 *methodName* defaults to :meth:`runTest`.
553
554 :class:`TestCase` instances provide three groups of methods: one group used
555 to run the test, another used by the test implementation to check conditions
556 and report failures, and some inquiry methods allowing information about the
557 test itself to be gathered.
558
559 Methods in the first group (running the test) are:
560
561
562 .. method:: setUp()
563
564 Method called to prepare the test fixture. This is called immediately
565 before calling the test method; any exception raised by this method will
566 be considered an error rather than a test failure. The default
567 implementation does nothing.
568
569
570 .. method:: tearDown()
571
572 Method called immediately after the test method has been called and the
573 result recorded. This is called even if the test method raised an
574 exception, so the implementation in subclasses may need to be particularly
575 careful about checking internal state. Any exception raised by this
576 method will be considered an error rather than a test failure. This
577 method will only be called if the :meth:`setUp` succeeds, regardless of
578 the outcome of the test method. The default implementation does nothing.
579
580
581 .. method:: run([result])
582
583 Run the test, collecting the result into the test result object passed as
584 *result*. If *result* is omitted or :const:`None`, a temporary result
585 object is created (by calling the :meth:`defaultTestCase` method) and
586 used; this result object is not returned to :meth:`run`'s caller.
587
588 The same effect may be had by simply calling the :class:`TestCase`
589 instance.
590
591
Benjamin Peterson47d97382009-03-26 20:05:50 +0000592 .. method:: skipTest(reason)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000593
Benjamin Peterson31b78062009-03-23 23:13:36 +0000594 Calling this during the a test method or :meth:`setUp` skips the current
595 test. See :ref:`unittest-skipping` for more information.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000596
597
598 .. method:: debug()
599
600 Run the test without collecting the result. This allows exceptions raised
601 by the test to be propagated to the caller, and can be used to support
602 running tests under a debugger.
603
604 The test code can use any of the following methods to check for and report
605 failures.
606
607
Gregory P. Smith28399852009-03-31 16:54:10 +0000608 .. method:: assertTrue(expr[, msg])
609 assert_(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000610 failUnless(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000611
Georg Brandl64034bb2009-04-25 14:51:31 +0000612 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson99721e02009-03-23 23:10:14 +0000613 will be *msg* if given, otherwise it will be :const:`None`.
614
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000615 .. deprecated:: 2.7
616 :meth:`failUnless`.
617
Benjamin Peterson99721e02009-03-23 23:10:14 +0000618
619 .. method:: assertEqual(first, second[, msg])
620 failUnlessEqual(first, second[, msg])
621
622 Test that *first* and *second* are equal. If the values do not compare
623 equal, the test will fail with the explanation given by *msg*, or
Gregory P. Smith28399852009-03-31 16:54:10 +0000624 :const:`None`. Note that using :meth:`assertEqual` improves upon
625 doing the comparison as the first parameter to :meth:`assertTrue`: the
626 default value for *msg* include representations of both *first* and
627 *second*.
628
629 In addition, if *first* and *second* are the exact same type and one of
630 list, tuple, dict, set, or frozenset or any type that a subclass
631 registers :meth:`addTypeEqualityFunc` the type specific equality function
632 will be called in order to generate a more useful default error message.
633
634 .. versionchanged:: 2.7
635 Added the automatic calling of type specific equality function.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000636
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000637 .. deprecated:: 2.7
638 :meth:`failUnlessEqual`.
639
Benjamin Peterson99721e02009-03-23 23:10:14 +0000640
641 .. method:: assertNotEqual(first, second[, msg])
642 failIfEqual(first, second[, msg])
643
644 Test that *first* and *second* are not equal. If the values do compare
645 equal, the test will fail with the explanation given by *msg*, or
Gregory P. Smith28399852009-03-31 16:54:10 +0000646 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
647 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson99721e02009-03-23 23:10:14 +0000648 default value for *msg* can be computed to include representations of both
649 *first* and *second*.
650
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000651 .. deprecated:: 2.7
652 :meth:`failIfEqual`.
653
Benjamin Peterson99721e02009-03-23 23:10:14 +0000654
655 .. method:: assertAlmostEqual(first, second[, places[, msg]])
656 failUnlessAlmostEqual(first, second[, places[, msg]])
657
658 Test that *first* and *second* are approximately equal by computing the
659 difference, rounding to the given number of decimal *places* (default 7),
660 and comparing to zero.
661
662 Note that comparing a given number of decimal places is not the same as
663 comparing a given number of significant digits. If the values do not
664 compare equal, the test will fail with the explanation given by *msg*, or
665 :const:`None`.
666
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000667 .. deprecated:: 2.7
668 :meth:`failUnlessAlmostEqual`.
669
Benjamin Peterson99721e02009-03-23 23:10:14 +0000670
671 .. method:: assertNotAlmostEqual(first, second[, places[, msg]])
672 failIfAlmostEqual(first, second[, places[, msg]])
673
674 Test that *first* and *second* are not approximately equal by computing
675 the difference, rounding to the given number of decimal *places* (default
676 7), and comparing to zero.
677
678 Note that comparing a given number of decimal places is not the same as
679 comparing a given number of significant digits. If the values do not
680 compare equal, the test will fail with the explanation given by *msg*, or
681 :const:`None`.
682
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000683 .. deprecated:: 2.7
684 :meth:`failIfAlmostEqual`.
685
Benjamin Peterson99721e02009-03-23 23:10:14 +0000686
Gregory P. Smith28399852009-03-31 16:54:10 +0000687 .. method:: assertGreater(first, second, msg=None)
688 assertGreaterEqual(first, second, msg=None)
689 assertLess(first, second, msg=None)
690 assertLessEqual(first, second, msg=None)
691
692 Test that *first* is respectively >, >=, < or <= than *second* depending
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000693 on the method name. If not, the test will fail with an explanation
Gregory P. Smith28399852009-03-31 16:54:10 +0000694 or with the explanation given by *msg*::
695
696 >>> self.assertGreaterEqual(3, 4)
697 AssertionError: "3" unexpectedly not greater than or equal to "4"
698
699 .. versionadded:: 2.7
700
701
702 .. method:: assertMultiLineEqual(self, first, second, msg=None)
703
704 Test that the multiline string *first* is equal to the string *second*.
705 When not equal a diff of the two strings highlighting the differences
706 will be included in the error message.
707
708 If specified *msg* will be used as the error message on failure.
709
710 .. versionadded:: 2.7
711
712
713 .. method:: assertRegexpMatches(text, regexp[, msg=None]):
714
715 Verifies that a *regexp* search matches *text*. Fails with an error
716 message including the pattern and the *text*. *regexp* may be
717 a regular expression object or a string containing a regular expression
718 suitable for use by :func:`re.search`.
719
720 .. versionadded:: 2.7
721
722
723 .. method:: assertIn(first, second, msg=None)
724 assertNotIn(first, second, msg=None)
725
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000726 Tests that *first* is or is not in *second* with an explanatory error
Gregory P. Smith28399852009-03-31 16:54:10 +0000727 message as appropriate.
728
729 If specified *msg* will be used as the error message on failure.
730
731 .. versionadded:: 2.7
732
733
734 .. method:: assertSameElements(expected, actual, msg=None)
735
736 Test that sequence *expected* contains the same elements as *actual*.
737 When they don't an error message listing the differences between the
738 sequences will be generated.
739
740 If specified *msg* will be used as the error message on failure.
741
742 .. versionadded:: 2.7
743
744
745 .. method:: assertSetEqual(set1, set2, msg=None)
746
747 Tests that two sets are equal. If not, an error message is constructed
748 that lists the differences between the sets.
749
750 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
751 method.
752
753 If specified *msg* will be used as the error message on failure.
754
755 .. versionadded:: 2.7
756
757
758 .. method:: assertDictEqual(expected, actual, msg=None)
759
760 Test that two dictionaries are equal. If not, an error message is
761 constructed that shows the differences in the dictionaries.
762
763 If specified *msg* will be used as the error message on failure.
764
765 .. versionadded:: 2.7
766
767
768 .. method:: assertDictContainsSubset(expected, actual, msg=None)
769
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000770 Tests whether the key/value pairs in dictionary *actual* are a
Gregory P. Smith28399852009-03-31 16:54:10 +0000771 superset of those in *expected*. If not, an error message listing
772 the missing keys and mismatched values is generated.
773
774 If specified *msg* will be used as the error message on failure.
775
776 .. versionadded:: 2.7
777
778
779 .. method:: assertListEqual(list1, list2, msg=None)
780 assertTupleEqual(tuple1, tuple2, msg=None)
781
782 Tests that two lists or tuples are equal. If not an error message is
783 constructed that shows only the differences between the two. An error
784 is also raised if either of the parameters are of the wrong type.
785
786 If specified *msg* will be used as the error message on failure.
787
788 .. versionadded:: 2.7
789
790
791 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
792
793 Tests that two sequences are equal. If a *seq_type* is supplied, both
794 *seq1* and *seq2* must be instances of *seq_type* or a failure will
795 be raised. If the sequences are different an error message is
796 constructed that shows the difference between the two.
797
798 If specified *msg* will be used as the error message on failure.
799
800 This method is used to implement :meth:`assertListEqual` and
801 :meth:`assertTupleEqual`.
802
803 .. versionadded:: 2.7
804
805
Benjamin Peterson99721e02009-03-23 23:10:14 +0000806 .. method:: assertRaises(exception[, callable, ...])
807 failUnlessRaises(exception[, callable, ...])
808
809 Test that an exception is raised when *callable* is called with any
810 positional or keyword arguments that are also passed to
811 :meth:`assertRaises`. The test passes if *exception* is raised, is an
812 error if another exception is raised, or fails if no exception is raised.
813 To catch any of a group of exceptions, a tuple containing the exception
814 classes may be passed as *exception*.
815
Benjamin Peterson7233acc2009-03-29 03:31:40 +0000816 If *callable* is omitted or None, returns a context manager so that the
817 code under test can be written inline rather than as a function::
818
819 with self.failUnlessRaises(some_error_class):
820 do_something()
821
Benjamin Peterson99721e02009-03-23 23:10:14 +0000822 .. versionchanged:: 2.7
Benjamin Peterson7233acc2009-03-29 03:31:40 +0000823 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000824
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000825 .. deprecated:: 2.7
826 :meth:`failUnlessRaises`.
827
Benjamin Peterson99721e02009-03-23 23:10:14 +0000828
Gregory P. Smith28399852009-03-31 16:54:10 +0000829 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000830
Gregory P. Smith28399852009-03-31 16:54:10 +0000831 Like :meth:`assertRaises` but also tests that *regexp* matches
832 on the string representation of the raised exception. *regexp* may be
833 a regular expression object or a string containing a regular expression
834 suitable for use by :func:`re.search`. Examples::
835
836 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
837 int, 'XYZ')
838
839 or::
840
841 with self.assertRaisesRegexp(ValueError, 'literal'):
842 int('XYZ')
843
844 .. versionadded:: 2.7
845
846
847 .. method:: assertIsNone(expr[, msg])
848
849 This signals a test failure if *expr* is not None.
850
851 .. versionadded:: 2.7
852
853
854 .. method:: assertIsNotNone(expr[, msg])
855
856 The inverse of the :meth:`assertIsNone` method.
857 This signals a test failure if *expr* is None.
858
859 .. versionadded:: 2.7
860
861
Michael Foordf2dfef12009-04-05 19:19:28 +0000862 .. method:: assertIs(expr1, expr2[, msg])
863
864 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
865 object.
866
867 .. versionadded:: 2.7
868
869
870 .. method:: assertIsNot(expr1, expr2[, msg])
871
872 The inverse of the :meth:`assertIs` method.
873 This signals a test failure if *expr1* and *expr2* evaluate to the same
874 object.
875
876 .. versionadded:: 2.7
877
878
Gregory P. Smith28399852009-03-31 16:54:10 +0000879 .. method:: assertFalse(expr[, msg])
880 failIf(expr[, msg])
881
882 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000883 This signals a test failure if *expr* is true, with *msg* or :const:`None`
884 for the error message.
885
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000886 .. deprecated:: 2.7
887 :meth:`failIf`.
888
Benjamin Peterson99721e02009-03-23 23:10:14 +0000889
890 .. method:: fail([msg])
891
892 Signals a test failure unconditionally, with *msg* or :const:`None` for
893 the error message.
894
895
896 .. attribute:: failureException
897
898 This class attribute gives the exception raised by the test method. If a
899 test framework needs to use a specialized exception, possibly to carry
900 additional information, it must subclass this exception in order to "play
901 fair" with the framework. The initial value of this attribute is
902 :exc:`AssertionError`.
903
Michael Foord345b2fe2009-04-02 03:20:38 +0000904
905 .. attribute:: longMessage
906
907 If set to True then any explicit failure message you pass in to the
908 assert methods will be appended to the end of the normal failure message.
909 The normal messages contain useful information about the objects involved,
910 for example the message from assertEqual shows you the repr of the two
911 unequal objects. Setting this attribute to True allows you to have a
912 custom error message in addition to the normal one.
913
914 This attribute defaults to False, meaning that a custom message passed
915 to an assert method will silence the normal message.
916
917 The class setting can be overridden in individual tests by assigning an
918 instance attribute to True or False before calling the assert methods.
919
920 .. versionadded:: 2.7
921
922
Benjamin Peterson99721e02009-03-23 23:10:14 +0000923 Testing frameworks can use the following methods to collect information on
924 the test:
925
926
927 .. method:: countTestCases()
928
929 Return the number of tests represented by this test object. For
930 :class:`TestCase` instances, this will always be ``1``.
931
932
933 .. method:: defaultTestResult()
934
935 Return an instance of the test result class that should be used for this
936 test case class (if no other result instance is provided to the
937 :meth:`run` method).
938
939 For :class:`TestCase` instances, this will always be an instance of
940 :class:`TestResult`; subclasses of :class:`TestCase` should override this
941 as necessary.
942
943
944 .. method:: id()
945
946 Return a string identifying the specific test case. This is usually the
947 full name of the test method, including the module and class name.
948
949
950 .. method:: shortDescription()
951
Gregory P. Smith28399852009-03-31 16:54:10 +0000952 Returns a description of the test, or :const:`None` if no description
953 has been provided. The default implementation of this method
954 returns the first line of the test method's docstring, if available,
955 along with the method name.
956
957 .. versionchanged:: 2.7
Gregory P. Smith28399852009-03-31 16:54:10 +0000958 In earlier versions this only returned the first line of the test
959 method's docstring, if available or the :const:`None`. That led to
960 undesirable behavior of not printing the test name when someone was
961 thoughtful enough to write a docstring.
962
963
964 .. method:: addTypeEqualityFunc(typeobj, function)
965
966 Registers a type specific :meth:`assertEqual` equality checking
967 function to be called by :meth:`assertEqual` when both objects it has
968 been asked to compare are exactly *typeobj* (not subclasses).
969 *function* must take two positional arguments and a third msg=None
970 keyword argument just as :meth:`assertEqual` does. It must raise
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000971 ``self.failureException`` when inequality between the first two
Gregory P. Smith28399852009-03-31 16:54:10 +0000972 parameters is detected.
973
974 One good use of custom equality checking functions for a type
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000975 is to raise ``self.failureException`` with an error message useful
976 for debugging the problem by explaining the inequalities in detail.
Gregory P. Smith28399852009-03-31 16:54:10 +0000977
978 .. versionadded:: 2.7
Georg Brandl8ec7f652007-08-15 14:28:01 +0000979
980
Michael Foorde2fb98f2009-05-02 20:15:05 +0000981 .. method:: addCleanup(function[, *args[, **kwargs]])
982
983 Add a function to be called after :meth:`tearDown` to cleanup resources
984 used during the test. Functions will be called in reverse order to the
985 order they are added (LIFO). They are called with any arguments and
986 keyword arguments passed into :meth:`addCleanup` when they are
987 added.
988
989 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
990 then any cleanup functions added will still be called.
991
992 .. versionadded:: 2.7
993
994
995 .. method:: doCleanups()
996
997 This method is called uncoditionally after :meth:`tearDown`, or
998 after :meth:`setUp` if :meth:`setUp` raises an exception.
999
1000 It is responsible for calling all the cleanup functions added by
1001 :meth:`addCleanup`. If you need cleanup functions to be called
1002 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1003 yourself.
1004
1005 :meth:`doCleanups` pops methods off the stack of cleanup
1006 functions one at a time, so it can be called at any time.
1007
1008 .. versionadded:: 2.7
1009
1010
Georg Brandl8ec7f652007-08-15 14:28:01 +00001011.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
1012
1013 This class implements the portion of the :class:`TestCase` interface which
1014 allows the test runner to drive the test, but does not provide the methods which
1015 test code can use to check and report errors. This is used to create test cases
1016 using legacy test code, allowing it to be integrated into a :mod:`unittest`\
1017 -based test framework.
1018
1019
Benjamin Peterson99721e02009-03-23 23:10:14 +00001020.. _testsuite-objects:
1021
1022Grouping tests
1023~~~~~~~~~~~~~~
1024
Georg Brandl8ec7f652007-08-15 14:28:01 +00001025.. class:: TestSuite([tests])
1026
1027 This class represents an aggregation of individual tests cases and test suites.
1028 The class presents the interface needed by the test runner to allow it to be run
1029 as any other test case. Running a :class:`TestSuite` instance is the same as
1030 iterating over the suite, running each test individually.
1031
1032 If *tests* is given, it must be an iterable of individual test cases or other
1033 test suites that will be used to build the suite initially. Additional methods
1034 are provided to add test cases and suites to the collection later on.
1035
Benjamin Peterson99721e02009-03-23 23:10:14 +00001036 :class:`TestSuite` (including :class:`ClassTestSuite`) objects behave much
1037 like :class:`TestCase` objects, except they do not actually implement a test.
1038 Instead, they are used to aggregate tests into groups of tests that should be
1039 run together. Some additional methods are available to add tests to
1040 :class:`TestSuite` instances:
1041
1042
1043 .. method:: TestSuite.addTest(test)
1044
1045 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1046
1047
1048 .. method:: TestSuite.addTests(tests)
1049
1050 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1051 instances to this test suite.
1052
1053 This is equivalent to iterating over *tests*, calling :meth:`addTest` for each
1054 element.
1055
1056 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1057
1058
1059 .. method:: run(result)
1060
1061 Run the tests associated with this suite, collecting the result into the
1062 test result object passed as *result*. Note that unlike
1063 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1064 be passed in.
1065
1066
1067 .. method:: debug()
1068
1069 Run the tests associated with this suite without collecting the
1070 result. This allows exceptions raised by the test to be propagated to the
1071 caller and can be used to support running tests under a debugger.
1072
1073
1074 .. method:: countTestCases()
1075
1076 Return the number of tests represented by this test object, including all
1077 individual tests and sub-suites.
1078
Georg Brandl9bc66822009-04-27 17:04:23 +00001079
1080 .. method:: __iter__()
1081
1082 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1083 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1084 that this method maybe called several times on a single suite
1085 (for example when counting tests or comparing for equality)
1086 so the tests returned must be the same for repeated iterations.
1087
1088 .. versionchanged:: 2.7
1089 In earlier versions the :class:`TestSuite` accessed tests directly rather
1090 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1091 for providing tests.
1092
Benjamin Peterson99721e02009-03-23 23:10:14 +00001093 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1094 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1095
1096
Benjamin Peterson692428e2009-03-23 21:50:21 +00001097.. class:: ClassTestSuite(tests, collected_from)
1098
1099 This subclass of :class:`TestSuite` repesents an aggregation of individuals
1100 tests from one :class:`TestCase` class. *tests* is an iterable of
1101 :class:`TestCase` instances created from the class. *collected_from* is the
1102 class they came from.
1103
Georg Brandl8ec7f652007-08-15 14:28:01 +00001104
Benjamin Peterson99721e02009-03-23 23:10:14 +00001105Loading and running tests
1106~~~~~~~~~~~~~~~~~~~~~~~~~
1107
Georg Brandl8ec7f652007-08-15 14:28:01 +00001108.. class:: TestLoader()
1109
Benjamin Peterson99721e02009-03-23 23:10:14 +00001110 The :class:`TestLoader` class is used to create test suites from classes and
1111 modules. Normally, there is no need to create an instance of this class; the
1112 :mod:`unittest` module provides an instance that can be shared as
1113 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1114 customization of some configurable properties.
1115
1116 :class:`TestLoader` objects have the following methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001117
1118
Benjamin Peterson99721e02009-03-23 23:10:14 +00001119 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001120
Benjamin Peterson99721e02009-03-23 23:10:14 +00001121 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1122 :class:`testCaseClass`.
1123
1124
1125 .. method:: loadTestsFromModule(module)
1126
1127 Return a suite of all tests cases contained in the given module. This
1128 method searches *module* for classes derived from :class:`TestCase` and
1129 creates an instance of the class for each test method defined for the
1130 class.
1131
Georg Brandl16a57f62009-04-27 15:29:09 +00001132 .. note::
Benjamin Peterson99721e02009-03-23 23:10:14 +00001133
1134 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1135 convenient in sharing fixtures and helper functions, defining test
1136 methods on base classes that are not intended to be instantiated
1137 directly does not play well with this method. Doing so, however, can
1138 be useful when the fixtures are different and defined in subclasses.
1139
1140
1141 .. method:: loadTestsFromName(name[, module])
1142
1143 Return a suite of all tests cases given a string specifier.
1144
1145 The specifier *name* is a "dotted name" that may resolve either to a
1146 module, a test case class, a test method within a test case class, a
1147 :class:`TestSuite` instance, or a callable object which returns a
1148 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1149 applied in the order listed here; that is, a method on a possible test
1150 case class will be picked up as "a test method within a test case class",
1151 rather than "a callable object".
1152
1153 For example, if you have a module :mod:`SampleTests` containing a
1154 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1155 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
1156 specifier ``'SampleTests.SampleTestCase'`` would cause this method to return a
1157 suite which will run all three test methods. Using the specifier
1158 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test suite
1159 which will run only the :meth:`test_two` test method. The specifier can refer
1160 to modules and packages which have not been imported; they will be imported as a
1161 side-effect.
1162
1163 The method optionally resolves *name* relative to the given *module*.
1164
1165
1166 .. method:: loadTestsFromNames(names[, module])
1167
1168 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1169 than a single name. The return value is a test suite which supports all
1170 the tests defined for each name.
1171
1172
1173 .. method:: getTestCaseNames(testCaseClass)
1174
1175 Return a sorted sequence of method names found within *testCaseClass*;
1176 this should be a subclass of :class:`TestCase`.
1177
1178 The following attributes of a :class:`TestLoader` can be configured either by
1179 subclassing or assignment on an instance:
1180
1181
1182 .. attribute:: testMethodPrefix
1183
1184 String giving the prefix of method names which will be interpreted as test
1185 methods. The default value is ``'test'``.
1186
1187 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1188 methods.
1189
1190
1191 .. attribute:: sortTestMethodsUsing
1192
1193 Function to be used to compare method names when sorting them in
1194 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
1195 default value is the built-in :func:`cmp` function; the attribute can also
1196 be set to :const:`None` to disable the sort.
1197
1198
1199 .. attribute:: suiteClass
1200
1201 Callable object that constructs a test suite from a list of tests. No
1202 methods on the resulting object are needed. The default value is the
1203 :class:`TestSuite` class.
1204
1205 This affects all the :meth:`loadTestsFrom\*` methods.
1206
1207
1208 .. attribute:: classSuiteClass
1209
1210 Callable object that constructs a test suite for the tests cases from one
1211 class. The default value is :class:`ClassTestSuite`.
1212
1213
1214.. class:: TestResult
1215
1216 This class is used to compile information about which tests have succeeded
1217 and which have failed.
1218
1219 A :class:`TestResult` object stores the results of a set of tests. The
1220 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1221 properly recorded; test authors do not need to worry about recording the
1222 outcome of tests.
1223
1224 Testing frameworks built on top of :mod:`unittest` may want access to the
1225 :class:`TestResult` object generated by running a set of tests for reporting
1226 purposes; a :class:`TestResult` instance is returned by the
1227 :meth:`TestRunner.run` method for this purpose.
1228
1229 :class:`TestResult` instances have the following attributes that will be of
1230 interest when inspecting the results of running a set of tests:
1231
1232
1233 .. attribute:: errors
1234
1235 A list containing 2-tuples of :class:`TestCase` instances and strings
1236 holding formatted tracebacks. Each tuple represents a test which raised an
1237 unexpected exception.
1238
1239 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001240 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1241
1242
1243 .. attribute:: failures
1244
1245 A list containing 2-tuples of :class:`TestCase` instances and strings
1246 holding formatted tracebacks. Each tuple represents a test where a failure
1247 was explicitly signalled using the :meth:`TestCase.fail\*` or
1248 :meth:`TestCase.assert\*` methods.
1249
1250 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001251 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1252
1253 .. attribute:: skipped
1254
1255 A list containing 2-tuples of :class:`TestCase` instances and strings
1256 holding the reason for skipping the test.
1257
1258 .. versionadded:: 2.7
1259
1260 .. attribute:: expectedFailures
1261
1262 A list contaning 2-tuples of :class:`TestCase` instances and strings
1263 holding formatted tracebacks. Each tuple represents a expected failures
1264 of the test case.
1265
1266 .. attribute:: unexpectedSuccesses
1267
1268 A list containing :class:`TestCase` instances that were marked as expected
1269 failures, but succeeded.
1270
1271 .. attribute:: shouldStop
1272
1273 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1274
1275
1276 .. attribute:: testsRun
1277
1278 The total number of tests run so far.
1279
1280
1281 .. method:: wasSuccessful()
1282
1283 Return :const:`True` if all tests run so far have passed, otherwise returns
1284 :const:`False`.
1285
1286
1287 .. method:: stop()
1288
1289 This method can be called to signal that the set of tests being run should
1290 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1291 :class:`TestRunner` objects should respect this flag and return without
1292 running any additional tests.
1293
1294 For example, this feature is used by the :class:`TextTestRunner` class to
1295 stop the test framework when the user signals an interrupt from the
1296 keyboard. Interactive tools which provide :class:`TestRunner`
1297 implementations can use this in a similar manner.
1298
1299 The following methods of the :class:`TestResult` class are used to maintain
1300 the internal data structures, and may be extended in subclasses to support
1301 additional reporting requirements. This is particularly useful in building
1302 tools which support interactive reporting while tests are being run.
1303
1304
1305 .. method:: startTest(test)
1306
1307 Called when the test case *test* is about to be run.
1308
1309 The default implementation simply increments the instance's :attr:`testsRun`
1310 counter.
1311
1312
1313 .. method:: stopTest(test)
1314
1315 Called after the test case *test* has been executed, regardless of the
1316 outcome.
1317
1318 The default implementation does nothing.
1319
1320
Michael Foord07ef4872009-05-02 22:43:34 +00001321 .. method:: startTestRun(test)
1322
1323 Called once before any tests are executed.
1324
1325 .. versionadded:: 2.7
1326
1327
1328 .. method:: stopTestRun(test)
1329
1330 Called once before any tests are executed.
1331
1332 .. versionadded:: 2.7
1333
1334
Benjamin Peterson99721e02009-03-23 23:10:14 +00001335 .. method:: addError(test, err)
1336
1337 Called when the test case *test* raises an unexpected exception *err* is a
1338 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1339 traceback)``.
1340
1341 The default implementation appends a tuple ``(test, formatted_err)`` to
1342 the instance's :attr:`errors` attribute, where *formatted_err* is a
1343 formatted traceback derived from *err*.
1344
1345
1346 .. method:: addFailure(test, err)
1347
1348 Called when the test case *test* signals a failure. *err* is a tuple of the form
1349 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1350
1351 The default implementation appends a tuple ``(test, formatted_err)`` to
1352 the instance's :attr:`failures` attribute, where *formatted_err* is a
1353 formatted traceback derived from *err*.
1354
1355
1356 .. method:: addSuccess(test)
1357
1358 Called when the test case *test* succeeds.
1359
1360 The default implementation does nothing.
1361
1362
1363 .. method:: addSkip(test, reason)
1364
1365 Called when the test case *test* is skipped. *reason* is the reason the
1366 test gave for skipping.
1367
1368 The default implementation appends a tuple ``(test, reason)`` to the
1369 instance's :attr:`skipped` attribute.
1370
1371
1372 .. method:: addExpectedFailure(test, err)
1373
1374 Called when the test case *test* fails, but was marked with the
1375 :func:`expectedFailure` decorator.
1376
1377 The default implementation appends a tuple ``(test, formatted_err)`` to
1378 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1379 is a formatted traceback derived from *err*.
1380
1381
1382 .. method:: addUnexpectedSuccess(test)
1383
1384 Called when the test case *test* was marked with the
1385 :func:`expectedFailure` decorator, but succeeded.
1386
1387 The default implementation appends the test to the instance's
1388 :attr:`unexpectedSuccesses` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001389
1390
1391.. data:: defaultTestLoader
1392
1393 Instance of the :class:`TestLoader` class intended to be shared. If no
1394 customization of the :class:`TestLoader` is needed, this instance can be used
1395 instead of repeatedly creating new instances.
1396
1397
1398.. class:: TextTestRunner([stream[, descriptions[, verbosity]]])
1399
1400 A basic test runner implementation which prints results on standard error. It
1401 has a few configurable parameters, but is essentially very simple. Graphical
1402 applications which run test suites should provide alternate implementations.
1403
Georg Brandl9bc66822009-04-27 17:04:23 +00001404 .. method:: _makeResult()
1405
1406 This method returns the instance of ``TestResult`` used by :meth:`run`.
1407 It is not intended to be called directly, but can be overridden in
1408 subclasses to provide a custom ``TestResult``.
1409
Georg Brandl8ec7f652007-08-15 14:28:01 +00001410
Michael Foord829f6b82009-05-02 11:43:06 +00001411.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit]]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001412
1413 A command-line program that runs a set of tests; this is primarily for making
1414 test modules conveniently executable. The simplest use for this function is to
1415 include the following line at the end of a test script::
1416
1417 if __name__ == '__main__':
1418 unittest.main()
1419
1420 The *testRunner* argument can either be a test runner class or an already
Michael Foord829f6b82009-05-02 11:43:06 +00001421 created instance of it. By default ``main`` calls :func:`sys.exit` with
1422 an exit code indicating success or failure of the tests run.
1423
1424 ``main`` supports being used from the interactive interpreter by passing in the
1425 argument ``exit=False``. This displays the result on standard output without
1426 calling :func:`sys.exit`::
1427
1428 >>> from unittest import main
1429 >>> main(module='test_module', exit=False)
1430
1431 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1432 This stores the result of the tests run as the ``result`` attribute.
1433
1434 .. versionchanged:: 2.7
1435 The ``exit`` parameter was added.