blob: c9dc6b62a5fcb99858fa990e066130af24a63541 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`unittest` --- Unit testing framework
3==========================================
4
5.. module:: unittest
6 :synopsis: Unit testing framework for Python.
7.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
8.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
9.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
10.. sectionauthor:: Raymond Hettinger <python@rcn.com>
11
12
Benjamin Peterson5254c042009-03-23 22:25:03 +000013.. versionchanged:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +000014 Added test :ref:`skipping and expected failures <unittest-skipping>`.
Benjamin Peterson5254c042009-03-23 22:25:03 +000015
Georg Brandl116aa622007-08-15 14:28:22 +000016The Python unit testing framework, sometimes referred to as "PyUnit," is a
17Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
18turn, a Java version of Kent's Smalltalk testing framework. Each is the de
19facto standard unit testing framework for its respective language.
20
21:mod:`unittest` supports test automation, sharing of setup and shutdown code for
22tests, aggregation of tests into collections, and independence of the tests from
23the reporting framework. The :mod:`unittest` module provides classes that make
24it easy to support these qualities for a set of tests.
25
26To achieve this, :mod:`unittest` supports some important concepts:
27
28test fixture
29 A :dfn:`test fixture` represents the preparation needed to perform one or more
30 tests, and any associate cleanup actions. This may involve, for example,
31 creating temporary or proxy databases, directories, or starting a server
32 process.
33
34test case
35 A :dfn:`test case` is the smallest unit of testing. It checks for a specific
36 response to a particular set of inputs. :mod:`unittest` provides a base class,
37 :class:`TestCase`, which may be used to create new test cases.
38
39test suite
40 A :dfn:`test suite` is a collection of test cases, test suites, or both. It is
41 used to aggregate tests that should be executed together.
42
43test runner
44 A :dfn:`test runner` is a component which orchestrates the execution of tests
45 and provides the outcome to the user. The runner may use a graphical interface,
46 a textual interface, or return a special value to indicate the results of
47 executing the tests.
48
49The test case and test fixture concepts are supported through the
50:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
51used when creating new tests, and the latter can be used when integrating
52existing test code with a :mod:`unittest`\ -driven framework. When building test
Benjamin Peterson52baa292009-03-24 00:56:30 +000053fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
54:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
55and cleanup for the fixture. With :class:`FunctionTestCase`, existing functions
56can be passed to the constructor for these purposes. When the test is run, the
57fixture initialization is run first; if it succeeds, the cleanup method is run
58after the test has been executed, regardless of the outcome of the test. Each
59instance of the :class:`TestCase` will only be used to run a single test method,
60so a new fixture is created for each test.
Georg Brandl116aa622007-08-15 14:28:22 +000061
62Test suites are implemented by the :class:`TestSuite` class. This class allows
63individual tests and test suites to be aggregated; when the suite is executed,
Benjamin Peterson5254c042009-03-23 22:25:03 +000064all tests added directly to the suite and in "child" test suites are run. A
65:class:`ClassTestSuite` contains the test cases of a class.
Georg Brandl116aa622007-08-15 14:28:22 +000066
Benjamin Peterson52baa292009-03-24 00:56:30 +000067A test runner is an object that provides a single method,
68:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
69object as a parameter, and returns a result object. The class
70:class:`TestResult` is provided for use as the result object. :mod:`unittest`
71provides the :class:`TextTestRunner` as an example test runner which reports
72test results on the standard error stream by default. Alternate runners can be
73implemented for other environments (such as graphical environments) without any
74need to derive from a specific class.
Georg Brandl116aa622007-08-15 14:28:22 +000075
76
77.. seealso::
78
79 Module :mod:`doctest`
80 Another test-support module with a very different flavor.
81
82 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
83 Kent Beck's original paper on testing frameworks using the pattern shared by
84 :mod:`unittest`.
85
Raymond Hettinger6b232cd2009-03-24 00:22:53 +000086 `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
87 Third-party unittest frameworks with a lighter-weight syntax
88 for writing tests. For example, ``assert func(10) == 42``.
89
90 `python-mock <http://python-mock.sourceforge.net/>`_ and `minimock <http://blog.ianbicking.org/minimock.html>`_
91 Tools for creating mock test objects (objects simulating external resources).
Georg Brandl116aa622007-08-15 14:28:22 +000092
93.. _unittest-minimal-example:
94
95Basic example
96-------------
97
98The :mod:`unittest` module provides a rich set of tools for constructing and
99running tests. This section demonstrates that a small subset of the tools
100suffice to meet the needs of most users.
101
102Here is a short script to test three functions from the :mod:`random` module::
103
104 import random
105 import unittest
106
107 class TestSequenceFunctions(unittest.TestCase):
108
109 def setUp(self):
110 self.seq = range(10)
111
Benjamin Peterson52baa292009-03-24 00:56:30 +0000112 def test_shuffle(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000113 # make sure the shuffled sequence does not lose any elements
114 random.shuffle(self.seq)
115 self.seq.sort()
116 self.assertEqual(self.seq, range(10))
117
Benjamin Peterson52baa292009-03-24 00:56:30 +0000118 def test_choice(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000119 element = random.choice(self.seq)
120 self.assert_(element in self.seq)
121
Benjamin Peterson52baa292009-03-24 00:56:30 +0000122 def test_sample(self):
Georg Brandl116aa622007-08-15 14:28:22 +0000123 self.assertRaises(ValueError, random.sample, self.seq, 20)
124 for element in random.sample(self.seq, 5):
125 self.assert_(element in self.seq)
126
127 if __name__ == '__main__':
128 unittest.main()
129
Benjamin Peterson52baa292009-03-24 00:56:30 +0000130A testcase is created by subclassing :class:`unittest.TestCase`. The three
Georg Brandl116aa622007-08-15 14:28:22 +0000131individual tests are defined with methods whose names start with the letters
132``test``. This naming convention informs the test runner about which methods
133represent tests.
134
Benjamin Peterson52baa292009-03-24 00:56:30 +0000135The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
136expected result; :meth:`~TestCase.assert_` to verify a condition; or
137:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
138These methods are used instead of the :keyword:`assert` statement so the test
139runner can accumulate all test results and produce a report.
Georg Brandl116aa622007-08-15 14:28:22 +0000140
Benjamin Peterson52baa292009-03-24 00:56:30 +0000141When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
142method prior to each test. Likewise, if a :meth:`~TestCase.tearDown` method is
143defined, the test runner will invoke that method after each test. In the
144example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
145test.
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147The final block shows a simple way to run the tests. :func:`unittest.main`
148provides a command line interface to the test script. When run from the command
149line, the above script produces an output that looks like this::
150
151 ...
152 ----------------------------------------------------------------------
153 Ran 3 tests in 0.000s
154
155 OK
156
157Instead of :func:`unittest.main`, there are other ways to run the tests with a
158finer level of control, less terse output, and no requirement to be run from the
159command line. For example, the last two lines may be replaced with::
160
161 suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
162 unittest.TextTestRunner(verbosity=2).run(suite)
163
164Running the revised script from the interpreter or another script produces the
165following output::
166
167 testchoice (__main__.TestSequenceFunctions) ... ok
168 testsample (__main__.TestSequenceFunctions) ... ok
169 testshuffle (__main__.TestSequenceFunctions) ... ok
170
171 ----------------------------------------------------------------------
172 Ran 3 tests in 0.110s
173
174 OK
175
176The above examples show the most commonly used :mod:`unittest` features which
177are sufficient to meet many everyday testing needs. The remainder of the
178documentation explores the full feature set from first principles.
179
180
181.. _organizing-tests:
182
183Organizing test code
184--------------------
185
186The basic building blocks of unit testing are :dfn:`test cases` --- single
187scenarios that must be set up and checked for correctness. In :mod:`unittest`,
188test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
189class. To make your own test cases you must write subclasses of
190:class:`TestCase`, or use :class:`FunctionTestCase`.
191
192An instance of a :class:`TestCase`\ -derived class is an object that can
193completely run a single test method, together with optional set-up and tidy-up
194code.
195
196The testing code of a :class:`TestCase` instance should be entirely self
197contained, such that it can be run either in isolation or in arbitrary
198combination with any number of other test cases.
199
Benjamin Peterson52baa292009-03-24 00:56:30 +0000200The simplest :class:`TestCase` subclass will simply override the
201:meth:`~TestCase.runTest` method in order to perform specific testing code::
Georg Brandl116aa622007-08-15 14:28:22 +0000202
203 import unittest
204
205 class DefaultWidgetSizeTestCase(unittest.TestCase):
206 def runTest(self):
207 widget = Widget('The widget')
208 self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
209
210Note that in order to test something, we use the one of the :meth:`assert\*` or
211:meth:`fail\*` methods provided by the :class:`TestCase` base class. If the
212test fails, an exception will be raised, and :mod:`unittest` will identify the
213test case as a :dfn:`failure`. Any other exceptions will be treated as
214:dfn:`errors`. This helps you identify where the problem is: :dfn:`failures` are
215caused by incorrect results - a 5 where you expected a 6. :dfn:`Errors` are
216caused by incorrect code - e.g., a :exc:`TypeError` caused by an incorrect
217function call.
218
219The way to run a test case will be described later. For now, note that to
220construct an instance of such a test case, we call its constructor without
221arguments::
222
223 testCase = DefaultWidgetSizeTestCase()
224
225Now, such test cases can be numerous, and their set-up can be repetitive. In
226the above case, constructing a :class:`Widget` in each of 100 Widget test case
227subclasses would mean unsightly duplication.
228
229Luckily, we can factor out such set-up code by implementing a method called
Benjamin Peterson52baa292009-03-24 00:56:30 +0000230:meth:`~TestCase.setUp`, which the testing framework will automatically call for
231us when we run the test::
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233 import unittest
234
235 class SimpleWidgetTestCase(unittest.TestCase):
236 def setUp(self):
237 self.widget = Widget('The widget')
238
239 class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
240 def runTest(self):
241 self.failUnless(self.widget.size() == (50,50),
242 'incorrect default size')
243
244 class WidgetResizeTestCase(SimpleWidgetTestCase):
245 def runTest(self):
246 self.widget.resize(100,150)
247 self.failUnless(self.widget.size() == (100,150),
248 'wrong size after resize')
249
Benjamin Peterson52baa292009-03-24 00:56:30 +0000250If the :meth:`~TestCase.setUp` method raises an exception while the test is
251running, the framework will consider the test to have suffered an error, and the
252:meth:`~TestCase.runTest` method will not be executed.
Georg Brandl116aa622007-08-15 14:28:22 +0000253
Benjamin Peterson52baa292009-03-24 00:56:30 +0000254Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
255after the :meth:`~TestCase.runTest` method has been run::
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257 import unittest
258
259 class SimpleWidgetTestCase(unittest.TestCase):
260 def setUp(self):
261 self.widget = Widget('The widget')
262
263 def tearDown(self):
264 self.widget.dispose()
265 self.widget = None
266
Benjamin Peterson52baa292009-03-24 00:56:30 +0000267If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
268be run whether :meth:`~TestCase.runTest` succeeded or not.
Georg Brandl116aa622007-08-15 14:28:22 +0000269
270Such a working environment for the testing code is called a :dfn:`fixture`.
271
272Often, many small test cases will use the same fixture. In this case, we would
273end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
274classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
Georg Brandl116aa622007-08-15 14:28:22 +0000275discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
276mechanism::
277
278 import unittest
279
280 class WidgetTestCase(unittest.TestCase):
281 def setUp(self):
282 self.widget = Widget('The widget')
283
284 def tearDown(self):
285 self.widget.dispose()
286 self.widget = None
287
288 def testDefaultSize(self):
289 self.failUnless(self.widget.size() == (50,50),
290 'incorrect default size')
291
292 def testResize(self):
293 self.widget.resize(100,150)
294 self.failUnless(self.widget.size() == (100,150),
295 'wrong size after resize')
296
Benjamin Peterson52baa292009-03-24 00:56:30 +0000297Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
298provided two different test methods. Class instances will now each run one of
299the :meth:`test\*` methods, with ``self.widget`` created and destroyed
300separately for each instance. When creating an instance we must specify the
301test method it is to run. We do this by passing the method name in the
302constructor::
Georg Brandl116aa622007-08-15 14:28:22 +0000303
304 defaultSizeTestCase = WidgetTestCase('testDefaultSize')
305 resizeTestCase = WidgetTestCase('testResize')
306
307Test case instances are grouped together according to the features they test.
308:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
309represented by :mod:`unittest`'s :class:`TestSuite` class::
310
311 widgetTestSuite = unittest.TestSuite()
312 widgetTestSuite.addTest(WidgetTestCase('testDefaultSize'))
313 widgetTestSuite.addTest(WidgetTestCase('testResize'))
314
315For the ease of running tests, as we will see later, it is a good idea to
316provide in each test module a callable object that returns a pre-built test
317suite::
318
319 def suite():
320 suite = unittest.TestSuite()
321 suite.addTest(WidgetTestCase('testDefaultSize'))
322 suite.addTest(WidgetTestCase('testResize'))
323 return suite
324
325or even::
326
327 def suite():
328 tests = ['testDefaultSize', 'testResize']
329
330 return unittest.TestSuite(map(WidgetTestCase, tests))
331
332Since it is a common pattern to create a :class:`TestCase` subclass with many
333similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
334class that can be used to automate the process of creating a test suite and
335populating it with individual tests. For example, ::
336
337 suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
338
339will create a test suite that will run ``WidgetTestCase.testDefaultSize()`` and
340``WidgetTestCase.testResize``. :class:`TestLoader` uses the ``'test'`` method
341name prefix to identify test methods automatically.
342
Mark Dickinsonc48d8342009-02-01 14:18:10 +0000343Note that the order in which the various test cases will be run is
344determined by sorting the test function names with respect to the
345built-in ordering for strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000346
347Often it is desirable to group suites of test cases together, so as to run tests
348for the whole system at once. This is easy, since :class:`TestSuite` instances
349can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
350added to a :class:`TestSuite`::
351
352 suite1 = module1.TheTestSuite()
353 suite2 = module2.TheTestSuite()
354 alltests = unittest.TestSuite([suite1, suite2])
355
356You can place the definitions of test cases and test suites in the same modules
357as the code they are to test (such as :file:`widget.py`), but there are several
358advantages to placing the test code in a separate module, such as
359:file:`test_widget.py`:
360
361* The test module can be run standalone from the command line.
362
363* The test code can more easily be separated from shipped code.
364
365* There is less temptation to change test code to fit the code it tests without
366 a good reason.
367
368* Test code should be modified much less frequently than the code it tests.
369
370* Tested code can be refactored more easily.
371
372* Tests for modules written in C must be in separate modules anyway, so why not
373 be consistent?
374
375* If the testing strategy changes, there is no need to change the source code.
376
377
378.. _legacy-unit-tests:
379
380Re-using old test code
381----------------------
382
383Some users will find that they have existing test code that they would like to
384run from :mod:`unittest`, without converting every old test function to a
385:class:`TestCase` subclass.
386
387For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
388This subclass of :class:`TestCase` can be used to wrap an existing test
389function. Set-up and tear-down functions can also be provided.
390
391Given the following test function::
392
393 def testSomething():
394 something = makeSomething()
395 assert something.name is not None
396 # ...
397
398one can create an equivalent test case instance as follows::
399
400 testcase = unittest.FunctionTestCase(testSomething)
401
402If there are additional set-up and tear-down methods that should be called as
403part of the test case's operation, they can also be provided like so::
404
405 testcase = unittest.FunctionTestCase(testSomething,
406 setUp=makeSomethingDB,
407 tearDown=deleteSomethingDB)
408
409To make migrating existing test suites easier, :mod:`unittest` supports tests
410raising :exc:`AssertionError` to indicate test failure. However, it is
411recommended that you use the explicit :meth:`TestCase.fail\*` and
412:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
413may treat :exc:`AssertionError` differently.
414
415.. note::
416
417 Even though :class:`FunctionTestCase` can be used to quickly convert an existing
418 test base over to a :mod:`unittest`\ -based system, this approach is not
419 recommended. Taking the time to set up proper :class:`TestCase` subclasses will
420 make future test refactorings infinitely easier.
421
Benjamin Peterson52baa292009-03-24 00:56:30 +0000422In some cases, the existing tests may have been written using the :mod:`doctest`
423module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
424automatically build :class:`unittest.TestSuite` instances from the existing
425:mod:`doctest`\ -based tests.
426
Georg Brandl116aa622007-08-15 14:28:22 +0000427
Benjamin Peterson5254c042009-03-23 22:25:03 +0000428.. _unittest-skipping:
429
430Skipping tests and expected failures
431------------------------------------
432
433Unittest supports skipping individual test methods and even whole classes of
434tests. In addition, it supports marking a test as a "expected failure," a test
435that is broken and will fail, but shouldn't be counted as a failure on a
436:class:`TestResult`.
437
438Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
439or one of its conditional variants.
440
441Basic skipping looks like this: ::
442
443 class MyTestCase(unittest.TestCase):
444
445 @unittest.skip("demonstrating skipping")
446 def test_nothing(self):
447 self.fail("shouldn't happen")
448
Benjamin Petersonded31c42009-03-30 15:04:16 +0000449 @unittest.skipIf(mylib.__version__ < (1, 3), "not supported in this library version")
450 def test_format(self):
451 # Tests that work for only a certain version of the library.
452 pass
453
454 @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
455 def test_windows_support(self):
456 # windows specific testing code
457 pass
458
Benjamin Peterson5254c042009-03-23 22:25:03 +0000459This is the output of running the example above in verbose mode: ::
460
Benjamin Petersonded31c42009-03-30 15:04:16 +0000461 test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000462 test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
Benjamin Petersonded31c42009-03-30 15:04:16 +0000463 test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
Benjamin Peterson5254c042009-03-23 22:25:03 +0000464
465 ----------------------------------------------------------------------
Benjamin Petersonded31c42009-03-30 15:04:16 +0000466 Ran 3 tests in 0.005s
467
468 OK (skipped=3)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000469
470Classes can be skipped just like methods: ::
471
472 @skip("showing class skipping")
473 class MySkippedTestCase(unittest.TestCase):
474 def test_not_run(self):
475 pass
476
Benjamin Peterson52baa292009-03-24 00:56:30 +0000477:meth:`TestCase.setUp` can also skip the test. This is useful when a resource
478that needs to be set up is not available.
479
Benjamin Peterson5254c042009-03-23 22:25:03 +0000480Expected failures use the :func:`expectedFailure` decorator. ::
481
482 class ExpectedFailureTestCase(unittest.TestCase):
483 @unittest.expectedFailure
484 def test_fail(self):
485 self.assertEqual(1, 0, "broken")
486
487It's easy to roll your own skipping decorators by making a decorator that calls
488:func:`skip` on the test when it wants it to be skipped. This decorator skips
489the test unless the passed object has a certain attribute: ::
490
491 def skipUnlessHasattr(obj, attr):
492 if hasattr(obj, attr):
493 return lambda func: func
494 return unittest.skip("{0!r} doesn't have {1!r}".format(obj, attr))
495
496The following decorators implement test skipping and expected failures:
497
498.. function:: skip(reason)
499
500 Unconditionally skip the decorated test. *reason* should describe why the
501 test is being skipped.
502
503.. function:: skipIf(condition, reason)
504
505 Skip the decorated test if *condition* is true.
506
507.. function:: skipUnless(condition, reason)
508
509 Skip the decoratored test unless *condition* is true.
510
511.. function:: expectedFailure
512
513 Mark the test as an expected failure. If the test fails when run, the test
514 is not counted as a failure.
515
516
Georg Brandl116aa622007-08-15 14:28:22 +0000517.. _unittest-contents:
518
519Classes and functions
520---------------------
521
Benjamin Peterson52baa292009-03-24 00:56:30 +0000522This section describes in depth the API of :mod:`unittest`.
523
524
525.. _testcase-objects:
526
527Test cases
528~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000529
530.. class:: TestCase([methodName])
531
532 Instances of the :class:`TestCase` class represent the smallest testable units
533 in the :mod:`unittest` universe. This class is intended to be used as a base
534 class, with specific tests being implemented by concrete subclasses. This class
535 implements the interface needed by the test runner to allow it to drive the
536 test, and methods that the test code can use to check for and report various
537 kinds of failure.
538
539 Each instance of :class:`TestCase` will run a single test method: the method
540 named *methodName*. If you remember, we had an earlier example that went
541 something like this::
542
543 def suite():
544 suite = unittest.TestSuite()
545 suite.addTest(WidgetTestCase('testDefaultSize'))
546 suite.addTest(WidgetTestCase('testResize'))
547 return suite
548
549 Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
550 single test.
551
Benjamin Peterson52baa292009-03-24 00:56:30 +0000552 *methodName* defaults to :meth:`runTest`.
553
554 :class:`TestCase` instances provide three groups of methods: one group used
555 to run the test, another used by the test implementation to check conditions
556 and report failures, and some inquiry methods allowing information about the
557 test itself to be gathered.
558
559 Methods in the first group (running the test) are:
560
561
562 .. method:: setUp()
563
564 Method called to prepare the test fixture. This is called immediately
565 before calling the test method; any exception raised by this method will
566 be considered an error rather than a test failure. The default
567 implementation does nothing.
568
569
570 .. method:: tearDown()
571
572 Method called immediately after the test method has been called and the
573 result recorded. This is called even if the test method raised an
574 exception, so the implementation in subclasses may need to be particularly
575 careful about checking internal state. Any exception raised by this
576 method will be considered an error rather than a test failure. This
577 method will only be called if the :meth:`setUp` succeeds, regardless of
578 the outcome of the test method. The default implementation does nothing.
579
580
581 .. method:: run([result])
582
583 Run the test, collecting the result into the test result object passed as
584 *result*. If *result* is omitted or :const:`None`, a temporary result
585 object is created (by calling the :meth:`defaultTestCase` method) and
586 used; this result object is not returned to :meth:`run`'s caller.
587
588 The same effect may be had by simply calling the :class:`TestCase`
589 instance.
590
591
Benjamin Petersone549ead2009-03-28 21:42:05 +0000592 .. method:: skipTest(reason)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000593
594 Calling this during the a test method or :meth:`setUp` skips the current
595 test. See :ref:`unittest-skipping` for more information.
596
597
598 .. method:: debug()
599
600 Run the test without collecting the result. This allows exceptions raised
601 by the test to be propagated to the caller, and can be used to support
602 running tests under a debugger.
603
604 The test code can use any of the following methods to check for and report
605 failures.
606
607
608 .. method:: assert_(expr[, msg])
609 failUnless(expr[, msg])
610 assertTrue(expr[, msg])
611
612 Signal a test failure if *expr* is false; the explanation for the error
613 will be *msg* if given, otherwise it will be :const:`None`.
614
615
616 .. method:: assertEqual(first, second[, msg])
617 failUnlessEqual(first, second[, msg])
618
619 Test that *first* and *second* are equal. If the values do not compare
620 equal, the test will fail with the explanation given by *msg*, or
621 :const:`None`. Note that using :meth:`failUnlessEqual` improves upon
622 doing the comparison as the first parameter to :meth:`failUnless`: the
623 default value for *msg* can be computed to include representations of both
624 *first* and *second*.
625
626
627 .. method:: assertNotEqual(first, second[, msg])
628 failIfEqual(first, second[, msg])
629
630 Test that *first* and *second* are not equal. If the values do compare
631 equal, the test will fail with the explanation given by *msg*, or
632 :const:`None`. Note that using :meth:`failIfEqual` improves upon doing
633 the comparison as the first parameter to :meth:`failUnless` is that the
634 default value for *msg* can be computed to include representations of both
635 *first* and *second*.
636
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000637
Benjamin Peterson52baa292009-03-24 00:56:30 +0000638 .. method:: assertAlmostEqual(first, second[, places[, msg]])
639 failUnlessAlmostEqual(first, second[, places[, msg]])
640
641 Test that *first* and *second* are approximately equal by computing the
642 difference, rounding to the given number of decimal *places* (default 7),
643 and comparing to zero.
644
645 Note that comparing a given number of decimal places is not the same as
646 comparing a given number of significant digits. If the values do not
647 compare equal, the test will fail with the explanation given by *msg*, or
648 :const:`None`.
649
650
651 .. method:: assertNotAlmostEqual(first, second[, places[, msg]])
652 failIfAlmostEqual(first, second[, places[, msg]])
653
654 Test that *first* and *second* are not approximately equal by computing
655 the difference, rounding to the given number of decimal *places* (default
656 7), and comparing to zero.
657
658 Note that comparing a given number of decimal places is not the same as
659 comparing a given number of significant digits. If the values do not
660 compare equal, the test will fail with the explanation given by *msg*, or
661 :const:`None`.
662
663
664 .. method:: assertRaises(exception[, callable, ...])
665 failUnlessRaises(exception[, callable, ...])
666
667 Test that an exception is raised when *callable* is called with any
668 positional or keyword arguments that are also passed to
669 :meth:`assertRaises`. The test passes if *exception* is raised, is an
670 error if another exception is raised, or fails if no exception is raised.
671 To catch any of a group of exceptions, a tuple containing the exception
672 classes may be passed as *exception*.
673
Benjamin Petersonded31c42009-03-30 15:04:16 +0000674 If *callable* is omitted or None, returns a context manager so that the
675 code under test can be written inline rather than as a function::
676
677 with self.failUnlessRaises(some_error_class):
678 do_something()
679
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000680 .. versionchanged:: 3.1
Benjamin Petersonded31c42009-03-30 15:04:16 +0000681 Added the ability to use :meth:`assertRaises` as a context manager.
Benjamin Peterson52baa292009-03-24 00:56:30 +0000682
Benjamin Peterson52baa292009-03-24 00:56:30 +0000683
684 .. method:: failIf(expr[, msg])
685 assertFalse(expr[, msg])
686
687 The inverse of the :meth:`failUnless` method is the :meth:`failIf` method.
688 This signals a test failure if *expr* is true, with *msg* or :const:`None`
689 for the error message.
690
691
692 .. method:: fail([msg])
693
694 Signals a test failure unconditionally, with *msg* or :const:`None` for
695 the error message.
696
697
698 .. attribute:: failureException
699
700 This class attribute gives the exception raised by the test method. If a
701 test framework needs to use a specialized exception, possibly to carry
702 additional information, it must subclass this exception in order to "play
703 fair" with the framework. The initial value of this attribute is
704 :exc:`AssertionError`.
705
706 Testing frameworks can use the following methods to collect information on
707 the test:
708
709
710 .. method:: countTestCases()
711
712 Return the number of tests represented by this test object. For
713 :class:`TestCase` instances, this will always be ``1``.
714
715
716 .. method:: defaultTestResult()
717
718 Return an instance of the test result class that should be used for this
719 test case class (if no other result instance is provided to the
720 :meth:`run` method).
721
722 For :class:`TestCase` instances, this will always be an instance of
723 :class:`TestResult`; subclasses of :class:`TestCase` should override this
724 as necessary.
725
726
727 .. method:: id()
728
729 Return a string identifying the specific test case. This is usually the
730 full name of the test method, including the module and class name.
731
732
733 .. method:: shortDescription()
734
735 Returns a one-line description of the test, or :const:`None` if no
736 description has been provided. The default implementation of this method
737 returns the first line of the test method's docstring, if available, or
738 :const:`None`.
Georg Brandl116aa622007-08-15 14:28:22 +0000739
740
741.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
742
743 This class implements the portion of the :class:`TestCase` interface which
744 allows the test runner to drive the test, but does not provide the methods which
745 test code can use to check and report errors. This is used to create test cases
746 using legacy test code, allowing it to be integrated into a :mod:`unittest`\
747 -based test framework.
748
749
Benjamin Peterson52baa292009-03-24 00:56:30 +0000750.. _testsuite-objects:
751
Benjamin Peterson52baa292009-03-24 00:56:30 +0000752Grouping tests
753~~~~~~~~~~~~~~
754
Georg Brandl116aa622007-08-15 14:28:22 +0000755.. class:: TestSuite([tests])
756
757 This class represents an aggregation of individual tests cases and test suites.
758 The class presents the interface needed by the test runner to allow it to be run
759 as any other test case. Running a :class:`TestSuite` instance is the same as
760 iterating over the suite, running each test individually.
761
762 If *tests* is given, it must be an iterable of individual test cases or other
763 test suites that will be used to build the suite initially. Additional methods
764 are provided to add test cases and suites to the collection later on.
765
Benjamin Peterson52baa292009-03-24 00:56:30 +0000766 :class:`TestSuite` (including :class:`ClassTestSuite`) objects behave much
767 like :class:`TestCase` objects, except they do not actually implement a test.
768 Instead, they are used to aggregate tests into groups of tests that should be
769 run together. Some additional methods are available to add tests to
770 :class:`TestSuite` instances:
771
772
773 .. method:: TestSuite.addTest(test)
774
775 Add a :class:`TestCase` or :class:`TestSuite` to the suite.
776
777
778 .. method:: TestSuite.addTests(tests)
779
780 Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
781 instances to this test suite.
782
783 This is equivalent to iterating over *tests*, calling :meth:`addTest` for each
784 element.
785
786 :class:`TestSuite` shares the following methods with :class:`TestCase`:
787
788
789 .. method:: run(result)
790
791 Run the tests associated with this suite, collecting the result into the
792 test result object passed as *result*. Note that unlike
793 :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
794 be passed in.
795
796
797 .. method:: debug()
798
799 Run the tests associated with this suite without collecting the
800 result. This allows exceptions raised by the test to be propagated to the
801 caller and can be used to support running tests under a debugger.
802
803
804 .. method:: countTestCases()
805
806 Return the number of tests represented by this test object, including all
807 individual tests and sub-suites.
808
809 In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
810 is invoked by a :class:`TestRunner` rather than by the end-user test harness.
811
812
Benjamin Peterson5254c042009-03-23 22:25:03 +0000813.. class:: ClassTestSuite(tests, collected_from)
814
815 This subclass of :class:`TestSuite` repesents an aggregation of individuals
816 tests from one :class:`TestCase` class. *tests* is an iterable of
817 :class:`TestCase` instances created from the class. *collected_from* is the
818 class they came from.
819
Georg Brandl116aa622007-08-15 14:28:22 +0000820
Benjamin Peterson52baa292009-03-24 00:56:30 +0000821Loading and running tests
822~~~~~~~~~~~~~~~~~~~~~~~~~
823
Georg Brandl116aa622007-08-15 14:28:22 +0000824.. class:: TestLoader()
825
Benjamin Peterson52baa292009-03-24 00:56:30 +0000826 The :class:`TestLoader` class is used to create test suites from classes and
827 modules. Normally, there is no need to create an instance of this class; the
828 :mod:`unittest` module provides an instance that can be shared as
829 ``unittest.defaultTestLoader``. Using a subclass or instance, however, allows
830 customization of some configurable properties.
831
832 :class:`TestLoader` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000833
834
Benjamin Peterson52baa292009-03-24 00:56:30 +0000835 .. method:: loadTestsFromTestCase(testCaseClass)
Georg Brandl116aa622007-08-15 14:28:22 +0000836
Benjamin Peterson52baa292009-03-24 00:56:30 +0000837 Return a suite of all tests cases contained in the :class:`TestCase`\ -derived
838 :class:`testCaseClass`.
839
840
841 .. method:: loadTestsFromModule(module)
842
843 Return a suite of all tests cases contained in the given module. This
844 method searches *module* for classes derived from :class:`TestCase` and
845 creates an instance of the class for each test method defined for the
846 class.
847
848 .. warning::
849
850 While using a hierarchy of :class:`TestCase`\ -derived classes can be
851 convenient in sharing fixtures and helper functions, defining test
852 methods on base classes that are not intended to be instantiated
853 directly does not play well with this method. Doing so, however, can
854 be useful when the fixtures are different and defined in subclasses.
855
856
857 .. method:: loadTestsFromName(name[, module])
858
859 Return a suite of all tests cases given a string specifier.
860
861 The specifier *name* is a "dotted name" that may resolve either to a
862 module, a test case class, a test method within a test case class, a
863 :class:`TestSuite` instance, or a callable object which returns a
864 :class:`TestCase` or :class:`TestSuite` instance. These checks are
865 applied in the order listed here; that is, a method on a possible test
866 case class will be picked up as "a test method within a test case class",
867 rather than "a callable object".
868
869 For example, if you have a module :mod:`SampleTests` containing a
870 :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
871 methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
872 specifier ``'SampleTests.SampleTestCase'`` would cause this method to return a
873 suite which will run all three test methods. Using the specifier
874 ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test suite
875 which will run only the :meth:`test_two` test method. The specifier can refer
876 to modules and packages which have not been imported; they will be imported as a
877 side-effect.
878
879 The method optionally resolves *name* relative to the given *module*.
880
881
882 .. method:: loadTestsFromNames(names[, module])
883
884 Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
885 than a single name. The return value is a test suite which supports all
886 the tests defined for each name.
887
888
889 .. method:: getTestCaseNames(testCaseClass)
890
891 Return a sorted sequence of method names found within *testCaseClass*;
892 this should be a subclass of :class:`TestCase`.
893
894 The following attributes of a :class:`TestLoader` can be configured either by
895 subclassing or assignment on an instance:
896
897
898 .. attribute:: testMethodPrefix
899
900 String giving the prefix of method names which will be interpreted as test
901 methods. The default value is ``'test'``.
902
903 This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
904 methods.
905
906
907 .. attribute:: sortTestMethodsUsing
908
909 Function to be used to compare method names when sorting them in
910 :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods.
911
912
913 .. attribute:: suiteClass
914
915 Callable object that constructs a test suite from a list of tests. No
916 methods on the resulting object are needed. The default value is the
917 :class:`TestSuite` class.
918
919 This affects all the :meth:`loadTestsFrom\*` methods.
920
921
922 .. attribute:: classSuiteClass
923
924 Callable object that constructs a test suite for the tests cases from one
925 class. The default value is :class:`ClassTestSuite`.
926
927
928.. class:: TestResult
929
930 This class is used to compile information about which tests have succeeded
931 and which have failed.
932
933 A :class:`TestResult` object stores the results of a set of tests. The
934 :class:`TestCase` and :class:`TestSuite` classes ensure that results are
935 properly recorded; test authors do not need to worry about recording the
936 outcome of tests.
937
938 Testing frameworks built on top of :mod:`unittest` may want access to the
939 :class:`TestResult` object generated by running a set of tests for reporting
940 purposes; a :class:`TestResult` instance is returned by the
941 :meth:`TestRunner.run` method for this purpose.
942
943 :class:`TestResult` instances have the following attributes that will be of
944 interest when inspecting the results of running a set of tests:
945
946
947 .. attribute:: errors
948
949 A list containing 2-tuples of :class:`TestCase` instances and strings
950 holding formatted tracebacks. Each tuple represents a test which raised an
951 unexpected exception.
952
Benjamin Peterson52baa292009-03-24 00:56:30 +0000953
954 .. attribute:: failures
955
956 A list containing 2-tuples of :class:`TestCase` instances and strings
957 holding formatted tracebacks. Each tuple represents a test where a failure
958 was explicitly signalled using the :meth:`TestCase.fail\*` or
959 :meth:`TestCase.assert\*` methods.
960
Benjamin Peterson52baa292009-03-24 00:56:30 +0000961 .. attribute:: skipped
962
963 A list containing 2-tuples of :class:`TestCase` instances and strings
964 holding the reason for skipping the test.
965
Benjamin Peterson70e32c82009-03-24 01:00:11 +0000966 .. versionadded:: 3.1
Benjamin Peterson52baa292009-03-24 00:56:30 +0000967
968 .. attribute:: expectedFailures
969
970 A list contaning 2-tuples of :class:`TestCase` instances and strings
971 holding formatted tracebacks. Each tuple represents a expected failures
972 of the test case.
973
974 .. attribute:: unexpectedSuccesses
975
976 A list containing :class:`TestCase` instances that were marked as expected
977 failures, but succeeded.
978
979 .. attribute:: shouldStop
980
981 Set to ``True`` when the execution of tests should stop by :meth:`stop`.
982
983
984 .. attribute:: testsRun
985
986 The total number of tests run so far.
987
988
989 .. method:: wasSuccessful()
990
991 Return :const:`True` if all tests run so far have passed, otherwise returns
992 :const:`False`.
993
994
995 .. method:: stop()
996
997 This method can be called to signal that the set of tests being run should
998 be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
999 :class:`TestRunner` objects should respect this flag and return without
1000 running any additional tests.
1001
1002 For example, this feature is used by the :class:`TextTestRunner` class to
1003 stop the test framework when the user signals an interrupt from the
1004 keyboard. Interactive tools which provide :class:`TestRunner`
1005 implementations can use this in a similar manner.
1006
1007 The following methods of the :class:`TestResult` class are used to maintain
1008 the internal data structures, and may be extended in subclasses to support
1009 additional reporting requirements. This is particularly useful in building
1010 tools which support interactive reporting while tests are being run.
1011
1012
1013 .. method:: startTest(test)
1014
1015 Called when the test case *test* is about to be run.
1016
1017 The default implementation simply increments the instance's :attr:`testsRun`
1018 counter.
1019
1020
1021 .. method:: stopTest(test)
1022
1023 Called after the test case *test* has been executed, regardless of the
1024 outcome.
1025
1026 The default implementation does nothing.
1027
1028
1029 .. method:: addError(test, err)
1030
1031 Called when the test case *test* raises an unexpected exception *err* is a
1032 tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
1033 traceback)``.
1034
1035 The default implementation appends a tuple ``(test, formatted_err)`` to
1036 the instance's :attr:`errors` attribute, where *formatted_err* is a
1037 formatted traceback derived from *err*.
1038
1039
1040 .. method:: addFailure(test, err)
1041
1042 Called when the test case *test* signals a failure. *err* is a tuple of the form
1043 returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1044
1045 The default implementation appends a tuple ``(test, formatted_err)`` to
1046 the instance's :attr:`failures` attribute, where *formatted_err* is a
1047 formatted traceback derived from *err*.
1048
1049
1050 .. method:: addSuccess(test)
1051
1052 Called when the test case *test* succeeds.
1053
1054 The default implementation does nothing.
1055
1056
1057 .. method:: addSkip(test, reason)
1058
1059 Called when the test case *test* is skipped. *reason* is the reason the
1060 test gave for skipping.
1061
1062 The default implementation appends a tuple ``(test, reason)`` to the
1063 instance's :attr:`skipped` attribute.
1064
1065
1066 .. method:: addExpectedFailure(test, err)
1067
1068 Called when the test case *test* fails, but was marked with the
1069 :func:`expectedFailure` decorator.
1070
1071 The default implementation appends a tuple ``(test, formatted_err)`` to
1072 the instance's :attr:`expectedFailures` attribute, where *formatted_err*
1073 is a formatted traceback derived from *err*.
1074
1075
1076 .. method:: addUnexpectedSuccess(test)
1077
1078 Called when the test case *test* was marked with the
1079 :func:`expectedFailure` decorator, but succeeded.
1080
1081 The default implementation appends the test to the instance's
1082 :attr:`unexpectedSuccesses` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001083
1084
1085.. data:: defaultTestLoader
1086
1087 Instance of the :class:`TestLoader` class intended to be shared. If no
1088 customization of the :class:`TestLoader` is needed, this instance can be used
1089 instead of repeatedly creating new instances.
1090
1091
1092.. class:: TextTestRunner([stream[, descriptions[, verbosity]]])
1093
1094 A basic test runner implementation which prints results on standard error. It
1095 has a few configurable parameters, but is essentially very simple. Graphical
1096 applications which run test suites should provide alternate implementations.
1097
1098
1099.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader]]]]])
1100
1101 A command-line program that runs a set of tests; this is primarily for making
1102 test modules conveniently executable. The simplest use for this function is to
1103 include the following line at the end of a test script::
1104
1105 if __name__ == '__main__':
1106 unittest.main()
1107
1108 The *testRunner* argument can either be a test runner class or an already
1109 created instance of it.