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