blob: f7ad475402ed93d2fe9e5a27a04a78e4c797fe29 [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
Georg Brandl93a56cd2014-10-30 22:25:41 +010088``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 Xicluna53b506be2010-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 Xicluna53b506be2010-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 Xicluna53b506be2010-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 Xicluna53b506be2010-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
Georg Brandl93a56cd2014-10-30 22:25:41 +0100144 :class:`unittest.TestCase` are run as tests. The :class:`Mixin` class in the example above
R David Murray78fc25c2012-04-09 08:55:42 -0400145 does not have any data and so can't be run by itself, thus it does not
Georg Brandl93a56cd2014-10-30 22:25:41 +0100146 inherit from :class:`unittest.TestCase`.
R David Murray78fc25c2012-04-09 08:55:42 -0400147
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
R David Murrayf1cdb602012-04-09 09:12:57 -0400163test.regrtest` used in previous Python versions still works). Running the
164script by itself automatically starts running all regression tests in the
165:mod:`test` package. It does this by finding all modules in the package whose
166name starts with ``test_``, importing them, and executing the function
167:func:`test_main` if present or loading the tests via
168unittest.TestLoader.loadTestsFromModule if ``test_main`` does not exist. The
169names of tests to execute may also be passed to the script. Specifying a single
170regression test (:program:`python -m test test_spam`) will minimize output and
171only print whether the test passed or failed.
Georg Brandl116aa622007-08-15 14:28:22 +0000172
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000173Running :mod:`test` directly allows what resources are available for
Éric Araujo713d3032010-11-18 16:38:46 +0000174tests to use to be set. You do this by using the ``-u`` command-line
R David Murray644cabe2012-04-11 20:11:53 -0400175option. Specifying ``all`` as the value for the ``-u`` option enables all
176possible resources: :program:`python -m test -uall`.
177If all but one resource is desired (a more common case), a
Georg Brandl116aa622007-08-15 14:28:22 +0000178comma-separated list of resources that are not desired may be listed after
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000179``all``. The command :program:`python -m test -uall,-audio,-largefile`
180will run :mod:`test` with all resources except the ``audio`` and
Éric Araujo713d3032010-11-18 16:38:46 +0000181``largefile`` resources. For a list of all resources and more command-line
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000182options, run :program:`python -m test -h`.
Georg Brandl116aa622007-08-15 14:28:22 +0000183
184Some other ways to execute the regression tests depend on what platform the
Éric Araujo713d3032010-11-18 16:38:46 +0000185tests are being executed on. On Unix, you can run :program:`make test` at the
186top-level directory where Python was built. On Windows,
Florent Xicluna53b506be2010-03-18 20:00:57 +0000187executing :program:`rt.bat` from your :file:`PCBuild` directory will run all
188regression tests.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190
Georg Brandleea6cda2011-07-30 09:00:48 +0200191:mod:`test.support` --- Utilities for the Python test suite
192===========================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000194.. module:: test.support
Georg Brandleea6cda2011-07-30 09:00:48 +0200195 :synopsis: Support for Python's regression test suite.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
197
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000198The :mod:`test.support` module provides support for Python's regression
Georg Brandleea6cda2011-07-30 09:00:48 +0200199test suite.
200
201.. note::
Larry Hastings3732ed22014-03-15 21:13:56 -0700202
Georg Brandleea6cda2011-07-30 09:00:48 +0200203 :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 Xicluna53b506be2010-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 Xicluna53b506be2010-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 Xicluna53b506be2010-03-18 20:00:57 +0000264 Used when tests are executed by :mod:`test.regrtest`.
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000267.. function:: findfile(filename, subdir=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000268
Florent Xicluna53b506be2010-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
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000273 Setting *subdir* indicates a relative path to use to find the file
274 rather than looking directly in the path directories.
275
Georg Brandl116aa622007-08-15 14:28:22 +0000276
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000277.. function:: run_unittest(\*classes)
Georg Brandl116aa622007-08-15 14:28:22 +0000278
279 Execute :class:`unittest.TestCase` subclasses passed to the function. The
Florent Xicluna53b506be2010-03-18 20:00:57 +0000280 function scans the classes for methods starting with the prefix ``test_``
281 and executes the tests individually.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283 It is also legal to pass strings as parameters; these should be keys in
284 ``sys.modules``. Each associated module will be scanned by
285 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
286 following :func:`test_main` function::
287
288 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +0000289 support.run_unittest(__name__)
Georg Brandl116aa622007-08-15 14:28:22 +0000290
291 This will run all tests defined in the named module.
292
Georg Brandl116aa622007-08-15 14:28:22 +0000293
Eli Benderskye1689652011-05-06 09:29:27 +0300294.. function:: run_doctest(module, verbosity=None)
295
296 Run :func:`doctest.testmod` on the given *module*. Return
297 ``(failure_count, test_count)``.
298
299 If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity
300 set to :data:`verbose`. Otherwise, it is run with verbosity set to
301 ``None``.
302
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000303.. function:: check_warnings(\*filters, quiet=True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000304
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000305 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
306 easier to test that a warning was correctly raised. It is approximately
307 equivalent to calling ``warnings.catch_warnings(record=True)`` with
308 :meth:`warnings.simplefilter` set to ``always`` and with the option to
309 automatically validate the results that are recorded.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000310
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000311 ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
312 WarningCategory)`` as positional arguments. If one or more *filters* are
Eli Benderskye1689652011-05-06 09:29:27 +0300313 provided, or if the optional keyword argument *quiet* is ``False``,
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000314 it checks to make sure the warnings are as expected: each specified filter
315 must match at least one of the warnings raised by the enclosed code or the
316 test fails, and if any warnings are raised that do not match any of the
317 specified filters the test fails. To disable the first of these checks,
Eli Benderskye1689652011-05-06 09:29:27 +0300318 set *quiet* to ``True``.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000319
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000320 If no arguments are specified, it defaults to::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000321
Florent Xicluna53b506be2010-03-18 20:00:57 +0000322 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000323
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000324 In this case all warnings are caught and no errors are raised.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000325
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000326 On entry to the context manager, a :class:`WarningRecorder` instance is
327 returned. The underlying warnings list from
328 :func:`~warnings.catch_warnings` is available via the recorder object's
329 :attr:`warnings` attribute. As a convenience, the attributes of the object
330 representing the most recent warning can also be accessed directly through
331 the recorder object (see example below). If no warning has been raised,
332 then any of the attributes that would otherwise be expected on an object
Eli Benderskye1689652011-05-06 09:29:27 +0300333 representing a warning will return ``None``.
Thomas Woutersed03b412007-08-28 21:37:11 +0000334
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000335 The recorder object also has a :meth:`reset` method, which clears the
336 warnings list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000337
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000338 The context manager is designed to be used like this::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000339
340 with check_warnings(("assertion is always true", SyntaxWarning),
341 ("", UserWarning)):
342 exec('assert(False, "Hey!")')
343 warnings.warn(UserWarning("Hide me!"))
344
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000345 In this case if either warning was not raised, or some other warning was
346 raised, :func:`check_warnings` would raise an error.
347
348 When a test needs to look more deeply into the warnings, rather than
349 just checking whether or not they occurred, code like this can be used::
350
Florent Xiclunab14930c2010-03-13 15:26:44 +0000351 with check_warnings(quiet=True) as w:
Thomas Woutersed03b412007-08-28 21:37:11 +0000352 warnings.warn("foo")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000353 assert str(w.args[0]) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000354 warnings.warn("bar")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000355 assert str(w.args[0]) == "bar"
356 assert str(w.warnings[0].args[0]) == "foo"
357 assert str(w.warnings[1].args[0]) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000358 w.reset()
359 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000360
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000361
362 Here all warnings will be caught, and the test code tests the captured
363 warnings directly.
364
Ezio Melottif8754a62010-03-21 07:16:43 +0000365 .. versionchanged:: 3.2
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000366 New optional arguments *filters* and *quiet*.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000367
Thomas Woutersed03b412007-08-28 21:37:11 +0000368
R David Murray5a33f812013-07-11 12:28:40 -0400369.. function:: captured_stdin()
370 captured_stdout()
371 captured_stderr()
Thomas Woutersed03b412007-08-28 21:37:11 +0000372
R David Murray5a33f812013-07-11 12:28:40 -0400373 A context managers that temporarily replaces the named stream with
374 :class:`io.StringIO` object.
Thomas Woutersed03b412007-08-28 21:37:11 +0000375
R David Murray5a33f812013-07-11 12:28:40 -0400376 Example use with output streams::
Thomas Woutersed03b412007-08-28 21:37:11 +0000377
R David Murray5a33f812013-07-11 12:28:40 -0400378 with captured_stdout() as stdout, captured_stderr() as stderr:
Collin Winterc79461b2007-09-01 23:34:30 +0000379 print("hello")
R David Murray5a33f812013-07-11 12:28:40 -0400380 print("error", file=sys.stderr)
381 assert stdout.getvalue() == "hello\n"
382 assert stderr.getvalue() == "error\n"
383
384 Example use with input stream::
385
386 with captured_stdin() as stdin:
387 stdin.write('hello\n')
388 stdin.seek(0)
389 # call test code that consumes from sys.stdin
390 captured = input()
391 self.assertEqual(captured, "hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000392
Thomas Woutersed03b412007-08-28 21:37:11 +0000393
Nick Coghlan55175962013-07-28 22:11:50 +1000394.. function:: temp_dir(path=None, quiet=False)
395
396 A context manager that creates a temporary directory at *path* and
397 yields the directory.
398
399 If *path* is None, the temporary directory is created using
400 :func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager
401 raises an exception on error. Otherwise, if *path* is specified and
402 cannot be created, only a warning is issued.
403
404
405.. function:: change_cwd(path, quiet=False)
Eli Benderskye1689652011-05-06 09:29:27 +0300406
407 A context manager that temporarily changes the current working
Nick Coghlan55175962013-07-28 22:11:50 +1000408 directory to *path* and yields the directory.
Eli Benderskye1689652011-05-06 09:29:27 +0300409
Nick Coghlan55175962013-07-28 22:11:50 +1000410 If *quiet* is ``False``, the context manager raises an exception
411 on error. Otherwise, it issues only a warning and keeps the current
412 working directory the same.
Eli Benderskye1689652011-05-06 09:29:27 +0300413
Nick Coghlan55175962013-07-28 22:11:50 +1000414
415.. function:: temp_cwd(name='tempcwd', quiet=False)
416
417 A context manager that temporarily creates a new directory and
418 changes the current working directory (CWD).
419
420 The context manager creates a temporary directory in the current
421 directory with name *name* before temporarily changing the current
422 working directory. If *name* is None, the temporary directory is
423 created using :func:`tempfile.mkdtemp`.
424
425 If *quiet* is ``False`` and it is not possible to create or change
426 the CWD, an error is raised. Otherwise, only a warning is raised
427 and the original CWD is used.
Eli Benderskye1689652011-05-06 09:29:27 +0300428
429
430.. function:: temp_umask(umask)
431
432 A context manager that temporarily sets the process umask.
433
434
435.. function:: can_symlink()
436
437 Return ``True`` if the OS supports symbolic links, ``False``
438 otherwise.
439
440
Nick Coghlan2496f332011-09-19 20:26:31 +1000441.. decorator:: skip_unless_symlink()
Eli Benderskye1689652011-05-06 09:29:27 +0300442
443 A decorator for running tests that require support for symbolic links.
444
445
Nick Coghlan2496f332011-09-19 20:26:31 +1000446.. decorator:: anticipate_failure(condition)
447
448 A decorator to conditionally mark tests with
449 :func:`unittest.expectedFailure`. Any use of this decorator should
450 have an associated comment identifying the relevant tracker issue.
451
452
453.. decorator:: run_with_locale(catstr, *locales)
Eli Benderskye1689652011-05-06 09:29:27 +0300454
455 A decorator for running a function in a different locale, correctly
456 resetting it after it has finished. *catstr* is the locale category as
457 a string (for example ``"LC_ALL"``). The *locales* passed will be tried
458 sequentially, and the first valid locale will be used.
459
460
461.. function:: make_bad_fd()
462
463 Create an invalid file descriptor by opening and closing a temporary file,
Zachary Waref012ba42014-07-23 12:00:29 -0500464 and returning its descriptor.
Eli Benderskye1689652011-05-06 09:29:27 +0300465
466
Nick Coghlanfce769e2009-04-11 14:30:59 +0000467.. function:: import_module(name, deprecated=False)
468
469 This function imports and returns the named module. Unlike a normal
470 import, this function raises :exc:`unittest.SkipTest` if the module
471 cannot be imported.
472
473 Module and package deprecation messages are suppressed during this import
Eli Benderskye1689652011-05-06 09:29:27 +0300474 if *deprecated* is ``True``.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000475
476 .. versionadded:: 3.1
477
478
Nick Coghlan47384702009-04-22 16:13:36 +0000479.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000480
Nick Coghlan47384702009-04-22 16:13:36 +0000481 This function imports and returns a fresh copy of the named Python module
482 by removing the named module from ``sys.modules`` before doing the import.
483 Note that unlike :func:`reload`, the original module is not affected by
484 this operation.
485
486 *fresh* is an iterable of additional module names that are also removed
487 from the ``sys.modules`` cache before doing the import.
488
Eli Benderskyba5517d2013-08-11 15:38:08 -0700489 *blocked* is an iterable of module names that are replaced with ``None``
Nick Coghlan47384702009-04-22 16:13:36 +0000490 in the module cache during the import to ensure that attempts to import
491 them raise :exc:`ImportError`.
492
493 The named module and any modules named in the *fresh* and *blocked*
494 parameters are saved before starting the import and then reinserted into
495 ``sys.modules`` when the fresh import is complete.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000496
497 Module and package deprecation messages are suppressed during this import
Eli Benderskye1689652011-05-06 09:29:27 +0300498 if *deprecated* is ``True``.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000499
Eli Benderskyba5517d2013-08-11 15:38:08 -0700500 This function will raise :exc:`ImportError` if the named module cannot be
501 imported.
Nick Coghlan47384702009-04-22 16:13:36 +0000502
503 Example use::
504
Eli Benderskyba5517d2013-08-11 15:38:08 -0700505 # Get copies of the warnings module for testing without affecting the
506 # version being used by the rest of the test suite. One copy uses the
507 # C implementation, the other is forced to use the pure Python fallback
508 # implementation
Nick Coghlan47384702009-04-22 16:13:36 +0000509 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
510 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
511
Nick Coghlanfce769e2009-04-11 14:30:59 +0000512 .. versionadded:: 3.1
513
514
Eli Benderskye1689652011-05-06 09:29:27 +0300515.. function:: bind_port(sock, host=HOST)
516
517 Bind the socket to a free port and return the port number. Relies on
518 ephemeral ports in order to ensure we are using an unbound port. This is
519 important as many tests may be running simultaneously, especially in a
520 buildbot environment. This method raises an exception if the
521 ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is
522 :const:`~socket.SOCK_STREAM`, and the socket has
523 :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it.
524 Tests should never set these socket options for TCP/IP sockets.
525 The only case for setting these options is testing multicasting via
526 multiple UDP sockets.
527
528 Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is
529 available (i.e. on Windows), it will be set on the socket. This will
530 prevent anyone else from binding to our host/port for the duration of the
531 test.
532
533
534.. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM)
535
536 Returns an unused port that should be suitable for binding. This is
537 achieved by creating a temporary socket with the same family and type as
538 the ``sock`` parameter (default is :const:`~socket.AF_INET`,
539 :const:`~socket.SOCK_STREAM`),
540 and binding it to the specified host address (defaults to ``0.0.0.0``)
541 with the port set to 0, eliciting an unused ephemeral port from the OS.
542 The temporary socket is then closed and deleted, and the ephemeral port is
543 returned.
544
545 Either this method or :func:`bind_port` should be used for any tests
546 where a server socket needs to be bound to a particular port for the
547 duration of the test.
548 Which one to use depends on whether the calling code is creating a python
549 socket, or if an unused port needs to be provided in a constructor
550 or passed to an external program (i.e. the ``-accept`` argument to
551 openssl's s_server mode). Always prefer :func:`bind_port` over
552 :func:`find_unused_port` where possible. Using a hard coded port is
553 discouraged since it can makes multiple instances of the test impossible to
554 run simultaneously, which is a problem for buildbots.
555
556
Zachary Waref012ba42014-07-23 12:00:29 -0500557.. function:: load_package_tests(pkg_dir, loader, standard_tests, pattern)
558
559 Generic implementation of the :mod:`unittest` ``load_tests`` protocol for
560 use in test packages. *pkg_dir* is the root directory of the package;
561 *loader*, *standard_tests*, and *pattern* are the arguments expected by
562 ``load_tests``. In simple cases, the test package's ``__init__.py``
563 can be the following::
564
565 import os
566 from test.support import load_package_tests
567
568 def load_tests(*args):
569 return load_package_tests(os.path.dirname(__file__), *args)
570
Gregory P. Smith4e72cce2015-04-14 13:26:06 -0700571.. function:: detect_api_mismatch(ref_api, other_api, *, ignore=()):
572
Zachary Ware3d3aedc2015-07-07 00:07:25 -0500573 Returns the set of attributes, functions or methods of *ref_api* not
574 found on *other_api*, except for a defined list of items to be
575 ignored in this check specified in *ignore*.
Gregory P. Smith4e72cce2015-04-14 13:26:06 -0700576
577 By default this skips private attributes beginning with '_' but
578 includes all magic methods, i.e. those starting and ending in '__'.
579
Gregory P. Smith7c63fd32015-04-14 15:25:01 -0700580 .. versionadded:: 3.5
581
Zachary Waref012ba42014-07-23 12:00:29 -0500582
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000583The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +0000584
Georg Brandl7f01a132009-09-16 15:58:14 +0000585.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000586
587 Instances are a context manager that raises :exc:`ResourceDenied` if the
588 specified exception type is raised. Any keyword arguments are treated as
589 attribute/value pairs to be compared against any exception raised within the
590 :keyword:`with` statement. Only if all pairs match properly against
591 attributes on the exception is :exc:`ResourceDenied` raised.
592
Georg Brandl116aa622007-08-15 14:28:22 +0000593
594.. class:: EnvironmentVarGuard()
595
Florent Xicluna53b506be2010-03-18 20:00:57 +0000596 Class used to temporarily set or unset environment variables. Instances can
597 be used as a context manager and have a complete dictionary interface for
598 querying/modifying the underlying ``os.environ``. After exit from the
599 context manager all changes to environment variables done through this
600 instance will be rolled back.
Georg Brandl116aa622007-08-15 14:28:22 +0000601
Georg Brandl705d9d52009-05-05 09:29:50 +0000602 .. versionchanged:: 3.1
Walter Dörwald155374d2009-05-01 19:58:58 +0000603 Added dictionary interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000604
605.. method:: EnvironmentVarGuard.set(envvar, value)
606
Florent Xicluna53b506be2010-03-18 20:00:57 +0000607 Temporarily set the environment variable ``envvar`` to the value of
608 ``value``.
Georg Brandl116aa622007-08-15 14:28:22 +0000609
610
611.. method:: EnvironmentVarGuard.unset(envvar)
612
613 Temporarily unset the environment variable ``envvar``.
Nick Coghlanb1304932008-07-13 12:25:08 +0000614
Walter Dörwald155374d2009-05-01 19:58:58 +0000615
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200616.. class:: SuppressCrashReport()
617
618 A context manager used to try to prevent crash dialog popups on tests that
619 are expected to crash a subprocess.
620
621 On Windows, it disables Windows Error Reporting dialogs using
622 `SetErrorMode <http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx>`_.
623
624 On UNIX, :func:`resource.setrlimit` is used to set
625 :attr:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file
626 creation.
627
628 On both platforms, the old value is restored by :meth:`__exit__`.
629
630
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000631.. class:: WarningsRecorder()
632
633 Class used to record warnings for unit tests. See documentation of
634 :func:`check_warnings` above for more details.