Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d239775

Browse files
committed
Merged revisions 72570,72582-72583,73027,73049,73071,73151,73247 via svnmerge from
svn+ssh://[email protected]/python/trunk ........ r72570 | michael.foord | 2009-05-11 12:59:43 -0500 (Mon, 11 May 2009) | 7 lines Adds a verbosity keyword argument to unittest.main plus a minor fix allowing you to specify test modules / classes from the command line. Closes issue 5995. Michael Foord ........ r72582 | michael.foord | 2009-05-12 05:46:23 -0500 (Tue, 12 May 2009) | 1 line Fix to restore command line behaviour for test modules using unittest.main(). Regression caused by issue 5995. Michael ........ r72583 | michael.foord | 2009-05-12 05:49:13 -0500 (Tue, 12 May 2009) | 1 line Better fix for modules using unittest.main(). Fixes regression caused by commit for issue 5995. Michael Foord ........ r73027 | michael.foord | 2009-05-29 15:33:46 -0500 (Fri, 29 May 2009) | 1 line Add test discovery to unittest. Issue 6001. ........ r73049 | georg.brandl | 2009-05-30 05:45:40 -0500 (Sat, 30 May 2009) | 1 line Rewrap a few long lines. ........ r73071 | georg.brandl | 2009-05-31 09:15:25 -0500 (Sun, 31 May 2009) | 1 line Fix markup. ........ r73151 | michael.foord | 2009-06-02 13:08:27 -0500 (Tue, 02 Jun 2009) | 1 line Restore default testRunner argument in unittest.main to None. Issue 6177 ........ r73247 | michael.foord | 2009-06-05 09:14:34 -0500 (Fri, 05 Jun 2009) | 1 line Fix unittest discovery tests for Windows. Issue 6199 ........
1 parent f7a6b50 commit d239775

3 files changed

Lines changed: 708 additions & 54 deletions

File tree

Doc/library/unittest.rst

Lines changed: 203 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -78,15 +78,82 @@ need to derive from a specific class.
7878
Another test-support module with a very different flavor.
7979

8080
`Simple Smalltalk Testing: With Patterns <http://www.XProgramming.com/testfram.htm>`_
81-
Kent Beck's original paper on testing frameworks using the pattern shared by
82-
:mod:`unittest`.
81+
Kent Beck's original paper on testing frameworks using the pattern shared
82+
by :mod:`unittest`.
8383

8484
`Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
85-
Third-party unittest frameworks with a lighter-weight syntax
86-
for writing tests. For example, ``assert func(10) == 42``.
85+
Third-party unittest frameworks with a lighter-weight syntax for writing
86+
tests. For example, ``assert func(10) == 42``.
8787

8888
`python-mock <http://python-mock.sourceforge.net/>`_ and `minimock <http://blog.ianbicking.org/minimock.html>`_
89-
Tools for creating mock test objects (objects simulating external resources).
89+
Tools for creating mock test objects (objects simulating external
90+
resources).
91+
92+
93+
.. _unittest-command-line-interface:
94+
95+
Command Line Interface
96+
----------------------
97+
98+
The unittest module can be used from the command line to run tests from
99+
modules, classes or even individual test methods::
100+
101+
python -m unittest test_module1 test_module2
102+
python -m unittest test_module.TestClass
103+
python -m unittest test_module.TestClass.test_method
104+
105+
You can pass in a list with any combination of module names, and fully
106+
qualified class or method names.
107+
108+
You can run tests with more detail (higher verbosity) by passing in the -v flag::
109+
110+
python-m unittest -v test_module
111+
112+
For a list of all the command line options::
113+
114+
python -m unittest -h
115+
116+
.. versionchanged:: 2.7
117+
In earlier versions it was only possible to run individual test methods and
118+
not modules or classes.
119+
120+
The command line can also be used for test discovery, for running all of the
121+
tests in a project or just a subset.
122+
123+
124+
.. _unittest-test-discovery:
125+
126+
Test Discovery
127+
--------------
128+
129+
.. versionadded:: 2.7
130+
131+
unittest supports simple test discovery. For a project's tests to be
132+
compatible with test discovery they must all be importable from the top level
133+
directory of the project; i.e. they must all be in Python packages.
134+
135+
Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
136+
used from the command line. The basic command line usage is::
137+
138+
cd project_directory
139+
python -m unittest discover
140+
141+
The ``discover`` sub-command has the following options:
142+
143+
-v, --verbose Verbose output
144+
-s directory Directory to start discovery ('.' default)
145+
-p pattern Pattern to match test files ('test*.py' default)
146+
-t directory Top level directory of project (default to
147+
start directory)
148+
149+
The -s, -p, & -t options can be passsed in as positional arguments. The
150+
following two command lines are equivalent::
151+
152+
python -m unittest -s project_directory -p '*_test.py'
153+
python -m unittest project_directory '*_test.py'
154+
155+
Test modules and packages can customize test loading and discovery by through
156+
the `load_tests protocol`_.
90157

