blob: 3b9ad104d8b4c764c737944b45a191e6fec885dd [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 Xicluna53b506be2010-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 Xicluna53b506be2010-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 Xicluna53b506be2010-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 Xicluna53b506be2010-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 Xicluna53b506be2010-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 Xicluna53b506be2010-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 Xicluna53b506be2010-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
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000224 Set to a name that is safe to use as the name of a temporary file. Any
225 temporary file that is created should be closed and unlinked (removed).
Georg Brandl116aa622007-08-15 14:28:22 +0000226
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
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000232 Remove the module named *module_name* from ``sys.modules`` and delete 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 Xicluna53b506be2010-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 Xicluna53b506be2010-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 Xicluna53b506be2010-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
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000275.. function:: check_warnings(*filters, quiet=True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000276
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000277 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
278 easier to test that a warning was correctly raised. It is approximately
279 equivalent to calling ``warnings.catch_warnings(record=True)`` with
280 :meth:`warnings.simplefilter` set to ``always`` and with the option to
281 automatically validate the results that are recorded.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000282
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000283 ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
284 WarningCategory)`` as positional arguments. If one or more *filters* are
285 provided, or if the optional keyword argument *quiet* is :const:`False`,
286 it checks to make sure the warnings are as expected: each specified filter
287 must match at least one of the warnings raised by the enclosed code or the
288 test fails, and if any warnings are raised that do not match any of the
289 specified filters the test fails. To disable the first of these checks,
290 set *quiet* to :const:`True`.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000291
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000292 If no arguments are specified, it defaults to::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000293
Florent Xicluna53b506be2010-03-18 20:00:57 +0000294 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000295
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000296 In this case all warnings are caught and no errors are raised.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000297
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000298 On entry to the context manager, a :class:`WarningRecorder` instance is
299 returned. The underlying warnings list from
300 :func:`~warnings.catch_warnings` is available via the recorder object's
301 :attr:`warnings` attribute. As a convenience, the attributes of the object
302 representing the most recent warning can also be accessed directly through
303 the recorder object (see example below). If no warning has been raised,
304 then any of the attributes that would otherwise be expected on an object
305 representing a warning will return :const:`None`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000306
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000307 The recorder object also has a :meth:`reset` method, which clears the
308 warnings list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000309
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000310 The context manager is designed to be used like this::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000311
312 with check_warnings(("assertion is always true", SyntaxWarning),
313 ("", UserWarning)):
314 exec('assert(False, "Hey!")')
315 warnings.warn(UserWarning("Hide me!"))
316
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000317 In this case if either warning was not raised, or some other warning was
318 raised, :func:`check_warnings` would raise an error.
319
320 When a test needs to look more deeply into the warnings, rather than
321 just checking whether or not they occurred, code like this can be used::
322
Florent Xiclunab14930c2010-03-13 15:26:44 +0000323 with check_warnings(quiet=True) as w:
Thomas Woutersed03b412007-08-28 21:37:11 +0000324 warnings.warn("foo")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000325 assert str(w.args[0]) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000326 warnings.warn("bar")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000327 assert str(w.args[0]) == "bar"
328 assert str(w.warnings[0].args[0]) == "foo"
329 assert str(w.warnings[1].args[0]) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000330 w.reset()
331 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000332
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000333
334 Here all warnings will be caught, and the test code tests the captured
335 warnings directly.
336
Ezio Melottif8754a62010-03-21 07:16:43 +0000337 .. versionchanged:: 3.2
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000338 New optional arguments *filters* and *quiet*.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000339
Thomas Woutersed03b412007-08-28 21:37:11 +0000340
341.. function:: captured_stdout()
342
Senthil Kumaranaf1d4342010-05-18 03:26:11 +0000343 This is a context manager that runs the :keyword:`with` statement body using
Thomas Woutersed03b412007-08-28 21:37:11 +0000344 a :class:`StringIO.StringIO` object as sys.stdout. That object can be
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000345 retrieved using the ``as`` clause of the :keyword:`with` statement.
Thomas Woutersed03b412007-08-28 21:37:11 +0000346
347 Example use::
348
349 with captured_stdout() as s:
Collin Winterc79461b2007-09-01 23:34:30 +0000350 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000351 assert s.getvalue() == "hello"
352
Thomas Woutersed03b412007-08-28 21:37:11 +0000353
Nick Coghlanfce769e2009-04-11 14:30:59 +0000354.. function:: import_module(name, deprecated=False)
355
356 This function imports and returns the named module. Unlike a normal
357 import, this function raises :exc:`unittest.SkipTest` if the module
358 cannot be imported.
359
360 Module and package deprecation messages are suppressed during this import
361 if *deprecated* is :const:`True`.
362
363 .. versionadded:: 3.1
364
365
Nick Coghlan47384702009-04-22 16:13:36 +0000366.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000367
Nick Coghlan47384702009-04-22 16:13:36 +0000368 This function imports and returns a fresh copy of the named Python module
369 by removing the named module from ``sys.modules`` before doing the import.
370 Note that unlike :func:`reload`, the original module is not affected by
371 this operation.
372
373 *fresh* is an iterable of additional module names that are also removed
374 from the ``sys.modules`` cache before doing the import.
375
376 *blocked* is an iterable of module names that are replaced with :const:`0`
377 in the module cache during the import to ensure that attempts to import
378 them raise :exc:`ImportError`.
379
380 The named module and any modules named in the *fresh* and *blocked*
381 parameters are saved before starting the import and then reinserted into
382 ``sys.modules`` when the fresh import is complete.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000383
384 Module and package deprecation messages are suppressed during this import
385 if *deprecated* is :const:`True`.
386
Nick Coghlan47384702009-04-22 16:13:36 +0000387 This function will raise :exc:`unittest.SkipTest` is the named module
388 cannot be imported.
389
390 Example use::
391
392 # Get copies of the warnings module for testing without
393 # affecting the version being used by the rest of the test suite
394 # One copy uses the C implementation, the other is forced to use
395 # the pure Python fallback implementation
396 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
397 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
398
Nick Coghlanfce769e2009-04-11 14:30:59 +0000399 .. versionadded:: 3.1
400
401
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000402The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +0000403
Georg Brandl7f01a132009-09-16 15:58:14 +0000404.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000405
406 Instances are a context manager that raises :exc:`ResourceDenied` if the
407 specified exception type is raised. Any keyword arguments are treated as
408 attribute/value pairs to be compared against any exception raised within the
409 :keyword:`with` statement. Only if all pairs match properly against
410 attributes on the exception is :exc:`ResourceDenied` raised.
411
Georg Brandl116aa622007-08-15 14:28:22 +0000412
413.. class:: EnvironmentVarGuard()
414
Florent Xicluna53b506be2010-03-18 20:00:57 +0000415 Class used to temporarily set or unset environment variables. Instances can
416 be used as a context manager and have a complete dictionary interface for
417 querying/modifying the underlying ``os.environ``. After exit from the
418 context manager all changes to environment variables done through this
419 instance will be rolled back.
Georg Brandl116aa622007-08-15 14:28:22 +0000420
Georg Brandl705d9d52009-05-05 09:29:50 +0000421 .. versionchanged:: 3.1
Walter Dörwald155374d2009-05-01 19:58:58 +0000422 Added dictionary interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000423
424.. method:: EnvironmentVarGuard.set(envvar, value)
425
Florent Xicluna53b506be2010-03-18 20:00:57 +0000426 Temporarily set the environment variable ``envvar`` to the value of
427 ``value``.
Georg Brandl116aa622007-08-15 14:28:22 +0000428
429
430.. method:: EnvironmentVarGuard.unset(envvar)
431
432 Temporarily unset the environment variable ``envvar``.
Nick Coghlanb1304932008-07-13 12:25:08 +0000433
Walter Dörwald155374d2009-05-01 19:58:58 +0000434
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000435.. class:: WarningsRecorder()
436
437 Class used to record warnings for unit tests. See documentation of
438 :func:`check_warnings` above for more details.