1111(If you are already familiar with the basic concepts of testing, you might want
1212to skip to :ref: `the list of assert methods <assert-methods >`.)
1313
14- The Python unit testing framework, sometimes referred to as "PyUnit," is a
15- Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
16- turn, a Java version of Kent's Smalltalk testing framework. Each is the de
17- facto standard unit testing framework for its respective language.
14+ The :mod: `unittest ` unit testing framework was originally inspired by JUnit
15+ and has a similar flavor as major unit testing frameworks in other
16+ languages. It supports test automation, sharing of setup and shutdown code
17+ for tests, aggregation of tests into collections, and independence of the
18+ tests from the reporting framework.
1819
19- :mod: `unittest ` supports test automation, sharing of setup and shutdown code for
20- tests, aggregation of tests into collections, and independence of the tests from
21- the reporting framework. The :mod: `unittest ` module provides classes that make
22- it easy to support these qualities for a set of tests.
23-
24- To achieve this, :mod: `unittest ` supports some important concepts:
20+ To achieve this, :mod: `unittest ` supports some important concepts in an
21+ object-oriented way:
2522
2623test fixture
2724 A :dfn: `test fixture ` represents the preparation needed to perform one or more
@@ -30,7 +27,7 @@ test fixture
3027 process.
3128
3229test case
33- A :dfn: `test case ` is the smallest unit of testing. It checks for a specific
30+ A :dfn: `test case ` is the individual unit of testing. It checks for a specific
3431 response to a particular set of inputs. :mod: `unittest ` provides a base class,
3532 :class: `TestCase `, which may be used to create new test cases.
3633
@@ -44,43 +41,12 @@ test runner
4441 a textual interface, or return a special value to indicate the results of
4542 executing the tests.
4643
47- The test case and test fixture concepts are supported through the
48- :class: `TestCase ` and :class: `FunctionTestCase ` classes; the former should be
49- used when creating new tests, and the latter can be used when integrating
50- existing test code with a :mod: `unittest `\ -driven framework. When building test
51- fixtures using :class: `TestCase `, the :meth: `~TestCase.setUp ` and
52- :meth: `~TestCase.tearDown ` methods can be overridden to provide initialization
53- and cleanup for the fixture. With :class: `FunctionTestCase `, existing functions
54- can be passed to the constructor for these purposes. When the test is run, the
55- fixture initialization is run first; if it succeeds, the cleanup method is run
56- after the test has been executed, regardless of the outcome of the test. Each
57- instance of the :class: `TestCase ` will only be used to run a single test method,
58- so a new fixture is created for each test.
59-
60- Test suites are implemented by the :class: `TestSuite ` class. This class allows
61- individual tests and test suites to be aggregated; when the suite is executed,
62- all tests added directly to the suite and in "child" test suites are run.
63-
64- A test runner is an object that provides a single method,
65- :meth: `~TestRunner.run `, which accepts a :class: `TestCase ` or :class: `TestSuite `
66- object as a parameter, and returns a result object. The class
67- :class: `TestResult ` is provided for use as the result object. :mod: `unittest `
68- provides the :class: `TextTestRunner ` as an example test runner which reports
69- test results on the standard error stream by default. Alternate runners can be
70- implemented for other environments (such as graphical environments) without any
71- need to derive from a specific class.
72-
7344
7445.. seealso ::
7546
7647 Module :mod: `doctest `
7748 Another test-support module with a very different flavor.
7849
79- `unittest2: A backport of new unittest features for Python 2.4-2.6 <http://pypi.python.org/pypi/unittest2 >`_
80- Many new features were added to unittest in Python 2.7, including test
81- discovery. unittest2 allows you to use these features with earlier
82- versions of Python.
83-
8450 `Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm >`_
8551 Kent Beck's original paper on testing frameworks using the pattern shared
8652 by :mod: `unittest `.
@@ -89,7 +55,7 @@ need to derive from a specific class.
8955 Third-party unittest frameworks with a lighter-weight syntax for writing
9056 tests. For example, ``assert func(10) == 42 ``.
9157
92- `The Python Testing Tools Taxonomy <http://pycheesecake. org/wiki /PythonTestingToolsTaxonomy >`_
58+ `The Python Testing Tools Taxonomy <http://wiki.python. org/moin /PythonTestingToolsTaxonomy >`_
9359 An extensive list of Python testing tools including functional testing
9460 frameworks and mock object libraries.
9561
@@ -173,15 +139,8 @@ line, the above script produces an output that looks like this::
173139
174140 OK
175141
176- Instead of :func: `unittest.main `, there are other ways to run the tests with a
177- finer level of control, less terse output, and no requirement to be run from the
178- command line. For example, the last two lines may be replaced with::
179-
180- suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
181- unittest.TextTestRunner(verbosity=2).run(suite)
182-
183- Running the revised script from the interpreter or another script produces the
184- following output::
142+ Passing the ``-v `` option to your test script will instruct :func: `unittest.main `
143+ to enable a higher level of verbosity, and produce the following output::
185144
186145 test_choice (__main__.TestSequenceFunctions) ... ok
187146 test_sample (__main__.TestSequenceFunctions) ... ok
@@ -359,69 +318,57 @@ test cases are represented by :class:`unittest.TestCase` instances.
359318To make your own test cases you must write subclasses of
360319:class: `TestCase ` or use :class: `FunctionTestCase `.
361320
362- An instance of a :class: `TestCase `\ -derived class is an object that can
363- completely run a single test method, together with optional set-up and tidy-up
364- code.
365-
366321The testing code of a :class: `TestCase ` instance should be entirely self
367322contained, such that it can be run either in isolation or in arbitrary
368323combination with any number of other test cases.
369324
370- The simplest :class: `TestCase ` subclass will simply override the
371- :meth: `~TestCase.runTest ` method in order to perform specific testing code::
325+ The simplest :class: `TestCase ` subclass will simply implement a test method
326+ (i.e. a method whose name starts with ``test ``) in order to perform specific
327+ testing code::
372328
373329 import unittest
374330
375331 class DefaultWidgetSizeTestCase(unittest.TestCase):
376- def runTest (self):
332+ def test_default_widget_size (self):
377333 widget = Widget('The widget')
378- self.assertEqual(widget.size(), (50, 50), 'incorrect default size' )
334+ self.assertEqual(widget.size(), (50, 50))
379335
380336Note that in order to test something, we use one of the :meth: `assert\* `
381337methods provided by the :class: `TestCase ` base class. If the test fails, an
382338exception will be raised, and :mod: `unittest ` will identify the test case as a
383- :dfn: `failure `. Any other exceptions will be treated as :dfn: `errors `. This
384- helps you identify where the problem is: :dfn: `failures ` are caused by incorrect
385- results - a 5 where you expected a 6. :dfn: `Errors ` are caused by incorrect
386- code - e.g., a :exc: `TypeError ` caused by an incorrect function call.
339+ :dfn: `failure `. Any other exceptions will be treated as :dfn: `errors `.
387340
388- The way to run a test case will be described later. For now, note that to
389- construct an instance of such a test case, we call its constructor without
390- arguments::
391-
392- testCase = DefaultWidgetSizeTestCase()
393-
394- Now, such test cases can be numerous, and their set-up can be repetitive. In
395- the above case, constructing a :class: `Widget ` in each of 100 Widget test case
396- subclasses would mean unsightly duplication.
397-
398- Luckily, we can factor out such set-up code by implementing a method called
399- :meth: `~TestCase.setUp `, which the testing framework will automatically call for
400- us when we run the test::
341+ Tests can be numerous, and their set-up can be repetitive. Luckily, we
342+ can factor out set-up code by implementing a method called
343+ :meth: `~TestCase.setUp `, which the testing framework will automatically
344+ call for every single test we run::
401345
402346 import unittest
403347
404348 class SimpleWidgetTestCase(unittest.TestCase):
405349 def setUp(self):
406350 self.widget = Widget('The widget')
407351
408- class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
409- def runTest(self):
352+ def test_default_widget_size(self):
410353 self.assertEqual(self.widget.size(), (50,50),
411354 'incorrect default size')
412355
413- class WidgetResizeTestCase(SimpleWidgetTestCase):
414- def runTest(self):
356+ def test_widget_resize(self):
415357 self.widget.resize(100,150)
416358 self.assertEqual(self.widget.size(), (100,150),
417359 'wrong size after resize')
418360
361+ .. note ::
362+ The order in which the various tests will be run is determined
363+ by sorting the test method names with respect to the built-in
364+ ordering for strings.
365+
419366If the :meth: `~TestCase.setUp ` method raises an exception while the test is
420- running, the framework will consider the test to have suffered an error, and the
421- :meth: ` ~TestCase.runTest ` method will not be executed.
367+ running, the framework will consider the test to have suffered an error, and
368+ the test method will not be executed.
422369
423370Similarly, we can provide a :meth: `~TestCase.tearDown ` method that tidies up
424- after the :meth: ` ~TestCase.runTest ` method has been run::
371+ after the test method has been run::
425372
426373 import unittest
427374
@@ -431,97 +378,27 @@ after the :meth:`~TestCase.runTest` method has been run::
431378
432379 def tearDown(self):
433380 self.widget.dispose()
434- self.widget = None
435381
436- If :meth: `~TestCase.setUp ` succeeded, the :meth: `~TestCase.tearDown ` method will
437- be run whether :meth: ` ~TestCase.runTest ` succeeded or not.
382+ If :meth: `~TestCase.setUp ` succeeded, :meth: `~TestCase.tearDown ` will be
383+ run whether the test method succeeded or not.
438384
439385Such a working environment for the testing code is called a :dfn: `fixture `.
440386
441- Often, many small test cases will use the same fixture. In this case, we would
442- end up subclassing :class: `SimpleWidgetTestCase ` into many small one-method
443- classes such as :class: `DefaultWidgetSizeTestCase `. This is time-consuming and
444- discouraging, so in the same vein as JUnit, :mod: `unittest ` provides a simpler
445- mechanism::
446-
447- import unittest
448-
449- class WidgetTestCase(unittest.TestCase):
450- def setUp(self):
451- self.widget = Widget('The widget')
452-
453- def tearDown(self):
454- self.widget.dispose()
455- self.widget = None
456-
457- def test_default_size(self):
458- self.assertEqual(self.widget.size(), (50,50),
459- 'incorrect default size')
460-
461- def test_resize(self):
462- self.widget.resize(100,150)
463- self.assertEqual(self.widget.size(), (100,150),
464- 'wrong size after resize')
465-
466- Here we have not provided a :meth: `~TestCase.runTest ` method, but have instead
467- provided two different test methods. Class instances will now each run one of
468- the :meth: `test_\* ` methods, with ``self.widget `` created and destroyed
469- separately for each instance. When creating an instance we must specify the
470- test method it is to run. We do this by passing the method name in the
471- constructor::
472-
473- defaultSizeTestCase = WidgetTestCase('test_default_size')
474- resizeTestCase = WidgetTestCase('test_resize')
475-
476387Test case instances are grouped together according to the features they test.
477388:mod: `unittest ` provides a mechanism for this: the :dfn: `test suite `,
478- represented by :mod: `unittest `'s :class: `TestSuite ` class::
479-
480- widgetTestSuite = unittest.TestSuite()
481- widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
482- widgetTestSuite.addTest(WidgetTestCase('test_resize'))
389+ represented by :mod: `unittest `'s :class: `TestSuite ` class. In most cases,
390+ calling :func: `unittest.main ` will do the right thing and collect all the
391+ module's test cases for you, and then execute them.
483392
484- For the ease of running tests, as we will see later, it is a good idea to
485- provide in each test module a callable object that returns a pre-built test
486- suite::
393+ However, should you want to customize the building of your test suite,
394+ you can do it yourself::
487395
488396 def suite():
489397 suite = unittest.TestSuite()
490398 suite.addTest(WidgetTestCase('test_default_size'))
491399 suite.addTest(WidgetTestCase('test_resize'))
492400 return suite
493401
494- or even::
495-
496- def suite():
497- tests = ['test_default_size', 'test_resize']
498-
499- return unittest.TestSuite(map(WidgetTestCase, tests))
500-
501- Since it is a common pattern to create a :class: `TestCase ` subclass with many
502- similarly named test functions, :mod: `unittest ` provides a :class: `TestLoader `
503- class that can be used to automate the process of creating a test suite and
504- populating it with individual tests. For example, ::
505-
506- suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
507-
508- will create a test suite that will run ``WidgetTestCase.test_default_size() `` and
509- ``WidgetTestCase.test_resize ``. :class: `TestLoader ` uses the ``'test' `` method
510- name prefix to identify test methods automatically.
511-
512- Note that the order in which the various test cases will be run is
513- determined by sorting the test function names with respect to the
514- built-in ordering for strings.
515-
516- Often it is desirable to group suites of test cases together, so as to run tests
517- for the whole system at once. This is easy, since :class: `TestSuite ` instances
518- can be added to a :class: `TestSuite ` just as :class: `TestCase ` instances can be
519- added to a :class: `TestSuite `::
520-
521- suite1 = module1.TheTestSuite()
522- suite2 = module2.TheTestSuite()
523- alltests = unittest.TestSuite([suite1, suite2])
524-
525402You can place the definitions of test cases and test suites in the same modules
526403as the code they are to test (such as :file: `widget.py `), but there are several
527404advantages to placing the test code in a separate module, such as
@@ -564,23 +441,13 @@ Given the following test function::
564441 assert something.name is not None
565442 # ...
566443
567- one can create an equivalent test case instance as follows::
568-
569- testcase = unittest.FunctionTestCase(testSomething)
570-
571- If there are additional set-up and tear-down methods that should be called as
572- part of the test case's operation, they can also be provided like so::
444+ one can create an equivalent test case instance as follows, with optional
445+ set-up and tear-down methods::
573446
574447 testcase = unittest.FunctionTestCase(testSomething,
575448 setUp=makeSomethingDB,
576449 tearDown=deleteSomethingDB)
577450
578- To make migrating existing test suites easier, :mod: `unittest ` supports tests
579- raising :exc: `AssertionError ` to indicate test failure. However, it is
580- recommended that you use the explicit :meth: `TestCase.fail\* ` and
581- :meth: `TestCase.assert\* ` methods instead, as future versions of :mod: `unittest `
582- may treat :exc: `AssertionError ` differently.
583-
584451.. note ::
585452
586453 Even though :class: `FunctionTestCase ` can be used to quickly convert an
@@ -704,32 +571,24 @@ Test cases
704571
705572.. class :: TestCase(methodName='runTest')
706573
707- Instances of the :class: `TestCase ` class represent the smallest testable units
574+ Instances of the :class: `TestCase ` class represent the logical test units
708575 in the :mod: `unittest ` universe. This class is intended to be used as a base
709576 class, with specific tests being implemented by concrete subclasses. This class
710577 implements the interface needed by the test runner to allow it to drive the
711- test , and methods that the test code can use to check for and report various
578+ tests , and methods that the test code can use to check for and report various
712579 kinds of failure.
713580
714- Each instance of :class: `TestCase ` will run a single test method: the method
715- named *methodName *. If you remember, we had an earlier example that went
716- something like this::
717-
718- def suite():
719- suite = unittest.TestSuite()
720- suite.addTest(WidgetTestCase('test_default_size'))
721- suite.addTest(WidgetTestCase('test_resize'))
722- return suite
723-
724- Here, we create two instances of :class: `WidgetTestCase `, each of which runs a
725- single test.
581+ Each instance of :class: `TestCase ` will run a single base method: the method
582+ named *methodName *. However, the standard implementation of the default
583+ *methodName *, ``runTest() ``, will run every method starting with ``test ``
584+ as an individual test, and count successes and failures accordingly.
585+ Therefore, in most uses of :class: `TestCase `, you will neither change
586+ the *methodName * nor reimplement the default ``runTest() `` method.
726587
727588 .. versionchanged :: 3.2
728- :class: `TestCase ` can be instantiated successfully without providing a method
729- name. This makes it easier to experiment with :class: `TestCase ` from the
730- interactive interpreter.
731-
732- *methodName * defaults to :meth: `runTest `.
589+ :class: `TestCase ` can be instantiated successfully without providing a
590+ *methodName *. This makes it easier to experiment with :class: `TestCase `
591+ from the interactive interpreter.
733592
734593 :class: `TestCase ` instances provide three groups of methods: one group used
735594 to run the test, another used by the test implementation to check conditions
@@ -738,7 +597,6 @@ Test cases
738597
739598 Methods in the first group (running the test) are:
740599
741-
742600 .. method :: setUp()
743601
744602 Method called to prepare the test fixture. This is called immediately
@@ -790,10 +648,11 @@ Test cases
790648
791649 .. method :: run(result=None)
792650
793- Run the test, collecting the result into the test result object passed as
794- *result *. If *result * is omitted or ``None ``, a temporary result
795- object is created (by calling the :meth: `defaultTestResult ` method) and
796- used. The result object is returned to :meth: `run `'s caller.
651+ Run the test, collecting the result into the :class: `TestResult ` object
652+ passed as *result *. If *result * is omitted or ``None ``, a temporary
653+ result object is created (by calling the :meth: `defaultTestResult `
654+ method) and used. The result object is returned to :meth: `run `'s
655+ caller.
797656
798657 The same effect may be had by simply calling the :class: `TestCase `
799658 instance.
0 commit comments