blob: 5034ed4943c9af5e5e84be266038149ecc73b484 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Benjamin Peterson5254c042009-03-23 22:25:03 +000012.. versionchanged:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +000013 Added test :ref:`skipping and expected failures <unittest-skipping>`.
Benjamin Peterson5254c042009-03-23 22:25:03 +000014
Georg Brandl116aa622007-08-15 14:28:22 +000015The Python unit testing framework, sometimes referred to as "PyUnit," is a
16Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
17turn, a Java version of Kent's Smalltalk testing framework. Each is the de
18facto standard unit testing framework for its respective language.
19
20:mod:`unittest` supports test automation, sharing of setup and shutdown code for
21tests, aggregation of tests into collections, and independence of the tests from
22the reporting framework. The :mod:`unittest` module provides classes that make
23it easy to support these qualities for a set of tests.
24
25To achieve this, :mod:`unittest` supports some important concepts:
26
27test fixture
28 A :dfn:`test fixture` represents the preparation needed to perform one or more
29 tests, and any associate cleanup actions. This may involve, for example,
30 creating temporary or proxy databases, directories, or starting a server
31 process.
32
33test case
34 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
35 response to a particular set of inputs. :mod:`unittest` provides a base class,
36 :class:`TestCase`, which may be used to create new test cases.
37
38test suite
39 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
40 used to aggregate tests that should be executed together.
41
42test runner
43 A :dfn:`test runner` is a component which orchestrates the execution of tests
44 and provides the outcome to the user. The runner may use a graphical interface,
45 a textual interface, or return a special value to indicate the results of
46 executing the tests.
47
48The test case and test fixture concepts are supported through the
49:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
50used when creating new tests, and the latter can be used when integrating
51existing test code with a :mod:`unittest`\ -driven framework. When building test
Benjamin Peterson52baa292009-03-24 00:56:30 +000052fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
53:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
54and cleanup for the fixture. With :class:`FunctionTestCase`, existing functions
55can be passed to the constructor for these purposes. When the test is run, the
56fixture initialization is run first; if it succeeds, the cleanup method is run
57after the test has been executed, regardless of the outcome of the test. Each
58instance of the :class:`TestCase` will only be used to run a single test method,
59so a new fixture is created for each test.
Georg Brandl116aa622007-08-15 14:28:22 +000060
61Test suites are implemented by the :class:`TestSuite` class. This class allows
62individual tests and test suites to be aggregated; when the suite is executed,
Benjamin Peterson5254c042009-03-23 22:25:03 +000063all tests added directly to the suite and in "child" test suites are run. A
64:class:`ClassTestSuite` contains the test cases of a class.
Georg Brandl116aa622007-08-15 14:28:22 +000065
Benjamin Peterson52baa292009-03-24 00:56:30 +000066A test runner is an object that provides a single method,
67:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
68object as a parameter, and returns a result object. The class
69:class:`TestResult` is provided for use as the result object. :mod:`unittest`
70provides the :class:`TextTestRunner` as an example test runner which reports
71test results on the standard error stream by default. Alternate runners can be
72implemented for other environments (such as graphical environments) without any
73need to derive from a specific class.
Georg Brandl116aa622007-08-15 14:28:22 +000074
75
76.. seealso::
77
78 Module :mod:`doctest`
79 Another test-support module with a very different flavor.
80
81 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
82 Kent Beck's original paper on testing frameworks using the pattern shared by
83 :mod:`unittest`.
84
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000085 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
86 Third-party unittest frameworks with a lighter-weight syntax
87 for writing tests. For example, ``assert func(10) == 42``.
88
89 `python-mock <http://python-mock.sourceforge.net/>`_ and `minimock <http://blog.ianbicking.org/minimock.html>`_
90 Tools for creating mock test objects (objects simulating external resources).
Georg Brandl116aa622007-08-15 14:28:22 +000091
92.. _unittest-minimal-example:
93
94Basic example
95-------------
96
97The :mod:`unittest` module provides a rich set of tools for constructing and
98running tests. This section demonstrates that a small subset of the tools
99suffice to meet the needs of most users.
100
101Here is a short script to test three functions from the :mod:`random` module::
102
103 import random
104 import unittest
105
106 class TestSequenceFunctions(unittest.TestCase):
107
108 def setUp(self):
109 self.seq = range(10)
110
Benjamin Peterson52baa292009-03-24 00:56:30 +0000111 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000112 # make sure the shuffled sequence does not lose any elements
113 random.shuffle(self.seq)
114 self.seq.sort()
115 self.assertEqual(self.seq, range(10))
116
Benjamin Peterson52baa292009-03-24 00:56:30 +0000117 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000118 element = random.choice(self.seq)
119 self.assert_(element in self.seq)
120
Benjamin Peterson52baa292009-03-24 00:56:30 +0000121 def test_sample(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000122 self.assertRaises(ValueError, random.sample, self.seq, 20)
123 for element in random.sample(self.seq, 5):
124 self.assert_(element in self.seq)
125
126 if __name__ == '__main__':
127 unittest.main()
128
Benjamin Peterson52baa292009-03-24 00:56:30 +0000129A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000130individual tests are defined with methods whose names start with the letters
131``test``. This naming convention informs the test runner about which methods
132represent tests.
133
Benjamin Peterson52baa292009-03-24 00:56:30 +0000134The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
135expected result; :meth:`~TestCase.assert_` to verify a condition; or
136:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
137These methods are used instead of the :keyword:`assert` statement so the test
138runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Benjamin Peterson52baa292009-03-24 00:56:30 +0000140When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
141method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
142defined, the test runner will invoke that method after each test. In the
143example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
144test.
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146The final block shows a simple way to run the tests. :func:`unittest.main`
147provides a command line interface to the test script. When run from the command
148line, the above script produces an output that looks like this::
149
150 ...
151 ----------------------------------------------------------------------
152 Ran 3 tests in 0.000s
153
154 OK
155
156Instead of :func:`unittest.main`, there are other ways to run the tests with a
157finer level of control, less terse output, and no requirement to be run from the
158command line. For example, the last two lines may be replaced with::
159
160 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
161 unittest.TextTestRunner(verbosity=2).run(suite)
162
163Running the revised script from the interpreter or another script produces the
164following output::
165
166 testchoice (__main__.TestSequenceFunctions) ... ok
167 testsample (__main__.TestSequenceFunctions) ... ok
168 testshuffle (__main__.TestSequenceFunctions) ... ok
169
170 ----------------------------------------------------------------------
171 Ran 3 tests in 0.110s
172
173 OK
174
175The above examples show the most commonly used :mod:`unittest` features which
176are sufficient to meet many everyday testing needs. The remainder of the
177documentation explores the full feature set from first principles.
178
179
180.. _organizing-tests:
181
182Organizing test code
183--------------------
184
185The basic building blocks of unit testing are :dfn:`test cases` --- single
186scenarios that must be set up and checked for correctness. In :mod:`unittest`,
187test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
188class. To make your own test cases you must write subclasses of
189:class:`TestCase`, or use :class:`FunctionTestCase`.
190
191An instance of a :class:`TestCase`\ -derived class is an object that can
192completely run a single test method, together with optional set-up and tidy-up
193code.
194
195The testing code of a :class:`TestCase` instance should be entirely self
196contained, such that it can be run either in isolation or in arbitrary
197combination with any number of other test cases.
198
Benjamin Peterson52baa292009-03-24 00:56:30 +0000199The simplest :class:`TestCase` subclass will simply override the
200:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202 import unittest
203
204 class DefaultWidgetSizeTestCase(unittest.TestCase):
205 def runTest(self):
206 widget = Widget('The widget')
207 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
208
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000209Note that in order to test something, we use the one of the :meth:`assert\*`
210methods provided by the :class:`TestCase` base class. If the
Georg Brandl116aa622007-08-15 14:28:22 +0000211test fails, an exception will be raised, and :mod:`unittest` will identify the
212test case as a :dfn:`failure`. Any other exceptions will be treated as
213:dfn:`errors`. This helps you identify where the problem is: :dfn:`failures` are
214caused by incorrect results - a 5 where you expected a 6. :dfn:`Errors` are
215caused by incorrect code - e.g., a :exc:`TypeError` caused by an incorrect
216function call.
217
218The way to run a test case will be described later. For now, note that to
219construct an instance of such a test case, we call its constructor without
220arguments::
221
222 testCase = DefaultWidgetSizeTestCase()
223
224Now, such test cases can be numerous, and their set-up can be repetitive. In
225the above case, constructing a :class:`Widget` in each of 100 Widget test case
226subclasses would mean unsightly duplication.
227
228Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000229:meth:`~TestCase.setUp`, which the testing framework will automatically call for
230us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000231
232 import unittest
233
234 class SimpleWidgetTestCase(unittest.TestCase):
235 def setUp(self):
236 self.widget = Widget('The widget')
237
238 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
239 def runTest(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000240 self.assertTrue(self.widget.size() == (50,50),
Georg Brandl116aa622007-08-15 14:28:22 +0000241 'incorrect default size')
242
243 class WidgetResizeTestCase(SimpleWidgetTestCase):
244 def runTest(self):
245 self.widget.resize(100,150)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000246 self.assertTrue(self.widget.size() == (100,150),
Georg Brandl116aa622007-08-15 14:28:22 +0000247 'wrong size after resize')
248
Benjamin Peterson52baa292009-03-24 00:56:30 +0000249If the :meth:`~TestCase.setUp` method raises an exception while the test is
250running, the framework will consider the test to have suffered an error, and the
251:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000252
Benjamin Peterson52baa292009-03-24 00:56:30 +0000253Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
254after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256 import unittest
257
258 class SimpleWidgetTestCase(unittest.TestCase):
259 def setUp(self):
260 self.widget = Widget('The widget')
261
262 def tearDown(self):
263 self.widget.dispose()
264 self.widget = None
265
Benjamin Peterson52baa292009-03-24 00:56:30 +0000266If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
267be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000268
269Such a working environment for the testing code is called a :dfn:`fixture`.
270
271Often, many small test cases will use the same fixture. In this case, we would
272end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
273classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000274discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
275mechanism::
276
277 import unittest
278
279 class WidgetTestCase(unittest.TestCase):
280 def setUp(self):
281 self.widget = Widget('The widget')
282
283 def tearDown(self):
284 self.widget.dispose()
285 self.widget = None
286
287 def testDefaultSize(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000288 self.assertTrue(self.widget.size() == (50,50),
Georg Brandl116aa622007-08-15 14:28:22 +0000289 'incorrect default size')
290
291 def testResize(self):
292 self.widget.resize(100,150)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000293 self.assertTrue(self.widget.size() == (100,150),
Georg Brandl116aa622007-08-15 14:28:22 +0000294 'wrong size after resize')
295
Benjamin Peterson52baa292009-03-24 00:56:30 +0000296Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
297provided two different test methods. Class instances will now each run one of
298the :meth:`test\*` methods, with ``self.widget`` created and destroyed
299separately for each instance. When creating an instance we must specify the
300test method it is to run. We do this by passing the method name in the
301constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000302
303 defaultSizeTestCase = WidgetTestCase('testDefaultSize')
304 resizeTestCase = WidgetTestCase('testResize')
305
306Test case instances are grouped together according to the features they test.
307:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
308represented by :mod:`unittest`'s :class:`TestSuite` class::
309
310 widgetTestSuite = unittest.TestSuite()
311 widgetTestSuite.addTest(WidgetTestCase('testDefaultSize'))
312 widgetTestSuite.addTest(WidgetTestCase('testResize'))
313
314For the ease of running tests, as we will see later, it is a good idea to
315provide in each test module a callable object that returns a pre-built test
316suite::
317
318 def suite():
319 suite = unittest.TestSuite()
320 suite.addTest(WidgetTestCase('testDefaultSize'))
321 suite.addTest(WidgetTestCase('testResize'))
322 return suite
323
324or even::
325
326 def suite():
327 tests = ['testDefaultSize', 'testResize']
328
329 return unittest.TestSuite(map(WidgetTestCase, tests))
330
331Since it is a common pattern to create a :class:`TestCase` subclass with many
332similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
333class that can be used to automate the process of creating a test suite and
334populating it with individual tests. For example, ::
335
336 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
337
338will create a test suite that will run ``WidgetTestCase.testDefaultSize()`` and
339``WidgetTestCase.testResize``. :class:`TestLoader` uses the ``'test'`` method
340name prefix to identify test methods automatically.
341
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000342Note that the order in which the various test cases will be run is
343determined by sorting the test function names with respect to the
344built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000345
346Often it is desirable to group suites of test cases together, so as to run tests
347for the whole system at once. This is easy, since :class:`TestSuite` instances
348can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
349added to a :class:`TestSuite`::
350
351 suite1 = module1.TheTestSuite()
352 suite2 = module2.TheTestSuite()
353 alltests = unittest.TestSuite([suite1, suite2])
354
355You can place the definitions of test cases and test suites in the same modules
356as the code they are to test (such as :file:`widget.py`), but there are several
357advantages to placing the test code in a separate module, such as
358:file:`test_widget.py`:
359
360* The test module can be run standalone from the command line.
361
362* The test code can more easily be separated from shipped code.
363
364* There is less temptation to change test code to fit the code it tests without
365 a good reason.
366
367* Test code should be modified much less frequently than the code it tests.
368
369* Tested code can be refactored more easily.
370
371* Tests for modules written in C must be in separate modules anyway, so why not
372 be consistent?
373
374* If the testing strategy changes, there is no need to change the source code.
375
376
377.. _legacy-unit-tests:
378
379Re-using old test code
380----------------------
381
382Some users will find that they have existing test code that they would like to
383run from :mod:`unittest`, without converting every old test function to a
384:class:`TestCase` subclass.
385
386For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
387This subclass of :class:`TestCase` can be used to wrap an existing test
388function. Set-up and tear-down functions can also be provided.
389
390Given the following test function::
391
392 def testSomething():
393 something = makeSomething()
394 assert something.name is not None
395 # ...
396
397one can create an equivalent test case instance as follows::
398
399 testcase = unittest.FunctionTestCase(testSomething)
400
401If there are additional set-up and tear-down methods that should be called as
402part of the test case's operation, they can also be provided like so::
403
404 testcase = unittest.FunctionTestCase(testSomething,
405 setUp=makeSomethingDB,
406 tearDown=deleteSomethingDB)
407
408To make migrating existing test suites easier, :mod:`unittest` supports tests
409raising :exc:`AssertionError` to indicate test failure. However, it is
410recommended that you use the explicit :meth:`TestCase.fail\*` and
411:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
412may treat :exc:`AssertionError` differently.
413
414.. note::
415
416 Even though :class:`FunctionTestCase` can be used to quickly convert an existing
417 test base over to a :mod:`unittest`\ -based system, this approach is not
418 recommended. Taking the time to set up proper :class:`TestCase` subclasses will
419 make future test refactorings infinitely easier.
420
Benjamin Peterson52baa292009-03-24 00:56:30 +0000421In some cases, the existing tests may have been written using the :mod:`doctest`
422module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
423automatically build :class:`unittest.TestSuite` instances from the existing
424:mod:`doctest`\ -based tests.
425
Georg Brandl116aa622007-08-15 14:28:22 +0000426
Benjamin Peterson5254c042009-03-23 22:25:03 +0000427.. _unittest-skipping:
428
429Skipping tests and expected failures
430------------------------------------
431
432Unittest supports skipping individual test methods and even whole classes of
433tests. In addition, it supports marking a test as a "expected failure," a test
434that is broken and will fail, but shouldn't be counted as a failure on a
435:class:`TestResult`.
436
437Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
438or one of its conditional variants.
439
440Basic skipping looks like this: ::
441
442 class MyTestCase(unittest.TestCase):
443
444 @unittest.skip("demonstrating skipping")
445 def test_nothing(self):
446 self.fail("shouldn't happen")
447
Benjamin Petersonded31c42009-03-30 15:04:16 +0000448 @unittest.skipIf(mylib.__version__ < (1, 3), "not supported in this library version")
449 def test_format(self):
450 # Tests that work for only a certain version of the library.
451 pass
452
453 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
454 def test_windows_support(self):
455 # windows specific testing code
456 pass
457
Benjamin Peterson5254c042009-03-23 22:25:03 +0000458This is the output of running the example above in verbose mode: ::
459
Benjamin Petersonded31c42009-03-30 15:04:16 +0000460 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000461 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000462 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000463
464 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000465 Ran 3 tests in 0.005s
466
467 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000468
469Classes can be skipped just like methods: ::
470
471 @skip("showing class skipping")
472 class MySkippedTestCase(unittest.TestCase):
473 def test_not_run(self):
474 pass
475
Benjamin Peterson52baa292009-03-24 00:56:30 +0000476:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
477that needs to be set up is not available.
478
Benjamin Peterson5254c042009-03-23 22:25:03 +0000479Expected failures use the :func:`expectedFailure` decorator. ::
480
481 class ExpectedFailureTestCase(unittest.TestCase):
482 @unittest.expectedFailure
483 def test_fail(self):
484 self.assertEqual(1, 0, "broken")
485
486It's easy to roll your own skipping decorators by making a decorator that calls
487:func:`skip` on the test when it wants it to be skipped. This decorator skips
488the test unless the passed object has a certain attribute: ::
489
490 def skipUnlessHasattr(obj, attr):
491 if hasattr(obj, attr):
492 return lambda func: func
493 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
494
495The following decorators implement test skipping and expected failures:
496
497.. function:: skip(reason)
498
499 Unconditionally skip the decorated test. *reason* should describe why the
500 test is being skipped.
501
502.. function:: skipIf(condition, reason)
503
504 Skip the decorated test if *condition* is true.
505
506.. function:: skipUnless(condition, reason)
507
508 Skip the decoratored test unless *condition* is true.
509
510.. function:: expectedFailure
511
512 Mark the test as an expected failure. If the test fails when run, the test
513 is not counted as a failure.
514
515
Georg Brandl116aa622007-08-15 14:28:22 +0000516.. _unittest-contents:
517
518Classes and functions
519---------------------
520
Benjamin Peterson52baa292009-03-24 00:56:30 +0000521This section describes in depth the API of :mod:`unittest`.
522
523
524.. _testcase-objects:
525
526Test cases
527~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529.. class:: TestCase([methodName])
530
531 Instances of the :class:`TestCase` class represent the smallest testable units
532 in the :mod:`unittest` universe. This class is intended to be used as a base
533 class, with specific tests being implemented by concrete subclasses. This class
534 implements the interface needed by the test runner to allow it to drive the
535 test, and methods that the test code can use to check for and report various
536 kinds of failure.
537
538 Each instance of :class:`TestCase` will run a single test method: the method
539 named *methodName*. If you remember, we had an earlier example that went
540 something like this::
541
542 def suite():
543 suite = unittest.TestSuite()
544 suite.addTest(WidgetTestCase('testDefaultSize'))
545 suite.addTest(WidgetTestCase('testResize'))
546 return suite
547
548 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
549 single test.
550
Benjamin Peterson52baa292009-03-24 00:56:30 +0000551 *methodName* defaults to :meth:`runTest`.
552
553 :class:`TestCase` instances provide three groups of methods: one group used
554 to run the test, another used by the test implementation to check conditions
555 and report failures, and some inquiry methods allowing information about the
556 test itself to be gathered.
557
558 Methods in the first group (running the test) are:
559
560
561 .. method:: setUp()
562
563 Method called to prepare the test fixture. This is called immediately
564 before calling the test method; any exception raised by this method will
565 be considered an error rather than a test failure. The default
566 implementation does nothing.
567
568
569 .. method:: tearDown()
570
571 Method called immediately after the test method has been called and the
572 result recorded. This is called even if the test method raised an
573 exception, so the implementation in subclasses may need to be particularly
574 careful about checking internal state. Any exception raised by this
575 method will be considered an error rather than a test failure. This
576 method will only be called if the :meth:`setUp` succeeds, regardless of
577 the outcome of the test method. The default implementation does nothing.
578
579
580 .. method:: run([result])
581
582 Run the test, collecting the result into the test result object passed as
583 *result*. If *result* is omitted or :const:`None`, a temporary result
584 object is created (by calling the :meth:`defaultTestCase` method) and
585 used; this result object is not returned to :meth:`run`'s caller.
586
587 The same effect may be had by simply calling the :class:`TestCase`
588 instance.
589
590
Benjamin Petersone549ead2009-03-28 21:42:05 +0000591 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000592
593 Calling this during the a test method or :meth:`setUp` skips the current
594 test. See :ref:`unittest-skipping` for more information.
595
596
597 .. method:: debug()
598
599 Run the test without collecting the result. This allows exceptions raised
600 by the test to be propagated to the caller, and can be used to support
601 running tests under a debugger.
602
603 The test code can use any of the following methods to check for and report
604 failures.
605
606
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000607 .. method:: assertTrue(expr[, msg])
608 assert_(expr[, msg])
Benjamin Peterson52baa292009-03-24 00:56:30 +0000609 failUnless(expr[, msg])
Benjamin Peterson52baa292009-03-24 00:56:30 +0000610
611 Signal a test failure if *expr* is false; the explanation for the error
612 will be *msg* if given, otherwise it will be :const:`None`.
613
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000614 .. deprecated:: 2.7
615 :meth:`failUnless`.
616
Benjamin Peterson52baa292009-03-24 00:56:30 +0000617
618 .. method:: assertEqual(first, second[, msg])
619 failUnlessEqual(first, second[, msg])
620
621 Test that *first* and *second* are equal. If the values do not compare
622 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000623 :const:`None`. Note that using :meth:`assertEqual` improves upon
624 doing the comparison as the first parameter to :meth:`assertTrue`: the
625 default value for *msg* include representations of both *first* and
626 *second*.
627
628 In addition, if *first* and *second* are the exact same type and one of
629 list, tuple, dict, set, or frozenset or any type that a subclass
630 registers :meth:`addTypeEqualityFunc` the type specific equality function
631 will be called in order to generate a more useful default error message.
632
633 .. versionchanged:: 2.7
634 Added the automatic calling of type specific equality function.
635
636 .. deprecated:: 2.7
637 :meth:`failUnlessEqual`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000638
639
640 .. method:: assertNotEqual(first, second[, msg])
641 failIfEqual(first, second[, msg])
642
643 Test that *first* and *second* are not equal. If the values do compare
644 equal, the test will fail with the explanation given by *msg*, or
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000645 :const:`None`. Note that using :meth:`assertNotEqual` improves upon doing
646 the comparison as the first parameter to :meth:`assertTrue` is that the
Benjamin Peterson52baa292009-03-24 00:56:30 +0000647 default value for *msg* can be computed to include representations of both
648 *first* and *second*.
649
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000650 .. deprecated:: 2.7
651 :meth:`failIfEqual`.
652
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000653
Benjamin Peterson52baa292009-03-24 00:56:30 +0000654 .. method:: assertAlmostEqual(first, second[, places[, msg]])
655 failUnlessAlmostEqual(first, second[, places[, msg]])
656
657 Test that *first* and *second* are approximately equal by computing the
658 difference, rounding to the given number of decimal *places* (default 7),
659 and comparing to zero.
660
661 Note that comparing a given number of decimal places is not the same as
662 comparing a given number of significant digits. If the values do not
663 compare equal, the test will fail with the explanation given by *msg*, or
664 :const:`None`.
665
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000666 .. deprecated:: 2.7
667 :meth:`failUnlessAlmostEqual`.
668
Benjamin Peterson52baa292009-03-24 00:56:30 +0000669
670 .. method:: assertNotAlmostEqual(first, second[, places[, msg]])
671 failIfAlmostEqual(first, second[, places[, msg]])
672
673 Test that *first* and *second* are not approximately equal by computing
674 the difference, rounding to the given number of decimal *places* (default
675 7), and comparing to zero.
676
677 Note that comparing a given number of decimal places is not the same as
678 comparing a given number of significant digits. If the values do not
679 compare equal, the test will fail with the explanation given by *msg*, or
680 :const:`None`.
681
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000682 .. deprecated:: 2.7
683 :meth:`failIfAlmostEqual`.
684
685
686 .. method:: assertGreater(first, second, msg=None)
687 assertGreaterEqual(first, second, msg=None)
688 assertLess(first, second, msg=None)
689 assertLessEqual(first, second, msg=None)
690
691 Test that *first* is respectively >, >=, < or <= than *second* depending
692 on the method name. If not, the test will fail with the nice explanation
693 or with the explanation given by *msg*::
694
695 >>> self.assertGreaterEqual(3, 4)
696 AssertionError: "3" unexpectedly not greater than or equal to "4"
697
698 .. versionadded:: 2.7
699
700
701 .. method:: assertMultiLineEqual(self, first, second, msg=None)
702
703 Test that the multiline string *first* is equal to the string *second*.
704 When not equal a diff of the two strings highlighting the differences
705 will be included in the error message.
706
707 If specified *msg* will be used as the error message on failure.
708
709 .. versionadded:: 2.7
710
711
712 .. method:: assertRegexpMatches(text, regexp[, msg=None]):
713
714 Verifies that a *regexp* search matches *text*. Fails with an error
715 message including the pattern and the *text*. *regexp* may be
716 a regular expression object or a string containing a regular expression
717 suitable for use by :func:`re.search`.
718
719 .. versionadded:: 2.7
720
721
722 .. method:: assertIn(first, second, msg=None)
723 assertNotIn(first, second, msg=None)
724
725 Tests that *first* is or is not in *second* with a nice explanitory error
726 message as appropriate.
727
728 If specified *msg* will be used as the error message on failure.
729
730 .. versionadded:: 2.7
731
732
733 .. method:: assertSameElements(expected, actual, msg=None)
734
735 Test that sequence *expected* contains the same elements as *actual*.
736 When they don't an error message listing the differences between the
737 sequences will be generated.
738
739 If specified *msg* will be used as the error message on failure.
740
741 .. versionadded:: 2.7
742
743
744 .. method:: assertSetEqual(set1, set2, msg=None)
745
746 Tests that two sets are equal. If not, an error message is constructed
747 that lists the differences between the sets.
748
749 Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
750 method.
751
752 If specified *msg* will be used as the error message on failure.
753
754 .. versionadded:: 2.7
755
756
757 .. method:: assertDictEqual(expected, actual, msg=None)
758
759 Test that two dictionaries are equal. If not, an error message is
760 constructed that shows the differences in the dictionaries.
761
762 If specified *msg* will be used as the error message on failure.
763
764 .. versionadded:: 2.7
765
766
767 .. method:: assertDictContainsSubset(expected, actual, msg=None)
768
769 Tests whether the key value pairs in dictionary *actual* are a
770 superset of those in *expected*. If not, an error message listing
771 the missing keys and mismatched values is generated.
772
773 If specified *msg* will be used as the error message on failure.
774
775 .. versionadded:: 2.7
776
777
778 .. method:: assertListEqual(list1, list2, msg=None)
779 assertTupleEqual(tuple1, tuple2, msg=None)
780
781 Tests that two lists or tuples are equal. If not an error message is
782 constructed that shows only the differences between the two. An error
783 is also raised if either of the parameters are of the wrong type.
784
785 If specified *msg* will be used as the error message on failure.
786
787 .. versionadded:: 2.7
788
789
790 .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
791
792 Tests that two sequences are equal. If a *seq_type* is supplied, both
793 *seq1* and *seq2* must be instances of *seq_type* or a failure will
794 be raised. If the sequences are different an error message is
795 constructed that shows the difference between the two.
796
797 If specified *msg* will be used as the error message on failure.
798
799 This method is used to implement :meth:`assertListEqual` and
800 :meth:`assertTupleEqual`.
801
802 .. versionadded:: 2.7
803
Benjamin Peterson52baa292009-03-24 00:56:30 +0000804
805 .. method:: assertRaises(exception[, callable, ...])
806 failUnlessRaises(exception[, callable, ...])
807
808 Test that an exception is raised when *callable* is called with any
809 positional or keyword arguments that are also passed to
810 :meth:`assertRaises`. The test passes if *exception* is raised, is an
811 error if another exception is raised, or fails if no exception is raised.
812 To catch any of a group of exceptions, a tuple containing the exception
813 classes may be passed as *exception*.
814
Benjamin Petersonded31c42009-03-30 15:04:16 +0000815 If *callable* is omitted or None, returns a context manager so that the
816 code under test can be written inline rather than as a function::
817
818 with self.failUnlessRaises(some_error_class):
819 do_something()
820
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000821 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000822 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000823
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000824 .. deprecated:: 2.7
825 :meth:`failUnlessRaises`.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000826
Benjamin Peterson52baa292009-03-24 00:56:30 +0000827
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000828 .. method:: assertRaisesRegexp(exception, regexp[, callable, ...])
829
830 Like :meth:`assertRaises` but also tests that *regexp* matches
831 on the string representation of the raised exception. *regexp* may be
832 a regular expression object or a string containing a regular expression
833 suitable for use by :func:`re.search`. Examples::
834
835 self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
836 int, 'XYZ')
837
838 or::
839
840 with self.assertRaisesRegexp(ValueError, 'literal'):
841 int('XYZ')
842
843 .. versionadded:: 2.7
844
845
846 .. method:: assertIsNone(expr[, msg])
847
848 This signals a test failure if *expr* is not None.
849
850 .. versionadded:: 2.7
851
852
853 .. method:: assertIsNotNone(expr[, msg])
854
855 The inverse of the :meth:`assertIsNone` method.
856 This signals a test failure if *expr* is None.
857
858 .. versionadded:: 2.7
859
860
861 .. method:: assertFalse(expr[, msg])
862 failIf(expr[, msg])
863
864 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000865 This signals a test failure if *expr* is true, with *msg* or :const:`None`
866 for the error message.
867
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000868 .. deprecated:: 2.7
869 :meth:`failIf`.
870
Benjamin Peterson52baa292009-03-24 00:56:30 +0000871
872 .. method:: fail([msg])
873
874 Signals a test failure unconditionally, with *msg* or :const:`None` for
875 the error message.
876
877
878 .. attribute:: failureException
879
880 This class attribute gives the exception raised by the test method. If a
881 test framework needs to use a specialized exception, possibly to carry
882 additional information, it must subclass this exception in order to "play
883 fair" with the framework. The initial value of this attribute is
884 :exc:`AssertionError`.
885
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000886
887 .. attribute:: longMessage
888
889 If set to True then any explicit failure message you pass in to the
890 assert methods will be appended to the end of the normal failure message.
891 The normal messages contain useful information about the objects involved,
892 for example the message from assertEqual shows you the repr of the two
893 unequal objects. Setting this attribute to True allows you to have a
894 custom error message in addition to the normal one.
895
896 This attribute defaults to False, meaning that a custom message passed
897 to an assert method will silence the normal message.
898
899 The class setting can be overridden in individual tests by assigning an
900 instance attribute to True or False before calling the assert methods.
901
902 .. versionadded:: 2.7
903
904
Benjamin Peterson52baa292009-03-24 00:56:30 +0000905 Testing frameworks can use the following methods to collect information on
906 the test:
907
908
909 .. method:: countTestCases()
910
911 Return the number of tests represented by this test object. For
912 :class:`TestCase` instances, this will always be ``1``.
913
914
915 .. method:: defaultTestResult()
916
917 Return an instance of the test result class that should be used for this
918 test case class (if no other result instance is provided to the
919 :meth:`run` method).
920
921 For :class:`TestCase` instances, this will always be an instance of
922 :class:`TestResult`; subclasses of :class:`TestCase` should override this
923 as necessary.
924
925
926 .. method:: id()
927
928 Return a string identifying the specific test case. This is usually the
929 full name of the test method, including the module and class name.
930
931
932 .. method:: shortDescription()
933
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000934 Returns a description of the test, or :const:`None` if no description
935 has been provided. The default implementation of this method
936 returns the first line of the test method's docstring, if available,
937 along with the method name.
938
939 .. versionchanged:: 2.7
940
941 In earlier versions this only returned the first line of the test
942 method's docstring, if available or the :const:`None`. That led to
943 undesirable behavior of not printing the test name when someone was
944 thoughtful enough to write a docstring.
945
946
947 .. method:: addTypeEqualityFunc(typeobj, function)
948
949 Registers a type specific :meth:`assertEqual` equality checking
950 function to be called by :meth:`assertEqual` when both objects it has
951 been asked to compare are exactly *typeobj* (not subclasses).
952 *function* must take two positional arguments and a third msg=None
953 keyword argument just as :meth:`assertEqual` does. It must raise
954 self.failureException when inequality between the first two
955 parameters is detected.
956
957 One good use of custom equality checking functions for a type
958 is to raise self.failureException with an error message useful
959 for debugging the by explaining the inequalities in detail.
960
961 .. versionadded:: 2.7
Georg Brandl116aa622007-08-15 14:28:22 +0000962
963
964.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
965
966 This class implements the portion of the :class:`TestCase` interface which
967 allows the test runner to drive the test, but does not provide the methods which
968 test code can use to check and report errors. This is used to create test cases
969 using legacy test code, allowing it to be integrated into a :mod:`unittest`\
970 -based test framework.
971
972
Benjamin Peterson52baa292009-03-24 00:56:30 +0000973.. _testsuite-objects:
974
Benjamin Peterson52baa292009-03-24 00:56:30 +0000975Grouping tests
976~~~~~~~~~~~~~~
977
Georg Brandl116aa622007-08-15 14:28:22 +0000978.. class:: TestSuite([tests])
979
980 This class represents an aggregation of individual tests cases and test suites.
981 The class presents the interface needed by the test runner to allow it to be run
982 as any other test case. Running a :class:`TestSuite` instance is the same as
983 iterating over the suite, running each test individually.
984
985 If *tests* is given, it must be an iterable of individual test cases or other
986 test suites that will be used to build the suite initially. Additional methods
987 are provided to add test cases and suites to the collection later on.
988
Benjamin Peterson52baa292009-03-24 00:56:30 +0000989 :class:`TestSuite` (including :class:`ClassTestSuite`) objects behave much
990 like :class:`TestCase` objects, except they do not actually implement a test.
991 Instead, they are used to aggregate tests into groups of tests that should be
992 run together. Some additional methods are available to add tests to
993 :class:`TestSuite` instances:
994
995
996 .. method:: TestSuite.addTest(test)
997
998 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
999
1000
1001 .. method:: TestSuite.addTests(tests)
1002
1003 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1004 instances to this test suite.
1005
1006 This is equivalent to iterating over *tests*, calling :meth:`addTest` for each
1007 element.
1008
1009 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1010
1011
1012 .. method:: run(result)
1013
1014 Run the tests associated with this suite, collecting the result into the
1015 test result object passed as *result*. Note that unlike
1016 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1017 be passed in.
1018
1019
1020 .. method:: debug()
1021
1022 Run the tests associated with this suite without collecting the
1023 result. This allows exceptions raised by the test to be propagated to the
1024 caller and can be used to support running tests under a debugger.
1025
1026
1027 .. method:: countTestCases()
1028
1029 Return the number of tests represented by this test object, including all
1030 individual tests and sub-suites.
1031
1032 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1033 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1034
1035
Benjamin Peterson5254c042009-03-23 22:25:03 +00001036.. class:: ClassTestSuite(tests, collected_from)
1037
1038 This subclass of :class:`TestSuite` repesents an aggregation of individuals
1039 tests from one :class:`TestCase` class. *tests* is an iterable of
1040 :class:`TestCase` instances created from the class. *collected_from* is the
1041 class they came from.
1042
Georg Brandl116aa622007-08-15 14:28:22 +00001043
Benjamin Peterson52baa292009-03-24 00:56:30 +00001044Loading and running tests
1045~~~~~~~~~~~~~~~~~~~~~~~~~
1046
Georg Brandl116aa622007-08-15 14:28:22 +00001047.. class:: TestLoader()
1048
Benjamin Peterson52baa292009-03-24 00:56:30 +00001049 The :class:`TestLoader` class is used to create test suites from classes and
1050 modules. Normally, there is no need to create an instance of this class; the
1051 :mod:`unittest` module provides an instance that can be shared as
1052 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1053 customization of some configurable properties.
1054
1055 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001056
1057
Benjamin Peterson52baa292009-03-24 00:56:30 +00001058 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001059
Benjamin Peterson52baa292009-03-24 00:56:30 +00001060 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1061 :class:`testCaseClass`.
1062
1063
1064 .. method:: loadTestsFromModule(module)
1065
1066 Return a suite of all tests cases contained in the given module. This
1067 method searches *module* for classes derived from :class:`TestCase` and
1068 creates an instance of the class for each test method defined for the
1069 class.
1070
1071 .. warning::
1072
1073 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1074 convenient in sharing fixtures and helper functions, defining test
1075 methods on base classes that are not intended to be instantiated
1076 directly does not play well with this method. Doing so, however, can
1077 be useful when the fixtures are different and defined in subclasses.
1078
1079
1080 .. method:: loadTestsFromName(name[, module])
1081
1082 Return a suite of all tests cases given a string specifier.
1083
1084 The specifier *name* is a "dotted name" that may resolve either to a
1085 module, a test case class, a test method within a test case class, a
1086 :class:`TestSuite` instance, or a callable object which returns a
1087 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1088 applied in the order listed here; that is, a method on a possible test
1089 case class will be picked up as "a test method within a test case class",
1090 rather than "a callable object".
1091
1092 For example, if you have a module :mod:`SampleTests` containing a
1093 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1094 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
1095 specifier ``'SampleTests.SampleTestCase'`` would cause this method to return a
1096 suite which will run all three test methods. Using the specifier
1097 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test suite
1098 which will run only the :meth:`test_two` test method. The specifier can refer
1099 to modules and packages which have not been imported; they will be imported as a
1100 side-effect.
1101
1102 The method optionally resolves *name* relative to the given *module*.
1103
1104
1105 .. method:: loadTestsFromNames(names[, module])
1106
1107 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1108 than a single name. The return value is a test suite which supports all
1109 the tests defined for each name.
1110
1111
1112 .. method:: getTestCaseNames(testCaseClass)
1113
1114 Return a sorted sequence of method names found within *testCaseClass*;
1115 this should be a subclass of :class:`TestCase`.
1116
1117 The following attributes of a :class:`TestLoader` can be configured either by
1118 subclassing or assignment on an instance:
1119
1120
1121 .. attribute:: testMethodPrefix
1122
1123 String giving the prefix of method names which will be interpreted as test
1124 methods. The default value is ``'test'``.
1125
1126 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1127 methods.
1128
1129
1130 .. attribute:: sortTestMethodsUsing
1131
1132 Function to be used to compare method names when sorting them in
1133 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1134
1135
1136 .. attribute:: suiteClass
1137
1138 Callable object that constructs a test suite from a list of tests. No
1139 methods on the resulting object are needed. The default value is the
1140 :class:`TestSuite` class.
1141
1142 This affects all the :meth:`loadTestsFrom\*` methods.
1143
1144
1145 .. attribute:: classSuiteClass
1146
1147 Callable object that constructs a test suite for the tests cases from one
1148 class. The default value is :class:`ClassTestSuite`.
1149
1150
1151.. class:: TestResult
1152
1153 This class is used to compile information about which tests have succeeded
1154 and which have failed.
1155
1156 A :class:`TestResult` object stores the results of a set of tests. The
1157 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1158 properly recorded; test authors do not need to worry about recording the
1159 outcome of tests.
1160
1161 Testing frameworks built on top of :mod:`unittest` may want access to the
1162 :class:`TestResult` object generated by running a set of tests for reporting
1163 purposes; a :class:`TestResult` instance is returned by the
1164 :meth:`TestRunner.run` method for this purpose.
1165
1166 :class:`TestResult` instances have the following attributes that will be of
1167 interest when inspecting the results of running a set of tests:
1168
1169
1170 .. attribute:: errors
1171
1172 A list containing 2-tuples of :class:`TestCase` instances and strings
1173 holding formatted tracebacks. Each tuple represents a test which raised an
1174 unexpected exception.
1175
Benjamin Peterson52baa292009-03-24 00:56:30 +00001176
1177 .. attribute:: failures
1178
1179 A list containing 2-tuples of :class:`TestCase` instances and strings
1180 holding formatted tracebacks. Each tuple represents a test where a failure
1181 was explicitly signalled using the :meth:`TestCase.fail\*` or
1182 :meth:`TestCase.assert\*` methods.
1183
Benjamin Peterson52baa292009-03-24 00:56:30 +00001184 .. attribute:: skipped
1185
1186 A list containing 2-tuples of :class:`TestCase` instances and strings
1187 holding the reason for skipping the test.
1188
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001189 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001190
1191 .. attribute:: expectedFailures
1192
1193 A list contaning 2-tuples of :class:`TestCase` instances and strings
1194 holding formatted tracebacks. Each tuple represents a expected failures
1195 of the test case.
1196
1197 .. attribute:: unexpectedSuccesses
1198
1199 A list containing :class:`TestCase` instances that were marked as expected
1200 failures, but succeeded.
1201
1202 .. attribute:: shouldStop
1203
1204 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1205
1206
1207 .. attribute:: testsRun
1208
1209 The total number of tests run so far.
1210
1211
1212 .. method:: wasSuccessful()
1213
1214 Return :const:`True` if all tests run so far have passed, otherwise returns
1215 :const:`False`.
1216
1217
1218 .. method:: stop()
1219
1220 This method can be called to signal that the set of tests being run should
1221 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1222 :class:`TestRunner` objects should respect this flag and return without
1223 running any additional tests.
1224
1225 For example, this feature is used by the :class:`TextTestRunner` class to
1226 stop the test framework when the user signals an interrupt from the
1227 keyboard. Interactive tools which provide :class:`TestRunner`
1228 implementations can use this in a similar manner.
1229
1230 The following methods of the :class:`TestResult` class are used to maintain
1231 the internal data structures, and may be extended in subclasses to support
1232 additional reporting requirements. This is particularly useful in building
1233 tools which support interactive reporting while tests are being run.
1234
1235
1236 .. method:: startTest(test)
1237
1238 Called when the test case *test* is about to be run.
1239
1240 The default implementation simply increments the instance's :attr:`testsRun`
1241 counter.
1242
1243
1244 .. method:: stopTest(test)
1245
1246 Called after the test case *test* has been executed, regardless of the
1247 outcome.
1248
1249 The default implementation does nothing.
1250
1251
1252 .. method:: addError(test, err)
1253
1254 Called when the test case *test* raises an unexpected exception *err* is a
1255 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1256 traceback)``.
1257
1258 The default implementation appends a tuple ``(test, formatted_err)`` to
1259 the instance's :attr:`errors` attribute, where *formatted_err* is a
1260 formatted traceback derived from *err*.
1261
1262
1263 .. method:: addFailure(test, err)
1264
1265 Called when the test case *test* signals a failure. *err* is a tuple of the form
1266 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1267
1268 The default implementation appends a tuple ``(test, formatted_err)`` to
1269 the instance's :attr:`failures` attribute, where *formatted_err* is a
1270 formatted traceback derived from *err*.
1271
1272
1273 .. method:: addSuccess(test)
1274
1275 Called when the test case *test* succeeds.
1276
1277 The default implementation does nothing.
1278
1279
1280 .. method:: addSkip(test, reason)
1281
1282 Called when the test case *test* is skipped. *reason* is the reason the
1283 test gave for skipping.
1284
1285 The default implementation appends a tuple ``(test, reason)`` to the
1286 instance's :attr:`skipped` attribute.
1287
1288
1289 .. method:: addExpectedFailure(test, err)
1290
1291 Called when the test case *test* fails, but was marked with the
1292 :func:`expectedFailure` decorator.
1293
1294 The default implementation appends a tuple ``(test, formatted_err)`` to
1295 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1296 is a formatted traceback derived from *err*.
1297
1298
1299 .. method:: addUnexpectedSuccess(test)
1300
1301 Called when the test case *test* was marked with the
1302 :func:`expectedFailure` decorator, but succeeded.
1303
1304 The default implementation appends the test to the instance's
1305 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001306
1307
1308.. data:: defaultTestLoader
1309
1310 Instance of the :class:`TestLoader` class intended to be shared. If no
1311 customization of the :class:`TestLoader` is needed, this instance can be used
1312 instead of repeatedly creating new instances.
1313
1314
1315.. class:: TextTestRunner([stream[, descriptions[, verbosity]]])
1316
1317 A basic test runner implementation which prints results on standard error. It
1318 has a few configurable parameters, but is essentially very simple. Graphical
1319 applications which run test suites should provide alternate implementations.
1320
1321
1322.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader]]]]])
1323
1324 A command-line program that runs a set of tests; this is primarily for making
1325 test modules conveniently executable. The simplest use for this function is to
1326 include the following line at the end of a test script::
1327
1328 if __name__ == '__main__':
1329 unittest.main()
1330
1331 The *testRunner* argument can either be a test runner class or an already
1332 created instance of it.