blob: 9f013f80589b60b090d8ebf9aa3dcde138402478 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`test` --- Regression tests package for Python
2===================================================
3
4.. module:: test
5 :synopsis: Regression tests package containing the testing suite for Python.
6.. sectionauthor:: Brett Cannon <brett@python.org>
7
8
9The :mod:`test` package contains all regression tests for Python as well as the
Nick Coghlan47384702009-04-22 16:13:36 +000010modules :mod:`test.support` and :mod:`test.regrtest`.
11:mod:`test.support` is used to enhance your tests while
Georg Brandl116aa622007-08-15 14:28:22 +000012:mod:`test.regrtest` drives the testing suite.
13
14Each module in the :mod:`test` package whose name starts with ``test_`` is a
15testing suite for a specific module or feature. All new tests should be written
16using the :mod:`unittest` or :mod:`doctest` module. Some older tests are
17written using a "traditional" testing style that compares output printed to
18``sys.stdout``; this style of test is considered deprecated.
19
20
21.. seealso::
22
23 Module :mod:`unittest`
24 Writing PyUnit regression tests.
25
26 Module :mod:`doctest`
27 Tests embedded in documentation strings.
28
29
30.. _writing-tests:
31
32Writing Unit Tests for the :mod:`test` package
33----------------------------------------------
34
Georg Brandl116aa622007-08-15 14:28:22 +000035It is preferred that tests that use the :mod:`unittest` module follow a few
36guidelines. One is to name the test module by starting it with ``test_`` and end
37it with the name of the module being tested. The test methods in the test module
38should start with ``test_`` and end with a description of what the method is
39testing. This is needed so that the methods are recognized by the test driver as
40test methods. Also, no documentation string for the method should be included. A
41comment (such as ``# Tests function returns only True or False``) should be used
42to provide documentation for test methods. This is done because documentation
43strings get printed out if they exist and thus what test is being run is not
44stated.
45
46A basic boilerplate is often used::
47
48 import unittest
Nick Coghlan47384702009-04-22 16:13:36 +000049 from test import support
Georg Brandl116aa622007-08-15 14:28:22 +000050
51 class MyTestCase1(unittest.TestCase):
52
53 # Only use setUp() and tearDown() if necessary
54
55 def setUp(self):
56 ... code to execute in preparation for tests ...
57
58 def tearDown(self):
59 ... code to execute to clean up after tests ...
60
61 def test_feature_one(self):
62 # Test feature one.
63 ... testing code ...
64
65 def test_feature_two(self):
66 # Test feature two.
67 ... testing code ...
68
69 ... more test methods ...
70
71 class MyTestCase2(unittest.TestCase):
72 ... same structure as MyTestCase1 ...
73
74 ... more test classes ...
75
76 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +000077 support.run_unittest(MyTestCase1,
Georg Brandl116aa622007-08-15 14:28:22 +000078 MyTestCase2,
79 ... list other tests ...
80 )
81
82 if __name__ == '__main__':
83 test_main()
84
85This boilerplate code allows the testing suite to be run by :mod:`test.regrtest`
86as well as on its own as a script.
87
88The goal for regression testing is to try to break code. This leads to a few
89guidelines to be followed:
90
91* The testing suite should exercise all classes, functions, and constants. This
Florent Xicluna53b506b2010-03-18 20:00:57 +000092 includes not just the external API that is to be presented to the outside
93 world but also "private" code.
Georg Brandl116aa622007-08-15 14:28:22 +000094
95* Whitebox testing (examining the code being tested when the tests are being
96 written) is preferred. Blackbox testing (testing only the published user
Florent Xicluna53b506b2010-03-18 20:00:57 +000097 interface) is not complete enough to make sure all boundary and edge cases
98 are tested.
Georg Brandl116aa622007-08-15 14:28:22 +000099
100* Make sure all possible values are tested including invalid ones. This makes
Florent Xicluna53b506b2010-03-18 20:00:57 +0000101 sure that not only all valid values are acceptable but also that improper
102 values are handled correctly.
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104* Exhaust as many code paths as possible. Test where branching occurs and thus
105 tailor input to make sure as many different paths through the code are taken.
106
107* Add an explicit test for any bugs discovered for the tested code. This will
108 make sure that the error does not crop up again if the code is changed in the
109 future.
110
111* Make sure to clean up after your tests (such as close and remove all temporary
112 files).
113
114* If a test is dependent on a specific condition of the operating system then
115 verify the condition already exists before attempting the test.
116
117* Import as few modules as possible and do it as soon as possible. This
118 minimizes external dependencies of tests and also minimizes possible anomalous
119 behavior from side-effects of importing a module.
120
121* Try to maximize code reuse. On occasion, tests will vary by something as small
Florent Xicluna53b506b2010-03-18 20:00:57 +0000122 as what type of input is used. Minimize code duplication by subclassing a
123 basic test class with a class that specifies the input::
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125 class TestFuncAcceptsSequences(unittest.TestCase):
126
127 func = mySuperWhammyFunction
128
129 def test_func(self):
130 self.func(self.arg)
131
132 class AcceptLists(TestFuncAcceptsSequences):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000133 arg = [1, 2, 3]
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135 class AcceptStrings(TestFuncAcceptsSequences):
136 arg = 'abc'
137
138 class AcceptTuples(TestFuncAcceptsSequences):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000139 arg = (1, 2, 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141
142.. seealso::
143
144 Test Driven Development
145 A book by Kent Beck on writing tests before code.
146
147
148.. _regrtest:
149
150Running tests using :mod:`test.regrtest`
151----------------------------------------
152
153:mod:`test.regrtest` can be used as a script to drive Python's regression test
154suite. Running the script by itself automatically starts running all regression
155tests in the :mod:`test` package. It does this by finding all modules in the
156package whose name starts with ``test_``, importing them, and executing the
Florent Xicluna53b506b2010-03-18 20:00:57 +0000157function :func:`test_main` if present. The names of tests to execute may also
158be passed to the script. Specifying a single regression test (:program:`python
159regrtest.py` :option:`test_spam.py`) will minimize output and only print
160whether the test passed or failed and thus minimize output.
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162Running :mod:`test.regrtest` directly allows what resources are available for
163tests to use to be set. You do this by using the :option:`-u` command-line
164option. Run :program:`python regrtest.py` :option:`-uall` to turn on all
165resources; specifying :option:`all` as an option for :option:`-u` enables all
166possible resources. If all but one resource is desired (a more common case), a
167comma-separated list of resources that are not desired may be listed after
168:option:`all`. The command :program:`python regrtest.py`
169:option:`-uall,-audio,-largefile` will run :mod:`test.regrtest` with all
170resources except the :option:`audio` and :option:`largefile` resources. For a
171list of all resources and more command-line options, run :program:`python
172regrtest.py` :option:`-h`.
173
174Some other ways to execute the regression tests depend on what platform the
Florent Xicluna53b506b2010-03-18 20:00:57 +0000175tests are being executed on. On Unix, you can run :program:`make`
176:option:`test` at the top-level directory where Python was built. On Windows,
177executing :program:`rt.bat` from your :file:`PCBuild` directory will run all
178regression tests.
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000181:mod:`test.support` --- Utility functions for tests
Georg Brandl7f01a132009-09-16 15:58:14 +0000182===================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000183
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000184.. module:: test.support
Georg Brandl116aa622007-08-15 14:28:22 +0000185 :synopsis: Support for Python regression tests.
186
187
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000188The :mod:`test.support` module provides support for Python's regression
Georg Brandl116aa622007-08-15 14:28:22 +0000189tests.
190
191This module defines the following exceptions:
192
193
194.. exception:: TestFailed
195
196 Exception to be raised when a test fails. This is deprecated in favor of
197 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
198 methods.
199
200
Georg Brandl116aa622007-08-15 14:28:22 +0000201.. exception:: ResourceDenied
202
Florent Xicluna53b506b2010-03-18 20:00:57 +0000203 Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a
204 network connection) is not available. Raised by the :func:`requires`
205 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000206
Nick Coghlanb1304932008-07-13 12:25:08 +0000207The :mod:`test.support` module defines the following constants:
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209
210.. data:: verbose
211
212 :const:`True` when verbose output is enabled. Should be checked when more
213 detailed information is desired about a running test. *verbose* is set by
214 :mod:`test.regrtest`.
215
216
Georg Brandl116aa622007-08-15 14:28:22 +0000217.. data:: is_jython
218
219 :const:`True` if the running interpreter is Jython.
220
221
222.. data:: TESTFN
223
Florent Xiclunab14930c2010-03-13 15:26:44 +0000224 Set to the name that a temporary file could use. Any temporary file that is
Georg Brandl116aa622007-08-15 14:28:22 +0000225 created should be closed and unlinked (removed).
226
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000227The :mod:`test.support` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229
230.. function:: forget(module_name)
231
Florent Xiclunab14930c2010-03-13 15:26:44 +0000232 Remove the module named *module_name* from ``sys.modules`` and deletes any
Georg Brandl116aa622007-08-15 14:28:22 +0000233 byte-compiled files of the module.
234
235
236.. function:: is_resource_enabled(resource)
237
Florent Xiclunab14930c2010-03-13 15:26:44 +0000238 Return :const:`True` if *resource* is enabled and available. The list of
Georg Brandl116aa622007-08-15 14:28:22 +0000239 available resources is only set when :mod:`test.regrtest` is executing the
240 tests.
241
242
Georg Brandl7f01a132009-09-16 15:58:14 +0000243.. function:: requires(resource, msg=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000244
Florent Xiclunab14930c2010-03-13 15:26:44 +0000245 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
Florent Xicluna53b506b2010-03-18 20:00:57 +0000246 argument to :exc:`ResourceDenied` if it is raised. Always returns
247 :const:`True` if called by a function whose ``__name__`` is ``'__main__'``.
248 Used when tests are executed by :mod:`test.regrtest`.
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250
251.. function:: findfile(filename)
252
Florent Xicluna53b506b2010-03-18 20:00:57 +0000253 Return the path to the file named *filename*. If no match is found
254 *filename* is returned. This does not equal a failure since it could be the
255 path to the file.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257
258.. function:: run_unittest(*classes)
259
260 Execute :class:`unittest.TestCase` subclasses passed to the function. The
Florent Xicluna53b506b2010-03-18 20:00:57 +0000261 function scans the classes for methods starting with the prefix ``test_``
262 and executes the tests individually.
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264 It is also legal to pass strings as parameters; these should be keys in
265 ``sys.modules``. Each associated module will be scanned by
266 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
267 following :func:`test_main` function::
268
269 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +0000270 support.run_unittest(__name__)
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272 This will run all tests defined in the named module.
273
Georg Brandl116aa622007-08-15 14:28:22 +0000274
Florent Xicluna53b506b2010-03-18 20:00:57 +0000275.. function:: check_warnings(*filters, quiet=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000276
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000277 A convenience wrapper for ``warnings.catch_warnings()`` that makes
278 it easier to test that a warning was correctly raised with a single
279 assertion. It is approximately equivalent to calling
280 ``warnings.catch_warnings(record=True)``.
281
Florent Xiclunab14930c2010-03-13 15:26:44 +0000282 It accepts 2-tuples ``("message regexp", WarningCategory)`` as positional
Florent Xicluna53b506b2010-03-18 20:00:57 +0000283 arguments. If there's some ``*filters`` defined, or if the optional keyword
284 argument ``quiet`` is :const:`False`, it checks if the warnings are
285 effective. If some filter did not catch any warning, the test fails. If some
286 warnings are not caught, the test fails, too. To disable these checks, set
287 argument ``quiet`` to :const:`True`.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000288
Florent Xicluna53b506b2010-03-18 20:00:57 +0000289 Without argument, it defaults to::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000290
Florent Xicluna53b506b2010-03-18 20:00:57 +0000291 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000292
Florent Xicluna53b506b2010-03-18 20:00:57 +0000293 Additionally, on entry to the context manager, a :class:`WarningRecorder`
294 instance is returned. The underlying warnings list is available via the
295 recorder object's :attr:`warnings` attribute, while the attributes of the
296 last raised warning are also accessible directly on the object. If no
297 warning has been raised, then the latter attributes will all be
298 :const:`None`.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000299
300 A :meth:`reset` method is also provided on the recorder object. This
Florent Xicluna53b506b2010-03-18 20:00:57 +0000301 method simply clears the warnings list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000302
Florent Xiclunab14930c2010-03-13 15:26:44 +0000303 The context manager may be used like this::
Thomas Woutersed03b412007-08-28 21:37:11 +0000304
Florent Xiclunab14930c2010-03-13 15:26:44 +0000305 import warnings
306
Florent Xicluna53b506b2010-03-18 20:00:57 +0000307 with check_warnings(quiet=False):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000308 exec('assert(False, "Hey!")')
309 warnings.warn(UserWarning("Hide me!"))
310
311 with check_warnings(("assertion is always true", SyntaxWarning),
312 ("", UserWarning)):
313 exec('assert(False, "Hey!")')
314 warnings.warn(UserWarning("Hide me!"))
315
316 with check_warnings(quiet=True) as w:
Nick Coghlanb1304932008-07-13 12:25:08 +0000317 warnings.simplefilter("always")
Thomas Woutersed03b412007-08-28 21:37:11 +0000318 warnings.warn("foo")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000319 assert str(w.args[0]) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000320 warnings.warn("bar")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000321 assert str(w.args[0]) == "bar"
322 assert str(w.warnings[0].args[0]) == "foo"
323 assert str(w.warnings[1].args[0]) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000324 w.reset()
325 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000326
Ezio Melottif8754a62010-03-21 07:16:43 +0000327 .. versionchanged:: 3.2
Florent Xiclunab14930c2010-03-13 15:26:44 +0000328 New optional attributes ``*filters`` and ``quiet``.
329
Thomas Woutersed03b412007-08-28 21:37:11 +0000330
331.. function:: captured_stdout()
332
333 This is a context manager than runs the :keyword:`with` statement body using
334 a :class:`StringIO.StringIO` object as sys.stdout. That object can be
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000335 retrieved using the ``as`` clause of the :keyword:`with` statement.
Thomas Woutersed03b412007-08-28 21:37:11 +0000336
337 Example use::
338
339 with captured_stdout() as s:
Collin Winterc79461b2007-09-01 23:34:30 +0000340 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000341 assert s.getvalue() == "hello"
342
Thomas Woutersed03b412007-08-28 21:37:11 +0000343
Nick Coghlanfce769e2009-04-11 14:30:59 +0000344.. function:: import_module(name, deprecated=False)
345
346 This function imports and returns the named module. Unlike a normal
347 import, this function raises :exc:`unittest.SkipTest` if the module
348 cannot be imported.
349
350 Module and package deprecation messages are suppressed during this import
351 if *deprecated* is :const:`True`.
352
353 .. versionadded:: 3.1
354
355
Nick Coghlan47384702009-04-22 16:13:36 +0000356.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000357
Nick Coghlan47384702009-04-22 16:13:36 +0000358 This function imports and returns a fresh copy of the named Python module
359 by removing the named module from ``sys.modules`` before doing the import.
360 Note that unlike :func:`reload`, the original module is not affected by
361 this operation.
362
363 *fresh* is an iterable of additional module names that are also removed
364 from the ``sys.modules`` cache before doing the import.
365
366 *blocked* is an iterable of module names that are replaced with :const:`0`
367 in the module cache during the import to ensure that attempts to import
368 them raise :exc:`ImportError`.
369
370 The named module and any modules named in the *fresh* and *blocked*
371 parameters are saved before starting the import and then reinserted into
372 ``sys.modules`` when the fresh import is complete.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000373
374 Module and package deprecation messages are suppressed during this import
375 if *deprecated* is :const:`True`.
376
Nick Coghlan47384702009-04-22 16:13:36 +0000377 This function will raise :exc:`unittest.SkipTest` is the named module
378 cannot be imported.
379
380 Example use::
381
382 # Get copies of the warnings module for testing without
383 # affecting the version being used by the rest of the test suite
384 # One copy uses the C implementation, the other is forced to use
385 # the pure Python fallback implementation
386 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
387 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
388
Nick Coghlanfce769e2009-04-11 14:30:59 +0000389 .. versionadded:: 3.1
390
391
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000392The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +0000393
Georg Brandl7f01a132009-09-16 15:58:14 +0000394.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396 Instances are a context manager that raises :exc:`ResourceDenied` if the
397 specified exception type is raised. Any keyword arguments are treated as
398 attribute/value pairs to be compared against any exception raised within the
399 :keyword:`with` statement. Only if all pairs match properly against
400 attributes on the exception is :exc:`ResourceDenied` raised.
401
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403.. class:: EnvironmentVarGuard()
404
Florent Xicluna53b506b2010-03-18 20:00:57 +0000405 Class used to temporarily set or unset environment variables. Instances can
406 be used as a context manager and have a complete dictionary interface for
407 querying/modifying the underlying ``os.environ``. After exit from the
408 context manager all changes to environment variables done through this
409 instance will be rolled back.
Georg Brandl116aa622007-08-15 14:28:22 +0000410
Georg Brandl705d9d52009-05-05 09:29:50 +0000411 .. versionchanged:: 3.1
Walter Dörwald155374d2009-05-01 19:58:58 +0000412 Added dictionary interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000413
414.. method:: EnvironmentVarGuard.set(envvar, value)
415
Florent Xicluna53b506b2010-03-18 20:00:57 +0000416 Temporarily set the environment variable ``envvar`` to the value of
417 ``value``.
Georg Brandl116aa622007-08-15 14:28:22 +0000418
419
420.. method:: EnvironmentVarGuard.unset(envvar)
421
422 Temporarily unset the environment variable ``envvar``.
Nick Coghlanb1304932008-07-13 12:25:08 +0000423
Walter Dörwald155374d2009-05-01 19:58:58 +0000424
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000425.. class:: WarningsRecorder()
426
427 Class used to record warnings for unit tests. See documentation of
428 :func:`check_warnings` above for more details.