blob: c27ee08b58afe76ff922510fb5152e6effb89352 [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
Antoine Pitrou197c9c92010-12-18 12:33:06 +00008.. note::
Antoine Pitrou36730e82010-12-12 18:25:25 +00009 The :mod:`test` package is meant for internal use by Python only. It is
10 documented for the benefit of the core developers of Python. Any use of
11 this package outside of Python's standard library is discouraged as code
12 mentioned here can change or be removed without notice between releases of
13 Python.
Brett Cannon3a4e50c2010-07-23 11:31:31 +000014
Georg Brandl116aa622007-08-15 14:28:22 +000015
16The :mod:`test` package contains all regression tests for Python as well as the
Nick Coghlan47384702009-04-22 16:13:36 +000017modules :mod:`test.support` and :mod:`test.regrtest`.
18:mod:`test.support` is used to enhance your tests while
Georg Brandl116aa622007-08-15 14:28:22 +000019:mod:`test.regrtest` drives the testing suite.
20
21Each module in the :mod:`test` package whose name starts with ``test_`` is a
22testing suite for a specific module or feature. All new tests should be written
23using the :mod:`unittest` or :mod:`doctest` module. Some older tests are
24written using a "traditional" testing style that compares output printed to
25``sys.stdout``; this style of test is considered deprecated.
26
27
28.. seealso::
29
30 Module :mod:`unittest`
31 Writing PyUnit regression tests.
32
33 Module :mod:`doctest`
34 Tests embedded in documentation strings.
35
36
37.. _writing-tests:
38
39Writing Unit Tests for the :mod:`test` package
40----------------------------------------------
41
Georg Brandl116aa622007-08-15 14:28:22 +000042It is preferred that tests that use the :mod:`unittest` module follow a few
43guidelines. One is to name the test module by starting it with ``test_`` and end
44it with the name of the module being tested. The test methods in the test module
45should start with ``test_`` and end with a description of what the method is
46testing. This is needed so that the methods are recognized by the test driver as
47test methods. Also, no documentation string for the method should be included. A
48comment (such as ``# Tests function returns only True or False``) should be used
49to provide documentation for test methods. This is done because documentation
50strings get printed out if they exist and thus what test is being run is not
51stated.
52
53A basic boilerplate is often used::
54
55 import unittest
Nick Coghlan47384702009-04-22 16:13:36 +000056 from test import support
Georg Brandl116aa622007-08-15 14:28:22 +000057
58 class MyTestCase1(unittest.TestCase):
59
60 # Only use setUp() and tearDown() if necessary
61
62 def setUp(self):
63 ... code to execute in preparation for tests ...
64
65 def tearDown(self):
66 ... code to execute to clean up after tests ...
67
68 def test_feature_one(self):
69 # Test feature one.
70 ... testing code ...
71
72 def test_feature_two(self):
73 # Test feature two.
74 ... testing code ...
75
76 ... more test methods ...
77
78 class MyTestCase2(unittest.TestCase):
79 ... same structure as MyTestCase1 ...
80
81 ... more test classes ...
82
83 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +000084 support.run_unittest(MyTestCase1,
Georg Brandl116aa622007-08-15 14:28:22 +000085 MyTestCase2,
86 ... list other tests ...
87 )
88
89 if __name__ == '__main__':
90 test_main()
91
92This boilerplate code allows the testing suite to be run by :mod:`test.regrtest`
93as well as on its own as a script.
94
95The goal for regression testing is to try to break code. This leads to a few
96guidelines to be followed:
97
98* The testing suite should exercise all classes, functions, and constants. This
Florent Xicluna53b506be2010-03-18 20:00:57 +000099 includes not just the external API that is to be presented to the outside
100 world but also "private" code.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102* Whitebox testing (examining the code being tested when the tests are being
103 written) is preferred. Blackbox testing (testing only the published user
Florent Xicluna53b506be2010-03-18 20:00:57 +0000104 interface) is not complete enough to make sure all boundary and edge cases
105 are tested.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107* Make sure all possible values are tested including invalid ones. This makes
Florent Xicluna53b506be2010-03-18 20:00:57 +0000108 sure that not only all valid values are acceptable but also that improper
109 values are handled correctly.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
111* Exhaust as many code paths as possible. Test where branching occurs and thus
112 tailor input to make sure as many different paths through the code are taken.
113
114* Add an explicit test for any bugs discovered for the tested code. This will
115 make sure that the error does not crop up again if the code is changed in the
116 future.
117
118* Make sure to clean up after your tests (such as close and remove all temporary
119 files).
120
121* If a test is dependent on a specific condition of the operating system then
122 verify the condition already exists before attempting the test.
123
124* Import as few modules as possible and do it as soon as possible. This
125 minimizes external dependencies of tests and also minimizes possible anomalous
126 behavior from side-effects of importing a module.
127
128* Try to maximize code reuse. On occasion, tests will vary by something as small
Florent Xicluna53b506be2010-03-18 20:00:57 +0000129 as what type of input is used. Minimize code duplication by subclassing a
130 basic test class with a class that specifies the input::
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132 class TestFuncAcceptsSequences(unittest.TestCase):
133
134 func = mySuperWhammyFunction
135
136 def test_func(self):
137 self.func(self.arg)
138
139 class AcceptLists(TestFuncAcceptsSequences):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000140 arg = [1, 2, 3]
Georg Brandl116aa622007-08-15 14:28:22 +0000141
142 class AcceptStrings(TestFuncAcceptsSequences):
143 arg = 'abc'
144
145 class AcceptTuples(TestFuncAcceptsSequences):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000146 arg = (1, 2, 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148
149.. seealso::
150
151 Test Driven Development
152 A book by Kent Beck on writing tests before code.
153
154
155.. _regrtest:
156
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000157Running tests using the command-line interface
158----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000159
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000160The :mod:`test` package can be run as a script to drive Python's regression
161test suite, thanks to the :option:`-m` option: :program:`python -m test`. Under
162the hood, it uses :mod:`test.regrtest`; the call :program:`python -m
163test.regrtest` used in previous Python versions still works).
164Running the script by itself automatically starts running all regression
Georg Brandl116aa622007-08-15 14:28:22 +0000165tests in the :mod:`test` package. It does this by finding all modules in the
166package whose name starts with ``test_``, importing them, and executing the
Florent Xicluna53b506be2010-03-18 20:00:57 +0000167function :func:`test_main` if present. The names of tests to execute may also
168be passed to the script. Specifying a single regression test (:program:`python
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000169-m test test_spam`) will minimize output and only print
Florent Xicluna53b506be2010-03-18 20:00:57 +0000170whether the test passed or failed and thus minimize output.
Georg Brandl116aa622007-08-15 14:28:22 +0000171
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000172Running :mod:`test` directly allows what resources are available for
Éric Araujo713d3032010-11-18 16:38:46 +0000173tests to use to be set. You do this by using the ``-u`` command-line
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000174option. Run :program:`python -m test -uall` to turn on all
Éric Araujo713d3032010-11-18 16:38:46 +0000175resources; specifying ``all`` as an option for ``-u`` enables all
Georg Brandl116aa622007-08-15 14:28:22 +0000176possible resources. If all but one resource is desired (a more common case), a
177comma-separated list of resources that are not desired may be listed after
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000178``all``. The command :program:`python -m test -uall,-audio,-largefile`
179will run :mod:`test` with all resources except the ``audio`` and
Éric Araujo713d3032010-11-18 16:38:46 +0000180``largefile`` resources. For a list of all resources and more command-line
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000181options, run :program:`python -m test -h`.
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183Some other ways to execute the regression tests depend on what platform the
Éric Araujo713d3032010-11-18 16:38:46 +0000184tests are being executed on. On Unix, you can run :program:`make test` at the
185top-level directory where Python was built. On Windows,
Florent Xicluna53b506be2010-03-18 20:00:57 +0000186executing :program:`rt.bat` from your :file:`PCBuild` directory will run all
187regression tests.
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189
Georg Brandleea6cda2011-07-30 09:00:48 +0200190:mod:`test.support` --- Utilities for the Python test suite
191===========================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000193.. module:: test.support
Georg Brandleea6cda2011-07-30 09:00:48 +0200194 :synopsis: Support for Python's regression test suite.
Georg Brandl116aa622007-08-15 14:28:22 +0000195
196
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000197The :mod:`test.support` module provides support for Python's regression
Georg Brandleea6cda2011-07-30 09:00:48 +0200198test suite.
199
200.. note::
201 :mod:`test.support` is not a public module. It is documented here to help
202 Python developers write tests. The API of this module is subject to change
203 without backwards compatibility concerns between releases.
204
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206This module defines the following exceptions:
207
Georg Brandl116aa622007-08-15 14:28:22 +0000208.. exception:: TestFailed
209
210 Exception to be raised when a test fails. This is deprecated in favor of
211 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
212 methods.
213
214
Georg Brandl116aa622007-08-15 14:28:22 +0000215.. exception:: ResourceDenied
216
Florent Xicluna53b506be2010-03-18 20:00:57 +0000217 Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a
218 network connection) is not available. Raised by the :func:`requires`
219 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000220
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Georg Brandleea6cda2011-07-30 09:00:48 +0200222The :mod:`test.support` module defines the following constants:
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224.. data:: verbose
225
226 :const:`True` when verbose output is enabled. Should be checked when more
227 detailed information is desired about a running test. *verbose* is set by
228 :mod:`test.regrtest`.
229
230
Georg Brandl116aa622007-08-15 14:28:22 +0000231.. data:: is_jython
232
233 :const:`True` if the running interpreter is Jython.
234
235
236.. data:: TESTFN
237
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000238 Set to a name that is safe to use as the name of a temporary file. Any
239 temporary file that is created should be closed and unlinked (removed).
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Georg Brandl116aa622007-08-15 14:28:22 +0000241
Georg Brandleea6cda2011-07-30 09:00:48 +0200242The :mod:`test.support` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244.. function:: forget(module_name)
245
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000246 Remove the module named *module_name* from ``sys.modules`` and delete any
Georg Brandl116aa622007-08-15 14:28:22 +0000247 byte-compiled files of the module.
248
249
250.. function:: is_resource_enabled(resource)
251
Florent Xiclunab14930c2010-03-13 15:26:44 +0000252 Return :const:`True` if *resource* is enabled and available. The list of
Georg Brandl116aa622007-08-15 14:28:22 +0000253 available resources is only set when :mod:`test.regrtest` is executing the
254 tests.
255
256
Georg Brandl7f01a132009-09-16 15:58:14 +0000257.. function:: requires(resource, msg=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000258
Florent Xiclunab14930c2010-03-13 15:26:44 +0000259 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
Florent Xicluna53b506be2010-03-18 20:00:57 +0000260 argument to :exc:`ResourceDenied` if it is raised. Always returns
261 :const:`True` if called by a function whose ``__name__`` is ``'__main__'``.
262 Used when tests are executed by :mod:`test.regrtest`.
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264
265.. function:: findfile(filename)
266
Florent Xicluna53b506be2010-03-18 20:00:57 +0000267 Return the path to the file named *filename*. If no match is found
268 *filename* is returned. This does not equal a failure since it could be the
269 path to the file.
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000272.. function:: run_unittest(\*classes)
Georg Brandl116aa622007-08-15 14:28:22 +0000273
274 Execute :class:`unittest.TestCase` subclasses passed to the function. The
Florent Xicluna53b506be2010-03-18 20:00:57 +0000275 function scans the classes for methods starting with the prefix ``test_``
276 and executes the tests individually.
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278 It is also legal to pass strings as parameters; these should be keys in
279 ``sys.modules``. Each associated module will be scanned by
280 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
281 following :func:`test_main` function::
282
283 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +0000284 support.run_unittest(__name__)
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286 This will run all tests defined in the named module.
287
Georg Brandl116aa622007-08-15 14:28:22 +0000288
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000289.. function:: check_warnings(\*filters, quiet=True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000290
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000291 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
292 easier to test that a warning was correctly raised. It is approximately
293 equivalent to calling ``warnings.catch_warnings(record=True)`` with
294 :meth:`warnings.simplefilter` set to ``always`` and with the option to
295 automatically validate the results that are recorded.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000296
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000297 ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
298 WarningCategory)`` as positional arguments. If one or more *filters* are
299 provided, or if the optional keyword argument *quiet* is :const:`False`,
300 it checks to make sure the warnings are as expected: each specified filter
301 must match at least one of the warnings raised by the enclosed code or the
302 test fails, and if any warnings are raised that do not match any of the
303 specified filters the test fails. To disable the first of these checks,
304 set *quiet* to :const:`True`.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000305
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000306 If no arguments are specified, it defaults to::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000307
Florent Xicluna53b506be2010-03-18 20:00:57 +0000308 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000309
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000310 In this case all warnings are caught and no errors are raised.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000311
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000312 On entry to the context manager, a :class:`WarningRecorder` instance is
313 returned. The underlying warnings list from
314 :func:`~warnings.catch_warnings` is available via the recorder object's
315 :attr:`warnings` attribute. As a convenience, the attributes of the object
316 representing the most recent warning can also be accessed directly through
317 the recorder object (see example below). If no warning has been raised,
318 then any of the attributes that would otherwise be expected on an object
319 representing a warning will return :const:`None`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000320
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000321 The recorder object also has a :meth:`reset` method, which clears the
322 warnings list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000323
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000324 The context manager is designed to be used like this::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000325
326 with check_warnings(("assertion is always true", SyntaxWarning),
327 ("", UserWarning)):
328 exec('assert(False, "Hey!")')
329 warnings.warn(UserWarning("Hide me!"))
330
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000331 In this case if either warning was not raised, or some other warning was
332 raised, :func:`check_warnings` would raise an error.
333
334 When a test needs to look more deeply into the warnings, rather than
335 just checking whether or not they occurred, code like this can be used::
336
Florent Xiclunab14930c2010-03-13 15:26:44 +0000337 with check_warnings(quiet=True) as w:
Thomas Woutersed03b412007-08-28 21:37:11 +0000338 warnings.warn("foo")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000339 assert str(w.args[0]) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000340 warnings.warn("bar")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000341 assert str(w.args[0]) == "bar"
342 assert str(w.warnings[0].args[0]) == "foo"
343 assert str(w.warnings[1].args[0]) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000344 w.reset()
345 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000346
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000347
348 Here all warnings will be caught, and the test code tests the captured
349 warnings directly.
350
Ezio Melottif8754a62010-03-21 07:16:43 +0000351 .. versionchanged:: 3.2
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000352 New optional arguments *filters* and *quiet*.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000353
Thomas Woutersed03b412007-08-28 21:37:11 +0000354
355.. function:: captured_stdout()
356
Senthil Kumaranaf1d4342010-05-18 03:26:11 +0000357 This is a context manager that runs the :keyword:`with` statement body using
Thomas Woutersed03b412007-08-28 21:37:11 +0000358 a :class:`StringIO.StringIO` object as sys.stdout. That object can be
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000359 retrieved using the ``as`` clause of the :keyword:`with` statement.
Thomas Woutersed03b412007-08-28 21:37:11 +0000360
361 Example use::
362
363 with captured_stdout() as s:
Collin Winterc79461b2007-09-01 23:34:30 +0000364 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000365 assert s.getvalue() == "hello"
366
Thomas Woutersed03b412007-08-28 21:37:11 +0000367
Nick Coghlanfce769e2009-04-11 14:30:59 +0000368.. function:: import_module(name, deprecated=False)
369
370 This function imports and returns the named module. Unlike a normal
371 import, this function raises :exc:`unittest.SkipTest` if the module
372 cannot be imported.
373
374 Module and package deprecation messages are suppressed during this import
375 if *deprecated* is :const:`True`.
376
377 .. versionadded:: 3.1
378
379
Nick Coghlan47384702009-04-22 16:13:36 +0000380.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000381
Nick Coghlan47384702009-04-22 16:13:36 +0000382 This function imports and returns a fresh copy of the named Python module
383 by removing the named module from ``sys.modules`` before doing the import.
384 Note that unlike :func:`reload`, the original module is not affected by
385 this operation.
386
387 *fresh* is an iterable of additional module names that are also removed
388 from the ``sys.modules`` cache before doing the import.
389
390 *blocked* is an iterable of module names that are replaced with :const:`0`
391 in the module cache during the import to ensure that attempts to import
392 them raise :exc:`ImportError`.
393
394 The named module and any modules named in the *fresh* and *blocked*
395 parameters are saved before starting the import and then reinserted into
396 ``sys.modules`` when the fresh import is complete.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000397
398 Module and package deprecation messages are suppressed during this import
399 if *deprecated* is :const:`True`.
400
Nick Coghlan47384702009-04-22 16:13:36 +0000401 This function will raise :exc:`unittest.SkipTest` is the named module
402 cannot be imported.
403
404 Example use::
405
406 # Get copies of the warnings module for testing without
407 # affecting the version being used by the rest of the test suite
408 # One copy uses the C implementation, the other is forced to use
409 # the pure Python fallback implementation
410 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
411 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
412
Nick Coghlanfce769e2009-04-11 14:30:59 +0000413 .. versionadded:: 3.1
414
415
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000416The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +0000417
Georg Brandl7f01a132009-09-16 15:58:14 +0000418.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420 Instances are a context manager that raises :exc:`ResourceDenied` if the
421 specified exception type is raised. Any keyword arguments are treated as
422 attribute/value pairs to be compared against any exception raised within the
423 :keyword:`with` statement. Only if all pairs match properly against
424 attributes on the exception is :exc:`ResourceDenied` raised.
425
Georg Brandl116aa622007-08-15 14:28:22 +0000426
427.. class:: EnvironmentVarGuard()
428
Florent Xicluna53b506be2010-03-18 20:00:57 +0000429 Class used to temporarily set or unset environment variables. Instances can
430 be used as a context manager and have a complete dictionary interface for
431 querying/modifying the underlying ``os.environ``. After exit from the
432 context manager all changes to environment variables done through this
433 instance will be rolled back.
Georg Brandl116aa622007-08-15 14:28:22 +0000434
Georg Brandl705d9d52009-05-05 09:29:50 +0000435 .. versionchanged:: 3.1
Walter Dörwald155374d2009-05-01 19:58:58 +0000436 Added dictionary interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438.. method:: EnvironmentVarGuard.set(envvar, value)
439
Florent Xicluna53b506be2010-03-18 20:00:57 +0000440 Temporarily set the environment variable ``envvar`` to the value of
441 ``value``.
Georg Brandl116aa622007-08-15 14:28:22 +0000442
443
444.. method:: EnvironmentVarGuard.unset(envvar)
445
446 Temporarily unset the environment variable ``envvar``.
Nick Coghlanb1304932008-07-13 12:25:08 +0000447
Walter Dörwald155374d2009-05-01 19:58:58 +0000448
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000449.. class:: WarningsRecorder()
450
451 Class used to record warnings for unit tests. See documentation of
452 :func:`check_warnings` above for more details.