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