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