91158
.. _unittest-minimal-example:
92159

@@ -175,7 +242,6 @@ The above examples show the most commonly used :mod:`unittest` features which
175242
are sufficient to meet many everyday testing needs. The remainder of the
176243
documentation explores the full feature set from first principles.
177244

178-
179245
.. _organizing-tests:
180246

181247
Organizing test code
@@ -206,13 +272,12 @@ The simplest :class:`TestCase` subclass will simply override the
206272
self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
207273

208274
Note that in order to test something, we use the one of the :meth:`assert\*`
209-
methods provided by the :class:`TestCase` base class. If the
210-
test fails, an exception will be raised, and :mod:`unittest` will identify the
211-
test case as a :dfn:`failure`. Any other exceptions will be treated as
212-
:dfn:`errors`. This helps you identify where the problem is: :dfn:`failures` are
213-
caused by incorrect results - a 5 where you expected a 6. :dfn:`Errors` are
214-
caused by incorrect code - e.g., a :exc:`TypeError` caused by an incorrect
215-
function call.
275+
methods provided by the :class:`TestCase` base class. If the test fails, an
276+
exception will be raised, and :mod:`unittest` will identify the test case as a
277+
:dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This
278+
helps you identify where the problem is: :dfn:`failures` are caused by incorrect
279+
results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
280+
code - e.g., a :exc:`TypeError` caused by an incorrect function call.
216281

217282
The way to run a test case will be described later. For now, note that to
218283
construct an instance of such a test case, we call its constructor without
@@ -412,10 +477,10 @@ may treat :exc:`AssertionError` differently.
412477

413478
.. note::
414479

415-
Even though :class:`FunctionTestCase` can be used to quickly convert an existing
416-
test base over to a :mod:`unittest`\ -based system, this approach is not
417-
recommended. Taking the time to set up proper :class:`TestCase` subclasses will
418-
make future test refactorings infinitely easier.
480+
Even though :class:`FunctionTestCase` can be used to quickly convert an
481+
existing test base over to a :mod:`unittest`\ -based system, this approach is
482+
not recommended. Taking the time to set up proper :class:`TestCase`
483+
subclasses will make future test refactorings infinitely easier.
419484

420485
In some cases, the existing tests may have been written using the :mod:`doctest`
421486
module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
@@ -444,7 +509,8 @@ Basic skipping looks like this: ::
444509
def test_nothing(self):
445510
self.fail("shouldn't happen")
446511

447-
@unittest.skipIf(mylib.__version__ < (1, 3), "not supported in this library version")
512+
@unittest.skipIf(mylib.__version__ < (1, 3),
513+
"not supported in this library version")
448514
def test_format(self):
449515
# Tests that work for only a certain version of the library.
450516
pass
@@ -1009,10 +1075,10 @@ Test cases
10091075
.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]])
10101076

