blob: f40dba040d54e7a10e0178c72af672e6fceed6ae [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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000614 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000615 :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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000633 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000634 Added the automatic calling of type specific equality function.
635
Raymond Hettinger35a88362009-04-09 00:08:24 +0000636 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000637 :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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000650 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000651 :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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000666 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000667 :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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000682 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000683 :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
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000692 on the method name. If not, the test will fail with an explanation
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000693 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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000698 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000699
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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000709 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000710
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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000719 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000720
721
722 .. method:: assertIn(first, second, msg=None)
723 assertNotIn(first, second, msg=None)
724
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000725 Tests that *first* is or is not in *second* with an explanatory error
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000726 message as appropriate.
727
728 If specified *msg* will be used as the error message on failure.
729
Raymond Hettinger35a88362009-04-09 00:08:24 +0000730 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000731
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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000741 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000742
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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000754 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000755
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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000764 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000765
766
767 .. method:: assertDictContainsSubset(expected, actual, msg=None)
768
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000769 Tests whether the key/value pairs in dictionary *actual* are a
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000770 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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000775 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000776
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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000787 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000788
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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000802 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000803
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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000824 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000825 :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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000843 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000844
845
846 .. method:: assertIsNone(expr[, msg])
847
848 This signals a test failure if *expr* is not None.
849
Raymond Hettinger35a88362009-04-09 00:08:24 +0000850 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000851
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
Raymond Hettinger35a88362009-04-09 00:08:24 +0000858 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000859
860
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000861 .. method:: assertIs(expr1, expr2[, msg])
862
863 This signals a test failure if *expr1* and *expr2* don't evaluate to the same
864 object.
865
866 .. versionadded:: 2.7
867
868
869 .. method:: assertIsNot(expr1, expr2[, msg])
870
871 The inverse of the :meth:`assertIs` method.
872 This signals a test failure if *expr1* and *expr2* evaluate to the same
873 object.
874
875 .. versionadded:: 2.7
876
877
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000878 .. method:: assertFalse(expr[, msg])
879 failIf(expr[, msg])
880
881 The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000882 This signals a test failure if *expr* is true, with *msg* or :const:`None`
883 for the error message.
884
Raymond Hettinger35a88362009-04-09 00:08:24 +0000885 .. deprecated:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000886 :meth:`failIf`.
887
Benjamin Peterson52baa292009-03-24 00:56:30 +0000888
889 .. method:: fail([msg])
890
891 Signals a test failure unconditionally, with *msg* or :const:`None` for
892 the error message.
893
894
895 .. attribute:: failureException
896
897 This class attribute gives the exception raised by the test method. If a
898 test framework needs to use a specialized exception, possibly to carry
899 additional information, it must subclass this exception in order to "play
900 fair" with the framework. The initial value of this attribute is
901 :exc:`AssertionError`.
902
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000903
904 .. attribute:: longMessage
905
906 If set to True then any explicit failure message you pass in to the
907 assert methods will be appended to the end of the normal failure message.
908 The normal messages contain useful information about the objects involved,
909 for example the message from assertEqual shows you the repr of the two
910 unequal objects. Setting this attribute to True allows you to have a
911 custom error message in addition to the normal one.
912
913 This attribute defaults to False, meaning that a custom message passed
914 to an assert method will silence the normal message.
915
916 The class setting can be overridden in individual tests by assigning an
917 instance attribute to True or False before calling the assert methods.
918
Raymond Hettinger35a88362009-04-09 00:08:24 +0000919 .. versionadded:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000920
921
Benjamin Peterson52baa292009-03-24 00:56:30 +0000922 Testing frameworks can use the following methods to collect information on
923 the test:
924
925
926 .. method:: countTestCases()
927
928 Return the number of tests represented by this test object. For
929 :class:`TestCase` instances, this will always be ``1``.
930
931
932 .. method:: defaultTestResult()
933
934 Return an instance of the test result class that should be used for this
935 test case class (if no other result instance is provided to the
936 :meth:`run` method).
937
938 For :class:`TestCase` instances, this will always be an instance of
939 :class:`TestResult`; subclasses of :class:`TestCase` should override this
940 as necessary.
941
942
943 .. method:: id()
944
945 Return a string identifying the specific test case. This is usually the
946 full name of the test method, including the module and class name.
947
948
949 .. method:: shortDescription()
950
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000951 Returns a description of the test, or :const:`None` if no description
952 has been provided. The default implementation of this method
953 returns the first line of the test method's docstring, if available,
954 along with the method name.
955
Raymond Hettinger35a88362009-04-09 00:08:24 +0000956 .. versionchanged:: 3.1
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000957
958 In earlier versions this only returned the first line of the test
959 method's docstring, if available or the :const:`None`. That led to
960 undesirable behavior of not printing the test name when someone was
961 thoughtful enough to write a docstring.
962
963
964 .. method:: addTypeEqualityFunc(typeobj, function)
965
966 Registers a type specific :meth:`assertEqual` equality checking
967 function to be called by :meth:`assertEqual` when both objects it has
968 been asked to compare are exactly *typeobj* (not subclasses).
969 *function* must take two positional arguments and a third msg=None
970 keyword argument just as :meth:`assertEqual` does. It must raise
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000971 ``self.failureException`` when inequality between the first two
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000972 parameters is detected.
973
974 One good use of custom equality checking functions for a type
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000975 is to raise ``self.failureException`` with an error message useful
976 for debugging the problem by explaining the inequalities in detail.
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000977
Raymond Hettinger35a88362009-04-09 00:08:24 +0000978 .. versionadded:: 3.1
Georg Brandl116aa622007-08-15 14:28:22 +0000979
980
981.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
982
983 This class implements the portion of the :class:`TestCase` interface which
984 allows the test runner to drive the test, but does not provide the methods which
985 test code can use to check and report errors. This is used to create test cases
986 using legacy test code, allowing it to be integrated into a :mod:`unittest`\
987 -based test framework.
988
989
Benjamin Peterson52baa292009-03-24 00:56:30 +0000990.. _testsuite-objects:
991
Benjamin Peterson52baa292009-03-24 00:56:30 +0000992Grouping tests
993~~~~~~~~~~~~~~
994
Georg Brandl116aa622007-08-15 14:28:22 +0000995.. class:: TestSuite([tests])
996
997 This class represents an aggregation of individual tests cases and test suites.
998 The class presents the interface needed by the test runner to allow it to be run
999 as any other test case. Running a :class:`TestSuite` instance is the same as
1000 iterating over the suite, running each test individually.
1001
1002 If *tests* is given, it must be an iterable of individual test cases or other
1003 test suites that will be used to build the suite initially. Additional methods
1004 are provided to add test cases and suites to the collection later on.
1005
Benjamin Peterson52baa292009-03-24 00:56:30 +00001006 :class:`TestSuite` (including :class:`ClassTestSuite`) objects behave much
1007 like :class:`TestCase` objects, except they do not actually implement a test.
1008 Instead, they are used to aggregate tests into groups of tests that should be
1009 run together. Some additional methods are available to add tests to
1010 :class:`TestSuite` instances:
1011
1012
1013 .. method:: TestSuite.addTest(test)
1014
1015 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
1016
1017
1018 .. method:: TestSuite.addTests(tests)
1019
1020 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
1021 instances to this test suite.
1022
1023 This is equivalent to iterating over *tests*, calling :meth:`addTest` for each
1024 element.
1025
1026 :class:`TestSuite` shares the following methods with :class:`TestCase`:
1027
1028
1029 .. method:: run(result)
1030
1031 Run the tests associated with this suite, collecting the result into the
1032 test result object passed as *result*. Note that unlike
1033 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
1034 be passed in.
1035
1036
1037 .. method:: debug()
1038
1039 Run the tests associated with this suite without collecting the
1040 result. This allows exceptions raised by the test to be propagated to the
1041 caller and can be used to support running tests under a debugger.
1042
1043
1044 .. method:: countTestCases()
1045
1046 Return the number of tests represented by this test object, including all
1047 individual tests and sub-suites.
1048
1049 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
1050 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
1051
1052
Benjamin Peterson5254c042009-03-23 22:25:03 +00001053.. class:: ClassTestSuite(tests, collected_from)
1054
1055 This subclass of :class:`TestSuite` repesents an aggregation of individuals
1056 tests from one :class:`TestCase` class. *tests* is an iterable of
1057 :class:`TestCase` instances created from the class. *collected_from* is the
1058 class they came from.
1059
Georg Brandl116aa622007-08-15 14:28:22 +00001060
Benjamin Peterson52baa292009-03-24 00:56:30 +00001061Loading and running tests
1062~~~~~~~~~~~~~~~~~~~~~~~~~
1063
Georg Brandl116aa622007-08-15 14:28:22 +00001064.. class:: TestLoader()
1065
Benjamin Peterson52baa292009-03-24 00:56:30 +00001066 The :class:`TestLoader` class is used to create test suites from classes and
1067 modules. Normally, there is no need to create an instance of this class; the
1068 :mod:`unittest` module provides an instance that can be shared as
1069 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
1070 customization of some configurable properties.
1071
1072 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001073
1074
Benjamin Peterson52baa292009-03-24 00:56:30 +00001075 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +00001076
Benjamin Peterson52baa292009-03-24 00:56:30 +00001077 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
1078 :class:`testCaseClass`.
1079
1080
1081 .. method:: loadTestsFromModule(module)
1082
1083 Return a suite of all tests cases contained in the given module. This
1084 method searches *module* for classes derived from :class:`TestCase` and
1085 creates an instance of the class for each test method defined for the
1086 class.
1087
Georg Brandle720c0a2009-04-27 16:20:50 +00001088 .. note::
Benjamin Peterson52baa292009-03-24 00:56:30 +00001089
1090 While using a hierarchy of :class:`TestCase`\ -derived classes can be
1091 convenient in sharing fixtures and helper functions, defining test
1092 methods on base classes that are not intended to be instantiated
1093 directly does not play well with this method. Doing so, however, can
1094 be useful when the fixtures are different and defined in subclasses.
1095
1096
1097 .. method:: loadTestsFromName(name[, module])
1098
1099 Return a suite of all tests cases given a string specifier.
1100
1101 The specifier *name* is a "dotted name" that may resolve either to a
1102 module, a test case class, a test method within a test case class, a
1103 :class:`TestSuite` instance, or a callable object which returns a
1104 :class:`TestCase` or :class:`TestSuite` instance. These checks are
1105 applied in the order listed here; that is, a method on a possible test
1106 case class will be picked up as "a test method within a test case class",
1107 rather than "a callable object".
1108
1109 For example, if you have a module :mod:`SampleTests` containing a
1110 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
1111 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
1112 specifier ``'SampleTests.SampleTestCase'`` would cause this method to return a
1113 suite which will run all three test methods. Using the specifier
1114 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test suite
1115 which will run only the :meth:`test_two` test method. The specifier can refer
1116 to modules and packages which have not been imported; they will be imported as a
1117 side-effect.
1118
1119 The method optionally resolves *name* relative to the given *module*.
1120
1121
1122 .. method:: loadTestsFromNames(names[, module])
1123
1124 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
1125 than a single name. The return value is a test suite which supports all
1126 the tests defined for each name.
1127
1128
1129 .. method:: getTestCaseNames(testCaseClass)
1130
1131 Return a sorted sequence of method names found within *testCaseClass*;
1132 this should be a subclass of :class:`TestCase`.
1133
1134 The following attributes of a :class:`TestLoader` can be configured either by
1135 subclassing or assignment on an instance:
1136
1137
1138 .. attribute:: testMethodPrefix
1139
1140 String giving the prefix of method names which will be interpreted as test
1141 methods. The default value is ``'test'``.
1142
1143 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
1144 methods.
1145
1146
1147 .. attribute:: sortTestMethodsUsing
1148
1149 Function to be used to compare method names when sorting them in
1150 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
1151
1152
1153 .. attribute:: suiteClass
1154
1155 Callable object that constructs a test suite from a list of tests. No
1156 methods on the resulting object are needed. The default value is the
1157 :class:`TestSuite` class.
1158
1159 This affects all the :meth:`loadTestsFrom\*` methods.
1160
1161
1162 .. attribute:: classSuiteClass
1163
1164 Callable object that constructs a test suite for the tests cases from one
1165 class. The default value is :class:`ClassTestSuite`.
1166
1167
1168.. class:: TestResult
1169
1170 This class is used to compile information about which tests have succeeded
1171 and which have failed.
1172
1173 A :class:`TestResult` object stores the results of a set of tests. The
1174 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
1175 properly recorded; test authors do not need to worry about recording the
1176 outcome of tests.
1177
1178 Testing frameworks built on top of :mod:`unittest` may want access to the
1179 :class:`TestResult` object generated by running a set of tests for reporting
1180 purposes; a :class:`TestResult` instance is returned by the
1181 :meth:`TestRunner.run` method for this purpose.
1182
1183 :class:`TestResult` instances have the following attributes that will be of
1184 interest when inspecting the results of running a set of tests:
1185
1186
1187 .. attribute:: errors
1188
1189 A list containing 2-tuples of :class:`TestCase` instances and strings
1190 holding formatted tracebacks. Each tuple represents a test which raised an
1191 unexpected exception.
1192
Benjamin Peterson52baa292009-03-24 00:56:30 +00001193
1194 .. attribute:: failures
1195
1196 A list containing 2-tuples of :class:`TestCase` instances and strings
1197 holding formatted tracebacks. Each tuple represents a test where a failure
1198 was explicitly signalled using the :meth:`TestCase.fail\*` or
1199 :meth:`TestCase.assert\*` methods.
1200
Benjamin Peterson52baa292009-03-24 00:56:30 +00001201 .. attribute:: skipped
1202
1203 A list containing 2-tuples of :class:`TestCase` instances and strings
1204 holding the reason for skipping the test.
1205
Benjamin Peterson70e32c82009-03-24 01:00:11 +00001206 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +00001207
1208 .. attribute:: expectedFailures
1209
1210 A list contaning 2-tuples of :class:`TestCase` instances and strings
1211 holding formatted tracebacks. Each tuple represents a expected failures
1212 of the test case.
1213
1214 .. attribute:: unexpectedSuccesses
1215
1216 A list containing :class:`TestCase` instances that were marked as expected
1217 failures, but succeeded.
1218
1219 .. attribute:: shouldStop
1220
1221 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
1222
1223
1224 .. attribute:: testsRun
1225
1226 The total number of tests run so far.
1227
1228
1229 .. method:: wasSuccessful()
1230
1231 Return :const:`True` if all tests run so far have passed, otherwise returns
1232 :const:`False`.
1233
1234
1235 .. method:: stop()
1236
1237 This method can be called to signal that the set of tests being run should
1238 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
1239 :class:`TestRunner` objects should respect this flag and return without
1240 running any additional tests.
1241
1242 For example, this feature is used by the :class:`TextTestRunner` class to
1243 stop the test framework when the user signals an interrupt from the
1244 keyboard. Interactive tools which provide :class:`TestRunner`
1245 implementations can use this in a similar manner.
1246
1247 The following methods of the :class:`TestResult` class are used to maintain
1248 the internal data structures, and may be extended in subclasses to support
1249 additional reporting requirements. This is particularly useful in building
1250 tools which support interactive reporting while tests are being run.
1251
1252
1253 .. method:: startTest(test)
1254
1255 Called when the test case *test* is about to be run.
1256
1257 The default implementation simply increments the instance's :attr:`testsRun`
1258 counter.
1259
1260
1261 .. method:: stopTest(test)
1262
1263 Called after the test case *test* has been executed, regardless of the
1264 outcome.
1265
1266 The default implementation does nothing.
1267
1268
1269 .. method:: addError(test, err)
1270
1271 Called when the test case *test* raises an unexpected exception *err* is a
1272 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1273 traceback)``.
1274
1275 The default implementation appends a tuple ``(test, formatted_err)`` to
1276 the instance's :attr:`errors` attribute, where *formatted_err* is a
1277 formatted traceback derived from *err*.
1278
1279
1280 .. method:: addFailure(test, err)
1281
1282 Called when the test case *test* signals a failure. *err* is a tuple of the form
1283 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1284
1285 The default implementation appends a tuple ``(test, formatted_err)`` to
1286 the instance's :attr:`failures` attribute, where *formatted_err* is a
1287 formatted traceback derived from *err*.
1288
1289
1290 .. method:: addSuccess(test)
1291
1292 Called when the test case *test* succeeds.
1293
1294 The default implementation does nothing.
1295
1296
1297 .. method:: addSkip(test, reason)
1298
1299 Called when the test case *test* is skipped. *reason* is the reason the
1300 test gave for skipping.
1301
1302 The default implementation appends a tuple ``(test, reason)`` to the
1303 instance's :attr:`skipped` attribute.
1304
1305
1306 .. method:: addExpectedFailure(test, err)
1307
1308 Called when the test case *test* fails, but was marked with the
1309 :func:`expectedFailure` decorator.
1310
1311 The default implementation appends a tuple ``(test, formatted_err)`` to
1312 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1313 is a formatted traceback derived from *err*.
1314
1315
1316 .. method:: addUnexpectedSuccess(test)
1317
1318 Called when the test case *test* was marked with the
1319 :func:`expectedFailure` decorator, but succeeded.
1320
1321 The default implementation appends the test to the instance's
1322 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001323
1324
1325.. data:: defaultTestLoader
1326
1327 Instance of the :class:`TestLoader` class intended to be shared. If no
1328 customization of the :class:`TestLoader` is needed, this instance can be used
1329 instead of repeatedly creating new instances.
1330
1331
1332.. class:: TextTestRunner([stream[, descriptions[, verbosity]]])
1333
1334 A basic test runner implementation which prints results on standard error. It
1335 has a few configurable parameters, but is essentially very simple. Graphical
1336 applications which run test suites should provide alternate implementations.
1337
1338
1339.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader]]]]])
1340
1341 A command-line program that runs a set of tests; this is primarily for making
1342 test modules conveniently executable. The simplest use for this function is to
1343 include the following line at the end of a test script::
1344
1345 if __name__ == '__main__':
1346 unittest.main()
1347
1348 The *testRunner* argument can either be a test runner class or an already
1349 created instance of it.