blob: a18197aed3f4a62f7d55f057f5f841ac8fbdf4a4 [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,
Stefan Grönkef1502d02017-09-25 18:58:10 +0200189executing :program:`rt.bat` from your :file:`PCbuild` directory will run all
Florent Xicluna53b506be2010-03-18 20:00:57 +0000190regression 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
Cheryl Sabella988fb282018-02-11 08:10:42 -0500240.. data:: is_android
241
242 ``True`` if the system is Android.
243
244
245.. data:: unix_shell
246
247 Path for shell if not on Windows; otherwise ``None``.
248
249
Victor Stinner24c62582019-10-30 12:41:43 +0100250.. data:: LOOPBACK_TIMEOUT
251
252 Timeout in seconds for tests using a network server listening on the network
253 local loopback interface like ``127.0.0.1``.
254
255 The timeout is long enough to prevent test failure: it takes into account
256 that the client and the server can run in different threads or even
257 different processes.
258
259 The timeout should be long enough for :meth:`~socket.socket.connect`,
260 :meth:`~socket.socket.recv` and :meth:`~socket.socket.send` methods of
261 :class:`socket.socket`.
262
263 Its default value is 5 seconds.
264
265 See also :data:`INTERNET_TIMEOUT`.
266
267
268.. data:: INTERNET_TIMEOUT
269
270 Timeout in seconds for network requests going to the Internet.
271
272 The timeout is short enough to prevent a test to wait for too long if the
273 Internet request is blocked for whatever reason.
274
275 Usually, a timeout using :data:`INTERNET_TIMEOUT` should not mark a test as
276 failed, but skip the test instead: see
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +0300277 :func:`~test.support.socket_helper.transient_internet`.
Victor Stinner24c62582019-10-30 12:41:43 +0100278
279 Its default value is 1 minute.
280
281 See also :data:`LOOPBACK_TIMEOUT`.
282
283
284.. data:: SHORT_TIMEOUT
285
286 Timeout in seconds to mark a test as failed if the test takes "too long".
287
288 The timeout value depends on the regrtest ``--timeout`` command line option.
289
290 If a test using :data:`SHORT_TIMEOUT` starts to fail randomly on slow
291 buildbots, use :data:`LONG_TIMEOUT` instead.
292
293 Its default value is 30 seconds.
294
295
296.. data:: LONG_TIMEOUT
297
298 Timeout in seconds to detect when a test hangs.
299
300 It is long enough to reduce the risk of test failure on the slowest Python
301 buildbots. It should not be used to mark a test as failed if the test takes
302 "too long". The timeout value depends on the regrtest ``--timeout`` command
303 line option.
304
305 Its default value is 5 minutes.
306
307 See also :data:`LOOPBACK_TIMEOUT`, :data:`INTERNET_TIMEOUT` and
308 :data:`SHORT_TIMEOUT`.
309
310
Cheryl Sabella988fb282018-02-11 08:10:42 -0500311.. data:: PGO
312
313 Set when tests can be skipped when they are not useful for PGO.
314
315
316.. data:: PIPE_MAX_SIZE
317
318 A constant that is likely larger than the underlying OS pipe buffer size,
319 to make writes blocking.
320
321
322.. data:: SOCK_MAX_SIZE
323
324 A constant that is likely larger than the underlying OS socket buffer size,
325 to make writes blocking.
326
327
328.. data:: TEST_SUPPORT_DIR
329
330 Set to the top level directory that contains :mod:`test.support`.
331
332
333.. data:: TEST_HOME_DIR
334
335 Set to the top level directory for the test package.
336
337
338.. data:: TEST_DATA_DIR
339
340 Set to the ``data`` directory within the test package.
341
342
343.. data:: MAX_Py_ssize_t
344
345 Set to :data:`sys.maxsize` for big memory tests.
346
347
348.. data:: max_memuse
349
350 Set by :func:`set_memlimit` as the memory limit for big memory tests.
351 Limited by :data:`MAX_Py_ssize_t`.
352
353
354.. data:: real_max_memuse
355
356 Set by :func:`set_memlimit` as the memory limit for big memory tests. Not
357 limited by :data:`MAX_Py_ssize_t`.
358
359
360.. data:: MISSING_C_DOCSTRINGS
361
362 Return ``True`` if running on CPython, not on Windows, and configuration
363 not set with ``WITH_DOC_STRINGS``.
364
365
366.. data:: HAVE_DOCSTRINGS
367
368 Check for presence of docstrings.
369
Serhiy Storchaka17e52642019-08-04 12:38:46 +0300370
Stéphane Wirtela40681d2019-02-22 14:45:36 +0100371.. data:: TEST_HTTP_URL
372
373 Define the URL of a dedicated HTTP server for the network tests.
374
Cheryl Sabella988fb282018-02-11 08:10:42 -0500375
Serhiy Storchaka17e52642019-08-04 12:38:46 +0300376.. data:: ALWAYS_EQ
377
378 Object that is equal to anything. Used to test mixed type comparison.
379
380
Serhiy Storchaka18b711c2019-08-04 14:12:48 +0300381.. data:: NEVER_EQ
382
383 Object that is not equal to anything (even to :data:`ALWAYS_EQ`).
384 Used to test mixed type comparison.
385
386
Serhiy Storchaka17e52642019-08-04 12:38:46 +0300387.. data:: LARGEST
388
389 Object that is greater than anything (except itself).
390 Used to test mixed type comparison.
391
392
393.. data:: SMALLEST
394
395 Object that is less than anything (except itself).
396 Used to test mixed type comparison.
397
Cheryl Sabella988fb282018-02-11 08:10:42 -0500398
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000399The :mod:`test.support` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000400
Georg Brandl116aa622007-08-15 14:28:22 +0000401.. function:: is_resource_enabled(resource)
402
Eli Benderskye1689652011-05-06 09:29:27 +0300403 Return ``True`` if *resource* is enabled and available. The list of
Georg Brandl116aa622007-08-15 14:28:22 +0000404 available resources is only set when :mod:`test.regrtest` is executing the
405 tests.
406
407
Cheryl Sabella988fb282018-02-11 08:10:42 -0500408.. function:: python_is_optimized()
409
410 Return ``True`` if Python was not built with ``-O0`` or ``-Og``.
411
412
413.. function:: with_pymalloc()
414
415 Return :data:`_testcapi.WITH_PYMALLOC`.
416
417
Georg Brandl7f01a132009-09-16 15:58:14 +0000418.. function:: requires(resource, msg=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Florent Xiclunab14930c2010-03-13 15:26:44 +0000420 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
Florent Xicluna53b506be2010-03-18 20:00:57 +0000421 argument to :exc:`ResourceDenied` if it is raised. Always returns
Eli Benderskye1689652011-05-06 09:29:27 +0300422 ``True`` if called by a function whose ``__name__`` is ``'__main__'``.
Florent Xicluna53b506be2010-03-18 20:00:57 +0000423 Used when tests are executed by :mod:`test.regrtest`.
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425
Cheryl Sabella988fb282018-02-11 08:10:42 -0500426.. function:: system_must_validate_cert(f)
427
428 Raise :exc:`unittest.SkipTest` on TLS certification validation failures.
429
430
431.. function:: sortdict(dict)
432
433 Return a repr of *dict* with keys sorted.
434
435
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000436.. function:: findfile(filename, subdir=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000437
Florent Xicluna53b506be2010-03-18 20:00:57 +0000438 Return the path to the file named *filename*. If no match is found
439 *filename* is returned. This does not equal a failure since it could be the
440 path to the file.
Georg Brandl116aa622007-08-15 14:28:22 +0000441
Cheryl Sabella988fb282018-02-11 08:10:42 -0500442 Setting *subdir* indicates a relative path to use to find the file
443 rather than looking directly in the path directories.
444
445
Cheryl Sabella988fb282018-02-11 08:10:42 -0500446.. function:: match_test(test)
447
448 Match *test* to patterns set in :func:`set_match_tests`.
449
450
451.. function:: set_match_tests(patterns)
452
453 Define match test with regular expression *patterns*.
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000454
Georg Brandl116aa622007-08-15 14:28:22 +0000455
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000456.. function:: run_unittest(\*classes)
Georg Brandl116aa622007-08-15 14:28:22 +0000457
458 Execute :class:`unittest.TestCase` subclasses passed to the function. The
Florent Xicluna53b506be2010-03-18 20:00:57 +0000459 function scans the classes for methods starting with the prefix ``test_``
460 and executes the tests individually.
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462 It is also legal to pass strings as parameters; these should be keys in
463 ``sys.modules``. Each associated module will be scanned by
464 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
465 following :func:`test_main` function::
466
467 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +0000468 support.run_unittest(__name__)
Georg Brandl116aa622007-08-15 14:28:22 +0000469
470 This will run all tests defined in the named module.
471
Georg Brandl116aa622007-08-15 14:28:22 +0000472
Cheryl Sabella988fb282018-02-11 08:10:42 -0500473.. function:: run_doctest(module, verbosity=None, optionflags=0)
Eli Benderskye1689652011-05-06 09:29:27 +0300474
475 Run :func:`doctest.testmod` on the given *module*. Return
476 ``(failure_count, test_count)``.
477
478 If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity
479 set to :data:`verbose`. Otherwise, it is run with verbosity set to
Cheryl Sabella988fb282018-02-11 08:10:42 -0500480 ``None``. *optionflags* is passed as ``optionflags`` to
481 :func:`doctest.testmod`.
482
483
484.. function:: setswitchinterval(interval)
485
486 Set the :func:`sys.setswitchinterval` to the given *interval*. Defines
487 a minimum interval for Android systems to prevent the system from hanging.
488
489
490.. function:: check_impl_detail(**guards)
491
492 Use this check to guard CPython's implementation-specific tests or to
493 run them only on the implementations guarded by the arguments::
494
495 check_impl_detail() # Only on CPython (default).
496 check_impl_detail(jython=True) # Only on Jython.
497 check_impl_detail(cpython=False) # Everywhere except CPython.
498
Eli Benderskye1689652011-05-06 09:29:27 +0300499
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000500.. function:: check_warnings(\*filters, quiet=True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000501
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000502 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
503 easier to test that a warning was correctly raised. It is approximately
504 equivalent to calling ``warnings.catch_warnings(record=True)`` with
505 :meth:`warnings.simplefilter` set to ``always`` and with the option to
506 automatically validate the results that are recorded.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000507
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000508 ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
509 WarningCategory)`` as positional arguments. If one or more *filters* are
Eli Benderskye1689652011-05-06 09:29:27 +0300510 provided, or if the optional keyword argument *quiet* is ``False``,
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000511 it checks to make sure the warnings are as expected: each specified filter
512 must match at least one of the warnings raised by the enclosed code or the
513 test fails, and if any warnings are raised that do not match any of the
514 specified filters the test fails. To disable the first of these checks,
Eli Benderskye1689652011-05-06 09:29:27 +0300515 set *quiet* to ``True``.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000516
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000517 If no arguments are specified, it defaults to::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000518
Florent Xicluna53b506be2010-03-18 20:00:57 +0000519 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000520
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000521 In this case all warnings are caught and no errors are raised.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000522
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000523 On entry to the context manager, a :class:`WarningRecorder` instance is
524 returned. The underlying warnings list from
525 :func:`~warnings.catch_warnings` is available via the recorder object's
526 :attr:`warnings` attribute. As a convenience, the attributes of the object
527 representing the most recent warning can also be accessed directly through
528 the recorder object (see example below). If no warning has been raised,
529 then any of the attributes that would otherwise be expected on an object
Eli Benderskye1689652011-05-06 09:29:27 +0300530 representing a warning will return ``None``.
Thomas Woutersed03b412007-08-28 21:37:11 +0000531
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000532 The recorder object also has a :meth:`reset` method, which clears the
533 warnings list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000534
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000535 The context manager is designed to be used like this::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000536
537 with check_warnings(("assertion is always true", SyntaxWarning),
538 ("", UserWarning)):
539 exec('assert(False, "Hey!")')
540 warnings.warn(UserWarning("Hide me!"))
541
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000542 In this case if either warning was not raised, or some other warning was
543 raised, :func:`check_warnings` would raise an error.
544
545 When a test needs to look more deeply into the warnings, rather than
546 just checking whether or not they occurred, code like this can be used::
547
Florent Xiclunab14930c2010-03-13 15:26:44 +0000548 with check_warnings(quiet=True) as w:
Thomas Woutersed03b412007-08-28 21:37:11 +0000549 warnings.warn("foo")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000550 assert str(w.args[0]) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000551 warnings.warn("bar")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000552 assert str(w.args[0]) == "bar"
553 assert str(w.warnings[0].args[0]) == "foo"
554 assert str(w.warnings[1].args[0]) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000555 w.reset()
556 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000557
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000558
559 Here all warnings will be caught, and the test code tests the captured
560 warnings directly.
561
Ezio Melottif8754a62010-03-21 07:16:43 +0000562 .. versionchanged:: 3.2
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000563 New optional arguments *filters* and *quiet*.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000564
Thomas Woutersed03b412007-08-28 21:37:11 +0000565
Cheryl Sabella988fb282018-02-11 08:10:42 -0500566.. function:: check_no_resource_warning(testcase)
567
568 Context manager to check that no :exc:`ResourceWarning` was raised. You
569 must remove the object which may emit :exc:`ResourceWarning` before the
570 end of the context manager.
571
572
573.. function:: set_memlimit(limit)
574
575 Set the values for :data:`max_memuse` and :data:`real_max_memuse` for big
576 memory tests.
577
578
579.. function:: record_original_stdout(stdout)
580
581 Store the value from *stdout*. It is meant to hold the stdout at the
582 time the regrtest began.
583
584
585.. function:: get_original_stdout
586
587 Return the original stdout set by :func:`record_original_stdout` or
588 ``sys.stdout`` if it's not set.
589
590
Cheryl Sabella988fb282018-02-11 08:10:42 -0500591.. function:: args_from_interpreter_flags()
592
593 Return a list of command line arguments reproducing the current settings
594 in ``sys.flags`` and ``sys.warnoptions``.
595
596
597.. function:: optim_args_from_interpreter_flags()
598
599 Return a list of command line arguments reproducing the current
600 optimization settings in ``sys.flags``.
601
602
R David Murray5a33f812013-07-11 12:28:40 -0400603.. function:: captured_stdin()
604 captured_stdout()
605 captured_stderr()
Thomas Woutersed03b412007-08-28 21:37:11 +0000606
R David Murray5a33f812013-07-11 12:28:40 -0400607 A context managers that temporarily replaces the named stream with
608 :class:`io.StringIO` object.
Thomas Woutersed03b412007-08-28 21:37:11 +0000609
R David Murray5a33f812013-07-11 12:28:40 -0400610 Example use with output streams::
Thomas Woutersed03b412007-08-28 21:37:11 +0000611
R David Murray5a33f812013-07-11 12:28:40 -0400612 with captured_stdout() as stdout, captured_stderr() as stderr:
Collin Winterc79461b2007-09-01 23:34:30 +0000613 print("hello")
R David Murray5a33f812013-07-11 12:28:40 -0400614 print("error", file=sys.stderr)
615 assert stdout.getvalue() == "hello\n"
616 assert stderr.getvalue() == "error\n"
617
618 Example use with input stream::
619
620 with captured_stdin() as stdin:
621 stdin.write('hello\n')
622 stdin.seek(0)
623 # call test code that consumes from sys.stdin
624 captured = input()
625 self.assertEqual(captured, "hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000626
Thomas Woutersed03b412007-08-28 21:37:11 +0000627
Cheryl Sabella988fb282018-02-11 08:10:42 -0500628.. function:: disable_faulthandler()
629
630 A context manager that replaces ``sys.stderr`` with ``sys.__stderr__``.
631
632
633.. function:: gc_collect()
634
635 Force as many objects as possible to be collected. This is needed because
636 timely deallocation is not guaranteed by the garbage collector. This means
637 that ``__del__`` methods may be called later than expected and weakrefs
638 may remain alive for longer than expected.
639
640
641.. function:: disable_gc()
642
643 A context manager that disables the garbage collector upon entry and
644 reenables it upon exit.
645
646
647.. function:: swap_attr(obj, attr, new_val)
648
649 Context manager to swap out an attribute with a new object.
650
651 Usage::
652
653 with swap_attr(obj, "attr", 5):
654 ...
655
656 This will set ``obj.attr`` to 5 for the duration of the ``with`` block,
657 restoring the old value at the end of the block. If ``attr`` doesn't
658 exist on ``obj``, it will be created and then deleted at the end of the
659 block.
660
661 The old value (or ``None`` if it doesn't exist) will be assigned to the
662 target of the "as" clause, if there is one.
663
664
665.. function:: swap_item(obj, attr, new_val)
666
667 Context manager to swap out an item with a new object.
668
669 Usage::
670
671 with swap_item(obj, "item", 5):
672 ...
673
674 This will set ``obj["item"]`` to 5 for the duration of the ``with`` block,
675 restoring the old value at the end of the block. If ``item`` doesn't
676 exist on ``obj``, it will be created and then deleted at the end of the
677 block.
678
679 The old value (or ``None`` if it doesn't exist) will be assigned to the
680 target of the "as" clause, if there is one.
681
682
Victor Stinnerd663d342020-04-23 19:03:52 +0200683.. function:: print_warning(msg)
684
685 Print a warning into :data:`sys.__stderr__`. Format the message as:
686 ``f"Warning -- {msg}"``. If *msg* is made of multiple lines, add
687 ``"Warning -- "`` prefix to each line.
688
689 .. versionadded:: 3.9
690
691
Victor Stinner278c1e12020-03-31 20:08:12 +0200692.. function:: wait_process(pid, *, exitcode, timeout=None)
693
694 Wait until process *pid* completes and check that the process exit code is
695 *exitcode*.
696
697 Raise an :exc:`AssertionError` if the process exit code is not equal to
698 *exitcode*.
699
700 If the process runs longer than *timeout* seconds (:data:`SHORT_TIMEOUT` by
701 default), kill the process and raise an :exc:`AssertionError`. The timeout
702 feature is not available on Windows.
703
704 .. versionadded:: 3.9
705
706
Cheryl Sabella988fb282018-02-11 08:10:42 -0500707.. function:: calcobjsize(fmt)
708
709 Return :func:`struct.calcsize` for ``nP{fmt}0n`` or, if ``gettotalrefcount``
710 exists, ``2PnP{fmt}0P``.
711
712
713.. function:: calcvobjsize(fmt)
714
715 Return :func:`struct.calcsize` for ``nPn{fmt}0n`` or, if ``gettotalrefcount``
716 exists, ``2PnPn{fmt}0P``.
717
718
719.. function:: checksizeof(test, o, size)
720
721 For testcase *test*, assert that the ``sys.getsizeof`` for *o* plus the GC
722 header size equals *size*.
723
724
Nick Coghlan2496f332011-09-19 20:26:31 +1000725.. decorator:: anticipate_failure(condition)
726
727 A decorator to conditionally mark tests with
728 :func:`unittest.expectedFailure`. Any use of this decorator should
729 have an associated comment identifying the relevant tracker issue.
730
731
732.. decorator:: run_with_locale(catstr, *locales)
Eli Benderskye1689652011-05-06 09:29:27 +0300733
734 A decorator for running a function in a different locale, correctly
735 resetting it after it has finished. *catstr* is the locale category as
736 a string (for example ``"LC_ALL"``). The *locales* passed will be tried
737 sequentially, and the first valid locale will be used.
738
739
Cheryl Sabella988fb282018-02-11 08:10:42 -0500740.. decorator:: run_with_tz(tz)
741
742 A decorator for running a function in a specific timezone, correctly
743 resetting it after it has finished.
744
745
746.. decorator:: requires_freebsd_version(*min_version)
747
748 Decorator for the minimum version when running test on FreeBSD. If the
749 FreeBSD version is less than the minimum, raise :exc:`unittest.SkipTest`.
750
751
752.. decorator:: requires_linux_version(*min_version)
753
754 Decorator for the minimum version when running test on Linux. If the
755 Linux version is less than the minimum, raise :exc:`unittest.SkipTest`.
756
757
758.. decorator:: requires_mac_version(*min_version)
759
760 Decorator for the minimum version when running test on Mac OS X. If the
761 MAC OS X version is less than the minimum, raise :exc:`unittest.SkipTest`.
762
763
764.. decorator:: requires_IEEE_754
765
766 Decorator for skipping tests on non-IEEE 754 platforms.
767
768
769.. decorator:: requires_zlib
770
771 Decorator for skipping tests if :mod:`zlib` doesn't exist.
772
773
774.. decorator:: requires_gzip
775
776 Decorator for skipping tests if :mod:`gzip` doesn't exist.
777
778
779.. decorator:: requires_bz2
780
781 Decorator for skipping tests if :mod:`bz2` doesn't exist.
782
783
784.. decorator:: requires_lzma
785
786 Decorator for skipping tests if :mod:`lzma` doesn't exist.
787
788
789.. decorator:: requires_resource(resource)
790
791 Decorator for skipping tests if *resource* is not available.
792
793
794.. decorator:: requires_docstrings
795
796 Decorator for only running the test if :data:`HAVE_DOCSTRINGS`.
797
798
799.. decorator:: cpython_only(test)
800
801 Decorator for tests only applicable to CPython.
802
803
804.. decorator:: impl_detail(msg=None, **guards)
805
806 Decorator for invoking :func:`check_impl_detail` on *guards*. If that
807 returns ``False``, then uses *msg* as the reason for skipping the test.
808
809
810.. decorator:: no_tracing(func)
811
812 Decorator to temporarily turn off tracing for the duration of the test.
813
814
815.. decorator:: refcount_test(test)
816
817 Decorator for tests which involve reference counting. The decorator does
818 not run the test if it is not run by CPython. Any trace function is unset
819 for the duration of the test to prevent unexpected refcounts caused by
820 the trace function.
821
822
Cheryl Sabella988fb282018-02-11 08:10:42 -0500823.. decorator:: bigmemtest(size, memuse, dry_run=True)
824
825 Decorator for bigmem tests.
826
827 *size* is a requested size for the test (in arbitrary, test-interpreted
828 units.) *memuse* is the number of bytes per unit for the test, or a good
829 estimate of it. For example, a test that needs two byte buffers, of 4 GiB
830 each, could be decorated with ``@bigmemtest(size=_4G, memuse=2)``.
831
832 The *size* argument is normally passed to the decorated test method as an
833 extra argument. If *dry_run* is ``True``, the value passed to the test
834 method may be less than the requested value. If *dry_run* is ``False``, it
835 means the test doesn't support dummy runs when ``-M`` is not specified.
836
837
838.. decorator:: bigaddrspacetest(f)
839
840 Decorator for tests that fill the address space. *f* is the function to
841 wrap.
842
843
Cheryl Sabella988fb282018-02-11 08:10:42 -0500844.. function:: check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None)
845
846 Test for syntax errors in *statement* by attempting to compile *statement*.
847 *testcase* is the :mod:`unittest` instance for the test. *errtext* is the
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +0200848 regular expression which should match the string representation of the
849 raised :exc:`SyntaxError`. If *lineno* is not ``None``, compares to
850 the line of the exception. If *offset* is not ``None``, compares to
851 the offset of the exception.
852
853
854.. function:: check_syntax_warning(testcase, statement, errtext='', *, lineno=1, offset=None)
855
856 Test for syntax warning in *statement* by attempting to compile *statement*.
857 Test also that the :exc:`SyntaxWarning` is emitted only once, and that it
858 will be converted to a :exc:`SyntaxError` when turned into error.
859 *testcase* is the :mod:`unittest` instance for the test. *errtext* is the
860 regular expression which should match the string representation of the
861 emitted :exc:`SyntaxWarning` and raised :exc:`SyntaxError`. If *lineno*
862 is not ``None``, compares to the line of the warning and exception.
863 If *offset* is not ``None``, compares to the offset of the exception.
864
865 .. versionadded:: 3.8
Cheryl Sabella988fb282018-02-11 08:10:42 -0500866
867
868.. function:: open_urlresource(url, *args, **kw)
869
870 Open *url*. If open fails, raises :exc:`TestFailed`.
871
872
Cheryl Sabella988fb282018-02-11 08:10:42 -0500873.. function:: reap_children()
874
875 Use this at the end of ``test_main`` whenever sub-processes are started.
876 This will help ensure that no extra children (zombies) stick around to
877 hog resources and create problems when looking for refleaks.
878
879
880.. function:: get_attribute(obj, name)
881
882 Get an attribute, raising :exc:`unittest.SkipTest` if :exc:`AttributeError`
883 is raised.
884
885
Victor Stinner6dbbe742019-05-25 00:09:38 +0200886.. function:: catch_unraisable_exception()
887
888 Context manager catching unraisable exception using
889 :func:`sys.unraisablehook`.
890
Victor Stinner6d22cc82019-06-13 14:44:54 +0200891 Storing the exception value (``cm.unraisable.exc_value``) creates a
892 reference cycle. The reference cycle is broken explicitly when the context
893 manager exits.
894
Victor Stinner212646c2019-06-14 18:03:22 +0200895 Storing the object (``cm.unraisable.object``) can resurrect it if it is set
896 to an object which is being finalized. Exiting the context manager clears
897 the stored object.
Victor Stinner6d22cc82019-06-13 14:44:54 +0200898
Victor Stinner6dbbe742019-05-25 00:09:38 +0200899 Usage::
900
901 with support.catch_unraisable_exception() as cm:
902 # code creating an "unraisable exception"
903 ...
904
905 # check the unraisable exception: use cm.unraisable
906 ...
907
908 # cm.unraisable attribute no longer exists at this point
909 # (to break a reference cycle)
910
911 .. versionadded:: 3.8
912
913
Zachary Waref012ba42014-07-23 12:00:29 -0500914.. function:: load_package_tests(pkg_dir, loader, standard_tests, pattern)
915
916 Generic implementation of the :mod:`unittest` ``load_tests`` protocol for
917 use in test packages. *pkg_dir* is the root directory of the package;
918 *loader*, *standard_tests*, and *pattern* are the arguments expected by
919 ``load_tests``. In simple cases, the test package's ``__init__.py``
920 can be the following::
921
922 import os
923 from test.support import load_package_tests
924
925 def load_tests(*args):
926 return load_package_tests(os.path.dirname(__file__), *args)
927
Louie Lu7fae81e2017-04-22 14:46:18 +0800928
929.. function:: detect_api_mismatch(ref_api, other_api, *, ignore=())
Gregory P. Smith4e72cce2015-04-14 13:26:06 -0700930
Zachary Ware3d3aedc2015-07-07 00:07:25 -0500931 Returns the set of attributes, functions or methods of *ref_api* not
932 found on *other_api*, except for a defined list of items to be
933 ignored in this check specified in *ignore*.
Gregory P. Smith4e72cce2015-04-14 13:26:06 -0700934
935 By default this skips private attributes beginning with '_' but
936 includes all magic methods, i.e. those starting and ending in '__'.
937
Gregory P. Smith7c63fd32015-04-14 15:25:01 -0700938 .. versionadded:: 3.5
939
Zachary Waref012ba42014-07-23 12:00:29 -0500940
Cheryl Sabella988fb282018-02-11 08:10:42 -0500941.. function:: patch(test_instance, object_to_patch, attr_name, new_value)
942
943 Override *object_to_patch.attr_name* with *new_value*. Also add
944 cleanup procedure to *test_instance* to restore *object_to_patch* for
945 *attr_name*. The *attr_name* should be a valid attribute for
946 *object_to_patch*.
947
948
949.. function:: run_in_subinterp(code)
950
951 Run *code* in subinterpreter. Raise :exc:`unittest.SkipTest` if
952 :mod:`tracemalloc` is enabled.
953
954
955.. function:: check_free_after_iterating(test, iter, cls, args=())
956
957 Assert that *iter* is deallocated after iterating.
958
959
960.. function:: missing_compiler_executable(cmd_names=[])
961
962 Check for the existence of the compiler executables whose names are listed
963 in *cmd_names* or all the compiler executables when *cmd_names* is empty
964 and return the first missing executable or ``None`` when none is found
965 missing.
966
967
Martin Panterd226d302015-11-14 11:47:00 +0000968.. function:: check__all__(test_case, module, name_of_module=None, extra=(), blacklist=())
969
970 Assert that the ``__all__`` variable of *module* contains all public names.
971
972 The module's public names (its API) are detected automatically
973 based on whether they match the public name convention and were defined in
974 *module*.
975
976 The *name_of_module* argument can specify (as a string or tuple thereof) what
Serhiy Storchakabac2d5b2018-03-28 22:14:26 +0300977 module(s) an API could be defined in order to be detected as a public
Martin Panterd226d302015-11-14 11:47:00 +0000978 API. One case for this is when *module* imports part of its public API from
979 other modules, possibly a C backend (like ``csv`` and its ``_csv``).
980
981 The *extra* argument can be a set of names that wouldn't otherwise be automatically
982 detected as "public", like objects without a proper ``__module__``
983 attribute. If provided, it will be added to the automatically detected ones.
984
985 The *blacklist* argument can be a set of names that must not be treated as part of
986 the public API even though their names indicate otherwise.
987
988 Example use::
989
990 import bar
991 import foo
992 import unittest
993 from test import support
994
995 class MiscTestCase(unittest.TestCase):
996 def test__all__(self):
997 support.check__all__(self, foo)
998
999 class OtherTestCase(unittest.TestCase):
1000 def test__all__(self):
1001 extra = {'BAR_CONST', 'FOO_CONST'}
1002 blacklist = {'baz'} # Undocumented name.
1003 # bar imports part of its API from _bar.
1004 support.check__all__(self, bar, ('bar', '_bar'),
1005 extra=extra, blacklist=blacklist)
1006
1007 .. versionadded:: 3.6
1008
1009
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001010The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +00001011
Georg Brandl7f01a132009-09-16 15:58:14 +00001012.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001013
1014 Instances are a context manager that raises :exc:`ResourceDenied` if the
1015 specified exception type is raised. Any keyword arguments are treated as
1016 attribute/value pairs to be compared against any exception raised within the
1017 :keyword:`with` statement. Only if all pairs match properly against
1018 attributes on the exception is :exc:`ResourceDenied` raised.
1019
Georg Brandl116aa622007-08-15 14:28:22 +00001020
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001021.. class:: SuppressCrashReport()
1022
1023 A context manager used to try to prevent crash dialog popups on tests that
1024 are expected to crash a subprocess.
1025
1026 On Windows, it disables Windows Error Reporting dialogs using
Georg Brandl5d941342016-02-26 19:37:12 +01001027 `SetErrorMode <https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx>`_.
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001028
1029 On UNIX, :func:`resource.setrlimit` is used to set
1030 :attr:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file
1031 creation.
1032
1033 On both platforms, the old value is restored by :meth:`__exit__`.
1034
1035
Cheryl Sabella988fb282018-02-11 08:10:42 -05001036.. class:: SaveSignals()
1037
1038 Class to save and restore signal handlers registered by the Python signal
1039 handler.
1040
1041
1042.. class:: Matcher()
1043
1044 .. method:: matches(self, d, **kwargs)
1045
1046 Try to match a single dict with the supplied arguments.
1047
1048
1049 .. method:: match_value(self, k, dv, v)
1050
1051 Try to match a single stored value (*dv*) with a supplied value (*v*).
1052
1053
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001054.. class:: WarningsRecorder()
1055
1056 Class used to record warnings for unit tests. See documentation of
1057 :func:`check_warnings` above for more details.
Cheryl Sabella988fb282018-02-11 08:10:42 -05001058
1059
1060.. class:: BasicTestRunner()
1061
1062 .. method:: run(test)
1063
1064 Run *test* and return the result.
1065
1066
Serhiy Storchaka16994912020-04-25 10:06:29 +03001067:mod:`test.support.socket_helper` --- Utilities for socket tests
1068================================================================
1069
1070.. module:: test.support.socket_helper
1071 :synopsis: Support for socket tests.
1072
1073
1074The :mod:`test.support.socket_helper` module provides support for socket tests.
1075
1076.. versionadded:: 3.9
1077
1078
1079.. data:: IPV6_ENABLED
1080
1081 Set to ``True`` if IPv6 is enabled on this host, ``False`` otherwise.
1082
1083
1084.. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM)
1085
1086 Returns an unused port that should be suitable for binding. This is
1087 achieved by creating a temporary socket with the same family and type as
1088 the ``sock`` parameter (default is :const:`~socket.AF_INET`,
1089 :const:`~socket.SOCK_STREAM`),
1090 and binding it to the specified host address (defaults to ``0.0.0.0``)
1091 with the port set to 0, eliciting an unused ephemeral port from the OS.
1092 The temporary socket is then closed and deleted, and the ephemeral port is
1093 returned.
1094
1095 Either this method or :func:`bind_port` should be used for any tests
1096 where a server socket needs to be bound to a particular port for the
1097 duration of the test.
1098 Which one to use depends on whether the calling code is creating a Python
1099 socket, or if an unused port needs to be provided in a constructor
1100 or passed to an external program (i.e. the ``-accept`` argument to
1101 openssl's s_server mode). Always prefer :func:`bind_port` over
1102 :func:`find_unused_port` where possible. Using a hard coded port is
1103 discouraged since it can make multiple instances of the test impossible to
1104 run simultaneously, which is a problem for buildbots.
1105
1106
1107.. function:: bind_port(sock, host=HOST)
1108
1109 Bind the socket to a free port and return the port number. Relies on
1110 ephemeral ports in order to ensure we are using an unbound port. This is
1111 important as many tests may be running simultaneously, especially in a
1112 buildbot environment. This method raises an exception if the
1113 ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is
1114 :const:`~socket.SOCK_STREAM`, and the socket has
1115 :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it.
1116 Tests should never set these socket options for TCP/IP sockets.
1117 The only case for setting these options is testing multicasting via
1118 multiple UDP sockets.
1119
1120 Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is
1121 available (i.e. on Windows), it will be set on the socket. This will
1122 prevent anyone else from binding to our host/port for the duration of the
1123 test.
1124
1125
1126.. function:: bind_unix_socket(sock, addr)
1127
1128 Bind a unix socket, raising :exc:`unittest.SkipTest` if
1129 :exc:`PermissionError` is raised.
1130
1131
1132.. decorator:: skip_unless_bind_unix_socket
1133
1134 A decorator for running tests that require a functional ``bind()`` for Unix
1135 sockets.
1136
1137
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001138.. function:: transient_internet(resource_name, *, timeout=30.0, errnos=())
1139
1140 A context manager that raises :exc:`~test.support.ResourceDenied` when
1141 various issues with the internet connection manifest themselves as
1142 exceptions.
1143
1144
Cheryl Sabella988fb282018-02-11 08:10:42 -05001145:mod:`test.support.script_helper` --- Utilities for the Python execution tests
1146==============================================================================
1147
1148.. module:: test.support.script_helper
1149 :synopsis: Support for Python's script execution tests.
1150
1151
1152The :mod:`test.support.script_helper` module provides support for Python's
1153script execution tests.
1154
1155.. function:: interpreter_requires_environment()
1156
1157 Return ``True`` if ``sys.executable interpreter`` requires environment
1158 variables in order to be able to run at all.
1159
1160 This is designed to be used with ``@unittest.skipIf()`` to annotate tests
1161 that need to use an ``assert_python*()`` function to launch an isolated
1162 mode (``-I``) or no environment mode (``-E``) sub-interpreter process.
1163
1164 A normal build & test does not run into this situation but it can happen
1165 when trying to run the standard library test suite from an interpreter that
1166 doesn't have an obvious home with Python's current home finding logic.
1167
1168 Setting :envvar:`PYTHONHOME` is one way to get most of the testsuite to run
1169 in that situation. :envvar:`PYTHONPATH` or :envvar:`PYTHONUSERSITE` are
1170 other common environment variables that might impact whether or not the
1171 interpreter can start.
1172
1173
1174.. function:: run_python_until_end(*args, **env_vars)
1175
1176 Set up the environment based on *env_vars* for running the interpreter
Nick Coghland5d9e022018-03-25 23:03:10 +10001177 in a subprocess. The values can include ``__isolated``, ``__cleanenv``,
1178 ``__cwd``, and ``TERM``.
Cheryl Sabella988fb282018-02-11 08:10:42 -05001179
Victor Stinner6cac1132019-12-08 08:38:16 +01001180 .. versionchanged:: 3.9
1181 The function no longer strips whitespaces from *stderr*.
1182
Cheryl Sabella988fb282018-02-11 08:10:42 -05001183
1184.. function:: assert_python_ok(*args, **env_vars)
1185
1186 Assert that running the interpreter with *args* and optional environment
1187 variables *env_vars* succeeds (``rc == 0``) and return a ``(return code,
1188 stdout, stderr)`` tuple.
1189
1190 If the ``__cleanenv`` keyword is set, *env_vars* is used as a fresh
1191 environment.
1192
1193 Python is started in isolated mode (command line option ``-I``),
1194 except if the ``__isolated`` keyword is set to ``False``.
1195
Victor Stinner6cac1132019-12-08 08:38:16 +01001196 .. versionchanged:: 3.9
1197 The function no longer strips whitespaces from *stderr*.
1198
Cheryl Sabella988fb282018-02-11 08:10:42 -05001199
1200.. function:: assert_python_failure(*args, **env_vars)
1201
1202 Assert that running the interpreter with *args* and optional environment
1203 variables *env_vars* fails (``rc != 0``) and return a ``(return code,
1204 stdout, stderr)`` tuple.
1205
1206 See :func:`assert_python_ok` for more options.
1207
Victor Stinner6cac1132019-12-08 08:38:16 +01001208 .. versionchanged:: 3.9
1209 The function no longer strips whitespaces from *stderr*.
1210
Cheryl Sabella988fb282018-02-11 08:10:42 -05001211
1212.. function:: spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw)
1213
1214 Run a Python subprocess with the given arguments.
1215
1216 *kw* is extra keyword args to pass to :func:`subprocess.Popen`. Returns a
1217 :class:`subprocess.Popen` object.
1218
1219
1220.. function:: kill_python(p)
1221
1222 Run the given :class:`subprocess.Popen` process until completion and return
1223 stdout.
1224
1225
1226.. function:: make_script(script_dir, script_basename, source, omit_suffix=False)
1227
1228 Create script containing *source* in path *script_dir* and *script_basename*.
1229 If *omit_suffix* is ``False``, append ``.py`` to the name. Return the full
1230 script path.
1231
1232
1233.. function:: make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None)
1234
1235 Create zip file at *zip_dir* and *zip_basename* with extension ``zip`` which
1236 contains the files in *script_name*. *name_in_zip* is the archive name.
1237 Return a tuple containing ``(full path, full path of archive name)``.
1238
1239
1240.. function:: make_pkg(pkg_dir, init_source='')
1241
1242 Create a directory named *pkg_dir* containing an ``__init__`` file with
1243 *init_source* as its contents.
1244
1245
1246.. function:: make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, \
1247 source, depth=1, compiled=False)
1248
1249 Create a zip package directory with a path of *zip_dir* and *zip_basename*
1250 containing an empty ``__init__`` file and a file *script_basename*
1251 containing the *source*. If *compiled* is ``True``, both source files will
1252 be compiled and added to the zip package. Return a tuple of the full zip
1253 path and the archive name for the zip file.
Joannah Nanjekye92777d52019-09-12 10:02:59 +01001254
1255
1256:mod:`test.support.bytecode_helper` --- Support tools for testing correct bytecode generation
1257=============================================================================================
1258
1259.. module:: test.support.bytecode_helper
1260 :synopsis: Support tools for testing correct bytecode generation.
1261
1262The :mod:`test.support.bytecode_helper` module provides support for testing
1263and inspecting bytecode generation.
1264
Gurupad Hegde6c7bb382019-12-28 17:16:02 -05001265The module defines the following class:
Joannah Nanjekye92777d52019-09-12 10:02:59 +01001266
1267.. class:: BytecodeTestCase(unittest.TestCase)
1268
1269 This class has custom assertion methods for inspecting bytecode.
1270
1271.. method:: BytecodeTestCase.get_disassembly_as_string(co)
1272
1273 Return the disassembly of *co* as string.
1274
1275
1276.. method:: BytecodeTestCase.assertInBytecode(x, opname, argval=_UNSPECIFIED)
1277
1278 Return instr if *opname* is found, otherwise throws :exc:`AssertionError`.
1279
1280
1281.. method:: BytecodeTestCase.assertNotInBytecode(x, opname, argval=_UNSPECIFIED)
1282
1283 Throws :exc:`AssertionError` if *opname* is found.
Hai Shie80697d2020-05-28 06:10:27 +08001284
1285
1286:mod:`test.support.threading_helper` --- Utilities for threading tests
1287======================================================================
1288
1289.. module:: test.support.threading_helper
1290 :synopsis: Support for threading tests.
1291
1292The :mod:`test.support.threading_helper` module provides support for threading tests.
1293
1294.. versionadded:: 3.10
1295
1296
1297.. function:: join_thread(thread, timeout=None)
1298
1299 Join a *thread* within *timeout*. Raise an :exc:`AssertionError` if thread
1300 is still alive after *timeout* seconds.
1301
1302
1303.. decorator:: reap_threads(func)
1304
1305 Decorator to ensure the threads are cleaned up even if the test fails.
1306
1307
1308.. function:: start_threads(threads, unlock=None)
1309
1310 Context manager to start *threads*. It attempts to join the threads upon
1311 exit.
1312
1313
1314.. function:: threading_cleanup(*original_values)
1315
1316 Cleanup up threads not specified in *original_values*. Designed to emit
1317 a warning if a test leaves running threads in the background.
1318
1319
1320.. function:: threading_setup()
1321
1322 Return current thread count and copy of dangling threads.
1323
1324
1325.. function:: wait_threads_exit(timeout=None)
1326
1327 Context manager to wait until all threads created in the ``with`` statement
1328 exit.
1329
1330
1331.. function:: catch_threading_exception()
1332
1333 Context manager catching :class:`threading.Thread` exception using
1334 :func:`threading.excepthook`.
1335
1336 Attributes set when an exception is catched:
1337
1338 * ``exc_type``
1339 * ``exc_value``
1340 * ``exc_traceback``
1341 * ``thread``
1342
1343 See :func:`threading.excepthook` documentation.
1344
1345 These attributes are deleted at the context manager exit.
1346
1347 Usage::
1348
1349 with threading_helper.catch_threading_exception() as cm:
1350 # code spawning a thread which raises an exception
1351 ...
1352
1353 # check the thread exception, use cm attributes:
1354 # exc_type, exc_value, exc_traceback, thread
1355 ...
1356
1357 # exc_type, exc_value, exc_traceback, thread attributes of cm no longer
1358 # exists at this point
1359 # (to avoid reference cycles)
1360
1361 .. versionadded:: 3.8
Hai Shi0d00b2a2020-06-10 20:29:02 +08001362
1363
1364:mod:`test.support.os_helper` --- Utilities for os tests
1365========================================================================
1366
1367.. module:: test.support.os_helper
1368 :synopsis: Support for os tests.
1369
1370The :mod:`test.support.os_helper` module provides support for os tests.
1371
1372.. versionadded:: 3.10
1373
1374
1375.. data:: FS_NONASCII
1376
1377 A non-ASCII character encodable by :func:`os.fsencode`.
1378
1379
1380.. data:: SAVEDCWD
1381
1382 Set to :func:`os.getcwd`.
1383
1384
1385.. data:: TESTFN
1386
1387 Set to a name that is safe to use as the name of a temporary file. Any
1388 temporary file that is created should be closed and unlinked (removed).
1389
1390
1391.. data:: TESTFN_NONASCII
1392
1393 Set to a filename containing the :data:`FS_NONASCII` character.
1394
1395
1396.. data:: TESTFN_UNENCODABLE
1397
1398 Set to a filename (str type) that should not be able to be encoded by file
1399 system encoding in strict mode. It may be ``None`` if it's not possible to
1400 generate such a filename.
1401
1402
1403.. data:: TESTFN_UNDECODABLE
1404
1405 Set to a filename (bytes type) that should not be able to be decoded by
1406 file system encoding in strict mode. It may be ``None`` if it's not
1407 possible to generate such a filename.
1408
1409
1410.. data:: TESTFN_UNICODE
1411
1412 Set to a non-ASCII name for a temporary file.
1413
1414
1415.. class:: EnvironmentVarGuard()
1416
1417 Class used to temporarily set or unset environment variables. Instances can
1418 be used as a context manager and have a complete dictionary interface for
1419 querying/modifying the underlying ``os.environ``. After exit from the
1420 context manager all changes to environment variables done through this
1421 instance will be rolled back.
1422
1423 .. versionchanged:: 3.1
1424 Added dictionary interface.
1425
1426
1427.. class:: FakePath(path)
1428
1429 Simple :term:`path-like object`. It implements the :meth:`__fspath__`
1430 method which just returns the *path* argument. If *path* is an exception,
1431 it will be raised in :meth:`!__fspath__`.
1432
1433
1434.. method:: EnvironmentVarGuard.set(envvar, value)
1435
1436 Temporarily set the environment variable ``envvar`` to the value of
1437 ``value``.
1438
1439
1440.. method:: EnvironmentVarGuard.unset(envvar)
1441
1442 Temporarily unset the environment variable ``envvar``.
1443
1444
1445.. function:: can_symlink()
1446
1447 Return ``True`` if the OS supports symbolic links, ``False``
1448 otherwise.
1449
1450
1451.. function:: can_xattr()
1452
1453 Return ``True`` if the OS supports xattr, ``False``
1454 otherwise.
1455
1456
1457.. function:: change_cwd(path, quiet=False)
1458
1459 A context manager that temporarily changes the current working
1460 directory to *path* and yields the directory.
1461
1462 If *quiet* is ``False``, the context manager raises an exception
1463 on error. Otherwise, it issues only a warning and keeps the current
1464 working directory the same.
1465
1466
1467.. function:: create_empty_file(filename)
1468
1469 Create an empty file with *filename*. If it already exists, truncate it.
1470
1471
1472.. function:: fd_count()
1473
1474 Count the number of open file descriptors.
1475
1476
1477.. function:: fs_is_case_insensitive(directory)
1478
1479 Return ``True`` if the file system for *directory* is case-insensitive.
1480
1481
1482.. function:: make_bad_fd()
1483
1484 Create an invalid file descriptor by opening and closing a temporary file,
1485 and returning its descriptor.
1486
1487
1488.. function:: rmdir(filename)
1489
1490 Call :func:`os.rmdir` on *filename*. On Windows platforms, this is
1491 wrapped with a wait loop that checks for the existence of the file.
1492
1493
1494.. function:: rmtree(path)
1495
1496 Call :func:`shutil.rmtree` on *path* or call :func:`os.lstat` and
1497 :func:`os.rmdir` to remove a path and its contents. On Windows platforms,
1498 this is wrapped with a wait loop that checks for the existence of the files.
1499
1500
1501.. decorator:: skip_unless_symlink
1502
1503 A decorator for running tests that require support for symbolic links.
1504
1505
1506.. decorator:: skip_unless_xattr
1507
1508 A decorator for running tests that require support for xattr.
1509
1510
1511.. function:: temp_cwd(name='tempcwd', quiet=False)
1512
1513 A context manager that temporarily creates a new directory and
1514 changes the current working directory (CWD).
1515
1516 The context manager creates a temporary directory in the current
1517 directory with name *name* before temporarily changing the current
1518 working directory. If *name* is ``None``, the temporary directory is
1519 created using :func:`tempfile.mkdtemp`.
1520
1521 If *quiet* is ``False`` and it is not possible to create or change
1522 the CWD, an error is raised. Otherwise, only a warning is raised
1523 and the original CWD is used.
1524
1525
1526.. function:: temp_dir(path=None, quiet=False)
1527
1528 A context manager that creates a temporary directory at *path* and
1529 yields the directory.
1530
1531 If *path* is ``None``, the temporary directory is created using
1532 :func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager
1533 raises an exception on error. Otherwise, if *path* is specified and
1534 cannot be created, only a warning is issued.
1535
1536
1537.. function:: temp_umask(umask)
1538
1539 A context manager that temporarily sets the process umask.
1540
1541
1542.. function:: unlink(filename)
1543
1544 Call :func:`os.unlink` on *filename*. On Windows platforms, this is
1545 wrapped with a wait loop that checks for the existence fo the file.
Hai Shi7f888c72020-06-11 07:51:18 +08001546
1547
1548:mod:`test.support.import_helper` --- Utilities for import tests
1549================================================================
1550
1551.. module:: test.support.import_helper
1552 :synopsis: Support for import tests.
1553
1554The :mod:`test.support.import_helper` module provides support for import tests.
1555
1556.. versionadded:: 3.10
1557
1558
1559.. function:: forget(module_name)
1560
1561 Remove the module named *module_name* from ``sys.modules`` and delete any
1562 byte-compiled files of the module.
1563
1564
1565.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
1566
1567 This function imports and returns a fresh copy of the named Python module
1568 by removing the named module from ``sys.modules`` before doing the import.
1569 Note that unlike :func:`reload`, the original module is not affected by
1570 this operation.
1571
1572 *fresh* is an iterable of additional module names that are also removed
1573 from the ``sys.modules`` cache before doing the import.
1574
1575 *blocked* is an iterable of module names that are replaced with ``None``
1576 in the module cache during the import to ensure that attempts to import
1577 them raise :exc:`ImportError`.
1578
1579 The named module and any modules named in the *fresh* and *blocked*
1580 parameters are saved before starting the import and then reinserted into
1581 ``sys.modules`` when the fresh import is complete.
1582
1583 Module and package deprecation messages are suppressed during this import
1584 if *deprecated* is ``True``.
1585
1586 This function will raise :exc:`ImportError` if the named module cannot be
1587 imported.
1588
1589 Example use::
1590
1591 # Get copies of the warnings module for testing without affecting the
1592 # version being used by the rest of the test suite. One copy uses the
1593 # C implementation, the other is forced to use the pure Python fallback
1594 # implementation
1595 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
1596 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
1597
1598 .. versionadded:: 3.1
1599
1600
1601.. function:: import_module(name, deprecated=False, *, required_on())
1602
1603 This function imports and returns the named module. Unlike a normal
1604 import, this function raises :exc:`unittest.SkipTest` if the module
1605 cannot be imported.
1606
1607 Module and package deprecation messages are suppressed during this import
1608 if *deprecated* is ``True``. If a module is required on a platform but
1609 optional for others, set *required_on* to an iterable of platform prefixes
1610 which will be compared against :data:`sys.platform`.
1611
1612 .. versionadded:: 3.1
1613
1614
1615.. function:: modules_setup()
1616
1617 Return a copy of :data:`sys.modules`.
1618
1619
1620.. function:: modules_cleanup(oldmodules)
1621
1622 Remove modules except for *oldmodules* and ``encodings`` in order to
1623 preserve internal cache.
1624
1625
1626.. function:: unload(name)
1627
1628 Delete *name* from ``sys.modules``.
1629
1630
1631.. function:: make_legacy_pyc(source)
1632
1633 Move a :pep:`3147`/:pep:`488` pyc file to its legacy pyc location and return the file
1634 system path to the legacy pyc file. The *source* value is the file system
1635 path to the source file. It does not need to exist, however the PEP
1636 3147/488 pyc file must exist.
1637
1638
1639.. class:: CleanImport(*module_names)
1640
1641 A context manager to force import to return a new module reference. This
1642 is useful for testing module-level behaviors, such as the emission of a
1643 DeprecationWarning on import. Example usage::
1644
1645 with CleanImport('foo'):
1646 importlib.import_module('foo') # New reference.
1647
1648
1649.. class:: DirsOnSysPath(*paths)
1650
1651 A context manager to temporarily add directories to sys.path.
1652
1653 This makes a copy of :data:`sys.path`, appends any directories given
1654 as positional arguments, then reverts :data:`sys.path` to the copied
1655 settings when the context ends.
1656
1657 Note that *all* :data:`sys.path` modifications in the body of the
1658 context manager, including replacement of the object,
1659 will be reverted at the end of the block.
1660
1661