10111077
This class implements the portion of the :class:`TestCase` interface which
1012-
allows the test runner to drive the test, but does not provide the methods which
1013-
test code can use to check and report errors. This is used to create test cases
1014-
using legacy test code, allowing it to be integrated into a :mod:`unittest`\
1015-
-based test framework.
1078+
allows the test runner to drive the test, but does not provide the methods
1079+
which test code can use to check and report errors. This is used to create
1080+
test cases using legacy test code, allowing it to be integrated into a
1081+
:mod:`unittest`-based test framework.
10161082

10171083

10181084
.. _testsuite-objects:
@@ -1047,8 +1113,8 @@ Grouping tests
10471113
Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
10481114
instances to this test suite.
10491115

1050-
This is equivalent to iterating over *tests*, calling :meth:`addTest` for each
1051-
element.
1116+
This is equivalent to iterating over *tests*, calling :meth:`addTest` for
1117+
each element.
10521118

10531119
:class:`TestSuite` shares the following methods with :class:`TestCase`:
10541120

@@ -1126,6 +1192,13 @@ Loading and running tests
11261192
directly does not play well with this method. Doing so, however, can
11271193
be useful when the fixtures are different and defined in subclasses.
11281194

1195+
If a module provides a ``load_tests`` function it will be called to
1196+
load the tests. This allows modules to customize test loading.
1197+
This is the `load_tests protocol`_.
1198+
1199+
.. versionchanged:: 2.7
1200+
Support for ``load_tests`` added.
1201+
11291202

11301203
.. method:: loadTestsFromName(name[, module])
11311204

@@ -1142,12 +1215,12 @@ Loading and running tests
11421215
For example, if you have a module :mod:`SampleTests` containing a
11431216
:class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
11441217
methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
1145-
specifier ``'SampleTests.SampleTestCase'`` would cause this method to return a
1146-
suite which will run all three test methods. Using the specifier
1147-
``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test suite
1148-
which will run only the :meth:`test_two` test method. The specifier can refer
1149-
to modules and packages which have not been imported; they will be imported as a
1150-
side-effect.
1218+
specifier ``'SampleTests.SampleTestCase'`` would cause this method to
1219+
return a suite which will run all three test methods. Using the specifier
1220+
``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
1221+
suite which will run only the :meth:`test_two` test method. The specifier
1222+
can refer to modules and packages which have not been imported; they will
1223+
be imported as a side-effect.
11511224

11521225
The method optionally resolves *name* relative to the given *module*.
11531226

@@ -1164,6 +1237,31 @@ Loading and running tests
11641237
Return a sorted sequence of method names found within *testCaseClass*;
11651238
this should be a subclass of :class:`TestCase`.
11661239

1240+
1241+
.. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)
1242+
1243+
Find and return all test modules from the specified start directory,
1244+
recursing into subdirectories to find them. Only test files that match
1245+
*pattern* will be loaded. (Using shell style pattern matching.)
1246+
1247+
All test modules must be importable from the top level of the project. If
1248+
the start directory is not the top level directory then the top level
1249+
directory must be specified separately.
1250+
1251+
If a test package name (directory with :file:`__init__.py`) matches the
1252+
pattern then the package will be checked for a ``load_tests``
1253+
function. If this exists then it will be called with *loader*, *tests*,
1254+
*pattern*.
1255+
1256+
If load_tests exists then discovery does *not* recurse into the package,
1257+
``load_tests`` is responsible for loading all tests in the package.
1258+
1259+
The pattern is deliberately not stored as a loader attribute so that
1260+
packages can continue discovery themselves. *top_level_dir* is stored so
1261+
``load_tests`` does not need to pass this argument in to
1262+
``loader.discover()``.
1263+
1264+
11671265
The following attributes of a :class:`TestLoader` can be configured either by
11681266
subclassing or assignment on an instance:
11691267

@@ -1319,8 +1417,8 @@ Loading and running tests
13191417

13201418
.. method:: addFailure(test, err)
13211419

1322-
Called when the test case *test* signals a failure. *err* is a tuple of the form
1323-
returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
1420+
Called when the test case *test* signals a failure. *err* is a tuple of
1421+
the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.
13241422

