blob: fab3e1fe4cc6adcf9be5760b9f8d32d383fbbb44 [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.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. sectionauthor:: Brett Cannon <brett@python.org>
8
Antoine Pitrou197c9c92010-12-18 12:33:06 +00009.. note::
Antoine Pitrou36730e82010-12-12 18:25:25 +000010 The :mod:`test` package is meant for internal use by Python only. It is
11 documented for the benefit of the core developers of Python. Any use of
12 this package outside of Python's standard library is discouraged as code
13 mentioned here can change or be removed without notice between releases of
14 Python.
Brett Cannon3a4e50c2010-07-23 11:31:31 +000015
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040016--------------
Georg Brandl116aa622007-08-15 14:28:22 +000017
18The :mod:`test` package contains all regression tests for Python as well as the
Nick Coghlan47384702009-04-22 16:13:36 +000019modules :mod:`test.support` and :mod:`test.regrtest`.
20:mod:`test.support` is used to enhance your tests while
Georg Brandl116aa622007-08-15 14:28:22 +000021:mod:`test.regrtest` drives the testing suite.
22
23Each module in the :mod:`test` package whose name starts with ``test_`` is a
24testing suite for a specific module or feature. All new tests should be written
25using the :mod:`unittest` or :mod:`doctest` module. Some older tests are
26written using a "traditional" testing style that compares output printed to
27``sys.stdout``; this style of test is considered deprecated.
28
29
30.. seealso::
31
32 Module :mod:`unittest`
33 Writing PyUnit regression tests.
34
35 Module :mod:`doctest`
36 Tests embedded in documentation strings.
37
38
39.. _writing-tests:
40
41Writing Unit Tests for the :mod:`test` package
42----------------------------------------------
43
Georg Brandl116aa622007-08-15 14:28:22 +000044It is preferred that tests that use the :mod:`unittest` module follow a few
45guidelines. One is to name the test module by starting it with ``test_`` and end
46it with the name of the module being tested. The test methods in the test module
47should start with ``test_`` and end with a description of what the method is
48testing. This is needed so that the methods are recognized by the test driver as
49test methods. Also, no documentation string for the method should be included. A
50comment (such as ``# Tests function returns only True or False``) should be used
51to provide documentation for test methods. This is done because documentation
52strings get printed out if they exist and thus what test is being run is not
53stated.
54
55A basic boilerplate is often used::
56
57 import unittest
Nick Coghlan47384702009-04-22 16:13:36 +000058 from test import support
Georg Brandl116aa622007-08-15 14:28:22 +000059
60 class MyTestCase1(unittest.TestCase):
61
62 # Only use setUp() and tearDown() if necessary
63
64 def setUp(self):
65 ... code to execute in preparation for tests ...
66
67 def tearDown(self):
68 ... code to execute to clean up after tests ...
69
70 def test_feature_one(self):
71 # Test feature one.
72 ... testing code ...
73
74 def test_feature_two(self):
75 # Test feature two.
76 ... testing code ...
77
78 ... more test methods ...
79
80 class MyTestCase2(unittest.TestCase):
81 ... same structure as MyTestCase1 ...
82
83 ... more test classes ...
84
Georg Brandl116aa622007-08-15 14:28:22 +000085 if __name__ == '__main__':
R David Murray78fc25c2012-04-09 08:55:42 -040086 unittest.main()
Georg Brandl116aa622007-08-15 14:28:22 +000087
R David Murray78fc25c2012-04-09 08:55:42 -040088This code pattern allows the testing suite to be run by :mod:`test.regrtest`,
89on its own as a script that supports the :mod:`unittest` CLI, or via the
Georg Brandl93a56cd2014-10-30 22:25:41 +010090``python -m unittest`` CLI.
Georg Brandl116aa622007-08-15 14:28:22 +000091
92The goal for regression testing is to try to break code. This leads to a few
93guidelines to be followed:
94
95* The testing suite should exercise all classes, functions, and constants. This
Florent Xicluna53b506be2010-03-18 20:00:57 +000096 includes not just the external API that is to be presented to the outside
97 world but also "private" code.
Georg Brandl116aa622007-08-15 14:28:22 +000098
99* Whitebox testing (examining the code being tested when the tests are being
100 written) is preferred. Blackbox testing (testing only the published user
Florent Xicluna53b506be2010-03-18 20:00:57 +0000101 interface) is not complete enough to make sure all boundary and edge cases
102 are tested.
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104* Make sure all possible values are tested including invalid ones. This makes
Florent Xicluna53b506be2010-03-18 20:00:57 +0000105 sure that not only all valid values are acceptable but also that improper
106 values are handled correctly.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108* Exhaust as many code paths as possible. Test where branching occurs and thus
109 tailor input to make sure as many different paths through the code are taken.
110
111* Add an explicit test for any bugs discovered for the tested code. This will
112 make sure that the error does not crop up again if the code is changed in the
113 future.
114
115* Make sure to clean up after your tests (such as close and remove all temporary
116 files).
117
118* If a test is dependent on a specific condition of the operating system then
119 verify the condition already exists before attempting the test.
120
121* Import as few modules as possible and do it as soon as possible. This
122 minimizes external dependencies of tests and also minimizes possible anomalous
123 behavior from side-effects of importing a module.
124
125* Try to maximize code reuse. On occasion, tests will vary by something as small
Florent Xicluna53b506be2010-03-18 20:00:57 +0000126 as what type of input is used. Minimize code duplication by subclassing a
127 basic test class with a class that specifies the input::
Georg Brandl116aa622007-08-15 14:28:22 +0000128
R David Murray78fc25c2012-04-09 08:55:42 -0400129 class TestFuncAcceptsSequencesMixin:
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131 func = mySuperWhammyFunction
132
133 def test_func(self):
134 self.func(self.arg)
135
R David Murray78fc25c2012-04-09 08:55:42 -0400136 class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000137 arg = [1, 2, 3]
Georg Brandl116aa622007-08-15 14:28:22 +0000138
R David Murray78fc25c2012-04-09 08:55:42 -0400139 class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +0000140 arg = 'abc'
141
R David Murray78fc25c2012-04-09 08:55:42 -0400142 class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000143 arg = (1, 2, 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000144
R David Murray78fc25c2012-04-09 08:55:42 -0400145 When using this pattern, remember that all classes that inherit from
Georg Brandl93a56cd2014-10-30 22:25:41 +0100146 :class:`unittest.TestCase` are run as tests. The :class:`Mixin` class in the example above
R David Murray78fc25c2012-04-09 08:55:42 -0400147 does not have any data and so can't be run by itself, thus it does not
Georg Brandl93a56cd2014-10-30 22:25:41 +0100148 inherit from :class:`unittest.TestCase`.
R David Murray78fc25c2012-04-09 08:55:42 -0400149
Georg Brandl116aa622007-08-15 14:28:22 +0000150
151.. seealso::
152
153 Test Driven Development
154 A book by Kent Beck on writing tests before code.
155
156
157.. _regrtest:
158
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000159Running tests using the command-line interface
160----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000161
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000162The :mod:`test` package can be run as a script to drive Python's regression
163test suite, thanks to the :option:`-m` option: :program:`python -m test`. Under
164the hood, it uses :mod:`test.regrtest`; the call :program:`python -m
Martin Panter9955a372015-10-07 10:26:23 +0000165test.regrtest` used in previous Python versions still works. Running the
R David Murrayf1cdb602012-04-09 09:12:57 -0400166script by itself automatically starts running all regression tests in the
167:mod:`test` package. It does this by finding all modules in the package whose
168name starts with ``test_``, importing them, and executing the function
169:func:`test_main` if present or loading the tests via
170unittest.TestLoader.loadTestsFromModule if ``test_main`` does not exist. The
171names of tests to execute may also be passed to the script. Specifying a single
172regression test (:program:`python -m test test_spam`) will minimize output and
173only print whether the test passed or failed.
Georg Brandl116aa622007-08-15 14:28:22 +0000174
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000175Running :mod:`test` directly allows what resources are available for
Éric Araujo713d3032010-11-18 16:38:46 +0000176tests to use to be set. You do this by using the ``-u`` command-line
R David Murray644cabe2012-04-11 20:11:53 -0400177option. Specifying ``all`` as the value for the ``-u`` option enables all
178possible resources: :program:`python -m test -uall`.
179If all but one resource is desired (a more common case), a
Georg Brandl116aa622007-08-15 14:28:22 +0000180comma-separated list of resources that are not desired may be listed after
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000181``all``. The command :program:`python -m test -uall,-audio,-largefile`
182will run :mod:`test` with all resources except the ``audio`` and
Éric Araujo713d3032010-11-18 16:38:46 +0000183``largefile`` resources. For a list of all resources and more command-line
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000184options, run :program:`python -m test -h`.
Georg Brandl116aa622007-08-15 14:28:22 +0000185
186Some other ways to execute the regression tests depend on what platform the
Éric Araujo713d3032010-11-18 16:38:46 +0000187tests are being executed on. On Unix, you can run :program:`make test` at the
188top-level directory where Python was built. On Windows,
Florent Xicluna53b506be2010-03-18 20:00:57 +0000189executing :program:`rt.bat` from your :file:`PCBuild` directory will run all
190regression tests.
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192
Georg Brandleea6cda2011-07-30 09:00:48 +0200193:mod:`test.support` --- Utilities for the Python test suite
194===========================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000195
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000196.. module:: test.support
Georg Brandleea6cda2011-07-30 09:00:48 +0200197 :synopsis: Support for Python's regression test suite.
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000200The :mod:`test.support` module provides support for Python's regression
Georg Brandleea6cda2011-07-30 09:00:48 +0200201test suite.
202
203.. note::
Larry Hastings3732ed22014-03-15 21:13:56 -0700204
Georg Brandleea6cda2011-07-30 09:00:48 +0200205 :mod:`test.support` is not a public module. It is documented here to help
206 Python developers write tests. The API of this module is subject to change
207 without backwards compatibility concerns between releases.
208
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210This module defines the following exceptions:
211
Georg Brandl116aa622007-08-15 14:28:22 +0000212.. exception:: TestFailed
213
214 Exception to be raised when a test fails. This is deprecated in favor of
215 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
216 methods.
217
218
Georg Brandl116aa622007-08-15 14:28:22 +0000219.. exception:: ResourceDenied
220
Florent Xicluna53b506be2010-03-18 20:00:57 +0000221 Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a
222 network connection) is not available. Raised by the :func:`requires`
223 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000224
Georg Brandl116aa622007-08-15 14:28:22 +0000225
Georg Brandleea6cda2011-07-30 09:00:48 +0200226The :mod:`test.support` module defines the following constants:
Georg Brandl116aa622007-08-15 14:28:22 +0000227
228.. data:: verbose
229
Eli Benderskye1689652011-05-06 09:29:27 +0300230 ``True`` when verbose output is enabled. Should be checked when more
Georg Brandl116aa622007-08-15 14:28:22 +0000231 detailed information is desired about a running test. *verbose* is set by
232 :mod:`test.regrtest`.
233
234
Georg Brandl116aa622007-08-15 14:28:22 +0000235.. data:: is_jython
236
Eli Benderskye1689652011-05-06 09:29:27 +0300237 ``True`` if the running interpreter is Jython.
Georg Brandl116aa622007-08-15 14:28:22 +0000238
239
240.. data:: TESTFN
241
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000242 Set to a name that is safe to use as the name of a temporary file. Any
243 temporary file that is created should be closed and unlinked (removed).
Georg Brandl116aa622007-08-15 14:28:22 +0000244
Eli Benderskye1689652011-05-06 09:29:27 +0300245
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000246The :mod:`test.support` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Georg Brandl116aa622007-08-15 14:28:22 +0000248.. function:: forget(module_name)
249
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000250 Remove the module named *module_name* from ``sys.modules`` and delete any
Georg Brandl116aa622007-08-15 14:28:22 +0000251 byte-compiled files of the module.
252
253
254.. function:: is_resource_enabled(resource)
255
Eli Benderskye1689652011-05-06 09:29:27 +0300256 Return ``True`` if *resource* is enabled and available. The list of
Georg Brandl116aa622007-08-15 14:28:22 +0000257 available resources is only set when :mod:`test.regrtest` is executing the
258 tests.
259
260
Georg Brandl7f01a132009-09-16 15:58:14 +0000261.. function:: requires(resource, msg=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000262
Florent Xiclunab14930c2010-03-13 15:26:44 +0000263 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
Florent Xicluna53b506be2010-03-18 20:00:57 +0000264 argument to :exc:`ResourceDenied` if it is raised. Always returns
Eli Benderskye1689652011-05-06 09:29:27 +0300265 ``True`` if called by a function whose ``__name__`` is ``'__main__'``.
Florent Xicluna53b506be2010-03-18 20:00:57 +0000266 Used when tests are executed by :mod:`test.regrtest`.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000269.. function:: findfile(filename, subdir=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000270
Florent Xicluna53b506be2010-03-18 20:00:57 +0000271 Return the path to the file named *filename*. If no match is found
272 *filename* is returned. This does not equal a failure since it could be the
273 path to the file.
Georg Brandl116aa622007-08-15 14:28:22 +0000274
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000275 Setting *subdir* indicates a relative path to use to find the file
276 rather than looking directly in the path directories.
277
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000279.. function:: run_unittest(\*classes)
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281 Execute :class:`unittest.TestCase` subclasses passed to the function. The
Florent Xicluna53b506be2010-03-18 20:00:57 +0000282 function scans the classes for methods starting with the prefix ``test_``
283 and executes the tests individually.
Georg Brandl116aa622007-08-15 14:28:22 +0000284
285 It is also legal to pass strings as parameters; these should be keys in
286 ``sys.modules``. Each associated module will be scanned by
287 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
288 following :func:`test_main` function::
289
290 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +0000291 support.run_unittest(__name__)
Georg Brandl116aa622007-08-15 14:28:22 +0000292
293 This will run all tests defined in the named module.
294
Georg Brandl116aa622007-08-15 14:28:22 +0000295
Eli Benderskye1689652011-05-06 09:29:27 +0300296.. function:: run_doctest(module, verbosity=None)
297
298 Run :func:`doctest.testmod` on the given *module*. Return
299 ``(failure_count, test_count)``.
300
301 If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity
302 set to :data:`verbose`. Otherwise, it is run with verbosity set to
303 ``None``.
304
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000305.. function:: check_warnings(\*filters, quiet=True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000306
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000307 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
308 easier to test that a warning was correctly raised. It is approximately
309 equivalent to calling ``warnings.catch_warnings(record=True)`` with
310 :meth:`warnings.simplefilter` set to ``always`` and with the option to
311 automatically validate the results that are recorded.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000312
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000313 ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
314 WarningCategory)`` as positional arguments. If one or more *filters* are
Eli Benderskye1689652011-05-06 09:29:27 +0300315 provided, or if the optional keyword argument *quiet* is ``False``,
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000316 it checks to make sure the warnings are as expected: each specified filter
317 must match at least one of the warnings raised by the enclosed code or the
318 test fails, and if any warnings are raised that do not match any of the
319 specified filters the test fails. To disable the first of these checks,
Eli Benderskye1689652011-05-06 09:29:27 +0300320 set *quiet* to ``True``.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000321
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000322 If no arguments are specified, it defaults to::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000323
Florent Xicluna53b506be2010-03-18 20:00:57 +0000324 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000325
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000326 In this case all warnings are caught and no errors are raised.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000327
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000328 On entry to the context manager, a :class:`WarningRecorder` instance is
329 returned. The underlying warnings list from
330 :func:`~warnings.catch_warnings` is available via the recorder object's
331 :attr:`warnings` attribute. As a convenience, the attributes of the object
332 representing the most recent warning can also be accessed directly through
333 the recorder object (see example below). If no warning has been raised,
334 then any of the attributes that would otherwise be expected on an object
Eli Benderskye1689652011-05-06 09:29:27 +0300335 representing a warning will return ``None``.
Thomas Woutersed03b412007-08-28 21:37:11 +0000336
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000337 The recorder object also has a :meth:`reset` method, which clears the
338 warnings list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000339
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000340 The context manager is designed to be used like this::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000341
342 with check_warnings(("assertion is always true", SyntaxWarning),
343 ("", UserWarning)):
344 exec('assert(False, "Hey!")')
345 warnings.warn(UserWarning("Hide me!"))
346
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000347 In this case if either warning was not raised, or some other warning was
348 raised, :func:`check_warnings` would raise an error.
349
350 When a test needs to look more deeply into the warnings, rather than
351 just checking whether or not they occurred, code like this can be used::
352
Florent Xiclunab14930c2010-03-13 15:26:44 +0000353 with check_warnings(quiet=True) as w:
Thomas Woutersed03b412007-08-28 21:37:11 +0000354 warnings.warn("foo")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000355 assert str(w.args[0]) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000356 warnings.warn("bar")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000357 assert str(w.args[0]) == "bar"
358 assert str(w.warnings[0].args[0]) == "foo"
359 assert str(w.warnings[1].args[0]) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000360 w.reset()
361 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000362
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000363
364 Here all warnings will be caught, and the test code tests the captured
365 warnings directly.
366
Ezio Melottif8754a62010-03-21 07:16:43 +0000367 .. versionchanged:: 3.2
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000368 New optional arguments *filters* and *quiet*.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000369
Thomas Woutersed03b412007-08-28 21:37:11 +0000370
R David Murray5a33f812013-07-11 12:28:40 -0400371.. function:: captured_stdin()
372 captured_stdout()
373 captured_stderr()
Thomas Woutersed03b412007-08-28 21:37:11 +0000374
R David Murray5a33f812013-07-11 12:28:40 -0400375 A context managers that temporarily replaces the named stream with
376 :class:`io.StringIO` object.
Thomas Woutersed03b412007-08-28 21:37:11 +0000377
R David Murray5a33f812013-07-11 12:28:40 -0400378 Example use with output streams::
Thomas Woutersed03b412007-08-28 21:37:11 +0000379
R David Murray5a33f812013-07-11 12:28:40 -0400380 with captured_stdout() as stdout, captured_stderr() as stderr:
Collin Winterc79461b2007-09-01 23:34:30 +0000381 print("hello")
R David Murray5a33f812013-07-11 12:28:40 -0400382 print("error", file=sys.stderr)
383 assert stdout.getvalue() == "hello\n"
384 assert stderr.getvalue() == "error\n"
385
386 Example use with input stream::
387
388 with captured_stdin() as stdin:
389 stdin.write('hello\n')
390 stdin.seek(0)
391 # call test code that consumes from sys.stdin
392 captured = input()
393 self.assertEqual(captured, "hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000394
Thomas Woutersed03b412007-08-28 21:37:11 +0000395
Nick Coghlan55175962013-07-28 22:11:50 +1000396.. function:: temp_dir(path=None, quiet=False)
397
398 A context manager that creates a temporary directory at *path* and
399 yields the directory.
400
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300401 If *path* is ``None``, the temporary directory is created using
Nick Coghlan55175962013-07-28 22:11:50 +1000402 :func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager
403 raises an exception on error. Otherwise, if *path* is specified and
404 cannot be created, only a warning is issued.
405
406
407.. function:: change_cwd(path, quiet=False)
Eli Benderskye1689652011-05-06 09:29:27 +0300408
409 A context manager that temporarily changes the current working
Nick Coghlan55175962013-07-28 22:11:50 +1000410 directory to *path* and yields the directory.
Eli Benderskye1689652011-05-06 09:29:27 +0300411
Nick Coghlan55175962013-07-28 22:11:50 +1000412 If *quiet* is ``False``, the context manager raises an exception
413 on error. Otherwise, it issues only a warning and keeps the current
414 working directory the same.
Eli Benderskye1689652011-05-06 09:29:27 +0300415
Nick Coghlan55175962013-07-28 22:11:50 +1000416
417.. function:: temp_cwd(name='tempcwd', quiet=False)
418
419 A context manager that temporarily creates a new directory and
420 changes the current working directory (CWD).
421
422 The context manager creates a temporary directory in the current
423 directory with name *name* before temporarily changing the current
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300424 working directory. If *name* is ``None``, the temporary directory is
Nick Coghlan55175962013-07-28 22:11:50 +1000425 created using :func:`tempfile.mkdtemp`.
426
427 If *quiet* is ``False`` and it is not possible to create or change
428 the CWD, an error is raised. Otherwise, only a warning is raised
429 and the original CWD is used.
Eli Benderskye1689652011-05-06 09:29:27 +0300430
431
432.. function:: temp_umask(umask)
433
434 A context manager that temporarily sets the process umask.
435
436
437.. function:: can_symlink()
438
439 Return ``True`` if the OS supports symbolic links, ``False``
440 otherwise.
441
442
Nick Coghlan2496f332011-09-19 20:26:31 +1000443.. decorator:: skip_unless_symlink()
Eli Benderskye1689652011-05-06 09:29:27 +0300444
445 A decorator for running tests that require support for symbolic links.
446
447
Nick Coghlan2496f332011-09-19 20:26:31 +1000448.. decorator:: anticipate_failure(condition)
449
450 A decorator to conditionally mark tests with
451 :func:`unittest.expectedFailure`. Any use of this decorator should
452 have an associated comment identifying the relevant tracker issue.
453
454
455.. decorator:: run_with_locale(catstr, *locales)
Eli Benderskye1689652011-05-06 09:29:27 +0300456
457 A decorator for running a function in a different locale, correctly
458 resetting it after it has finished. *catstr* is the locale category as
459 a string (for example ``"LC_ALL"``). The *locales* passed will be tried
460 sequentially, and the first valid locale will be used.
461
462
463.. function:: make_bad_fd()
464
465 Create an invalid file descriptor by opening and closing a temporary file,
Zachary Waref012ba42014-07-23 12:00:29 -0500466 and returning its descriptor.
Eli Benderskye1689652011-05-06 09:29:27 +0300467
468
Nick Coghlanfce769e2009-04-11 14:30:59 +0000469.. function:: import_module(name, deprecated=False)
470
471 This function imports and returns the named module. Unlike a normal
472 import, this function raises :exc:`unittest.SkipTest` if the module
473 cannot be imported.
474
475 Module and package deprecation messages are suppressed during this import
Eli Benderskye1689652011-05-06 09:29:27 +0300476 if *deprecated* is ``True``.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000477
478 .. versionadded:: 3.1
479
480
Nick Coghlan47384702009-04-22 16:13:36 +0000481.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000482
Nick Coghlan47384702009-04-22 16:13:36 +0000483 This function imports and returns a fresh copy of the named Python module
484 by removing the named module from ``sys.modules`` before doing the import.
485 Note that unlike :func:`reload`, the original module is not affected by
486 this operation.
487
488 *fresh* is an iterable of additional module names that are also removed
489 from the ``sys.modules`` cache before doing the import.
490
Eli Benderskyba5517d2013-08-11 15:38:08 -0700491 *blocked* is an iterable of module names that are replaced with ``None``
Nick Coghlan47384702009-04-22 16:13:36 +0000492 in the module cache during the import to ensure that attempts to import
493 them raise :exc:`ImportError`.
494
495 The named module and any modules named in the *fresh* and *blocked*
496 parameters are saved before starting the import and then reinserted into
497 ``sys.modules`` when the fresh import is complete.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000498
499 Module and package deprecation messages are suppressed during this import
Eli Benderskye1689652011-05-06 09:29:27 +0300500 if *deprecated* is ``True``.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000501
Eli Benderskyba5517d2013-08-11 15:38:08 -0700502 This function will raise :exc:`ImportError` if the named module cannot be
503 imported.
Nick Coghlan47384702009-04-22 16:13:36 +0000504
505 Example use::
506
Eli Benderskyba5517d2013-08-11 15:38:08 -0700507 # Get copies of the warnings module for testing without affecting the
508 # version being used by the rest of the test suite. One copy uses the
509 # C implementation, the other is forced to use the pure Python fallback
510 # implementation
Nick Coghlan47384702009-04-22 16:13:36 +0000511 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
512 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
513
Nick Coghlanfce769e2009-04-11 14:30:59 +0000514 .. versionadded:: 3.1
515
516
Eli Benderskye1689652011-05-06 09:29:27 +0300517.. function:: bind_port(sock, host=HOST)
518
519 Bind the socket to a free port and return the port number. Relies on
520 ephemeral ports in order to ensure we are using an unbound port. This is
521 important as many tests may be running simultaneously, especially in a
522 buildbot environment. This method raises an exception if the
523 ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is
524 :const:`~socket.SOCK_STREAM`, and the socket has
525 :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it.
526 Tests should never set these socket options for TCP/IP sockets.
527 The only case for setting these options is testing multicasting via
528 multiple UDP sockets.
529
530 Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is
531 available (i.e. on Windows), it will be set on the socket. This will
532 prevent anyone else from binding to our host/port for the duration of the
533 test.
534
535
536.. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM)
537
538 Returns an unused port that should be suitable for binding. This is
539 achieved by creating a temporary socket with the same family and type as
540 the ``sock`` parameter (default is :const:`~socket.AF_INET`,
541 :const:`~socket.SOCK_STREAM`),
542 and binding it to the specified host address (defaults to ``0.0.0.0``)
543 with the port set to 0, eliciting an unused ephemeral port from the OS.
544 The temporary socket is then closed and deleted, and the ephemeral port is
545 returned.
546
547 Either this method or :func:`bind_port` should be used for any tests
548 where a server socket needs to be bound to a particular port for the
549 duration of the test.
550 Which one to use depends on whether the calling code is creating a python
551 socket, or if an unused port needs to be provided in a constructor
552 or passed to an external program (i.e. the ``-accept`` argument to
553 openssl's s_server mode). Always prefer :func:`bind_port` over
554 :func:`find_unused_port` where possible. Using a hard coded port is
Martin Panter8f265652016-04-19 04:03:41 +0000555 discouraged since it can make multiple instances of the test impossible to
Eli Benderskye1689652011-05-06 09:29:27 +0300556 run simultaneously, which is a problem for buildbots.
557
558
Zachary Waref012ba42014-07-23 12:00:29 -0500559.. function:: load_package_tests(pkg_dir, loader, standard_tests, pattern)
560
561 Generic implementation of the :mod:`unittest` ``load_tests`` protocol for
562 use in test packages. *pkg_dir* is the root directory of the package;
563 *loader*, *standard_tests*, and *pattern* are the arguments expected by
564 ``load_tests``. In simple cases, the test package's ``__init__.py``
565 can be the following::
566
567 import os
568 from test.support import load_package_tests
569
570 def load_tests(*args):
571 return load_package_tests(os.path.dirname(__file__), *args)
572
Gregory P. Smith4e72cce2015-04-14 13:26:06 -0700573.. function:: detect_api_mismatch(ref_api, other_api, *, ignore=()):
574
Zachary Ware3d3aedc2015-07-07 00:07:25 -0500575 Returns the set of attributes, functions or methods of *ref_api* not
576 found on *other_api*, except for a defined list of items to be
577 ignored in this check specified in *ignore*.
Gregory P. Smith4e72cce2015-04-14 13:26:06 -0700578
579 By default this skips private attributes beginning with '_' but
580 includes all magic methods, i.e. those starting and ending in '__'.
581
Gregory P. Smith7c63fd32015-04-14 15:25:01 -0700582 .. versionadded:: 3.5
583
Zachary Waref012ba42014-07-23 12:00:29 -0500584
Martin Panterd226d302015-11-14 11:47:00 +0000585.. function:: check__all__(test_case, module, name_of_module=None, extra=(), blacklist=())
586
587 Assert that the ``__all__`` variable of *module* contains all public names.
588
589 The module's public names (its API) are detected automatically
590 based on whether they match the public name convention and were defined in
591 *module*.
592
593 The *name_of_module* argument can specify (as a string or tuple thereof) what
594 module(s) an API could be defined in in order to be detected as a public
595 API. One case for this is when *module* imports part of its public API from
596 other modules, possibly a C backend (like ``csv`` and its ``_csv``).
597
598 The *extra* argument can be a set of names that wouldn't otherwise be automatically
599 detected as "public", like objects without a proper ``__module__``
600 attribute. If provided, it will be added to the automatically detected ones.
601
602 The *blacklist* argument can be a set of names that must not be treated as part of
603 the public API even though their names indicate otherwise.
604
605 Example use::
606
607 import bar
608 import foo
609 import unittest
610 from test import support
611
612 class MiscTestCase(unittest.TestCase):
613 def test__all__(self):
614 support.check__all__(self, foo)
615
616 class OtherTestCase(unittest.TestCase):
617 def test__all__(self):
618 extra = {'BAR_CONST', 'FOO_CONST'}
619 blacklist = {'baz'} # Undocumented name.
620 # bar imports part of its API from _bar.
621 support.check__all__(self, bar, ('bar', '_bar'),
622 extra=extra, blacklist=blacklist)
623
624 .. versionadded:: 3.6
625
626
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000627The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +0000628
Georg Brandl7f01a132009-09-16 15:58:14 +0000629.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000630
631 Instances are a context manager that raises :exc:`ResourceDenied` if the
632 specified exception type is raised. Any keyword arguments are treated as
633 attribute/value pairs to be compared against any exception raised within the
634 :keyword:`with` statement. Only if all pairs match properly against
635 attributes on the exception is :exc:`ResourceDenied` raised.
636
Georg Brandl116aa622007-08-15 14:28:22 +0000637
638.. class:: EnvironmentVarGuard()
639
Florent Xicluna53b506be2010-03-18 20:00:57 +0000640 Class used to temporarily set or unset environment variables. Instances can
641 be used as a context manager and have a complete dictionary interface for
642 querying/modifying the underlying ``os.environ``. After exit from the
643 context manager all changes to environment variables done through this
644 instance will be rolled back.
Georg Brandl116aa622007-08-15 14:28:22 +0000645
Georg Brandl705d9d52009-05-05 09:29:50 +0000646 .. versionchanged:: 3.1
Walter Dörwald155374d2009-05-01 19:58:58 +0000647 Added dictionary interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000648
649.. method:: EnvironmentVarGuard.set(envvar, value)
650
Florent Xicluna53b506be2010-03-18 20:00:57 +0000651 Temporarily set the environment variable ``envvar`` to the value of
652 ``value``.
Georg Brandl116aa622007-08-15 14:28:22 +0000653
654
655.. method:: EnvironmentVarGuard.unset(envvar)
656
657 Temporarily unset the environment variable ``envvar``.
Nick Coghlanb1304932008-07-13 12:25:08 +0000658
Walter Dörwald155374d2009-05-01 19:58:58 +0000659
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200660.. class:: SuppressCrashReport()
661
662 A context manager used to try to prevent crash dialog popups on tests that
663 are expected to crash a subprocess.
664
665 On Windows, it disables Windows Error Reporting dialogs using
Georg Brandl5d941342016-02-26 19:37:12 +0100666 `SetErrorMode <https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx>`_.
Antoine Pitrou77e904e2013-10-08 23:04:32 +0200667
668 On UNIX, :func:`resource.setrlimit` is used to set
669 :attr:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file
670 creation.
671
672 On both platforms, the old value is restored by :meth:`__exit__`.
673
674
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000675.. class:: WarningsRecorder()
676
677 Class used to record warnings for unit tests. See documentation of
678 :func:`check_warnings` above for more details.