blob: af9ce451867ab95ffcc42b4243ad4afa241db729 [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
Georg Brandl116aa622007-08-15 14:28:22 +000083 if __name__ == '__main__':
R David Murray78fc25c2012-04-09 08:55:42 -040084 unittest.main()
Georg Brandl116aa622007-08-15 14:28:22 +000085
R David Murray78fc25c2012-04-09 08:55:42 -040086This code pattern allows the testing suite to be run by :mod:`test.regrtest`,
87on its own as a script that supports the :mod:`unittest` CLI, or via the
88`python -m unittest` CLI.
Georg Brandl116aa622007-08-15 14:28:22 +000089
90The goal for regression testing is to try to break code. This leads to a few
91guidelines to be followed:
92
93* The testing suite should exercise all classes, functions, and constants. This
Florent Xicluna53b506b2010-03-18 20:00:57 +000094 includes not just the external API that is to be presented to the outside
95 world but also "private" code.
Georg Brandl116aa622007-08-15 14:28:22 +000096
97* Whitebox testing (examining the code being tested when the tests are being
98 written) is preferred. Blackbox testing (testing only the published user
Florent Xicluna53b506b2010-03-18 20:00:57 +000099 interface) is not complete enough to make sure all boundary and edge cases
100 are tested.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102* Make sure all possible values are tested including invalid ones. This makes
Florent Xicluna53b506b2010-03-18 20:00:57 +0000103 sure that not only all valid values are acceptable but also that improper
104 values are handled correctly.
Georg Brandl116aa622007-08-15 14:28:22 +0000105
106* Exhaust as many code paths as possible. Test where branching occurs and thus
107 tailor input to make sure as many different paths through the code are taken.
108
109* Add an explicit test for any bugs discovered for the tested code. This will
110 make sure that the error does not crop up again if the code is changed in the
111 future.
112
113* Make sure to clean up after your tests (such as close and remove all temporary
114 files).
115
116* If a test is dependent on a specific condition of the operating system then
117 verify the condition already exists before attempting the test.
118
119* Import as few modules as possible and do it as soon as possible. This
120 minimizes external dependencies of tests and also minimizes possible anomalous
121 behavior from side-effects of importing a module.
122
123* Try to maximize code reuse. On occasion, tests will vary by something as small
Florent Xicluna53b506b2010-03-18 20:00:57 +0000124 as what type of input is used. Minimize code duplication by subclassing a
125 basic test class with a class that specifies the input::
Georg Brandl116aa622007-08-15 14:28:22 +0000126
R David Murray78fc25c2012-04-09 08:55:42 -0400127 class TestFuncAcceptsSequencesMixin:
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129 func = mySuperWhammyFunction
130
131 def test_func(self):
132 self.func(self.arg)
133
R David Murray78fc25c2012-04-09 08:55:42 -0400134 class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000135 arg = [1, 2, 3]
Georg Brandl116aa622007-08-15 14:28:22 +0000136
R David Murray78fc25c2012-04-09 08:55:42 -0400137 class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +0000138 arg = 'abc'
139
R David Murray78fc25c2012-04-09 08:55:42 -0400140 class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000141 arg = (1, 2, 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000142
R David Murray78fc25c2012-04-09 08:55:42 -0400143 When using this pattern, remember that all classes that inherit from
144 `unittest.TestCase` are run as tests. The `Mixin` class in the example above
145 does not have any data and so can't be run by itself, thus it does not
146 inherit from `unittest.TestCase`.
147
Georg Brandl116aa622007-08-15 14:28:22 +0000148
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
R David Murray78fc25c2012-04-09 08:55:42 -0400167function :func:`test_main` if present or loading the tests via
168unittest.TestLoader.loadTestsFromModule if ``test_main`` does not exist.
169The names of tests to execute may also
Florent Xicluna53b506b2010-03-18 20:00:57 +0000170be passed to the script. Specifying a single regression test (:program:`python
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000171-m test test_spam`) will minimize output and only print
R David Murray78fc25c2012-04-09 08:55:42 -0400172whether the test passed or failed.
Georg Brandl116aa622007-08-15 14:28:22 +0000173
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000174Running :mod:`test` directly allows what resources are available for
Éric Araujo713d3032010-11-18 16:38:46 +0000175tests to use to be set. You do this by using the ``-u`` command-line
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000176option. Run :program:`python -m test -uall` to turn on all
Éric Araujo713d3032010-11-18 16:38:46 +0000177resources; specifying ``all`` as an option for ``-u`` enables all
Georg Brandl116aa622007-08-15 14:28:22 +0000178possible resources. If all but one resource is desired (a more common case), a
179comma-separated list of resources that are not desired may be listed after
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000180``all``. The command :program:`python -m test -uall,-audio,-largefile`
181will run :mod:`test` with all resources except the ``audio`` and
Éric Araujo713d3032010-11-18 16:38:46 +0000182``largefile`` resources. For a list of all resources and more command-line
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000183options, run :program:`python -m test -h`.
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185Some other ways to execute the regression tests depend on what platform the
Éric Araujo713d3032010-11-18 16:38:46 +0000186tests are being executed on. On Unix, you can run :program:`make test` at the
187top-level directory where Python was built. On Windows,
Florent Xicluna53b506b2010-03-18 20:00:57 +0000188executing :program:`rt.bat` from your :file:`PCBuild` directory will run all
189regression tests.
Georg Brandl116aa622007-08-15 14:28:22 +0000190
191
Georg Brandleea6cda2011-07-30 09:00:48 +0200192:mod:`test.support` --- Utilities for the Python test suite
193===========================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000194
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000195.. module:: test.support
Georg Brandleea6cda2011-07-30 09:00:48 +0200196 :synopsis: Support for Python's regression test suite.
Georg Brandl116aa622007-08-15 14:28:22 +0000197
198
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000199The :mod:`test.support` module provides support for Python's regression
Georg Brandleea6cda2011-07-30 09:00:48 +0200200test suite.
201
202.. note::
203 :mod:`test.support` is not a public module. It is documented here to help
204 Python developers write tests. The API of this module is subject to change
205 without backwards compatibility concerns between releases.
206
Georg Brandl116aa622007-08-15 14:28:22 +0000207
208This module defines the following exceptions:
209
Georg Brandl116aa622007-08-15 14:28:22 +0000210.. exception:: TestFailed
211
212 Exception to be raised when a test fails. This is deprecated in favor of
213 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
214 methods.
215
216
Georg Brandl116aa622007-08-15 14:28:22 +0000217.. exception:: ResourceDenied
218
Florent Xicluna53b506b2010-03-18 20:00:57 +0000219 Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a
220 network connection) is not available. Raised by the :func:`requires`
221 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000222
Georg Brandl116aa622007-08-15 14:28:22 +0000223
Georg Brandleea6cda2011-07-30 09:00:48 +0200224The :mod:`test.support` module defines the following constants:
Georg Brandl116aa622007-08-15 14:28:22 +0000225
226.. data:: verbose
227
Eli Benderskye1689652011-05-06 09:29:27 +0300228 ``True`` when verbose output is enabled. Should be checked when more
Georg Brandl116aa622007-08-15 14:28:22 +0000229 detailed information is desired about a running test. *verbose* is set by
230 :mod:`test.regrtest`.
231
232
Georg Brandl116aa622007-08-15 14:28:22 +0000233.. data:: is_jython
234
Eli Benderskye1689652011-05-06 09:29:27 +0300235 ``True`` if the running interpreter is Jython.
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237
238.. data:: TESTFN
239
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000240 Set to a name that is safe to use as the name of a temporary file. Any
241 temporary file that is created should be closed and unlinked (removed).
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Eli Benderskye1689652011-05-06 09:29:27 +0300243
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000244The :mod:`test.support` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000245
Georg Brandl116aa622007-08-15 14:28:22 +0000246.. function:: forget(module_name)
247
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000248 Remove the module named *module_name* from ``sys.modules`` and delete any
Georg Brandl116aa622007-08-15 14:28:22 +0000249 byte-compiled files of the module.
250
251
252.. function:: is_resource_enabled(resource)
253
Eli Benderskye1689652011-05-06 09:29:27 +0300254 Return ``True`` if *resource* is enabled and available. The list of
Georg Brandl116aa622007-08-15 14:28:22 +0000255 available resources is only set when :mod:`test.regrtest` is executing the
256 tests.
257
258
Georg Brandl7f01a132009-09-16 15:58:14 +0000259.. function:: requires(resource, msg=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Florent Xiclunab14930c2010-03-13 15:26:44 +0000261 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
Florent Xicluna53b506b2010-03-18 20:00:57 +0000262 argument to :exc:`ResourceDenied` if it is raised. Always returns
Eli Benderskye1689652011-05-06 09:29:27 +0300263 ``True`` if called by a function whose ``__name__`` is ``'__main__'``.
Florent Xicluna53b506b2010-03-18 20:00:57 +0000264 Used when tests are executed by :mod:`test.regrtest`.
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266
267.. function:: findfile(filename)
268
Florent Xicluna53b506b2010-03-18 20:00:57 +0000269 Return the path to the file named *filename*. If no match is found
270 *filename* is returned. This does not equal a failure since it could be the
271 path to the file.
Georg Brandl116aa622007-08-15 14:28:22 +0000272
273
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000274.. function:: run_unittest(\*classes)
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276 Execute :class:`unittest.TestCase` subclasses passed to the function. The
Florent Xicluna53b506b2010-03-18 20:00:57 +0000277 function scans the classes for methods starting with the prefix ``test_``
278 and executes the tests individually.
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280 It is also legal to pass strings as parameters; these should be keys in
281 ``sys.modules``. Each associated module will be scanned by
282 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
283 following :func:`test_main` function::
284
285 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +0000286 support.run_unittest(__name__)
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288 This will run all tests defined in the named module.
289
Georg Brandl116aa622007-08-15 14:28:22 +0000290
Eli Benderskye1689652011-05-06 09:29:27 +0300291.. function:: run_doctest(module, verbosity=None)
292
293 Run :func:`doctest.testmod` on the given *module*. Return
294 ``(failure_count, test_count)``.
295
296 If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity
297 set to :data:`verbose`. Otherwise, it is run with verbosity set to
298 ``None``.
299
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000300.. function:: check_warnings(\*filters, quiet=True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000301
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000302 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
303 easier to test that a warning was correctly raised. It is approximately
304 equivalent to calling ``warnings.catch_warnings(record=True)`` with
305 :meth:`warnings.simplefilter` set to ``always`` and with the option to
306 automatically validate the results that are recorded.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000307
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000308 ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
309 WarningCategory)`` as positional arguments. If one or more *filters* are
Eli Benderskye1689652011-05-06 09:29:27 +0300310 provided, or if the optional keyword argument *quiet* is ``False``,
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000311 it checks to make sure the warnings are as expected: each specified filter
312 must match at least one of the warnings raised by the enclosed code or the
313 test fails, and if any warnings are raised that do not match any of the
314 specified filters the test fails. To disable the first of these checks,
Eli Benderskye1689652011-05-06 09:29:27 +0300315 set *quiet* to ``True``.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000316
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000317 If no arguments are specified, it defaults to::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000318
Florent Xicluna53b506b2010-03-18 20:00:57 +0000319 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000320
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000321 In this case all warnings are caught and no errors are raised.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000322
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000323 On entry to the context manager, a :class:`WarningRecorder` instance is
324 returned. The underlying warnings list from
325 :func:`~warnings.catch_warnings` is available via the recorder object's
326 :attr:`warnings` attribute. As a convenience, the attributes of the object
327 representing the most recent warning can also be accessed directly through
328 the recorder object (see example below). If no warning has been raised,
329 then any of the attributes that would otherwise be expected on an object
Eli Benderskye1689652011-05-06 09:29:27 +0300330 representing a warning will return ``None``.
Thomas Woutersed03b412007-08-28 21:37:11 +0000331
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000332 The recorder object also has a :meth:`reset` method, which clears the
333 warnings list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000334
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000335 The context manager is designed to be used like this::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000336
337 with check_warnings(("assertion is always true", SyntaxWarning),
338 ("", UserWarning)):
339 exec('assert(False, "Hey!")')
340 warnings.warn(UserWarning("Hide me!"))
341
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000342 In this case if either warning was not raised, or some other warning was
343 raised, :func:`check_warnings` would raise an error.
344
345 When a test needs to look more deeply into the warnings, rather than
346 just checking whether or not they occurred, code like this can be used::
347
Florent Xiclunab14930c2010-03-13 15:26:44 +0000348 with check_warnings(quiet=True) as w:
Thomas Woutersed03b412007-08-28 21:37:11 +0000349 warnings.warn("foo")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000350 assert str(w.args[0]) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000351 warnings.warn("bar")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000352 assert str(w.args[0]) == "bar"
353 assert str(w.warnings[0].args[0]) == "foo"
354 assert str(w.warnings[1].args[0]) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000355 w.reset()
356 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000357
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000358
359 Here all warnings will be caught, and the test code tests the captured
360 warnings directly.
361
Ezio Melottif8754a62010-03-21 07:16:43 +0000362 .. versionchanged:: 3.2
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000363 New optional arguments *filters* and *quiet*.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000364
Thomas Woutersed03b412007-08-28 21:37:11 +0000365
366.. function:: captured_stdout()
367
Eli Benderskye1689652011-05-06 09:29:27 +0300368 A context manager that runs the :keyword:`with` statement body using
Thomas Woutersed03b412007-08-28 21:37:11 +0000369 a :class:`StringIO.StringIO` object as sys.stdout. That object can be
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000370 retrieved using the ``as`` clause of the :keyword:`with` statement.
Thomas Woutersed03b412007-08-28 21:37:11 +0000371
372 Example use::
373
374 with captured_stdout() as s:
Collin Winterc79461b2007-09-01 23:34:30 +0000375 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000376 assert s.getvalue() == "hello"
377
Thomas Woutersed03b412007-08-28 21:37:11 +0000378
Eli Benderskye1689652011-05-06 09:29:27 +0300379.. function:: temp_cwd(name='tempcwd', quiet=False, path=None)
380
381 A context manager that temporarily changes the current working
382 directory (CWD).
383
384 An existing path may be provided as *path*, in which case this function
385 makes no changes to the file system.
386
387 Otherwise, the new CWD is created in the current directory and it's named
388 *name*. If *quiet* is ``False`` and it's not possible to create or
389 change the CWD, an error is raised. If it's ``True``, only a warning
390 is raised and the original CWD is used.
391
392
393.. function:: temp_umask(umask)
394
395 A context manager that temporarily sets the process umask.
396
397
398.. function:: can_symlink()
399
400 Return ``True`` if the OS supports symbolic links, ``False``
401 otherwise.
402
403
Nick Coghlan2496f332011-09-19 20:26:31 +1000404.. decorator:: skip_unless_symlink()
Eli Benderskye1689652011-05-06 09:29:27 +0300405
406 A decorator for running tests that require support for symbolic links.
407
408
Nick Coghlan2496f332011-09-19 20:26:31 +1000409.. decorator:: anticipate_failure(condition)
410
411 A decorator to conditionally mark tests with
412 :func:`unittest.expectedFailure`. Any use of this decorator should
413 have an associated comment identifying the relevant tracker issue.
414
415
416.. decorator:: run_with_locale(catstr, *locales)
Eli Benderskye1689652011-05-06 09:29:27 +0300417
418 A decorator for running a function in a different locale, correctly
419 resetting it after it has finished. *catstr* is the locale category as
420 a string (for example ``"LC_ALL"``). The *locales* passed will be tried
421 sequentially, and the first valid locale will be used.
422
423
424.. function:: make_bad_fd()
425
426 Create an invalid file descriptor by opening and closing a temporary file,
427 and returning its descripor.
428
429
Nick Coghlanfce769e2009-04-11 14:30:59 +0000430.. function:: import_module(name, deprecated=False)
431
432 This function imports and returns the named module. Unlike a normal
433 import, this function raises :exc:`unittest.SkipTest` if the module
434 cannot be imported.
435
436 Module and package deprecation messages are suppressed during this import
Eli Benderskye1689652011-05-06 09:29:27 +0300437 if *deprecated* is ``True``.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000438
439 .. versionadded:: 3.1
440
441
Nick Coghlan47384702009-04-22 16:13:36 +0000442.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000443
Nick Coghlan47384702009-04-22 16:13:36 +0000444 This function imports and returns a fresh copy of the named Python module
445 by removing the named module from ``sys.modules`` before doing the import.
446 Note that unlike :func:`reload`, the original module is not affected by
447 this operation.
448
449 *fresh* is an iterable of additional module names that are also removed
450 from the ``sys.modules`` cache before doing the import.
451
452 *blocked* is an iterable of module names that are replaced with :const:`0`
453 in the module cache during the import to ensure that attempts to import
454 them raise :exc:`ImportError`.
455
456 The named module and any modules named in the *fresh* and *blocked*
457 parameters are saved before starting the import and then reinserted into
458 ``sys.modules`` when the fresh import is complete.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000459
460 Module and package deprecation messages are suppressed during this import
Eli Benderskye1689652011-05-06 09:29:27 +0300461 if *deprecated* is ``True``.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000462
Eli Benderskyc353f682011-07-27 20:29:59 +0300463 This function will raise :exc:`unittest.SkipTest` if the named module
Nick Coghlan47384702009-04-22 16:13:36 +0000464 cannot be imported.
465
466 Example use::
467
468 # Get copies of the warnings module for testing without
469 # affecting the version being used by the rest of the test suite
470 # One copy uses the C implementation, the other is forced to use
471 # the pure Python fallback implementation
472 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
473 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
474
Nick Coghlanfce769e2009-04-11 14:30:59 +0000475 .. versionadded:: 3.1
476
477
Eli Benderskye1689652011-05-06 09:29:27 +0300478.. function:: bind_port(sock, host=HOST)
479
480 Bind the socket to a free port and return the port number. Relies on
481 ephemeral ports in order to ensure we are using an unbound port. This is
482 important as many tests may be running simultaneously, especially in a
483 buildbot environment. This method raises an exception if the
484 ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is
485 :const:`~socket.SOCK_STREAM`, and the socket has
486 :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it.
487 Tests should never set these socket options for TCP/IP sockets.
488 The only case for setting these options is testing multicasting via
489 multiple UDP sockets.
490
491 Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is
492 available (i.e. on Windows), it will be set on the socket. This will
493 prevent anyone else from binding to our host/port for the duration of the
494 test.
495
496
497.. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM)
498
499 Returns an unused port that should be suitable for binding. This is
500 achieved by creating a temporary socket with the same family and type as
501 the ``sock`` parameter (default is :const:`~socket.AF_INET`,
502 :const:`~socket.SOCK_STREAM`),
503 and binding it to the specified host address (defaults to ``0.0.0.0``)
504 with the port set to 0, eliciting an unused ephemeral port from the OS.
505 The temporary socket is then closed and deleted, and the ephemeral port is
506 returned.
507
508 Either this method or :func:`bind_port` should be used for any tests
509 where a server socket needs to be bound to a particular port for the
510 duration of the test.
511 Which one to use depends on whether the calling code is creating a python
512 socket, or if an unused port needs to be provided in a constructor
513 or passed to an external program (i.e. the ``-accept`` argument to
514 openssl's s_server mode). Always prefer :func:`bind_port` over
515 :func:`find_unused_port` where possible. Using a hard coded port is
516 discouraged since it can makes multiple instances of the test impossible to
517 run simultaneously, which is a problem for buildbots.
518
519
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000520The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +0000521
Georg Brandl7f01a132009-09-16 15:58:14 +0000522.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524 Instances are a context manager that raises :exc:`ResourceDenied` if the
525 specified exception type is raised. Any keyword arguments are treated as
526 attribute/value pairs to be compared against any exception raised within the
527 :keyword:`with` statement. Only if all pairs match properly against
528 attributes on the exception is :exc:`ResourceDenied` raised.
529
Georg Brandl116aa622007-08-15 14:28:22 +0000530
531.. class:: EnvironmentVarGuard()
532
Florent Xicluna53b506b2010-03-18 20:00:57 +0000533 Class used to temporarily set or unset environment variables. Instances can
534 be used as a context manager and have a complete dictionary interface for
535 querying/modifying the underlying ``os.environ``. After exit from the
536 context manager all changes to environment variables done through this
537 instance will be rolled back.
Georg Brandl116aa622007-08-15 14:28:22 +0000538
Georg Brandl705d9d52009-05-05 09:29:50 +0000539 .. versionchanged:: 3.1
Walter Dörwald155374d2009-05-01 19:58:58 +0000540 Added dictionary interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542.. method:: EnvironmentVarGuard.set(envvar, value)
543
Florent Xicluna53b506b2010-03-18 20:00:57 +0000544 Temporarily set the environment variable ``envvar`` to the value of
545 ``value``.
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547
548.. method:: EnvironmentVarGuard.unset(envvar)
549
550 Temporarily unset the environment variable ``envvar``.
Nick Coghlanb1304932008-07-13 12:25:08 +0000551
Walter Dörwald155374d2009-05-01 19:58:58 +0000552
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000553.. class:: WarningsRecorder()
554
555 Class used to record warnings for unit tests. See documentation of
556 :func:`check_warnings` above for more details.