13251423
The default implementation appends a tuple ``(test, formatted_err)`` to
13261424
the instance's :attr:`failures` attribute, where *formatted_err* is a
@@ -1382,7 +1480,7 @@ Loading and running tests
13821480
subclasses to provide a custom ``TestResult``.
13831481

13841482

1385-
.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit]]]]]])
1483+
.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit, [verbosity]]]]]]])
13861484

13871485
A command-line program that runs a set of tests; this is primarily for making
13881486
test modules conveniently executable. The simplest use for this function is to
@@ -1391,6 +1489,12 @@ Loading and running tests
13911489
if __name__ == '__main__':
13921490
unittest.main()
13931491

1492+
You can run tests with more detailed information by passing in the verbosity
1493+
argument::
1494+
1495+
if __name__ == '__main__':
1496+
unittest.main(verbosity=2)
1497+
13941498
The *testRunner* argument can either be a test runner class or an already
13951499
created instance of it. By default ``main`` calls :func:`sys.exit` with
13961500
an exit code indicating success or failure of the tests run.
@@ -1406,4 +1510,69 @@ Loading and running tests
14061510
This stores the result of the tests run as the ``result`` attribute.
14071511

14081512
.. versionchanged:: 2.7
1409-
The ``exit`` parameter was added.
1513+
The ``exit`` and ``verbosity`` parameters were added.
1514+
1515+
1516+
load_tests Protocol
1517+
###################
1518+
1519+
Modules or packages can customize how tests are loaded from them during normal
1520+
test runs or test discovery by implementing a function called ``load_tests``.
1521+
1522+
If a test module defines ``load_tests`` it will be called by
1523+
:meth:`TestLoader.loadTestsFromModule` with the following arguments::
1524+
1525+
load_tests(loader, standard_tests, None)
1526+
1527+
It should return a :class:`TestSuite`.
1528+
1529+
*loader* is the instance of :class:`TestLoader` doing the loading.
1530+
*standard_tests* are the tests that would be loaded by default from the
1531+
module. It is common for test modules to only want to add or remove tests
1532+
from the standard set of tests.
1533+
The third argument is used when loading packages as part of test discovery.
1534+
1535+
A typical ``load_tests`` function that loads tests from a specific set of
1536+
:class:`TestCase` classes may look like::
1537+
1538+
test_cases = (TestCase1, TestCase2, TestCase3)
1539+
1540+
def load_tests(loader, tests, pattern):
1541+
suite = TestSuite()
1542+
for test_class in test_cases:
1543+
tests = loader.loadTestsFromTestCase(test_class)
1544+
suite.addTests(tests)
1545+
return suite
1546+
1547+
If discovery is started, either from the command line or by calling
1548+
:meth:`TestLoader.discover`, with a pattern that matches a package
1549+
name then the package :file:`__init__.py` will be checked for ``load_tests``.
1550+
1551+
.. note::
1552+
1553+
The default pattern is 'test*.py'. This matches all python files
1554+
that start with 'test' but *won't* match any test directories.
1555+
1556+
A pattern like 'test*' will match test packages as well as
1557+
modules.
1558+
1559+
If the package :file:`__init__.py` defines ``load_tests`` then it will be
1560+
called and discovery not continued into the package. ``load_tests``
1561+
is called with the following arguments::
1562+
1563+
load_tests(loader, standard_tests, pattern)
1564+
1565+
This should return a :class:`TestSuite` representing all the tests
1566+
from the package. (``standard_tests`` will only contain tests
1567+
collected from :file:`__init__.py`.)
1568+
1569+
Because the pattern is passed into ``load_tests`` the package is free to
1570+
continue (and potentially modify) test discovery. A 'do nothing'
1571+
``load_tests`` function for a test package would look like::
1572+
1573+
def load_tests(loader, standard_tests, pattern):
1574+
# top level directory cached on loader instance
1575+
this_dir = os.path.dirname(__file__)
1576+
package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
1577+
standard_tests.addTests(package_tests)
1578+
return standard_tests

0 commit comments

Comments
 (0)