blob: 39fbb79c54e9af3794c22155ba4cbf85d743eea6 [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 Peterson176a56c2009-05-25 00:48:58 +000065all tests added directly to the suite and in "child" test suites are run.
Georg Brandl8ec7f652007-08-15 14:28:01 +000066
Benjamin Peterson99721e02009-03-23 23:10:14 +000067A test runner is an object that provides a single method,
68:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
69object as a parameter, and returns a result object. The class
70:class:`TestResult` is provided for use as the result object. :mod:`unittest`
71provides the :class:`TextTestRunner` as an example test runner which reports
72test results on the standard error stream by default. Alternate runners can be
73implemented for other environments (such as graphical environments) without any
74need to derive from a specific class.
Georg Brandl8ec7f652007-08-15 14:28:01 +000075
76
77.. seealso::
78
79 Module :mod:`doctest`
80 Another test-support module with a very different flavor.
81
82 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
83 Kent Beck's original paper on testing frameworks using the pattern shared by
84 :mod:`unittest`.
85
Raymond Hettinger21b617b2009-03-24 00:17:11 +000086 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
87 Third-party unittest frameworks with a lighter-weight syntax
88 for writing tests. For example, ``assert func(10) == 42``.
89
90 `python-mock <http://python-mock.sourceforge.net/>`_ and `minimock <http://blog.ianbicking.org/minimock.html>`_
91 Tools for creating mock test objects (objects simulating external resources).
Georg Brandl8ec7f652007-08-15 14:28:01 +000092
Michael Foord5d31e052009-05-11 17:59:43 +000093Command Line Interface
94----------------------
95
96The unittest module can be used from the command line to run tests from
97modules, classes or even individual test methods::
98
99 python -m unittest test_module1 test_module2
100 python -m unittest test_module.TestClass
101 python -m unittest test_module.TestClass.test_method
102
103You can pass in a list with any combination of module names, and fully qualified class or
104method names.
105
106You can run tests with more detail (higher verbosity) by passing in the -v flag::
107
108 python-m unittest -v test_module
109
110For a list of all the command line options::
111
112 python -m unittest -h
113
114.. versionchanged:: 27
115 In earlier versions it was only possible to run individual test methods and not modules
116 or classes.
117
Georg Brandl8ec7f652007-08-15 14:28:01 +0000118.. _unittest-minimal-example:
119
120Basic example
121-------------
122
123The :mod:`unittest` module provides a rich set of tools for constructing and
124running tests. This section demonstrates that a small subset of the tools
125suffice to meet the needs of most users.
126
127Here is a short script to test three functions from the :mod:`random` module::
128
129 import random
130 import unittest
131
132 class TestSequenceFunctions(unittest.TestCase):
133
134 def setUp(self):
135 self.seq = range(10)
136
Benjamin Peterson99721e02009-03-23 23:10:14 +0000137 def test_shuffle(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000138 # make sure the shuffled sequence does not lose any elements
139 random.shuffle(self.seq)
140 self.seq.sort()
141 self.assertEqual(self.seq, range(10))
142
Benjamin Peterson99721e02009-03-23 23:10:14 +0000143 def test_choice(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000144 element = random.choice(self.seq)
145 self.assert_(element in self.seq)
146
Benjamin Peterson99721e02009-03-23 23:10:14 +0000147 def test_sample(self):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000148 self.assertRaises(ValueError, random.sample, self.seq, 20)
149 for element in random.sample(self.seq, 5):
150 self.assert_(element in self.seq)
151
152 if __name__ == '__main__':
153 unittest.main()
154
Benjamin Peterson99721e02009-03-23 23:10:14 +0000155A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl8ec7f652007-08-15 14:28:01 +0000156individual tests are defined with methods whose names start with the letters
157``test``. This naming convention informs the test runner about which methods
158represent tests.
159
Benjamin Peterson99721e02009-03-23 23:10:14 +0000160The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
161expected result; :meth:`~TestCase.assert_` to verify a condition; or
162:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
163These methods are used instead of the :keyword:`assert` statement so the test
164runner can accumulate all test results and produce a report.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000165
Benjamin Peterson99721e02009-03-23 23:10:14 +0000166When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
167method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
168defined, the test runner will invoke that method after each test. In the
169example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
170test.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171
172The final block shows a simple way to run the tests. :func:`unittest.main`
173provides a command line interface to the test script. When run from the command
174line, the above script produces an output that looks like this::
175
176 ...
177 ----------------------------------------------------------------------
178 Ran 3 tests in 0.000s
179
180 OK
181
182Instead of :func:`unittest.main`, there are other ways to run the tests with a
183finer level of control, less terse output, and no requirement to be run from the
184command line. For example, the last two lines may be replaced with::
185
186 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
187 unittest.TextTestRunner(verbosity=2).run(suite)
188
189Running the revised script from the interpreter or another script produces the
190following output::
191
192 testchoice (__main__.TestSequenceFunctions) ... ok
193 testsample (__main__.TestSequenceFunctions) ... ok
194 testshuffle (__main__.TestSequenceFunctions) ... ok
195
196 ----------------------------------------------------------------------
197 Ran 3 tests in 0.110s
198
199 OK
200
201The above examples show the most commonly used :mod:`unittest` features which
202are sufficient to meet many everyday testing needs. The remainder of the
203documentation explores the full feature set from first principles.
204
Georg Brandl8ec7f652007-08-15 14:28:01 +0000205.. _organizing-tests:
206
207Organizing test code
208--------------------
209
210The basic building blocks of unit testing are :dfn:`test cases` --- single
211scenarios that must be set up and checked for correctness. In :mod:`unittest`,
212test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
213class. To make your own test cases you must write subclasses of
214:class:`TestCase`, or use :class:`FunctionTestCase`.
215
216An instance of a :class:`TestCase`\ -derived class is an object that can
217completely run a single test method, together with optional set-up and tidy-up
218code.
219
220The testing code of a :class:`TestCase` instance should be entirely self
221contained, such that it can be run either in isolation or in arbitrary
222combination with any number of other test cases.
223
Benjamin Peterson99721e02009-03-23 23:10:14 +0000224The simplest :class:`TestCase` subclass will simply override the
225:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000226
227 import unittest
228
229 class DefaultWidgetSizeTestCase(unittest.TestCase):
230 def runTest(self):
231 widget = Widget('The widget')
232 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
233
Gregory P. Smith28399852009-03-31 16:54:10 +0000234Note that in order to test something, we use the one of the :meth:`assert\*`
235methods provided by the :class:`TestCase` base class. If the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000236test fails, an exception will be raised, and :mod:`unittest` will identify the
237test case as a :dfn:`failure`. Any other exceptions will be treated as
238:dfn:`errors`. This helps you identify where the problem is: :dfn:`failures` are
239caused by incorrect results - a 5 where you expected a 6. :dfn:`Errors` are
240caused by incorrect code - e.g., a :exc:`TypeError` caused by an incorrect
241function call.
242
243The way to run a test case will be described later. For now, note that to
244construct an instance of such a test case, we call its constructor without
245arguments::
246
247 testCase = DefaultWidgetSizeTestCase()
248
249Now, such test cases can be numerous, and their set-up can be repetitive. In
250the above case, constructing a :class:`Widget` in each of 100 Widget test case
251subclasses would mean unsightly duplication.
252
253Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson99721e02009-03-23 23:10:14 +0000254:meth:`~TestCase.setUp`, which the testing framework will automatically call for
255us when we run the test::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000256
257 import unittest
258
259 class SimpleWidgetTestCase(unittest.TestCase):
260 def setUp(self):
261 self.widget = Widget('The widget')
262
263 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
264 def runTest(self):
Gregory P. Smith28399852009-03-31 16:54:10 +0000265 self.assertTrue(self.widget.size() == (50,50),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000266 'incorrect default size')
267
268 class WidgetResizeTestCase(SimpleWidgetTestCase):
269 def runTest(self):
270 self.widget.resize(100,150)
Gregory P. Smith28399852009-03-31 16:54:10 +0000271 self.assertTrue(self.widget.size() == (100,150),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000272 'wrong size after resize')
273
Benjamin Peterson99721e02009-03-23 23:10:14 +0000274If the :meth:`~TestCase.setUp` method raises an exception while the test is
275running, the framework will consider the test to have suffered an error, and the
276:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277
Benjamin Peterson99721e02009-03-23 23:10:14 +0000278Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
279after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000280
281 import unittest
282
283 class SimpleWidgetTestCase(unittest.TestCase):
284 def setUp(self):
285 self.widget = Widget('The widget')
286
287 def tearDown(self):
288 self.widget.dispose()
289 self.widget = None
290
Benjamin Peterson99721e02009-03-23 23:10:14 +0000291If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
292be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000293
294Such a working environment for the testing code is called a :dfn:`fixture`.
295
296Often, many small test cases will use the same fixture. In this case, we would
297end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
298classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000299discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
300mechanism::
301
302 import unittest
303
304 class WidgetTestCase(unittest.TestCase):
305 def setUp(self):
306 self.widget = Widget('The widget')
307
308 def tearDown(self):
309 self.widget.dispose()
310 self.widget = None
311
312 def testDefaultSize(self):
Gregory P. Smith28399852009-03-31 16:54:10 +0000313 self.assertTrue(self.widget.size() == (50,50),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000314 'incorrect default size')
315
316 def testResize(self):
317 self.widget.resize(100,150)
Gregory P. Smith28399852009-03-31 16:54:10 +0000318 self.assertTrue(self.widget.size() == (100,150),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000319 'wrong size after resize')
320
Benjamin Peterson99721e02009-03-23 23:10:14 +0000321Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
322provided two different test methods. Class instances will now each run one of
323the :meth:`test\*` methods, with ``self.widget`` created and destroyed
324separately for each instance. When creating an instance we must specify the
325test method it is to run. We do this by passing the method name in the
326constructor::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000327
328 defaultSizeTestCase = WidgetTestCase('testDefaultSize')
329 resizeTestCase = WidgetTestCase('testResize')
330
331Test case instances are grouped together according to the features they test.
332:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
333represented by :mod:`unittest`'s :class:`TestSuite` class::
334
335 widgetTestSuite = unittest.TestSuite()
336 widgetTestSuite.addTest(WidgetTestCase('testDefaultSize'))
337 widgetTestSuite.addTest(WidgetTestCase('testResize'))
338
339For the ease of running tests, as we will see later, it is a good idea to
340provide in each test module a callable object that returns a pre-built test
341suite::
342
343 def suite():
344 suite = unittest.TestSuite()
345 suite.addTest(WidgetTestCase('testDefaultSize'))
346 suite.addTest(WidgetTestCase('testResize'))
347 return suite
348
349or even::
350
351 def suite():
352 tests = ['testDefaultSize', 'testResize']
353
354 return unittest.TestSuite(map(WidgetTestCase, tests))
355
356Since it is a common pattern to create a :class:`TestCase` subclass with many
357similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
358class that can be used to automate the process of creating a test suite and
359populating it with individual tests. For example, ::
360
361 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
362
363will create a test suite that will run ``WidgetTestCase.testDefaultSize()`` and
364``WidgetTestCase.testResize``. :class:`TestLoader` uses the ``'test'`` method
365name prefix to identify test methods automatically.
366
367Note that the order in which the various test cases will be run is determined by
368sorting the test function names with the built-in :func:`cmp` function.
369
370Often it is desirable to group suites of test cases together, so as to run tests
371for the whole system at once. This is easy, since :class:`TestSuite` instances
372can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
373added to a :class:`TestSuite`::
374
375 suite1 = module1.TheTestSuite()
376 suite2 = module2.TheTestSuite()
377 alltests = unittest.TestSuite([suite1, suite2])
378
379You can place the definitions of test cases and test suites in the same modules
380as the code they are to test (such as :file:`widget.py`), but there are several
381advantages to placing the test code in a separate module, such as
382:file:`test_widget.py`:
383
384* The test module can be run standalone from the command line.
385
386* The test code can more easily be separated from shipped code.
387
388* There is less temptation to change test code to fit the code it tests without
389 a good reason.
390
391* Test code should be modified much less frequently than the code it tests.
392
393* Tested code can be refactored more easily.
394
395* Tests for modules written in C must be in separate modules anyway, so why not
396 be consistent?
397
398* If the testing strategy changes, there is no need to change the source code.
399
400
401.. _legacy-unit-tests:
402
403Re-using old test code
404----------------------
405
406Some users will find that they have existing test code that they would like to
407run from :mod:`unittest`, without converting every old test function to a
408:class:`TestCase` subclass.
409
410For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
411This subclass of :class:`TestCase` can be used to wrap an existing test
412function. Set-up and tear-down functions can also be provided.
413
414Given the following test function::
415
416 def testSomething():
417 something = makeSomething()
418 assert something.name is not None
419 # ...
420
421one can create an equivalent test case instance as follows::
422
423 testcase = unittest.FunctionTestCase(testSomething)
424
425If there are additional set-up and tear-down methods that should be called as
426part of the test case's operation, they can also be provided like so::
427
428 testcase = unittest.FunctionTestCase(testSomething,
429 setUp=makeSomethingDB,
430 tearDown=deleteSomethingDB)
431
432To make migrating existing test suites easier, :mod:`unittest` supports tests
433raising :exc:`AssertionError` to indicate test failure. However, it is
434recommended that you use the explicit :meth:`TestCase.fail\*` and
435:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
436may treat :exc:`AssertionError` differently.
437
438.. note::
439
440 Even though :class:`FunctionTestCase` can be used to quickly convert an existing
441 test base over to a :mod:`unittest`\ -based system, this approach is not
442 recommended. Taking the time to set up proper :class:`TestCase` subclasses will
443 make future test refactorings infinitely easier.
444
Benjamin Peterson99721e02009-03-23 23:10:14 +0000445In some cases, the existing tests may have been written using the :mod:`doctest`
446module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
447automatically build :class:`unittest.TestSuite` instances from the existing
448:mod:`doctest`\ -based tests.
449
Georg Brandl8ec7f652007-08-15 14:28:01 +0000450
Benjamin Peterson692428e2009-03-23 21:50:21 +0000451.. _unittest-skipping:
452
453Skipping tests and expected failures
454------------------------------------
455
456Unittest supports skipping individual test methods and even whole classes of
457tests. In addition, it supports marking a test as a "expected failure," a test
458that is broken and will fail, but shouldn't be counted as a failure on a
459:class:`TestResult`.
460
461Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
462or one of its conditional variants.
463
464Basic skipping looks like this: ::
465
466 class MyTestCase(unittest.TestCase):
467
468 @unittest.skip("demonstrating skipping")
469 def test_nothing(self):
470 self.fail("shouldn't happen")
471
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000472 @unittest.skipIf(mylib.__version__ < (1, 3), "not supported in this library version")
473 def test_format(self):
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000474 # Tests that work for only a certain version of the library.
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000475 pass
476
477 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
478 def test_windows_support(self):
479 # windows specific testing code
480 pass
481
Benjamin Peterson692428e2009-03-23 21:50:21 +0000482This is the output of running the example above in verbose mode: ::
483
Benjamin Peterson097aafd2009-03-29 03:39:58 +0000484 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000485 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000486 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson692428e2009-03-23 21:50:21 +0000487
488 ----------------------------------------------------------------------
Benjamin Petersonbe76d4c2009-03-29 03:16:57 +0000489 Ran 3 tests in 0.005s
490
491 OK (skipped=3)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000492
493Classes can be skipped just like methods: ::
494
495 @skip("showing class skipping")
496 class MySkippedTestCase(unittest.TestCase):
497 def test_not_run(self):
498 pass
499
Benjamin Peterson31b78062009-03-23 23:13:36 +0000500:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
501that needs to be set up is not available.
502
Benjamin Peterson692428e2009-03-23 21:50:21 +0000503Expected failures use the :func:`expectedFailure` decorator. ::
504
505 class ExpectedFailureTestCase(unittest.TestCase):
506 @unittest.expectedFailure
507 def test_fail(self):
508 self.assertEqual(1, 0, "broken")
509
510It's easy to roll your own skipping decorators by making a decorator that calls
511:func:`skip` on the test when it wants it to be skipped. This decorator skips
512the test unless the passed object has a certain attribute: ::
513
514 def skipUnlessHasattr(obj, attr):
515 if hasattr(obj, attr):
516 return lambda func: func
517 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
518
519The following decorators implement test skipping and expected failures:
520
521.. function:: skip(reason)
522
523 Unconditionally skip the decorated test. *reason* should describe why the
524 test is being skipped.
525
526.. function:: skipIf(condition, reason)
527
528 Skip the decorated test if *condition* is true.
529
530.. function:: skipUnless(condition, reason)
531
532 Skip the decoratored test unless *condition* is true.
533
534.. function:: expectedFailure
535
536 Mark the test as an expected failure. If the test fails when run, the test
537 is not counted as a failure.
538
539
Georg Brandl8ec7f652007-08-15 14:28:01 +0000540.. _unittest-contents:
541
542Classes and functions
543---------------------
544
Benjamin Peterson99721e02009-03-23 23:10:14 +0000545This section describes in depth the API of :mod:`unittest`.
546
547
548.. _testcase-objects:
549
550Test cases
551~~~~~~~~~~
Georg Brandl8ec7f652007-08-15 14:28:01 +0000552
553.. class:: TestCase([methodName])
554
555 Instances of the :class:`TestCase` class represent the smallest testable units
556 in the :mod:`unittest` universe. This class is intended to be used as a base
557 class, with specific tests being implemented by concrete subclasses. This class
558 implements the interface needed by the test runner to allow it to drive the
559 test, and methods that the test code can use to check for and report various
560 kinds of failure.
561
562 Each instance of :class:`TestCase` will run a single test method: the method
563 named *methodName*. If you remember, we had an earlier example that went
564 something like this::
565
566 def suite():
567 suite = unittest.TestSuite()
568 suite.addTest(WidgetTestCase('testDefaultSize'))
569 suite.addTest(WidgetTestCase('testResize'))
570 return suite
571
572 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
573 single test.
574
Benjamin Peterson99721e02009-03-23 23:10:14 +0000575 *methodName* defaults to :meth:`runTest`.
576
577 :class:`TestCase` instances provide three groups of methods: one group used
578 to run the test, another used by the test implementation to check conditions
579 and report failures, and some inquiry methods allowing information about the
580 test itself to be gathered.
581
582 Methods in the first group (running the test) are:
583
584
585 .. method:: setUp()
586
587 Method called to prepare the test fixture. This is called immediately
588 before calling the test method; any exception raised by this method will
589 be considered an error rather than a test failure. The default
590 implementation does nothing.
591
592
593 .. method:: tearDown()
594
595 Method called immediately after the test method has been called and the
596 result recorded. This is called even if the test method raised an
597 exception, so the implementation in subclasses may need to be particularly
598 careful about checking internal state. Any exception raised by this
599 method will be considered an error rather than a test failure. This
600 method will only be called if the :meth:`setUp` succeeds, regardless of
601 the outcome of the test method. The default implementation does nothing.
602
603
604 .. method:: run([result])
605
606 Run the test, collecting the result into the test result object passed as
607 *result*. If *result* is omitted or :const:`None`, a temporary result
608 object is created (by calling the :meth:`defaultTestCase` method) and
609 used; this result object is not returned to :meth:`run`'s caller.
610
611 The same effect may be had by simply calling the :class:`TestCase`
612 instance.
613
614
Benjamin Peterson47d97382009-03-26 20:05:50 +0000615 .. method:: skipTest(reason)
Benjamin Peterson99721e02009-03-23 23:10:14 +0000616
Benjamin Peterson31b78062009-03-23 23:13:36 +0000617 Calling this during the a test method or :meth:`setUp` skips the current
618 test. See :ref:`unittest-skipping` for more information.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000619
620
621 .. method:: debug()
622
623 Run the test without collecting the result. This allows exceptions raised
624 by the test to be propagated to the caller, and can be used to support
625 running tests under a debugger.
626
627 The test code can use any of the following methods to check for and report
628 failures.
629
630
Gregory P. Smith28399852009-03-31 16:54:10 +0000631 .. method:: assertTrue(expr[, msg])
632 assert_(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000633 failUnless(expr[, msg])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000634
Georg Brandl64034bb2009-04-25 14:51:31 +0000635 Signal a test failure if *expr* is false; the explanation for the failure
Benjamin Peterson99721e02009-03-23 23:10:14 +0000636 will be *msg* if given, otherwise it will be :const:`None`.
637
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000638 .. deprecated:: 2.7
639 :meth:`failUnless`.
640
Benjamin Peterson99721e02009-03-23 23:10:14 +0000641
642 .. method:: assertEqual(first, second[, msg])
643 failUnlessEqual(first, second[, msg])
644
645 Test that *first* and *second* are equal. If the values do not compare
646 equal, the test will fail with the explanation given by *msg*, or
Gregory P. Smith28399852009-03-31 16:54:10 +0000647 :const:`None`. Note that using :meth:`assertEqual` improves upon
648 doing the comparison as the first parameter to :meth:`assertTrue`: the
649 default value for *msg* include representations of both *first* and
650 *second*.
651
652 In addition, if *first* and *second* are the exact same type and one of
653 list, tuple, dict, set, or frozenset or any type that a subclass
654 registers :meth:`addTypeEqualityFunc` the type specific equality function
655 will be called in order to generate a more useful default error message.
656
657 .. versionchanged:: 2.7
658 Added the automatic calling of type specific equality function.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000659
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000660 .. deprecated:: 2.7
661 :meth:`failUnlessEqual`.
662
Benjamin Peterson99721e02009-03-23 23:10:14 +0000663
664 .. method:: assertNotEqual(first, second[, msg])
665 failIfEqual(first, second[, msg])
666
667 Test that *first* and *second* are not equal. If the values do compare
668 equal, the test will fail with the explanation given by *msg*, or
Gregory P. Smith28399852009-03-31 16:54:10 +0000669 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
670 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson99721e02009-03-23 23:10:14 +0000671 default value for *msg* can be computed to include representations of both
672 *first* and *second*.
673
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000674 .. deprecated:: 2.7
675 :meth:`failIfEqual`.
676
Benjamin Peterson99721e02009-03-23 23:10:14 +0000677
678 .. method:: assertAlmostEqual(first, second[, places[, msg]])
679 failUnlessAlmostEqual(first, second[, places[, msg]])
680
681 Test that *first* and *second* are approximately equal by computing the
682 difference, rounding to the given number of decimal *places* (default 7),
683 and comparing to zero.
684
685 Note that comparing a given number of decimal places is not the same as
686 comparing a given number of significant digits. If the values do not
687 compare equal, the test will fail with the explanation given by *msg*, or
688 :const:`None`.
689
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000690 .. deprecated:: 2.7
691 :meth:`failUnlessAlmostEqual`.
692
Benjamin Peterson99721e02009-03-23 23:10:14 +0000693
694 .. method:: assertNotAlmostEqual(first, second[, places[, msg]])
695 failIfAlmostEqual(first, second[, places[, msg]])
696
697 Test that *first* and *second* are not approximately equal by computing
698 the difference, rounding to the given number of decimal *places* (default
699 7), and comparing to zero.
700
701 Note that comparing a given number of decimal places is not the same as
702 comparing a given number of significant digits. If the values do not
703 compare equal, the test will fail with the explanation given by *msg*, or
704 :const:`None`.
705
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000706 .. deprecated:: 2.7
707 :meth:`failIfAlmostEqual`.
708
Benjamin Peterson99721e02009-03-23 23:10:14 +0000709
Gregory P. Smith28399852009-03-31 16:54:10 +0000710 .. method:: assertGreater(first, second, msg=None)
711 assertGreaterEqual(first, second, msg=None)
712 assertLess(first, second, msg=None)
713 assertLessEqual(first, second, msg=None)
714
715 Test that *first* is respectively >, >=, < or <= than *second* depending
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000716 on the method name. If not, the test will fail with an explanation
Gregory P. Smith28399852009-03-31 16:54:10 +0000717 or with the explanation given by *msg*::
718
719 >>> self.assertGreaterEqual(3, 4)
720 AssertionError: "3" unexpectedly not greater than or equal to "4"
721
722 .. versionadded:: 2.7
723
724
725 .. method:: assertMultiLineEqual(self, first, second, msg=None)
726
727 Test that the multiline string *first* is equal to the string *second*.
728 When not equal a diff of the two strings highlighting the differences
729 will be included in the error message.
730
731 If specified *msg* will be used as the error message on failure.
732
733 .. versionadded:: 2.7
734
735
736 .. method:: assertRegexpMatches(text, regexp[, msg=None]):
737
738 Verifies that a *regexp* search matches *text*. Fails with an error
739 message including the pattern and the *text*. *regexp* may be
740 a regular expression object or a string containing a regular expression
741 suitable for use by :func:`re.search`.
742
743 .. versionadded:: 2.7
744
745
746 .. method:: assertIn(first, second, msg=None)
747 assertNotIn(first, second, msg=None)
748
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000749 Tests that *first* is or is not in *second* with an explanatory error
Gregory P. Smith28399852009-03-31 16:54:10 +0000750 message as appropriate.
751
752 If specified *msg* will be used as the error message on failure.
753
754 .. versionadded:: 2.7
755
756
757 .. method:: assertSameElements(expected, actual, msg=None)
758
759 Test that sequence *expected* contains the same elements as *actual*.
760 When they don't an error message listing the differences between the
761 sequences will be generated.
762
763 If specified *msg* will be used as the error message on failure.
764
765 .. versionadded:: 2.7
766
767
768 .. method:: assertSetEqual(set1, set2, msg=None)
769
770 Tests that two sets are equal. If not, an error message is constructed
771 that lists the differences between the sets.
772
773 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
774 method.
775
776 If specified *msg* will be used as the error message on failure.
777
778 .. versionadded:: 2.7
779
780
781 .. method:: assertDictEqual(expected, actual, msg=None)
782
783 Test that two dictionaries are equal. If not, an error message is
784 constructed that shows the differences in the dictionaries.
785
786 If specified *msg* will be used as the error message on failure.
787
788 .. versionadded:: 2.7
789
790
791 .. method:: assertDictContainsSubset(expected, actual, msg=None)
792
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000793 Tests whether the key/value pairs in dictionary *actual* are a
Gregory P. Smith28399852009-03-31 16:54:10 +0000794 superset of those in *expected*. If not, an error message listing
795 the missing keys and mismatched values is generated.
796
797 If specified *msg* will be used as the error message on failure.
798
799 .. versionadded:: 2.7
800
801
802 .. method:: assertListEqual(list1, list2, msg=None)
803 assertTupleEqual(tuple1, tuple2, msg=None)
804
805 Tests that two lists or tuples are equal. If not an error message is
806 constructed that shows only the differences between the two. An error
807 is also raised if either of the parameters are of the wrong type.
808
809 If specified *msg* will be used as the error message on failure.
810
811 .. versionadded:: 2.7
812
813
814 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
815
816 Tests that two sequences are equal. If a *seq_type* is supplied, both
817 *seq1* and *seq2* must be instances of *seq_type* or a failure will
818 be raised. If the sequences are different an error message is
819 constructed that shows the difference between the two.
820
821 If specified *msg* will be used as the error message on failure.
822
823 This method is used to implement :meth:`assertListEqual` and
824 :meth:`assertTupleEqual`.
825
826 .. versionadded:: 2.7
827
828
Benjamin Peterson99721e02009-03-23 23:10:14 +0000829 .. method:: assertRaises(exception[, callable, ...])
830 failUnlessRaises(exception[, callable, ...])
831
832 Test that an exception is raised when *callable* is called with any
833 positional or keyword arguments that are also passed to
834 :meth:`assertRaises`. The test passes if *exception* is raised, is an
835 error if another exception is raised, or fails if no exception is raised.
836 To catch any of a group of exceptions, a tuple containing the exception
837 classes may be passed as *exception*.
838
Benjamin Peterson7233acc2009-03-29 03:31:40 +0000839 If *callable* is omitted or None, returns a context manager so that the
840 code under test can be written inline rather than as a function::
841
842 with self.failUnlessRaises(some_error_class):
843 do_something()
844
Benjamin Peterson99721e02009-03-23 23:10:14 +0000845 .. versionchanged:: 2.7
Benjamin Peterson7233acc2009-03-29 03:31:40 +0000846 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000847
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000848 .. deprecated:: 2.7
849 :meth:`failUnlessRaises`.
850
Benjamin Peterson99721e02009-03-23 23:10:14 +0000851
Gregory P. Smith28399852009-03-31 16:54:10 +0000852 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
Benjamin Peterson99721e02009-03-23 23:10:14 +0000853
Gregory P. Smith28399852009-03-31 16:54:10 +0000854 Like :meth:`assertRaises` but also tests that *regexp* matches
855 on the string representation of the raised exception. *regexp* may be
856 a regular expression object or a string containing a regular expression
857 suitable for use by :func:`re.search`. Examples::
858
859 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
860 int, 'XYZ')
861
862 or::
863
864 with self.assertRaisesRegexp(ValueError, 'literal'):
865 int('XYZ')
866
867 .. versionadded:: 2.7
868
869
870 .. method:: assertIsNone(expr[, msg])
871
872 This signals a test failure if *expr* is not None.
873
874 .. versionadded:: 2.7
875
876
877 .. method:: assertIsNotNone(expr[, msg])
878
879 The inverse of the :meth:`assertIsNone` method.
880 This signals a test failure if *expr* is None.
881
882 .. versionadded:: 2.7
883
884
Michael Foordf2dfef12009-04-05 19:19:28 +0000885 .. method:: assertIs(expr1, expr2[, msg])
886
887 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
888 object.
889
890 .. versionadded:: 2.7
891
892
893 .. method:: assertIsNot(expr1, expr2[, msg])
894
895 The inverse of the :meth:`assertIs` method.
896 This signals a test failure if *expr1* and *expr2* evaluate to the same
897 object.
898
899 .. versionadded:: 2.7
900
901
Gregory P. Smith28399852009-03-31 16:54:10 +0000902 .. method:: assertFalse(expr[, msg])
903 failIf(expr[, msg])
904
905 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson99721e02009-03-23 23:10:14 +0000906 This signals a test failure if *expr* is true, with *msg* or :const:`None`
907 for the error message.
908
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000909 .. deprecated:: 2.7
910 :meth:`failIf`.
911
Benjamin Peterson99721e02009-03-23 23:10:14 +0000912
913 .. method:: fail([msg])
914
915 Signals a test failure unconditionally, with *msg* or :const:`None` for
916 the error message.
917
918
919 .. attribute:: failureException
920
921 This class attribute gives the exception raised by the test method. If a
922 test framework needs to use a specialized exception, possibly to carry
923 additional information, it must subclass this exception in order to "play
924 fair" with the framework. The initial value of this attribute is
925 :exc:`AssertionError`.
926
Michael Foord345b2fe2009-04-02 03:20:38 +0000927
928 .. attribute:: longMessage
929
930 If set to True then any explicit failure message you pass in to the
931 assert methods will be appended to the end of the normal failure message.
932 The normal messages contain useful information about the objects involved,
933 for example the message from assertEqual shows you the repr of the two
934 unequal objects. Setting this attribute to True allows you to have a
935 custom error message in addition to the normal one.
936
937 This attribute defaults to False, meaning that a custom message passed
938 to an assert method will silence the normal message.
939
940 The class setting can be overridden in individual tests by assigning an
941 instance attribute to True or False before calling the assert methods.
942
943 .. versionadded:: 2.7
944
945
Benjamin Peterson99721e02009-03-23 23:10:14 +0000946 Testing frameworks can use the following methods to collect information on
947 the test:
948
949
950 .. method:: countTestCases()
951
952 Return the number of tests represented by this test object. For
953 :class:`TestCase` instances, this will always be ``1``.
954
955
956 .. method:: defaultTestResult()
957
958 Return an instance of the test result class that should be used for this
959 test case class (if no other result instance is provided to the
960 :meth:`run` method).
961
962 For :class:`TestCase` instances, this will always be an instance of
963 :class:`TestResult`; subclasses of :class:`TestCase` should override this
964 as necessary.
965
966
967 .. method:: id()
968
969 Return a string identifying the specific test case. This is usually the
970 full name of the test method, including the module and class name.
971
972
973 .. method:: shortDescription()
974
Gregory P. Smith28399852009-03-31 16:54:10 +0000975 Returns a description of the test, or :const:`None` if no description
976 has been provided. The default implementation of this method
977 returns the first line of the test method's docstring, if available,
978 along with the method name.
979
980 .. versionchanged:: 2.7
Gregory P. Smith28399852009-03-31 16:54:10 +0000981 In earlier versions this only returned the first line of the test
982 method's docstring, if available or the :const:`None`. That led to
983 undesirable behavior of not printing the test name when someone was
984 thoughtful enough to write a docstring.
985
986
987 .. method:: addTypeEqualityFunc(typeobj, function)
988
989 Registers a type specific :meth:`assertEqual` equality checking
990 function to be called by :meth:`assertEqual` when both objects it has
991 been asked to compare are exactly *typeobj* (not subclasses).
992 *function* must take two positional arguments and a third msg=None
993 keyword argument just as :meth:`assertEqual` does. It must raise
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000994 ``self.failureException`` when inequality between the first two
Gregory P. Smith28399852009-03-31 16:54:10 +0000995 parameters is detected.
996
997 One good use of custom equality checking functions for a type
Andrew M. Kuchling59631852009-04-09 11:23:36 +0000998 is to raise ``self.failureException`` with an error message useful
999 for debugging the problem by explaining the inequalities in detail.
Gregory P. Smith28399852009-03-31 16:54:10 +00001000
1001 .. versionadded:: 2.7
Georg Brandl8ec7f652007-08-15 14:28:01 +00001002
1003
Michael Foorde2fb98f2009-05-02 20:15:05 +00001004 .. method:: addCleanup(function[, *args[, **kwargs]])
1005
1006 Add a function to be called after :meth:`tearDown` to cleanup resources
1007 used during the test. Functions will be called in reverse order to the
1008 order they are added (LIFO). They are called with any arguments and
1009 keyword arguments passed into :meth:`addCleanup` when they are
1010 added.
1011
1012 If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
1013 then any cleanup functions added will still be called.
1014
1015 .. versionadded:: 2.7
1016
1017
1018 .. method:: doCleanups()
1019
1020 This method is called uncoditionally after :meth:`tearDown`, or
1021 after :meth:`setUp` if :meth:`setUp` raises an exception.
1022
1023 It is responsible for calling all the cleanup functions added by
1024 :meth:`addCleanup`. If you need cleanup functions to be called
1025 *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
1026 yourself.
1027
1028 :meth:`doCleanups` pops methods off the stack of cleanup
1029 functions one at a time, so it can be called at any time.
1030
1031 .. versionadded:: 2.7
1032
1033
Georg Brandl8ec7f652007-08-15 14:28:01 +00001034.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
1035
1036 This class implements the portion of the :class:`TestCase` interface which
1037 allows the test runner to drive the test, but does not provide the methods which
1038 test code can use to check and report errors. This is used to create test cases
1039 using legacy test code, allowing it to be integrated into a :mod:`unittest`\
1040 -based test framework.
1041
1042
Benjamin Peterson99721e02009-03-23 23:10:14 +00001043.. _testsuite-objects:
1044
1045Grouping tests
1046~~~~~~~~~~~~~~
1047
Georg Brandl8ec7f652007-08-15 14:28:01 +00001048.. class:: TestSuite([tests])
1049
1050 This class represents an aggregation of individual tests cases and test suites.
1051 The class presents the interface needed by the test runner to allow it to be run
1052 as any other test case. Running a :class:`TestSuite` instance is the same as
1053 iterating over the suite, running each test individually.
1054
1055 If *tests* is given, it must be an iterable of individual test cases or other
1056 test suites that will be used to build the suite initially. Additional methods
1057 are provided to add test cases and suites to the collection later on.
1058
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001059 :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
1060 they do not actually implement a test. Instead, they are used to aggregate
1061 tests into groups of tests that should be run together. Some additional
1062 methods are available to add tests to :class:`TestSuite` instances:
Benjamin Peterson99721e02009-03-23 23:10:14 +00001063
1064
1065 .. method:: TestSuite.addTest(test)
1066
1067 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1068
1069
1070 .. method:: TestSuite.addTests(tests)
1071
1072 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1073 instances to this test suite.
1074
1075 This is equivalent to iterating over *tests*, calling :meth:`addTest` for each
1076 element.
1077
1078 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1079
1080
1081 .. method:: run(result)
1082
1083 Run the tests associated with this suite, collecting the result into the
1084 test result object passed as *result*. Note that unlike
1085 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1086 be passed in.
1087
1088
1089 .. method:: debug()
1090
1091 Run the tests associated with this suite without collecting the
1092 result. This allows exceptions raised by the test to be propagated to the
1093 caller and can be used to support running tests under a debugger.
1094
1095
1096 .. method:: countTestCases()
1097
1098 Return the number of tests represented by this test object, including all
1099 individual tests and sub-suites.
1100
Georg Brandl9bc66822009-04-27 17:04:23 +00001101
1102 .. method:: __iter__()
1103
1104 Tests grouped by a :class:`TestSuite` are always accessed by iteration.
1105 Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
1106 that this method maybe called several times on a single suite
1107 (for example when counting tests or comparing for equality)
1108 so the tests returned must be the same for repeated iterations.
1109
1110 .. versionchanged:: 2.7
1111 In earlier versions the :class:`TestSuite` accessed tests directly rather
1112 than through iteration, so overriding :meth:`__iter__` wasn't sufficient
1113 for providing tests.
1114
Benjamin Peterson99721e02009-03-23 23:10:14 +00001115 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1116 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1117
1118
Benjamin Peterson99721e02009-03-23 23:10:14 +00001119Loading and running tests
1120~~~~~~~~~~~~~~~~~~~~~~~~~
1121
Georg Brandl8ec7f652007-08-15 14:28:01 +00001122.. class:: TestLoader()
1123
Benjamin Peterson99721e02009-03-23 23:10:14 +00001124 The :class:`TestLoader` class is used to create test suites from classes and
1125 modules. Normally, there is no need to create an instance of this class; the
1126 :mod:`unittest` module provides an instance that can be shared as
1127 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1128 customization of some configurable properties.
1129
1130 :class:`TestLoader` objects have the following methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001131
1132
Benjamin Peterson99721e02009-03-23 23:10:14 +00001133 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001134
Benjamin Peterson99721e02009-03-23 23:10:14 +00001135 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1136 :class:`testCaseClass`.
1137
1138
1139 .. method:: loadTestsFromModule(module)
1140
1141 Return a suite of all tests cases contained in the given module. This
1142 method searches *module* for classes derived from :class:`TestCase` and
1143 creates an instance of the class for each test method defined for the
1144 class.
1145
Georg Brandl16a57f62009-04-27 15:29:09 +00001146 .. note::
Benjamin Peterson99721e02009-03-23 23:10:14 +00001147
1148 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1149 convenient in sharing fixtures and helper functions, defining test
1150 methods on base classes that are not intended to be instantiated
1151 directly does not play well with this method. Doing so, however, can
1152 be useful when the fixtures are different and defined in subclasses.
1153
1154
1155 .. method:: loadTestsFromName(name[, module])
1156
1157 Return a suite of all tests cases given a string specifier.
1158
1159 The specifier *name* is a "dotted name" that may resolve either to a
1160 module, a test case class, a test method within a test case class, a
1161 :class:`TestSuite` instance, or a callable object which returns a
1162 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1163 applied in the order listed here; that is, a method on a possible test
1164 case class will be picked up as "a test method within a test case class",
1165 rather than "a callable object".
1166
1167 For example, if you have a module :mod:`SampleTests` containing a
1168 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1169 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
1170 specifier ``'SampleTests.SampleTestCase'`` would cause this method to return a
1171 suite which will run all three test methods. Using the specifier
1172 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test suite
1173 which will run only the :meth:`test_two` test method. The specifier can refer
1174 to modules and packages which have not been imported; they will be imported as a
1175 side-effect.
1176
1177 The method optionally resolves *name* relative to the given *module*.
1178
1179
1180 .. method:: loadTestsFromNames(names[, module])
1181
1182 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1183 than a single name. The return value is a test suite which supports all
1184 the tests defined for each name.
1185
1186
1187 .. method:: getTestCaseNames(testCaseClass)
1188
1189 Return a sorted sequence of method names found within *testCaseClass*;
1190 this should be a subclass of :class:`TestCase`.
1191
1192 The following attributes of a :class:`TestLoader` can be configured either by
1193 subclassing or assignment on an instance:
1194
1195
1196 .. attribute:: testMethodPrefix
1197
1198 String giving the prefix of method names which will be interpreted as test
1199 methods. The default value is ``'test'``.
1200
1201 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1202 methods.
1203
1204
1205 .. attribute:: sortTestMethodsUsing
1206
1207 Function to be used to compare method names when sorting them in
1208 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
1209 default value is the built-in :func:`cmp` function; the attribute can also
1210 be set to :const:`None` to disable the sort.
1211
1212
1213 .. attribute:: suiteClass
1214
1215 Callable object that constructs a test suite from a list of tests. No
1216 methods on the resulting object are needed. The default value is the
1217 :class:`TestSuite` class.
1218
1219 This affects all the :meth:`loadTestsFrom\*` methods.
1220
1221
Benjamin Peterson99721e02009-03-23 23:10:14 +00001222.. class:: TestResult
1223
1224 This class is used to compile information about which tests have succeeded
1225 and which have failed.
1226
1227 A :class:`TestResult` object stores the results of a set of tests. The
1228 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1229 properly recorded; test authors do not need to worry about recording the
1230 outcome of tests.
1231
1232 Testing frameworks built on top of :mod:`unittest` may want access to the
1233 :class:`TestResult` object generated by running a set of tests for reporting
1234 purposes; a :class:`TestResult` instance is returned by the
1235 :meth:`TestRunner.run` method for this purpose.
1236
1237 :class:`TestResult` instances have the following attributes that will be of
1238 interest when inspecting the results of running a set of tests:
1239
1240
1241 .. attribute:: errors
1242
1243 A list containing 2-tuples of :class:`TestCase` instances and strings
1244 holding formatted tracebacks. Each tuple represents a test which raised an
1245 unexpected exception.
1246
1247 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001248 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1249
1250
1251 .. attribute:: failures
1252
1253 A list containing 2-tuples of :class:`TestCase` instances and strings
1254 holding formatted tracebacks. Each tuple represents a test where a failure
1255 was explicitly signalled using the :meth:`TestCase.fail\*` or
1256 :meth:`TestCase.assert\*` methods.
1257
1258 .. versionchanged:: 2.2
Benjamin Peterson99721e02009-03-23 23:10:14 +00001259 Contains formatted tracebacks instead of :func:`sys.exc_info` results.
1260
1261 .. attribute:: skipped
1262
1263 A list containing 2-tuples of :class:`TestCase` instances and strings
1264 holding the reason for skipping the test.
1265
1266 .. versionadded:: 2.7
1267
1268 .. attribute:: expectedFailures
1269
1270 A list contaning 2-tuples of :class:`TestCase` instances and strings
1271 holding formatted tracebacks. Each tuple represents a expected failures
1272 of the test case.
1273
1274 .. attribute:: unexpectedSuccesses
1275
1276 A list containing :class:`TestCase` instances that were marked as expected
1277 failures, but succeeded.
1278
1279 .. attribute:: shouldStop
1280
1281 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1282
1283
1284 .. attribute:: testsRun
1285
1286 The total number of tests run so far.
1287
1288
1289 .. method:: wasSuccessful()
1290
1291 Return :const:`True` if all tests run so far have passed, otherwise returns
1292 :const:`False`.
1293
1294
1295 .. method:: stop()
1296
1297 This method can be called to signal that the set of tests being run should
1298 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1299 :class:`TestRunner` objects should respect this flag and return without
1300 running any additional tests.
1301
1302 For example, this feature is used by the :class:`TextTestRunner` class to
1303 stop the test framework when the user signals an interrupt from the
1304 keyboard. Interactive tools which provide :class:`TestRunner`
1305 implementations can use this in a similar manner.
1306
1307 The following methods of the :class:`TestResult` class are used to maintain
1308 the internal data structures, and may be extended in subclasses to support
1309 additional reporting requirements. This is particularly useful in building
1310 tools which support interactive reporting while tests are being run.
1311
1312
1313 .. method:: startTest(test)
1314
1315 Called when the test case *test* is about to be run.
1316
1317 The default implementation simply increments the instance's :attr:`testsRun`
1318 counter.
1319
1320
1321 .. method:: stopTest(test)
1322
1323 Called after the test case *test* has been executed, regardless of the
1324 outcome.
1325
1326 The default implementation does nothing.
1327
1328
Michael Foord07ef4872009-05-02 22:43:34 +00001329 .. method:: startTestRun(test)
1330
1331 Called once before any tests are executed.
1332
1333 .. versionadded:: 2.7
1334
1335
1336 .. method:: stopTestRun(test)
1337
1338 Called once before any tests are executed.
1339
1340 .. versionadded:: 2.7
1341
1342
Benjamin Peterson99721e02009-03-23 23:10:14 +00001343 .. method:: addError(test, err)
1344
1345 Called when the test case *test* raises an unexpected exception *err* is a
1346 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1347 traceback)``.
1348
1349 The default implementation appends a tuple ``(test, formatted_err)`` to
1350 the instance's :attr:`errors` attribute, where *formatted_err* is a
1351 formatted traceback derived from *err*.
1352
1353
1354 .. method:: addFailure(test, err)
1355
1356 Called when the test case *test* signals a failure. *err* is a tuple of the form
1357 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1358
1359 The default implementation appends a tuple ``(test, formatted_err)`` to
1360 the instance's :attr:`failures` attribute, where *formatted_err* is a
1361 formatted traceback derived from *err*.
1362
1363
1364 .. method:: addSuccess(test)
1365
1366 Called when the test case *test* succeeds.
1367
1368 The default implementation does nothing.
1369
1370
1371 .. method:: addSkip(test, reason)
1372
1373 Called when the test case *test* is skipped. *reason* is the reason the
1374 test gave for skipping.
1375
1376 The default implementation appends a tuple ``(test, reason)`` to the
1377 instance's :attr:`skipped` attribute.
1378
1379
1380 .. method:: addExpectedFailure(test, err)
1381
1382 Called when the test case *test* fails, but was marked with the
1383 :func:`expectedFailure` decorator.
1384
1385 The default implementation appends a tuple ``(test, formatted_err)`` to
1386 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1387 is a formatted traceback derived from *err*.
1388
1389
1390 .. method:: addUnexpectedSuccess(test)
1391
1392 Called when the test case *test* was marked with the
1393 :func:`expectedFailure` decorator, but succeeded.
1394
1395 The default implementation appends the test to the instance's
1396 :attr:`unexpectedSuccesses` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001397
1398
1399.. data:: defaultTestLoader
1400
1401 Instance of the :class:`TestLoader` class intended to be shared. If no
1402 customization of the :class:`TestLoader` is needed, this instance can be used
1403 instead of repeatedly creating new instances.
1404
1405
1406.. class:: TextTestRunner([stream[, descriptions[, verbosity]]])
1407
1408 A basic test runner implementation which prints results on standard error. It
1409 has a few configurable parameters, but is essentially very simple. Graphical
1410 applications which run test suites should provide alternate implementations.
1411
Georg Brandl9bc66822009-04-27 17:04:23 +00001412 .. method:: _makeResult()
1413
1414 This method returns the instance of ``TestResult`` used by :meth:`run`.
1415 It is not intended to be called directly, but can be overridden in
1416 subclasses to provide a custom ``TestResult``.
1417
Georg Brandl8ec7f652007-08-15 14:28:01 +00001418
Michael Foord5d31e052009-05-11 17:59:43 +00001419.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit, [verbosity]]]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001420
1421 A command-line program that runs a set of tests; this is primarily for making
1422 test modules conveniently executable. The simplest use for this function is to
1423 include the following line at the end of a test script::
1424
1425 if __name__ == '__main__':
1426 unittest.main()
1427
Michael Foord5d31e052009-05-11 17:59:43 +00001428 You can run tests with more detailed information by passing in the verbosity
1429 argument::
1430
1431 if __name__ == '__main__':
1432 unittest.main(verbosity=2)
1433
Georg Brandl8ec7f652007-08-15 14:28:01 +00001434 The *testRunner* argument can either be a test runner class or an already
Michael Foord829f6b82009-05-02 11:43:06 +00001435 created instance of it. By default ``main`` calls :func:`sys.exit` with
1436 an exit code indicating success or failure of the tests run.
1437
1438 ``main`` supports being used from the interactive interpreter by passing in the
1439 argument ``exit=False``. This displays the result on standard output without
1440 calling :func:`sys.exit`::
1441
1442 >>> from unittest import main
1443 >>> main(module='test_module', exit=False)
1444
1445 Calling ``main`` actually returns an instance of the ``TestProgram`` class.
1446 This stores the result of the tests run as the ``result`` attribute.
1447
1448 .. versionchanged:: 2.7
Michael Foord5d31e052009-05-11 17:59:43 +00001449 The ``exit`` and ``verbosity`` parameters were added.