blob: 2c515497ca85743d9c79ddbc1e2226d98fcd697e [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 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
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
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::
202 :mod:`test.support` is not a public module. It is documented here to help
203 Python developers write tests. The API of this module is subject to change
204 without backwards compatibility concerns between releases.
205
Georg Brandl116aa622007-08-15 14:28:22 +0000206
207This module defines the following exceptions:
208
Georg Brandl116aa622007-08-15 14:28:22 +0000209.. exception:: TestFailed
210
211 Exception to be raised when a test fails. This is deprecated in favor of
212 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
213 methods.
214
215
Georg Brandl116aa622007-08-15 14:28:22 +0000216.. exception:: ResourceDenied
217
Florent Xicluna53b506be2010-03-18 20:00:57 +0000218 Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a
219 network connection) is not available. Raised by the :func:`requires`
220 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Georg Brandl116aa622007-08-15 14:28:22 +0000222
Georg Brandleea6cda2011-07-30 09:00:48 +0200223The :mod:`test.support` module defines the following constants:
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225.. data:: verbose
226
Eli Benderskye1689652011-05-06 09:29:27 +0300227 ``True`` when verbose output is enabled. Should be checked when more
Georg Brandl116aa622007-08-15 14:28:22 +0000228 detailed information is desired about a running test. *verbose* is set by
229 :mod:`test.regrtest`.
230
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232.. data:: is_jython
233
Eli Benderskye1689652011-05-06 09:29:27 +0300234 ``True`` if the running interpreter is Jython.
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236
237.. data:: TESTFN
238
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000239 Set to a name that is safe to use as the name of a temporary file. Any
240 temporary file that is created should be closed and unlinked (removed).
Georg Brandl116aa622007-08-15 14:28:22 +0000241
Eli Benderskye1689652011-05-06 09:29:27 +0300242
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000243The :mod:`test.support` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000244
Georg Brandl116aa622007-08-15 14:28:22 +0000245.. function:: forget(module_name)
246
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000247 Remove the module named *module_name* from ``sys.modules`` and delete any
Georg Brandl116aa622007-08-15 14:28:22 +0000248 byte-compiled files of the module.
249
250
251.. function:: is_resource_enabled(resource)
252
Eli Benderskye1689652011-05-06 09:29:27 +0300253 Return ``True`` if *resource* is enabled and available. The list of
Georg Brandl116aa622007-08-15 14:28:22 +0000254 available resources is only set when :mod:`test.regrtest` is executing the
255 tests.
256
257
Georg Brandl7f01a132009-09-16 15:58:14 +0000258.. function:: requires(resource, msg=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Florent Xiclunab14930c2010-03-13 15:26:44 +0000260 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
Florent Xicluna53b506be2010-03-18 20:00:57 +0000261 argument to :exc:`ResourceDenied` if it is raised. Always returns
Eli Benderskye1689652011-05-06 09:29:27 +0300262 ``True`` if called by a function whose ``__name__`` is ``'__main__'``.
Florent Xicluna53b506be2010-03-18 20:00:57 +0000263 Used when tests are executed by :mod:`test.regrtest`.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000266.. function:: findfile(filename, subdir=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000267
Florent Xicluna53b506be2010-03-18 20:00:57 +0000268 Return the path to the file named *filename*. If no match is found
269 *filename* is returned. This does not equal a failure since it could be the
270 path to the file.
Georg Brandl116aa622007-08-15 14:28:22 +0000271
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000272 Setting *subdir* indicates a relative path to use to find the file
273 rather than looking directly in the path directories.
274
Georg Brandl116aa622007-08-15 14:28:22 +0000275
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000276.. function:: run_unittest(\*classes)
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278 Execute :class:`unittest.TestCase` subclasses passed to the function. The
Florent Xicluna53b506be2010-03-18 20:00:57 +0000279 function scans the classes for methods starting with the prefix ``test_``
280 and executes the tests individually.
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282 It is also legal to pass strings as parameters; these should be keys in
283 ``sys.modules``. Each associated module will be scanned by
284 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
285 following :func:`test_main` function::
286
287 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +0000288 support.run_unittest(__name__)
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290 This will run all tests defined in the named module.
291
Georg Brandl116aa622007-08-15 14:28:22 +0000292
Eli Benderskye1689652011-05-06 09:29:27 +0300293.. function:: run_doctest(module, verbosity=None)
294
295 Run :func:`doctest.testmod` on the given *module*. Return
296 ``(failure_count, test_count)``.
297
298 If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity
299 set to :data:`verbose`. Otherwise, it is run with verbosity set to
300 ``None``.
301
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000302.. function:: check_warnings(\*filters, quiet=True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000303
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000304 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
305 easier to test that a warning was correctly raised. It is approximately
306 equivalent to calling ``warnings.catch_warnings(record=True)`` with
307 :meth:`warnings.simplefilter` set to ``always`` and with the option to
308 automatically validate the results that are recorded.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000309
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000310 ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
311 WarningCategory)`` as positional arguments. If one or more *filters* are
Eli Benderskye1689652011-05-06 09:29:27 +0300312 provided, or if the optional keyword argument *quiet* is ``False``,
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000313 it checks to make sure the warnings are as expected: each specified filter
314 must match at least one of the warnings raised by the enclosed code or the
315 test fails, and if any warnings are raised that do not match any of the
316 specified filters the test fails. To disable the first of these checks,
Eli Benderskye1689652011-05-06 09:29:27 +0300317 set *quiet* to ``True``.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000318
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000319 If no arguments are specified, it defaults to::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000320
Florent Xicluna53b506be2010-03-18 20:00:57 +0000321 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000322
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000323 In this case all warnings are caught and no errors are raised.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000324
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000325 On entry to the context manager, a :class:`WarningRecorder` instance is
326 returned. The underlying warnings list from
327 :func:`~warnings.catch_warnings` is available via the recorder object's
328 :attr:`warnings` attribute. As a convenience, the attributes of the object
329 representing the most recent warning can also be accessed directly through
330 the recorder object (see example below). If no warning has been raised,
331 then any of the attributes that would otherwise be expected on an object
Eli Benderskye1689652011-05-06 09:29:27 +0300332 representing a warning will return ``None``.
Thomas Woutersed03b412007-08-28 21:37:11 +0000333
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000334 The recorder object also has a :meth:`reset` method, which clears the
335 warnings list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000336
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000337 The context manager is designed to be used like this::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000338
339 with check_warnings(("assertion is always true", SyntaxWarning),
340 ("", UserWarning)):
341 exec('assert(False, "Hey!")')
342 warnings.warn(UserWarning("Hide me!"))
343
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000344 In this case if either warning was not raised, or some other warning was
345 raised, :func:`check_warnings` would raise an error.
346
347 When a test needs to look more deeply into the warnings, rather than
348 just checking whether or not they occurred, code like this can be used::
349
Florent Xiclunab14930c2010-03-13 15:26:44 +0000350 with check_warnings(quiet=True) as w:
Thomas Woutersed03b412007-08-28 21:37:11 +0000351 warnings.warn("foo")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000352 assert str(w.args[0]) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000353 warnings.warn("bar")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000354 assert str(w.args[0]) == "bar"
355 assert str(w.warnings[0].args[0]) == "foo"
356 assert str(w.warnings[1].args[0]) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000357 w.reset()
358 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000359
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000360
361 Here all warnings will be caught, and the test code tests the captured
362 warnings directly.
363
Ezio Melottif8754a62010-03-21 07:16:43 +0000364 .. versionchanged:: 3.2
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000365 New optional arguments *filters* and *quiet*.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000366
Thomas Woutersed03b412007-08-28 21:37:11 +0000367
R David Murray5a33f812013-07-11 12:28:40 -0400368.. function:: captured_stdin()
369 captured_stdout()
370 captured_stderr()
Thomas Woutersed03b412007-08-28 21:37:11 +0000371
R David Murray5a33f812013-07-11 12:28:40 -0400372 A context managers that temporarily replaces the named stream with
373 :class:`io.StringIO` object.
Thomas Woutersed03b412007-08-28 21:37:11 +0000374
R David Murray5a33f812013-07-11 12:28:40 -0400375 Example use with output streams::
Thomas Woutersed03b412007-08-28 21:37:11 +0000376
R David Murray5a33f812013-07-11 12:28:40 -0400377 with captured_stdout() as stdout, captured_stderr() as stderr:
Collin Winterc79461b2007-09-01 23:34:30 +0000378 print("hello")
R David Murray5a33f812013-07-11 12:28:40 -0400379 print("error", file=sys.stderr)
380 assert stdout.getvalue() == "hello\n"
381 assert stderr.getvalue() == "error\n"
382
383 Example use with input stream::
384
385 with captured_stdin() as stdin:
386 stdin.write('hello\n')
387 stdin.seek(0)
388 # call test code that consumes from sys.stdin
389 captured = input()
390 self.assertEqual(captured, "hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000391
Thomas Woutersed03b412007-08-28 21:37:11 +0000392
Nick Coghlan55175962013-07-28 22:11:50 +1000393.. function:: temp_dir(path=None, quiet=False)
394
395 A context manager that creates a temporary directory at *path* and
396 yields the directory.
397
398 If *path* is None, the temporary directory is created using
399 :func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager
400 raises an exception on error. Otherwise, if *path* is specified and
401 cannot be created, only a warning is issued.
402
403
404.. function:: change_cwd(path, quiet=False)
Eli Benderskye1689652011-05-06 09:29:27 +0300405
406 A context manager that temporarily changes the current working
Nick Coghlan55175962013-07-28 22:11:50 +1000407 directory to *path* and yields the directory.
Eli Benderskye1689652011-05-06 09:29:27 +0300408
Nick Coghlan55175962013-07-28 22:11:50 +1000409 If *quiet* is ``False``, the context manager raises an exception
410 on error. Otherwise, it issues only a warning and keeps the current
411 working directory the same.
Eli Benderskye1689652011-05-06 09:29:27 +0300412
Nick Coghlan55175962013-07-28 22:11:50 +1000413
414.. function:: temp_cwd(name='tempcwd', quiet=False)
415
416 A context manager that temporarily creates a new directory and
417 changes the current working directory (CWD).
418
419 The context manager creates a temporary directory in the current
420 directory with name *name* before temporarily changing the current
421 working directory. If *name* is None, the temporary directory is
422 created using :func:`tempfile.mkdtemp`.
423
424 If *quiet* is ``False`` and it is not possible to create or change
425 the CWD, an error is raised. Otherwise, only a warning is raised
426 and the original CWD is used.
Eli Benderskye1689652011-05-06 09:29:27 +0300427
428
429.. function:: temp_umask(umask)
430
431 A context manager that temporarily sets the process umask.
432
433
434.. function:: can_symlink()
435
436 Return ``True`` if the OS supports symbolic links, ``False``
437 otherwise.
438
439
Nick Coghlan2496f332011-09-19 20:26:31 +1000440.. decorator:: skip_unless_symlink()
Eli Benderskye1689652011-05-06 09:29:27 +0300441
442 A decorator for running tests that require support for symbolic links.
443
444
Nick Coghlan2496f332011-09-19 20:26:31 +1000445.. decorator:: anticipate_failure(condition)
446
447 A decorator to conditionally mark tests with
448 :func:`unittest.expectedFailure`. Any use of this decorator should
449 have an associated comment identifying the relevant tracker issue.
450
451
452.. decorator:: run_with_locale(catstr, *locales)
Eli Benderskye1689652011-05-06 09:29:27 +0300453
454 A decorator for running a function in a different locale, correctly
455 resetting it after it has finished. *catstr* is the locale category as
456 a string (for example ``"LC_ALL"``). The *locales* passed will be tried
457 sequentially, and the first valid locale will be used.
458
459
460.. function:: make_bad_fd()
461
462 Create an invalid file descriptor by opening and closing a temporary file,
463 and returning its descripor.
464
465
Nick Coghlanfce769e2009-04-11 14:30:59 +0000466.. function:: import_module(name, deprecated=False)
467
468 This function imports and returns the named module. Unlike a normal
469 import, this function raises :exc:`unittest.SkipTest` if the module
470 cannot be imported.
471
472 Module and package deprecation messages are suppressed during this import
Eli Benderskye1689652011-05-06 09:29:27 +0300473 if *deprecated* is ``True``.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000474
475 .. versionadded:: 3.1
476
477
Nick Coghlan47384702009-04-22 16:13:36 +0000478.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000479
Nick Coghlan47384702009-04-22 16:13:36 +0000480 This function imports and returns a fresh copy of the named Python module
481 by removing the named module from ``sys.modules`` before doing the import.
482 Note that unlike :func:`reload`, the original module is not affected by
483 this operation.
484
485 *fresh* is an iterable of additional module names that are also removed
486 from the ``sys.modules`` cache before doing the import.
487
Eli Benderskyba5517d2013-08-11 15:38:08 -0700488 *blocked* is an iterable of module names that are replaced with ``None``
Nick Coghlan47384702009-04-22 16:13:36 +0000489 in the module cache during the import to ensure that attempts to import
490 them raise :exc:`ImportError`.
491
492 The named module and any modules named in the *fresh* and *blocked*
493 parameters are saved before starting the import and then reinserted into
494 ``sys.modules`` when the fresh import is complete.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000495
496 Module and package deprecation messages are suppressed during this import
Eli Benderskye1689652011-05-06 09:29:27 +0300497 if *deprecated* is ``True``.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000498
Eli Benderskyba5517d2013-08-11 15:38:08 -0700499 This function will raise :exc:`ImportError` if the named module cannot be
500 imported.
Nick Coghlan47384702009-04-22 16:13:36 +0000501
502 Example use::
503
Eli Benderskyba5517d2013-08-11 15:38:08 -0700504 # Get copies of the warnings module for testing without affecting the
505 # version being used by the rest of the test suite. One copy uses the
506 # C implementation, the other is forced to use the pure Python fallback
507 # implementation
Nick Coghlan47384702009-04-22 16:13:36 +0000508 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
509 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
510
Nick Coghlanfce769e2009-04-11 14:30:59 +0000511 .. versionadded:: 3.1
512
513
Eli Benderskye1689652011-05-06 09:29:27 +0300514.. function:: bind_port(sock, host=HOST)
515
516 Bind the socket to a free port and return the port number. Relies on
517 ephemeral ports in order to ensure we are using an unbound port. This is
518 important as many tests may be running simultaneously, especially in a
519 buildbot environment. This method raises an exception if the
520 ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is
521 :const:`~socket.SOCK_STREAM`, and the socket has
522 :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it.
523 Tests should never set these socket options for TCP/IP sockets.
524 The only case for setting these options is testing multicasting via
525 multiple UDP sockets.
526
527 Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is
528 available (i.e. on Windows), it will be set on the socket. This will
529 prevent anyone else from binding to our host/port for the duration of the
530 test.
531
532
533.. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM)
534
535 Returns an unused port that should be suitable for binding. This is
536 achieved by creating a temporary socket with the same family and type as
537 the ``sock`` parameter (default is :const:`~socket.AF_INET`,
538 :const:`~socket.SOCK_STREAM`),
539 and binding it to the specified host address (defaults to ``0.0.0.0``)
540 with the port set to 0, eliciting an unused ephemeral port from the OS.
541 The temporary socket is then closed and deleted, and the ephemeral port is
542 returned.
543
544 Either this method or :func:`bind_port` should be used for any tests
545 where a server socket needs to be bound to a particular port for the
546 duration of the test.
547 Which one to use depends on whether the calling code is creating a python
548 socket, or if an unused port needs to be provided in a constructor
549 or passed to an external program (i.e. the ``-accept`` argument to
550 openssl's s_server mode). Always prefer :func:`bind_port` over
551 :func:`find_unused_port` where possible. Using a hard coded port is
552 discouraged since it can makes multiple instances of the test impossible to
553 run simultaneously, which is a problem for buildbots.
554
555
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000556The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +0000557
Georg Brandl7f01a132009-09-16 15:58:14 +0000558.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000559
560 Instances are a context manager that raises :exc:`ResourceDenied` if the
561 specified exception type is raised. Any keyword arguments are treated as
562 attribute/value pairs to be compared against any exception raised within the
563 :keyword:`with` statement. Only if all pairs match properly against
564 attributes on the exception is :exc:`ResourceDenied` raised.
565
Georg Brandl116aa622007-08-15 14:28:22 +0000566
567.. class:: EnvironmentVarGuard()
568
Florent Xicluna53b506be2010-03-18 20:00:57 +0000569 Class used to temporarily set or unset environment variables. Instances can
570 be used as a context manager and have a complete dictionary interface for
571 querying/modifying the underlying ``os.environ``. After exit from the
572 context manager all changes to environment variables done through this
573 instance will be rolled back.
Georg Brandl116aa622007-08-15 14:28:22 +0000574
Georg Brandl705d9d52009-05-05 09:29:50 +0000575 .. versionchanged:: 3.1
Walter Dörwald155374d2009-05-01 19:58:58 +0000576 Added dictionary interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000577
578.. method:: EnvironmentVarGuard.set(envvar, value)
579
Florent Xicluna53b506be2010-03-18 20:00:57 +0000580 Temporarily set the environment variable ``envvar`` to the value of
581 ``value``.
Georg Brandl116aa622007-08-15 14:28:22 +0000582
583
584.. method:: EnvironmentVarGuard.unset(envvar)
585
586 Temporarily unset the environment variable ``envvar``.
Nick Coghlanb1304932008-07-13 12:25:08 +0000587
Walter Dörwald155374d2009-05-01 19:58:58 +0000588
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200589.. class:: SuppressCrashReport()
590
591 A context manager used to try to prevent crash dialog popups on tests that
592 are expected to crash a subprocess.
593
594 On Windows, it disables Windows Error Reporting dialogs using
595 `SetErrorMode <http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx>`_.
596
597 On UNIX, :func:`resource.setrlimit` is used to set
598 :attr:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file
599 creation.
600
601 On both platforms, the old value is restored by :meth:`__exit__`.
602
603
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000604.. class:: WarningsRecorder()
605
606 Class used to record warnings for unit tests. See documentation of
607 :func:`check_warnings` above for more details.