blob: d8dd46c26e667862b76747ccb3b8e76af49e48b6 [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
92 includes not just the external API that is to be presented to the outside world
93 but also "private" code.
94
95* Whitebox testing (examining the code being tested when the tests are being
96 written) is preferred. Blackbox testing (testing only the published user
97 interface) is not complete enough to make sure all boundary and edge cases are
98 tested.
99
100* Make sure all possible values are tested including invalid ones. This makes
101 sure that not only all valid values are acceptable but also that improper values
102 are handled correctly.
103
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
122 as what type of input is used. Minimize code duplication by subclassing a basic
123 test class with a class that specifies the input::
124
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
157function :func:`test_main` if present. The names of tests to execute may also be
158passed to the script. Specifying a single regression test (:program:`python
159regrtest.py` :option:`test_spam.py`) will minimize output and only print whether
160the test passed or failed and thus minimize output.
161
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
175tests are being executed on. On Unix, you can run :program:`make` :option:`test`
176at the top-level directory where Python was built. On Windows, executing
177:program:`rt.bat` from your :file:`PCBuild` directory will run all regression
178tests.
179
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 Xiclunab14930c2010-03-13 15:26:44 +0000203 Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a network
Georg Brandl116aa622007-08-15 14:28:22 +0000204 connection) is not available. Raised by the :func:`requires` function.
205
Nick Coghlanb1304932008-07-13 12:25:08 +0000206The :mod:`test.support` module defines the following constants:
Georg Brandl116aa622007-08-15 14:28:22 +0000207
208
209.. data:: verbose
210
211 :const:`True` when verbose output is enabled. Should be checked when more
212 detailed information is desired about a running test. *verbose* is set by
213 :mod:`test.regrtest`.
214
215
Georg Brandl116aa622007-08-15 14:28:22 +0000216.. data:: is_jython
217
218 :const:`True` if the running interpreter is Jython.
219
220
221.. data:: TESTFN
222
Florent Xiclunab14930c2010-03-13 15:26:44 +0000223 Set to the name that a temporary file could use. Any temporary file that is
Georg Brandl116aa622007-08-15 14:28:22 +0000224 created should be closed and unlinked (removed).
225
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000226The :mod:`test.support` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000227
228
229.. function:: forget(module_name)
230
Florent Xiclunab14930c2010-03-13 15:26:44 +0000231 Remove the module named *module_name* from ``sys.modules`` and deletes any
Georg Brandl116aa622007-08-15 14:28:22 +0000232 byte-compiled files of the module.
233
234
235.. function:: is_resource_enabled(resource)
236
Florent Xiclunab14930c2010-03-13 15:26:44 +0000237 Return :const:`True` if *resource* is enabled and available. The list of
Georg Brandl116aa622007-08-15 14:28:22 +0000238 available resources is only set when :mod:`test.regrtest` is executing the
239 tests.
240
241
Georg Brandl7f01a132009-09-16 15:58:14 +0000242.. function:: requires(resource, msg=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000243
Florent Xiclunab14930c2010-03-13 15:26:44 +0000244 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
245 argument to :exc:`ResourceDenied` if it is raised. Always returns True if called
Georg Brandl116aa622007-08-15 14:28:22 +0000246 by a function whose ``__name__`` is ``'__main__'``. Used when tests are executed
247 by :mod:`test.regrtest`.
248
249
250.. function:: findfile(filename)
251
252 Return the path to the file named *filename*. If no match is found *filename* is
253 returned. This does not equal a failure since it could be the path to the file.
254
255
256.. function:: run_unittest(*classes)
257
258 Execute :class:`unittest.TestCase` subclasses passed to the function. The
259 function scans the classes for methods starting with the prefix ``test_`` and
260 executes the tests individually.
261
262 It is also legal to pass strings as parameters; these should be keys in
263 ``sys.modules``. Each associated module will be scanned by
264 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
265 following :func:`test_main` function::
266
267 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +0000268 support.run_unittest(__name__)
Georg Brandl116aa622007-08-15 14:28:22 +0000269
270 This will run all tests defined in the named module.
271
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Florent Xiclunab14930c2010-03-13 15:26:44 +0000273.. function:: check_warnings(*filters, quiet=False)
Thomas Woutersed03b412007-08-28 21:37:11 +0000274
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000275 A convenience wrapper for ``warnings.catch_warnings()`` that makes
276 it easier to test that a warning was correctly raised with a single
277 assertion. It is approximately equivalent to calling
278 ``warnings.catch_warnings(record=True)``.
279
Florent Xiclunab14930c2010-03-13 15:26:44 +0000280 It accepts 2-tuples ``("message regexp", WarningCategory)`` as positional
281 arguments. When the optional keyword argument ``quiet`` is True, it does
282 not fail if a filter catches nothing. Without argument, it defaults to::
283
284 check_warnings(("", Warning), quiet=False)
285
286 The main difference is that it verifies the warnings raised. If some filter
287 did not catch any warning, the test fails. If some warnings are not caught,
288 the test fails, too. To disable these checks, use argument ``quiet=True``.
289
290 Another significant difference is that on entry to the context manager, a
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000291 :class:`WarningRecorder` instance is returned instead of a simple list.
292 The underlying warnings list is available via the recorder object's
293 :attr:`warnings` attribute, while the attributes of the last raised
294 warning are also accessible directly on the object. If no warning has
295 been raised, then the latter attributes will all be :const:`None`.
296
297 A :meth:`reset` method is also provided on the recorder object. This
298 method simply clears the warning list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000299
Florent Xiclunab14930c2010-03-13 15:26:44 +0000300 The context manager may be used like this::
Thomas Woutersed03b412007-08-28 21:37:11 +0000301
Florent Xiclunab14930c2010-03-13 15:26:44 +0000302 import warnings
303
304 with check_warnings():
305 exec('assert(False, "Hey!")')
306 warnings.warn(UserWarning("Hide me!"))
307
308 with check_warnings(("assertion is always true", SyntaxWarning),
309 ("", UserWarning)):
310 exec('assert(False, "Hey!")')
311 warnings.warn(UserWarning("Hide me!"))
312
313 with check_warnings(quiet=True) as w:
Nick Coghlanb1304932008-07-13 12:25:08 +0000314 warnings.simplefilter("always")
Thomas Woutersed03b412007-08-28 21:37:11 +0000315 warnings.warn("foo")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000316 assert str(w.args[0]) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000317 warnings.warn("bar")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000318 assert str(w.args[0]) == "bar"
319 assert str(w.warnings[0].args[0]) == "foo"
320 assert str(w.warnings[1].args[0]) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000321 w.reset()
322 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000323
Florent Xiclunab14930c2010-03-13 15:26:44 +0000324 .. versionchanged:: 2.7
325 The test fails when the context manager do not catch any warning.
326 New optional attributes ``*filters`` and ``quiet``.
327
Thomas Woutersed03b412007-08-28 21:37:11 +0000328
329.. function:: captured_stdout()
330
331 This is a context manager than runs the :keyword:`with` statement body using
332 a :class:`StringIO.StringIO` object as sys.stdout. That object can be
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000333 retrieved using the ``as`` clause of the :keyword:`with` statement.
Thomas Woutersed03b412007-08-28 21:37:11 +0000334
335 Example use::
336
337 with captured_stdout() as s:
Collin Winterc79461b2007-09-01 23:34:30 +0000338 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000339 assert s.getvalue() == "hello"
340
Thomas Woutersed03b412007-08-28 21:37:11 +0000341
Nick Coghlanfce769e2009-04-11 14:30:59 +0000342.. function:: import_module(name, deprecated=False)
343
344 This function imports and returns the named module. Unlike a normal
345 import, this function raises :exc:`unittest.SkipTest` if the module
346 cannot be imported.
347
348 Module and package deprecation messages are suppressed during this import
349 if *deprecated* is :const:`True`.
350
351 .. versionadded:: 3.1
352
353
Nick Coghlan47384702009-04-22 16:13:36 +0000354.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000355
Nick Coghlan47384702009-04-22 16:13:36 +0000356 This function imports and returns a fresh copy of the named Python module
357 by removing the named module from ``sys.modules`` before doing the import.
358 Note that unlike :func:`reload`, the original module is not affected by
359 this operation.
360
361 *fresh* is an iterable of additional module names that are also removed
362 from the ``sys.modules`` cache before doing the import.
363
364 *blocked* is an iterable of module names that are replaced with :const:`0`
365 in the module cache during the import to ensure that attempts to import
366 them raise :exc:`ImportError`.
367
368 The named module and any modules named in the *fresh* and *blocked*
369 parameters are saved before starting the import and then reinserted into
370 ``sys.modules`` when the fresh import is complete.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000371
372 Module and package deprecation messages are suppressed during this import
373 if *deprecated* is :const:`True`.
374
Nick Coghlan47384702009-04-22 16:13:36 +0000375 This function will raise :exc:`unittest.SkipTest` is the named module
376 cannot be imported.
377
378 Example use::
379
380 # Get copies of the warnings module for testing without
381 # affecting the version being used by the rest of the test suite
382 # One copy uses the C implementation, the other is forced to use
383 # the pure Python fallback implementation
384 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
385 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
386
Nick Coghlanfce769e2009-04-11 14:30:59 +0000387 .. versionadded:: 3.1
388
389
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000390The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +0000391
Georg Brandl7f01a132009-09-16 15:58:14 +0000392.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394 Instances are a context manager that raises :exc:`ResourceDenied` if the
395 specified exception type is raised. Any keyword arguments are treated as
396 attribute/value pairs to be compared against any exception raised within the
397 :keyword:`with` statement. Only if all pairs match properly against
398 attributes on the exception is :exc:`ResourceDenied` raised.
399
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401.. class:: EnvironmentVarGuard()
402
403 Class used to temporarily set or unset environment variables. Instances can be
Walter Dörwald155374d2009-05-01 19:58:58 +0000404 used as a context manager and have a complete dictionary interface for
405 querying/modifying the underlying ``os.environ``. After exit from the context
406 manager all changes to environment variables done through this instance will
407 be rolled back.
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Georg Brandl705d9d52009-05-05 09:29:50 +0000409 .. versionchanged:: 3.1
Walter Dörwald155374d2009-05-01 19:58:58 +0000410 Added dictionary interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000411
412.. method:: EnvironmentVarGuard.set(envvar, value)
413
414 Temporarily set the environment variable ``envvar`` to the value of ``value``.
415
416
417.. method:: EnvironmentVarGuard.unset(envvar)
418
419 Temporarily unset the environment variable ``envvar``.
Nick Coghlanb1304932008-07-13 12:25:08 +0000420
Walter Dörwald155374d2009-05-01 19:58:58 +0000421
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000422.. class:: WarningsRecorder()
423
424 Class used to record warnings for unit tests. See documentation of
425 :func:`check_warnings` above for more details.
426