blob: b21e177c0ad4efc7ff9ea45a2f53764d5aa7d987 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`test` --- Regression tests package for Python
3===================================================
4
5.. module:: test
6 :synopsis: Regression tests package containing the testing suite for Python.
7.. sectionauthor:: Brett Cannon <brett@python.org>
8
9
10The :mod:`test` package contains all regression tests for Python as well as the
11modules :mod:`test.test_support` and :mod:`test.regrtest`.
12:mod:`test.test_support` is used to enhance your tests while
13:mod:`test.regrtest` drives the testing suite.
14
15Each module in the :mod:`test` package whose name starts with ``test_`` is a
16testing suite for a specific module or feature. All new tests should be written
17using the :mod:`unittest` or :mod:`doctest` module. Some older tests are
18written using a "traditional" testing style that compares output printed to
19``sys.stdout``; this style of test is considered deprecated.
20
21
22.. seealso::
23
24 Module :mod:`unittest`
25 Writing PyUnit regression tests.
26
27 Module :mod:`doctest`
28 Tests embedded in documentation strings.
29
30
31.. _writing-tests:
32
33Writing Unit Tests for the :mod:`test` package
34----------------------------------------------
35
Georg Brandl8ec7f652007-08-15 14:28:01 +000036It is preferred that tests that use the :mod:`unittest` module follow a few
37guidelines. One is to name the test module by starting it with ``test_`` and end
38it with the name of the module being tested. The test methods in the test module
39should start with ``test_`` and end with a description of what the method is
40testing. This is needed so that the methods are recognized by the test driver as
41test methods. Also, no documentation string for the method should be included. A
42comment (such as ``# Tests function returns only True or False``) should be used
43to provide documentation for test methods. This is done because documentation
44strings get printed out if they exist and thus what test is being run is not
45stated.
46
47A basic boilerplate is often used::
48
49 import unittest
50 from test import test_support
51
52 class MyTestCase1(unittest.TestCase):
53
54 # Only use setUp() and tearDown() if necessary
55
56 def setUp(self):
57 ... code to execute in preparation for tests ...
58
59 def tearDown(self):
60 ... code to execute to clean up after tests ...
61
62 def test_feature_one(self):
63 # Test feature one.
64 ... testing code ...
65
66 def test_feature_two(self):
67 # Test feature two.
68 ... testing code ...
69
70 ... more test methods ...
71
72 class MyTestCase2(unittest.TestCase):
73 ... same structure as MyTestCase1 ...
74
75 ... more test classes ...
76
77 def test_main():
78 test_support.run_unittest(MyTestCase1,
79 MyTestCase2,
80 ... list other tests ...
81 )
82
83 if __name__ == '__main__':
84 test_main()
85
86This boilerplate code allows the testing suite to be run by :mod:`test.regrtest`
87as well as on its own as a script.
88
89The goal for regression testing is to try to break code. This leads to a few
90guidelines to be followed:
91
92* The testing suite should exercise all classes, functions, and constants. This
Florent Xicluna73588542010-03-18 19:51:47 +000093 includes not just the external API that is to be presented to the outside
94 world but also "private" code.
Georg Brandl8ec7f652007-08-15 14:28:01 +000095
96* Whitebox testing (examining the code being tested when the tests are being
97 written) is preferred. Blackbox testing (testing only the published user
Florent Xicluna73588542010-03-18 19:51:47 +000098 interface) is not complete enough to make sure all boundary and edge cases
99 are tested.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000100
101* Make sure all possible values are tested including invalid ones. This makes
Florent Xicluna73588542010-03-18 19:51:47 +0000102 sure that not only all valid values are acceptable but also that improper
103 values are handled correctly.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000104
105* Exhaust as many code paths as possible. Test where branching occurs and thus
106 tailor input to make sure as many different paths through the code are taken.
107
108* Add an explicit test for any bugs discovered for the tested code. This will
109 make sure that the error does not crop up again if the code is changed in the
110 future.
111
112* Make sure to clean up after your tests (such as close and remove all temporary
113 files).
114
115* If a test is dependent on a specific condition of the operating system then
116 verify the condition already exists before attempting the test.
117
118* Import as few modules as possible and do it as soon as possible. This
119 minimizes external dependencies of tests and also minimizes possible anomalous
120 behavior from side-effects of importing a module.
121
122* Try to maximize code reuse. On occasion, tests will vary by something as small
Florent Xicluna73588542010-03-18 19:51:47 +0000123 as what type of input is used. Minimize code duplication by subclassing a
124 basic test class with a class that specifies the input::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000125
126 class TestFuncAcceptsSequences(unittest.TestCase):
127
128 func = mySuperWhammyFunction
129
130 def test_func(self):
131 self.func(self.arg)
132
133 class AcceptLists(TestFuncAcceptsSequences):
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000134 arg = [1, 2, 3]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000135
136 class AcceptStrings(TestFuncAcceptsSequences):
137 arg = 'abc'
138
139 class AcceptTuples(TestFuncAcceptsSequences):
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000140 arg = (1, 2, 3)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000141
142
143.. seealso::
144
145 Test Driven Development
146 A book by Kent Beck on writing tests before code.
147
148
149.. _regrtest:
150
151Running tests using :mod:`test.regrtest`
152----------------------------------------
153
154:mod:`test.regrtest` can be used as a script to drive Python's regression test
155suite. Running the script by itself automatically starts running all regression
156tests in the :mod:`test` package. It does this by finding all modules in the
157package whose name starts with ``test_``, importing them, and executing the
Florent Xicluna73588542010-03-18 19:51:47 +0000158function :func:`test_main` if present. The names of tests to execute may also
159be passed to the script. Specifying a single regression test (:program:`python
160regrtest.py` :option:`test_spam.py`) will minimize output and only print
161whether the test passed or failed and thus minimize output.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000162
163Running :mod:`test.regrtest` directly allows what resources are available for
164tests to use to be set. You do this by using the :option:`-u` command-line
165option. Run :program:`python regrtest.py` :option:`-uall` to turn on all
166resources; specifying :option:`all` as an option for :option:`-u` enables all
167possible resources. If all but one resource is desired (a more common case), a
168comma-separated list of resources that are not desired may be listed after
169:option:`all`. The command :program:`python regrtest.py`
170:option:`-uall,-audio,-largefile` will run :mod:`test.regrtest` with all
171resources except the :option:`audio` and :option:`largefile` resources. For a
172list of all resources and more command-line options, run :program:`python
173regrtest.py` :option:`-h`.
174
175Some other ways to execute the regression tests depend on what platform the
Florent Xicluna73588542010-03-18 19:51:47 +0000176tests are being executed on. On Unix, you can run :program:`make`
177:option:`test` at the top-level directory where Python was built. On Windows,
178executing :program:`rt.bat` from your :file:`PCBuild` directory will run all
179regression tests.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000180
181
182:mod:`test.test_support` --- Utility functions for tests
183========================================================
184
185.. module:: test.test_support
186 :synopsis: Support for Python regression tests.
187
Brett Cannone76e4d72008-05-20 22:08:20 +0000188.. note::
189
190 The :mod:`test.test_support` module has been renamed to :mod:`test.support`
Benjamin Peterson9b14ae82010-05-28 03:10:31 +0000191 in Python 3.x.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000192
193The :mod:`test.test_support` module provides support for Python's regression
194tests.
195
196This module defines the following exceptions:
197
198
199.. exception:: TestFailed
200
201 Exception to be raised when a test fails. This is deprecated in favor of
202 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
203 methods.
204
205
Georg Brandl8ec7f652007-08-15 14:28:01 +0000206.. exception:: ResourceDenied
207
Florent Xicluna73588542010-03-18 19:51:47 +0000208 Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a
209 network connection) is not available. Raised by the :func:`requires`
210 function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000211
212The :mod:`test.test_support` module defines the following constants:
213
214
215.. data:: verbose
216
217 :const:`True` when verbose output is enabled. Should be checked when more
218 detailed information is desired about a running test. *verbose* is set by
219 :mod:`test.regrtest`.
220
221
222.. data:: have_unicode
223
224 :const:`True` when Unicode support is available.
225
226
227.. data:: is_jython
228
229 :const:`True` if the running interpreter is Jython.
230
231
232.. data:: TESTFN
233
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000234 Set to a name that is safe to use as the name of a temporary file. Any
235 temporary file that is created should be closed and unlinked (removed).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000236
237The :mod:`test.test_support` module defines the following functions:
238
239
240.. function:: forget(module_name)
241
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000242 Remove the module named *module_name* from ``sys.modules`` and delete any
Georg Brandl8ec7f652007-08-15 14:28:01 +0000243 byte-compiled files of the module.
244
245
246.. function:: is_resource_enabled(resource)
247
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000248 Return :const:`True` if *resource* is enabled and available. The list of
Georg Brandl8ec7f652007-08-15 14:28:01 +0000249 available resources is only set when :mod:`test.regrtest` is executing the
250 tests.
251
252
253.. function:: requires(resource[, msg])
254
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000255 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
Florent Xicluna73588542010-03-18 19:51:47 +0000256 argument to :exc:`ResourceDenied` if it is raised. Always returns
257 :const:`True` if called by a function whose ``__name__`` is ``'__main__'``.
258 Used when tests are executed by :mod:`test.regrtest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000259
260
261.. function:: findfile(filename)
262
Florent Xicluna73588542010-03-18 19:51:47 +0000263 Return the path to the file named *filename*. If no match is found
264 *filename* is returned. This does not equal a failure since it could be the
265 path to the file.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000266
267
268.. function:: run_unittest(*classes)
269
270 Execute :class:`unittest.TestCase` subclasses passed to the function. The
Florent Xicluna73588542010-03-18 19:51:47 +0000271 function scans the classes for methods starting with the prefix ``test_``
272 and executes the tests individually.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000273
274 It is also legal to pass strings as parameters; these should be keys in
275 ``sys.modules``. Each associated module will be scanned by
276 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
277 following :func:`test_main` function::
278
279 def test_main():
280 test_support.run_unittest(__name__)
281
282 This will run all tests defined in the named module.
283
Georg Brandl8ec7f652007-08-15 14:28:01 +0000284
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000285.. function:: check_warnings(*filters, quiet=True)
Georg Brandld558f672007-08-24 18:27:43 +0000286
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000287 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
288 easier to test that a warning was correctly raised. It is approximately
289 equivalent to calling ``warnings.catch_warnings(record=True)`` with
290 :meth:`warnings.simplefilter` set to ``always`` and with the option to
291 automatically validate the results that are recorded.
Nick Coghland2e09382008-09-11 12:11:06 +0000292
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000293 ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
294 WarningCategory)`` as positional arguments. If one or more *filters* are
295 provided, or if the optional keyword argument *quiet* is :const:`False`,
296 it checks to make sure the warnings are as expected: each specified filter
297 must match at least one of the warnings raised by the enclosed code or the
298 test fails, and if any warnings are raised that do not match any of the
299 specified filters the test fails. To disable the first of these checks,
300 set *quiet* to :const:`True`.
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000301
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000302 If no arguments are specified, it defaults to::
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000303
Florent Xicluna73588542010-03-18 19:51:47 +0000304 check_warnings(("", Warning), quiet=True)
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000305
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000306 In this case all warnings are caught and no errors are raised.
Nick Coghland2e09382008-09-11 12:11:06 +0000307
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000308 On entry to the context manager, a :class:`WarningRecorder` instance is
309 returned. The underlying warnings list from
310 :func:`~warnings.catch_warnings` is available via the recorder object's
311 :attr:`warnings` attribute. As a convenience, the attributes of the object
312 representing the most recent warning can also be accessed directly through
313 the recorder object (see example below). If no warning has been raised,
314 then any of the attributes that would otherwise be expected on an object
315 representing a warning will return :const:`None`.
Georg Brandld558f672007-08-24 18:27:43 +0000316
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000317 The recorder object also has a :meth:`reset` method, which clears the
318 warnings list.
Georg Brandld558f672007-08-24 18:27:43 +0000319
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000320 The context manager is designed to be used like this::
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000321
322 with check_warnings(("assertion is always true", SyntaxWarning),
323 ("", UserWarning)):
324 exec('assert(False, "Hey!")')
325 warnings.warn(UserWarning("Hide me!"))
326
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000327 In this case if either warning was not raised, or some other warning was
328 raised, :func:`check_warnings` would raise an error.
329
330 When a test needs to look more deeply into the warnings, rather than
331 just checking whether or not they occurred, code like this can be used::
332
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000333 with check_warnings(quiet=True) as w:
Georg Brandld558f672007-08-24 18:27:43 +0000334 warnings.warn("foo")
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000335 assert str(w.args[0]) == "foo"
Nick Coghlan38469e22008-07-13 12:23:47 +0000336 warnings.warn("bar")
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000337 assert str(w.args[0]) == "bar"
338 assert str(w.warnings[0].args[0]) == "foo"
339 assert str(w.warnings[1].args[0]) == "bar"
Nick Coghland2e09382008-09-11 12:11:06 +0000340 w.reset()
341 assert len(w.warnings) == 0
Georg Brandld558f672007-08-24 18:27:43 +0000342
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000343 Here all warnings will be caught, and the test code tests the captured
344 warnings directly.
345
Georg Brandld558f672007-08-24 18:27:43 +0000346 .. versionadded:: 2.6
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000347 .. versionchanged:: 2.7
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000348 New optional arguments *filters* and *quiet*.
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000349
350
351.. function:: check_py3k_warnings(*filters, quiet=False)
352
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000353 Similar to :func:`check_warnings`, but for Python 3 compatibility warnings.
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000354 If ``sys.py3kwarning == 1``, it checks if the warning is effectively raised.
R. David Murray6c9fc4c2010-04-01 01:28:39 +0000355 If ``sys.py3kwarning == 0``, it checks that no warning is raised. It
356 accepts 2-tuples of the form ``("message regexp", WarningCategory)`` as
357 positional arguments. When the optional keyword argument *quiet* is
358 :const:`True`, it does not fail if a filter catches nothing. Without
359 arguments, it defaults to::
Florent Xiclunafc8a1ed2010-03-07 19:14:12 +0000360
361 check_py3k_warnings(("", DeprecationWarning), quiet=False)
362
363 .. versionadded:: 2.7
Georg Brandld558f672007-08-24 18:27:43 +0000364
365
366.. function:: captured_stdout()
367
Senthil Kumaran71a63242010-05-18 03:20:43 +0000368 This is a context manager that runs the :keyword:`with` statement body using
Georg Brandld558f672007-08-24 18:27:43 +0000369 a :class:`StringIO.StringIO` object as sys.stdout. That object can be
Andrew M. Kuchlingf15ff462008-01-15 01:29:44 +0000370 retrieved using the ``as`` clause of the :keyword:`with` statement.
Georg Brandld558f672007-08-24 18:27:43 +0000371
372 Example use::
373
374 with captured_stdout() as s:
375 print "hello"
376 assert s.getvalue() == "hello"
377
378 .. versionadded:: 2.6
379
380
Nick Coghlancd2e7042009-04-11 13:31:31 +0000381.. function:: import_module(name, deprecated=False)
382
383 This function imports and returns the named module. Unlike a normal
384 import, this function raises :exc:`unittest.SkipTest` if the module
385 cannot be imported.
386
387 Module and package deprecation messages are suppressed during this import
388 if *deprecated* is :const:`True`.
389
390 .. versionadded:: 2.7
391
392
Nick Coghlan5533ff62009-04-22 15:26:04 +0000393.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlancd2e7042009-04-11 13:31:31 +0000394
Nick Coghlan5533ff62009-04-22 15:26:04 +0000395 This function imports and returns a fresh copy of the named Python module
396 by removing the named module from ``sys.modules`` before doing the import.
397 Note that unlike :func:`reload`, the original module is not affected by
398 this operation.
399
400 *fresh* is an iterable of additional module names that are also removed
401 from the ``sys.modules`` cache before doing the import.
402
403 *blocked* is an iterable of module names that are replaced with :const:`0`
404 in the module cache during the import to ensure that attempts to import
405 them raise :exc:`ImportError`.
406
407 The named module and any modules named in the *fresh* and *blocked*
408 parameters are saved before starting the import and then reinserted into
409 ``sys.modules`` when the fresh import is complete.
Nick Coghlancd2e7042009-04-11 13:31:31 +0000410
411 Module and package deprecation messages are suppressed during this import
412 if *deprecated* is :const:`True`.
413
Nick Coghlan5533ff62009-04-22 15:26:04 +0000414 This function will raise :exc:`unittest.SkipTest` is the named module
415 cannot be imported.
416
417 Example use::
418
419 # Get copies of the warnings module for testing without
420 # affecting the version being used by the rest of the test suite
421 # One copy uses the C implementation, the other is forced to use
422 # the pure Python fallback implementation
423 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
424 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
425
Nick Coghlancd2e7042009-04-11 13:31:31 +0000426 .. versionadded:: 2.7
427
428
Georg Brandld558f672007-08-24 18:27:43 +0000429The :mod:`test.test_support` module defines the following classes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000430
431.. class:: TransientResource(exc[, **kwargs])
432
433 Instances are a context manager that raises :exc:`ResourceDenied` if the
434 specified exception type is raised. Any keyword arguments are treated as
435 attribute/value pairs to be compared against any exception raised within the
436 :keyword:`with` statement. Only if all pairs match properly against
437 attributes on the exception is :exc:`ResourceDenied` raised.
438
439 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000440.. class:: EnvironmentVarGuard()
441
Florent Xicluna73588542010-03-18 19:51:47 +0000442 Class used to temporarily set or unset environment variables. Instances can
443 be used as a context manager and have a complete dictionary interface for
444 querying/modifying the underlying ``os.environ``. After exit from the
445 context manager all changes to environment variables done through this
446 instance will be rolled back.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000447
448 .. versionadded:: 2.6
Walter Dörwald6733bed2009-05-01 17:35:37 +0000449 .. versionchanged:: 2.7
450 Added dictionary interface.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000451
452
453.. method:: EnvironmentVarGuard.set(envvar, value)
454
Florent Xicluna73588542010-03-18 19:51:47 +0000455 Temporarily set the environment variable ``envvar`` to the value of
456 ``value``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000457
458
459.. method:: EnvironmentVarGuard.unset(envvar)
460
461 Temporarily unset the environment variable ``envvar``.
Nick Coghlan38469e22008-07-13 12:23:47 +0000462
Walter Dörwald6733bed2009-05-01 17:35:37 +0000463
Nick Coghland2e09382008-09-11 12:11:06 +0000464.. class:: WarningsRecorder()
465
466 Class used to record warnings for unit tests. See documentation of
467 :func:`check_warnings` above for more details.
468
469 .. versionadded:: 2.6