blob: 54ad620d7dae9d6631040845cf61b54498620fb5 [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
250.. data:: FS_NONASCII
251
252 A non-ASCII character encodable by :func:`os.fsencode`.
253
254
Georg Brandl116aa622007-08-15 14:28:22 +0000255.. data:: TESTFN
256
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000257 Set to a name that is safe to use as the name of a temporary file. Any
258 temporary file that is created should be closed and unlinked (removed).
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Eli Benderskye1689652011-05-06 09:29:27 +0300260
Cheryl Sabella988fb282018-02-11 08:10:42 -0500261.. data:: TESTFN_UNICODE
262
263 Set to a non-ASCII name for a temporary file.
264
265
266.. data:: TESTFN_ENCODING
267
268 Set to :func:`sys.getfilesystemencoding`.
269
270
271.. data:: TESTFN_UNENCODABLE
272
273 Set to a filename (str type) that should not be able to be encoded by file
274 system encoding in strict mode. It may be ``None`` if it's not possible to
275 generate such a filename.
276
277
278.. data:: TESTFN_UNDECODABLE
279
280 Set to a filename (bytes type) that should not be able to be decoded by
281 file system encoding in strict mode. It may be ``None`` if it's not
282 possible to generate such a filename.
283
284
285.. data:: TESTFN_NONASCII
286
287 Set to a filename containing the :data:`FS_NONASCII` character.
288
289
Victor Stinner24c62582019-10-30 12:41:43 +0100290.. data:: LOOPBACK_TIMEOUT
291
292 Timeout in seconds for tests using a network server listening on the network
293 local loopback interface like ``127.0.0.1``.
294
295 The timeout is long enough to prevent test failure: it takes into account
296 that the client and the server can run in different threads or even
297 different processes.
298
299 The timeout should be long enough for :meth:`~socket.socket.connect`,
300 :meth:`~socket.socket.recv` and :meth:`~socket.socket.send` methods of
301 :class:`socket.socket`.
302
303 Its default value is 5 seconds.
304
305 See also :data:`INTERNET_TIMEOUT`.
306
307
308.. data:: INTERNET_TIMEOUT
309
310 Timeout in seconds for network requests going to the Internet.
311
312 The timeout is short enough to prevent a test to wait for too long if the
313 Internet request is blocked for whatever reason.
314
315 Usually, a timeout using :data:`INTERNET_TIMEOUT` should not mark a test as
316 failed, but skip the test instead: see
317 :func:`~test.support.transient_internet`.
318
319 Its default value is 1 minute.
320
321 See also :data:`LOOPBACK_TIMEOUT`.
322
323
324.. data:: SHORT_TIMEOUT
325
326 Timeout in seconds to mark a test as failed if the test takes "too long".
327
328 The timeout value depends on the regrtest ``--timeout`` command line option.
329
330 If a test using :data:`SHORT_TIMEOUT` starts to fail randomly on slow
331 buildbots, use :data:`LONG_TIMEOUT` instead.
332
333 Its default value is 30 seconds.
334
335
336.. data:: LONG_TIMEOUT
337
338 Timeout in seconds to detect when a test hangs.
339
340 It is long enough to reduce the risk of test failure on the slowest Python
341 buildbots. It should not be used to mark a test as failed if the test takes
342 "too long". The timeout value depends on the regrtest ``--timeout`` command
343 line option.
344
345 Its default value is 5 minutes.
346
347 See also :data:`LOOPBACK_TIMEOUT`, :data:`INTERNET_TIMEOUT` and
348 :data:`SHORT_TIMEOUT`.
349
350
Cheryl Sabella988fb282018-02-11 08:10:42 -0500351.. data:: IPV6_ENABLED
352
353 Set to ``True`` if IPV6 is enabled on this host, ``False`` otherwise.
354
355
356.. data:: SAVEDCWD
357
358 Set to :func:`os.getcwd`.
359
360
361.. data:: PGO
362
363 Set when tests can be skipped when they are not useful for PGO.
364
365
366.. data:: PIPE_MAX_SIZE
367
368 A constant that is likely larger than the underlying OS pipe buffer size,
369 to make writes blocking.
370
371
372.. data:: SOCK_MAX_SIZE
373
374 A constant that is likely larger than the underlying OS socket buffer size,
375 to make writes blocking.
376
377
378.. data:: TEST_SUPPORT_DIR
379
380 Set to the top level directory that contains :mod:`test.support`.
381
382
383.. data:: TEST_HOME_DIR
384
385 Set to the top level directory for the test package.
386
387
388.. data:: TEST_DATA_DIR
389
390 Set to the ``data`` directory within the test package.
391
392
393.. data:: MAX_Py_ssize_t
394
395 Set to :data:`sys.maxsize` for big memory tests.
396
397
398.. data:: max_memuse
399
400 Set by :func:`set_memlimit` as the memory limit for big memory tests.
401 Limited by :data:`MAX_Py_ssize_t`.
402
403
404.. data:: real_max_memuse
405
406 Set by :func:`set_memlimit` as the memory limit for big memory tests. Not
407 limited by :data:`MAX_Py_ssize_t`.
408
409
410.. data:: MISSING_C_DOCSTRINGS
411
412 Return ``True`` if running on CPython, not on Windows, and configuration
413 not set with ``WITH_DOC_STRINGS``.
414
415
416.. data:: HAVE_DOCSTRINGS
417
418 Check for presence of docstrings.
419
Serhiy Storchaka17e52642019-08-04 12:38:46 +0300420
Stéphane Wirtela40681d2019-02-22 14:45:36 +0100421.. data:: TEST_HTTP_URL
422
423 Define the URL of a dedicated HTTP server for the network tests.
424
Cheryl Sabella988fb282018-02-11 08:10:42 -0500425
Serhiy Storchaka17e52642019-08-04 12:38:46 +0300426.. data:: ALWAYS_EQ
427
428 Object that is equal to anything. Used to test mixed type comparison.
429
430
Serhiy Storchaka18b711c2019-08-04 14:12:48 +0300431.. data:: NEVER_EQ
432
433 Object that is not equal to anything (even to :data:`ALWAYS_EQ`).
434 Used to test mixed type comparison.
435
436
Serhiy Storchaka17e52642019-08-04 12:38:46 +0300437.. data:: LARGEST
438
439 Object that is greater than anything (except itself).
440 Used to test mixed type comparison.
441
442
443.. data:: SMALLEST
444
445 Object that is less than anything (except itself).
446 Used to test mixed type comparison.
447
Cheryl Sabella988fb282018-02-11 08:10:42 -0500448
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000449The :mod:`test.support` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000450
Georg Brandl116aa622007-08-15 14:28:22 +0000451.. function:: forget(module_name)
452
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000453 Remove the module named *module_name* from ``sys.modules`` and delete any
Georg Brandl116aa622007-08-15 14:28:22 +0000454 byte-compiled files of the module.
455
456
Cheryl Sabella988fb282018-02-11 08:10:42 -0500457.. function:: unload(name)
458
459 Delete *name* from ``sys.modules``.
460
461
462.. function:: unlink(filename)
463
464 Call :func:`os.unlink` on *filename*. On Windows platforms, this is
465 wrapped with a wait loop that checks for the existence fo the file.
466
467
468.. function:: rmdir(filename)
469
470 Call :func:`os.rmdir` on *filename*. On Windows platforms, this is
471 wrapped with a wait loop that checks for the existence of the file.
472
473
474.. function:: rmtree(path)
475
476 Call :func:`shutil.rmtree` on *path* or call :func:`os.lstat` and
477 :func:`os.rmdir` to remove a path and its contents. On Windows platforms,
478 this is wrapped with a wait loop that checks for the existence of the files.
479
480
481.. function:: make_legacy_pyc(source)
482
Stéphane Wirtel12e696b2018-10-27 00:58:26 +0200483 Move a :pep:`3147`/:pep:`488` pyc file to its legacy pyc location and return the file
Cheryl Sabella988fb282018-02-11 08:10:42 -0500484 system path to the legacy pyc file. The *source* value is the file system
485 path to the source file. It does not need to exist, however the PEP
486 3147/488 pyc file must exist.
487
488
Georg Brandl116aa622007-08-15 14:28:22 +0000489.. function:: is_resource_enabled(resource)
490
Eli Benderskye1689652011-05-06 09:29:27 +0300491 Return ``True`` if *resource* is enabled and available. The list of
Georg Brandl116aa622007-08-15 14:28:22 +0000492 available resources is only set when :mod:`test.regrtest` is executing the
493 tests.
494
495
Cheryl Sabella988fb282018-02-11 08:10:42 -0500496.. function:: python_is_optimized()
497
498 Return ``True`` if Python was not built with ``-O0`` or ``-Og``.
499
500
501.. function:: with_pymalloc()
502
503 Return :data:`_testcapi.WITH_PYMALLOC`.
504
505
Georg Brandl7f01a132009-09-16 15:58:14 +0000506.. function:: requires(resource, msg=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000507
Florent Xiclunab14930c2010-03-13 15:26:44 +0000508 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
Florent Xicluna53b506be2010-03-18 20:00:57 +0000509 argument to :exc:`ResourceDenied` if it is raised. Always returns
Eli Benderskye1689652011-05-06 09:29:27 +0300510 ``True`` if called by a function whose ``__name__`` is ``'__main__'``.
Florent Xicluna53b506be2010-03-18 20:00:57 +0000511 Used when tests are executed by :mod:`test.regrtest`.
Georg Brandl116aa622007-08-15 14:28:22 +0000512
513
Cheryl Sabella988fb282018-02-11 08:10:42 -0500514.. function:: system_must_validate_cert(f)
515
516 Raise :exc:`unittest.SkipTest` on TLS certification validation failures.
517
518
519.. function:: sortdict(dict)
520
521 Return a repr of *dict* with keys sorted.
522
523
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000524.. function:: findfile(filename, subdir=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000525
Florent Xicluna53b506be2010-03-18 20:00:57 +0000526 Return the path to the file named *filename*. If no match is found
527 *filename* is returned. This does not equal a failure since it could be the
528 path to the file.
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Cheryl Sabella988fb282018-02-11 08:10:42 -0500530 Setting *subdir* indicates a relative path to use to find the file
531 rather than looking directly in the path directories.
532
533
534.. function:: create_empty_file(filename)
535
536 Create an empty file with *filename*. If it already exists, truncate it.
537
538
539.. function:: fd_count()
540
541 Count the number of open file descriptors.
542
543
544.. function:: match_test(test)
545
546 Match *test* to patterns set in :func:`set_match_tests`.
547
548
549.. function:: set_match_tests(patterns)
550
551 Define match test with regular expression *patterns*.
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000552
Georg Brandl116aa622007-08-15 14:28:22 +0000553
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000554.. function:: run_unittest(\*classes)
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556 Execute :class:`unittest.TestCase` subclasses passed to the function. The
Florent Xicluna53b506be2010-03-18 20:00:57 +0000557 function scans the classes for methods starting with the prefix ``test_``
558 and executes the tests individually.
Georg Brandl116aa622007-08-15 14:28:22 +0000559
560 It is also legal to pass strings as parameters; these should be keys in
561 ``sys.modules``. Each associated module will be scanned by
562 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
563 following :func:`test_main` function::
564
565 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +0000566 support.run_unittest(__name__)
Georg Brandl116aa622007-08-15 14:28:22 +0000567
568 This will run all tests defined in the named module.
569
Georg Brandl116aa622007-08-15 14:28:22 +0000570
Cheryl Sabella988fb282018-02-11 08:10:42 -0500571.. function:: run_doctest(module, verbosity=None, optionflags=0)
Eli Benderskye1689652011-05-06 09:29:27 +0300572
573 Run :func:`doctest.testmod` on the given *module*. Return
574 ``(failure_count, test_count)``.
575
576 If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity
577 set to :data:`verbose`. Otherwise, it is run with verbosity set to
Cheryl Sabella988fb282018-02-11 08:10:42 -0500578 ``None``. *optionflags* is passed as ``optionflags`` to
579 :func:`doctest.testmod`.
580
581
582.. function:: setswitchinterval(interval)
583
584 Set the :func:`sys.setswitchinterval` to the given *interval*. Defines
585 a minimum interval for Android systems to prevent the system from hanging.
586
587
588.. function:: check_impl_detail(**guards)
589
590 Use this check to guard CPython's implementation-specific tests or to
591 run them only on the implementations guarded by the arguments::
592
593 check_impl_detail() # Only on CPython (default).
594 check_impl_detail(jython=True) # Only on Jython.
595 check_impl_detail(cpython=False) # Everywhere except CPython.
596
Eli Benderskye1689652011-05-06 09:29:27 +0300597
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000598.. function:: check_warnings(\*filters, quiet=True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000599
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000600 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
601 easier to test that a warning was correctly raised. It is approximately
602 equivalent to calling ``warnings.catch_warnings(record=True)`` with
603 :meth:`warnings.simplefilter` set to ``always`` and with the option to
604 automatically validate the results that are recorded.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000605
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000606 ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
607 WarningCategory)`` as positional arguments. If one or more *filters* are
Eli Benderskye1689652011-05-06 09:29:27 +0300608 provided, or if the optional keyword argument *quiet* is ``False``,
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000609 it checks to make sure the warnings are as expected: each specified filter
610 must match at least one of the warnings raised by the enclosed code or the
611 test fails, and if any warnings are raised that do not match any of the
612 specified filters the test fails. To disable the first of these checks,
Eli Benderskye1689652011-05-06 09:29:27 +0300613 set *quiet* to ``True``.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000614
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000615 If no arguments are specified, it defaults to::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000616
Florent Xicluna53b506be2010-03-18 20:00:57 +0000617 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000618
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000619 In this case all warnings are caught and no errors are raised.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000620
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000621 On entry to the context manager, a :class:`WarningRecorder` instance is
622 returned. The underlying warnings list from
623 :func:`~warnings.catch_warnings` is available via the recorder object's
624 :attr:`warnings` attribute. As a convenience, the attributes of the object
625 representing the most recent warning can also be accessed directly through
626 the recorder object (see example below). If no warning has been raised,
627 then any of the attributes that would otherwise be expected on an object
Eli Benderskye1689652011-05-06 09:29:27 +0300628 representing a warning will return ``None``.
Thomas Woutersed03b412007-08-28 21:37:11 +0000629
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000630 The recorder object also has a :meth:`reset` method, which clears the
631 warnings list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000632
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000633 The context manager is designed to be used like this::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000634
635 with check_warnings(("assertion is always true", SyntaxWarning),
636 ("", UserWarning)):
637 exec('assert(False, "Hey!")')
638 warnings.warn(UserWarning("Hide me!"))
639
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000640 In this case if either warning was not raised, or some other warning was
641 raised, :func:`check_warnings` would raise an error.
642
643 When a test needs to look more deeply into the warnings, rather than
644 just checking whether or not they occurred, code like this can be used::
645
Florent Xiclunab14930c2010-03-13 15:26:44 +0000646 with check_warnings(quiet=True) as w:
Thomas Woutersed03b412007-08-28 21:37:11 +0000647 warnings.warn("foo")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000648 assert str(w.args[0]) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000649 warnings.warn("bar")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000650 assert str(w.args[0]) == "bar"
651 assert str(w.warnings[0].args[0]) == "foo"
652 assert str(w.warnings[1].args[0]) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000653 w.reset()
654 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000655
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000656
657 Here all warnings will be caught, and the test code tests the captured
658 warnings directly.
659
Ezio Melottif8754a62010-03-21 07:16:43 +0000660 .. versionchanged:: 3.2
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000661 New optional arguments *filters* and *quiet*.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000662
Thomas Woutersed03b412007-08-28 21:37:11 +0000663
Cheryl Sabella988fb282018-02-11 08:10:42 -0500664.. function:: check_no_resource_warning(testcase)
665
666 Context manager to check that no :exc:`ResourceWarning` was raised. You
667 must remove the object which may emit :exc:`ResourceWarning` before the
668 end of the context manager.
669
670
671.. function:: set_memlimit(limit)
672
673 Set the values for :data:`max_memuse` and :data:`real_max_memuse` for big
674 memory tests.
675
676
677.. function:: record_original_stdout(stdout)
678
679 Store the value from *stdout*. It is meant to hold the stdout at the
680 time the regrtest began.
681
682
683.. function:: get_original_stdout
684
685 Return the original stdout set by :func:`record_original_stdout` or
686 ``sys.stdout`` if it's not set.
687
688
Cheryl Sabella988fb282018-02-11 08:10:42 -0500689.. function:: args_from_interpreter_flags()
690
691 Return a list of command line arguments reproducing the current settings
692 in ``sys.flags`` and ``sys.warnoptions``.
693
694
695.. function:: optim_args_from_interpreter_flags()
696
697 Return a list of command line arguments reproducing the current
698 optimization settings in ``sys.flags``.
699
700
R David Murray5a33f812013-07-11 12:28:40 -0400701.. function:: captured_stdin()
702 captured_stdout()
703 captured_stderr()
Thomas Woutersed03b412007-08-28 21:37:11 +0000704
R David Murray5a33f812013-07-11 12:28:40 -0400705 A context managers that temporarily replaces the named stream with
706 :class:`io.StringIO` object.
Thomas Woutersed03b412007-08-28 21:37:11 +0000707
R David Murray5a33f812013-07-11 12:28:40 -0400708 Example use with output streams::
Thomas Woutersed03b412007-08-28 21:37:11 +0000709
R David Murray5a33f812013-07-11 12:28:40 -0400710 with captured_stdout() as stdout, captured_stderr() as stderr:
Collin Winterc79461b2007-09-01 23:34:30 +0000711 print("hello")
R David Murray5a33f812013-07-11 12:28:40 -0400712 print("error", file=sys.stderr)
713 assert stdout.getvalue() == "hello\n"
714 assert stderr.getvalue() == "error\n"
715
716 Example use with input stream::
717
718 with captured_stdin() as stdin:
719 stdin.write('hello\n')
720 stdin.seek(0)
721 # call test code that consumes from sys.stdin
722 captured = input()
723 self.assertEqual(captured, "hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000724
Thomas Woutersed03b412007-08-28 21:37:11 +0000725
Nick Coghlan55175962013-07-28 22:11:50 +1000726.. function:: temp_dir(path=None, quiet=False)
727
728 A context manager that creates a temporary directory at *path* and
729 yields the directory.
730
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300731 If *path* is ``None``, the temporary directory is created using
Nick Coghlan55175962013-07-28 22:11:50 +1000732 :func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager
733 raises an exception on error. Otherwise, if *path* is specified and
734 cannot be created, only a warning is issued.
735
736
737.. function:: change_cwd(path, quiet=False)
Eli Benderskye1689652011-05-06 09:29:27 +0300738
739 A context manager that temporarily changes the current working
Nick Coghlan55175962013-07-28 22:11:50 +1000740 directory to *path* and yields the directory.
Eli Benderskye1689652011-05-06 09:29:27 +0300741
Nick Coghlan55175962013-07-28 22:11:50 +1000742 If *quiet* is ``False``, the context manager raises an exception
743 on error. Otherwise, it issues only a warning and keeps the current
744 working directory the same.
Eli Benderskye1689652011-05-06 09:29:27 +0300745
Nick Coghlan55175962013-07-28 22:11:50 +1000746
747.. function:: temp_cwd(name='tempcwd', quiet=False)
748
749 A context manager that temporarily creates a new directory and
750 changes the current working directory (CWD).
751
752 The context manager creates a temporary directory in the current
753 directory with name *name* before temporarily changing the current
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300754 working directory. If *name* is ``None``, the temporary directory is
Nick Coghlan55175962013-07-28 22:11:50 +1000755 created using :func:`tempfile.mkdtemp`.
756
757 If *quiet* is ``False`` and it is not possible to create or change
758 the CWD, an error is raised. Otherwise, only a warning is raised
759 and the original CWD is used.
Eli Benderskye1689652011-05-06 09:29:27 +0300760
761
762.. function:: temp_umask(umask)
763
764 A context manager that temporarily sets the process umask.
765
766
Cheryl Sabella988fb282018-02-11 08:10:42 -0500767.. function:: transient_internet(resource_name, *, timeout=30.0, errnos=())
768
769 A context manager that raises :exc:`ResourceDenied` when various issues
770 with the internet connection manifest themselves as exceptions.
771
772
773.. function:: disable_faulthandler()
774
775 A context manager that replaces ``sys.stderr`` with ``sys.__stderr__``.
776
777
778.. function:: gc_collect()
779
780 Force as many objects as possible to be collected. This is needed because
781 timely deallocation is not guaranteed by the garbage collector. This means
782 that ``__del__`` methods may be called later than expected and weakrefs
783 may remain alive for longer than expected.
784
785
786.. function:: disable_gc()
787
788 A context manager that disables the garbage collector upon entry and
789 reenables it upon exit.
790
791
792.. function:: swap_attr(obj, attr, new_val)
793
794 Context manager to swap out an attribute with a new object.
795
796 Usage::
797
798 with swap_attr(obj, "attr", 5):
799 ...
800
801 This will set ``obj.attr`` to 5 for the duration of the ``with`` block,
802 restoring the old value at the end of the block. If ``attr`` doesn't
803 exist on ``obj``, it will be created and then deleted at the end of the
804 block.
805
806 The old value (or ``None`` if it doesn't exist) will be assigned to the
807 target of the "as" clause, if there is one.
808
809
810.. function:: swap_item(obj, attr, new_val)
811
812 Context manager to swap out an item with a new object.
813
814 Usage::
815
816 with swap_item(obj, "item", 5):
817 ...
818
819 This will set ``obj["item"]`` to 5 for the duration of the ``with`` block,
820 restoring the old value at the end of the block. If ``item`` doesn't
821 exist on ``obj``, it will be created and then deleted at the end of the
822 block.
823
824 The old value (or ``None`` if it doesn't exist) will be assigned to the
825 target of the "as" clause, if there is one.
826
827
828.. function:: wait_threads_exit(timeout=60.0)
829
Ville Skyttä61f82e02018-04-20 23:08:45 +0300830 Context manager to wait until all threads created in the ``with`` statement
Cheryl Sabella988fb282018-02-11 08:10:42 -0500831 exit.
832
833
834.. function:: start_threads(threads, unlock=None)
835
836 Context manager to start *threads*. It attempts to join the threads upon
837 exit.
838
839
840.. function:: calcobjsize(fmt)
841
842 Return :func:`struct.calcsize` for ``nP{fmt}0n`` or, if ``gettotalrefcount``
843 exists, ``2PnP{fmt}0P``.
844
845
846.. function:: calcvobjsize(fmt)
847
848 Return :func:`struct.calcsize` for ``nPn{fmt}0n`` or, if ``gettotalrefcount``
849 exists, ``2PnPn{fmt}0P``.
850
851
852.. function:: checksizeof(test, o, size)
853
854 For testcase *test*, assert that the ``sys.getsizeof`` for *o* plus the GC
855 header size equals *size*.
856
857
Eli Benderskye1689652011-05-06 09:29:27 +0300858.. function:: can_symlink()
859
860 Return ``True`` if the OS supports symbolic links, ``False``
861 otherwise.
862
863
Cheryl Sabella988fb282018-02-11 08:10:42 -0500864.. function:: can_xattr()
865
866 Return ``True`` if the OS supports xattr, ``False``
867 otherwise.
868
869
Daisuke Miyakawa0e61e672017-10-12 23:39:43 +0900870.. decorator:: skip_unless_symlink
Eli Benderskye1689652011-05-06 09:29:27 +0300871
872 A decorator for running tests that require support for symbolic links.
873
874
Cheryl Sabella988fb282018-02-11 08:10:42 -0500875.. decorator:: skip_unless_xattr
876
877 A decorator for running tests that require support for xattr.
878
879
880.. decorator:: skip_unless_bind_unix_socket
881
882 A decorator for running tests that require a functional bind() for Unix
883 sockets.
884
885
Nick Coghlan2496f332011-09-19 20:26:31 +1000886.. decorator:: anticipate_failure(condition)
887
888 A decorator to conditionally mark tests with
889 :func:`unittest.expectedFailure`. Any use of this decorator should
890 have an associated comment identifying the relevant tracker issue.
891
892
893.. decorator:: run_with_locale(catstr, *locales)
Eli Benderskye1689652011-05-06 09:29:27 +0300894
895 A decorator for running a function in a different locale, correctly
896 resetting it after it has finished. *catstr* is the locale category as
897 a string (for example ``"LC_ALL"``). The *locales* passed will be tried
898 sequentially, and the first valid locale will be used.
899
900
Cheryl Sabella988fb282018-02-11 08:10:42 -0500901.. decorator:: run_with_tz(tz)
902
903 A decorator for running a function in a specific timezone, correctly
904 resetting it after it has finished.
905
906
907.. decorator:: requires_freebsd_version(*min_version)
908
909 Decorator for the minimum version when running test on FreeBSD. If the
910 FreeBSD version is less than the minimum, raise :exc:`unittest.SkipTest`.
911
912
913.. decorator:: requires_linux_version(*min_version)
914
915 Decorator for the minimum version when running test on Linux. If the
916 Linux version is less than the minimum, raise :exc:`unittest.SkipTest`.
917
918
919.. decorator:: requires_mac_version(*min_version)
920
921 Decorator for the minimum version when running test on Mac OS X. If the
922 MAC OS X version is less than the minimum, raise :exc:`unittest.SkipTest`.
923
924
925.. decorator:: requires_IEEE_754
926
927 Decorator for skipping tests on non-IEEE 754 platforms.
928
929
930.. decorator:: requires_zlib
931
932 Decorator for skipping tests if :mod:`zlib` doesn't exist.
933
934
935.. decorator:: requires_gzip
936
937 Decorator for skipping tests if :mod:`gzip` doesn't exist.
938
939
940.. decorator:: requires_bz2
941
942 Decorator for skipping tests if :mod:`bz2` doesn't exist.
943
944
945.. decorator:: requires_lzma
946
947 Decorator for skipping tests if :mod:`lzma` doesn't exist.
948
949
950.. decorator:: requires_resource(resource)
951
952 Decorator for skipping tests if *resource* is not available.
953
954
955.. decorator:: requires_docstrings
956
957 Decorator for only running the test if :data:`HAVE_DOCSTRINGS`.
958
959
960.. decorator:: cpython_only(test)
961
962 Decorator for tests only applicable to CPython.
963
964
965.. decorator:: impl_detail(msg=None, **guards)
966
967 Decorator for invoking :func:`check_impl_detail` on *guards*. If that
968 returns ``False``, then uses *msg* as the reason for skipping the test.
969
970
971.. decorator:: no_tracing(func)
972
973 Decorator to temporarily turn off tracing for the duration of the test.
974
975
976.. decorator:: refcount_test(test)
977
978 Decorator for tests which involve reference counting. The decorator does
979 not run the test if it is not run by CPython. Any trace function is unset
980 for the duration of the test to prevent unexpected refcounts caused by
981 the trace function.
982
983
984.. decorator:: reap_threads(func)
985
986 Decorator to ensure the threads are cleaned up even if the test fails.
987
988
989.. decorator:: bigmemtest(size, memuse, dry_run=True)
990
991 Decorator for bigmem tests.
992
993 *size* is a requested size for the test (in arbitrary, test-interpreted
994 units.) *memuse* is the number of bytes per unit for the test, or a good
995 estimate of it. For example, a test that needs two byte buffers, of 4 GiB
996 each, could be decorated with ``@bigmemtest(size=_4G, memuse=2)``.
997
998 The *size* argument is normally passed to the decorated test method as an
999 extra argument. If *dry_run* is ``True``, the value passed to the test
1000 method may be less than the requested value. If *dry_run* is ``False``, it
1001 means the test doesn't support dummy runs when ``-M`` is not specified.
1002
1003
1004.. decorator:: bigaddrspacetest(f)
1005
1006 Decorator for tests that fill the address space. *f* is the function to
1007 wrap.
1008
1009
Eli Benderskye1689652011-05-06 09:29:27 +03001010.. function:: make_bad_fd()
1011
1012 Create an invalid file descriptor by opening and closing a temporary file,
Zachary Waref012ba42014-07-23 12:00:29 -05001013 and returning its descriptor.
Eli Benderskye1689652011-05-06 09:29:27 +03001014
1015
Cheryl Sabella988fb282018-02-11 08:10:42 -05001016.. function:: check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None)
1017
1018 Test for syntax errors in *statement* by attempting to compile *statement*.
1019 *testcase* is the :mod:`unittest` instance for the test. *errtext* is the
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001020 regular expression which should match the string representation of the
1021 raised :exc:`SyntaxError`. If *lineno* is not ``None``, compares to
1022 the line of the exception. If *offset* is not ``None``, compares to
1023 the offset of the exception.
1024
1025
1026.. function:: check_syntax_warning(testcase, statement, errtext='', *, lineno=1, offset=None)
1027
1028 Test for syntax warning in *statement* by attempting to compile *statement*.
1029 Test also that the :exc:`SyntaxWarning` is emitted only once, and that it
1030 will be converted to a :exc:`SyntaxError` when turned into error.
1031 *testcase* is the :mod:`unittest` instance for the test. *errtext* is the
1032 regular expression which should match the string representation of the
1033 emitted :exc:`SyntaxWarning` and raised :exc:`SyntaxError`. If *lineno*
1034 is not ``None``, compares to the line of the warning and exception.
1035 If *offset* is not ``None``, compares to the offset of the exception.
1036
1037 .. versionadded:: 3.8
Cheryl Sabella988fb282018-02-11 08:10:42 -05001038
1039
1040.. function:: open_urlresource(url, *args, **kw)
1041
1042 Open *url*. If open fails, raises :exc:`TestFailed`.
1043
1044
1045.. function:: import_module(name, deprecated=False, *, required_on())
Nick Coghlanfce769e2009-04-11 14:30:59 +00001046
1047 This function imports and returns the named module. Unlike a normal
1048 import, this function raises :exc:`unittest.SkipTest` if the module
1049 cannot be imported.
1050
1051 Module and package deprecation messages are suppressed during this import
Cheryl Sabella988fb282018-02-11 08:10:42 -05001052 if *deprecated* is ``True``. If a module is required on a platform but
1053 optional for others, set *required_on* to an iterable of platform prefixes
1054 which will be compared against :data:`sys.platform`.
Nick Coghlanfce769e2009-04-11 14:30:59 +00001055
1056 .. versionadded:: 3.1
1057
1058
Nick Coghlan47384702009-04-22 16:13:36 +00001059.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlanfce769e2009-04-11 14:30:59 +00001060
Nick Coghlan47384702009-04-22 16:13:36 +00001061 This function imports and returns a fresh copy of the named Python module
1062 by removing the named module from ``sys.modules`` before doing the import.
1063 Note that unlike :func:`reload`, the original module is not affected by
1064 this operation.
1065
1066 *fresh* is an iterable of additional module names that are also removed
1067 from the ``sys.modules`` cache before doing the import.
1068
Eli Benderskyba5517d2013-08-11 15:38:08 -07001069 *blocked* is an iterable of module names that are replaced with ``None``
Nick Coghlan47384702009-04-22 16:13:36 +00001070 in the module cache during the import to ensure that attempts to import
1071 them raise :exc:`ImportError`.
1072
1073 The named module and any modules named in the *fresh* and *blocked*
1074 parameters are saved before starting the import and then reinserted into
1075 ``sys.modules`` when the fresh import is complete.
Nick Coghlanfce769e2009-04-11 14:30:59 +00001076
1077 Module and package deprecation messages are suppressed during this import
Eli Benderskye1689652011-05-06 09:29:27 +03001078 if *deprecated* is ``True``.
Nick Coghlanfce769e2009-04-11 14:30:59 +00001079
Eli Benderskyba5517d2013-08-11 15:38:08 -07001080 This function will raise :exc:`ImportError` if the named module cannot be
1081 imported.
Nick Coghlan47384702009-04-22 16:13:36 +00001082
1083 Example use::
1084
Eli Benderskyba5517d2013-08-11 15:38:08 -07001085 # Get copies of the warnings module for testing without affecting the
1086 # version being used by the rest of the test suite. One copy uses the
1087 # C implementation, the other is forced to use the pure Python fallback
1088 # implementation
Nick Coghlan47384702009-04-22 16:13:36 +00001089 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
1090 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
1091
Nick Coghlanfce769e2009-04-11 14:30:59 +00001092 .. versionadded:: 3.1
1093
1094
Cheryl Sabella988fb282018-02-11 08:10:42 -05001095.. function:: modules_setup()
1096
1097 Return a copy of :data:`sys.modules`.
1098
1099
1100.. function:: modules_cleanup(oldmodules)
1101
1102 Remove modules except for *oldmodules* and ``encodings`` in order to
1103 preserve internal cache.
1104
1105
1106.. function:: threading_setup()
1107
1108 Return current thread count and copy of dangling threads.
1109
1110
1111.. function:: threading_cleanup(*original_values)
1112
1113 Cleanup up threads not specified in *original_values*. Designed to emit
1114 a warning if a test leaves running threads in the background.
1115
1116
1117.. function:: join_thread(thread, timeout=30.0)
1118
1119 Join a *thread* within *timeout*. Raise an :exc:`AssertionError` if thread
1120 is still alive after *timeout* seconds.
1121
1122
1123.. function:: reap_children()
1124
1125 Use this at the end of ``test_main`` whenever sub-processes are started.
1126 This will help ensure that no extra children (zombies) stick around to
1127 hog resources and create problems when looking for refleaks.
1128
1129
1130.. function:: get_attribute(obj, name)
1131
1132 Get an attribute, raising :exc:`unittest.SkipTest` if :exc:`AttributeError`
1133 is raised.
1134
1135
Eli Benderskye1689652011-05-06 09:29:27 +03001136.. function:: bind_port(sock, host=HOST)
1137
1138 Bind the socket to a free port and return the port number. Relies on
1139 ephemeral ports in order to ensure we are using an unbound port. This is
1140 important as many tests may be running simultaneously, especially in a
1141 buildbot environment. This method raises an exception if the
1142 ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is
1143 :const:`~socket.SOCK_STREAM`, and the socket has
1144 :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it.
1145 Tests should never set these socket options for TCP/IP sockets.
1146 The only case for setting these options is testing multicasting via
1147 multiple UDP sockets.
1148
1149 Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is
1150 available (i.e. on Windows), it will be set on the socket. This will
1151 prevent anyone else from binding to our host/port for the duration of the
1152 test.
1153
1154
Cheryl Sabella988fb282018-02-11 08:10:42 -05001155.. function:: bind_unix_socket(sock, addr)
1156
1157 Bind a unix socket, raising :exc:`unittest.SkipTest` if
1158 :exc:`PermissionError` is raised.
1159
1160
Victor Stinner91b4f7a2019-07-09 13:00:23 +02001161.. function:: catch_threading_exception()
1162
1163 Context manager catching :class:`threading.Thread` exception using
1164 :func:`threading.excepthook`.
1165
1166 Attributes set when an exception is catched:
1167
1168 * ``exc_type``
1169 * ``exc_value``
1170 * ``exc_traceback``
1171 * ``thread``
1172
1173 See :func:`threading.excepthook` documentation.
1174
1175 These attributes are deleted at the context manager exit.
1176
1177 Usage::
1178
1179 with support.catch_threading_exception() as cm:
1180 # code spawning a thread which raises an exception
1181 ...
1182
1183 # check the thread exception, use cm attributes:
1184 # exc_type, exc_value, exc_traceback, thread
1185 ...
1186
1187 # exc_type, exc_value, exc_traceback, thread attributes of cm no longer
1188 # exists at this point
1189 # (to avoid reference cycles)
1190
1191 .. versionadded:: 3.8
1192
1193
Victor Stinner6dbbe742019-05-25 00:09:38 +02001194.. function:: catch_unraisable_exception()
1195
1196 Context manager catching unraisable exception using
1197 :func:`sys.unraisablehook`.
1198
Victor Stinner6d22cc82019-06-13 14:44:54 +02001199 Storing the exception value (``cm.unraisable.exc_value``) creates a
1200 reference cycle. The reference cycle is broken explicitly when the context
1201 manager exits.
1202
Victor Stinner212646c2019-06-14 18:03:22 +02001203 Storing the object (``cm.unraisable.object``) can resurrect it if it is set
1204 to an object which is being finalized. Exiting the context manager clears
1205 the stored object.
Victor Stinner6d22cc82019-06-13 14:44:54 +02001206
Victor Stinner6dbbe742019-05-25 00:09:38 +02001207 Usage::
1208
1209 with support.catch_unraisable_exception() as cm:
1210 # code creating an "unraisable exception"
1211 ...
1212
1213 # check the unraisable exception: use cm.unraisable
1214 ...
1215
1216 # cm.unraisable attribute no longer exists at this point
1217 # (to break a reference cycle)
1218
1219 .. versionadded:: 3.8
1220
1221
Eli Benderskye1689652011-05-06 09:29:27 +03001222.. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM)
1223
1224 Returns an unused port that should be suitable for binding. This is
1225 achieved by creating a temporary socket with the same family and type as
1226 the ``sock`` parameter (default is :const:`~socket.AF_INET`,
1227 :const:`~socket.SOCK_STREAM`),
1228 and binding it to the specified host address (defaults to ``0.0.0.0``)
1229 with the port set to 0, eliciting an unused ephemeral port from the OS.
1230 The temporary socket is then closed and deleted, and the ephemeral port is
1231 returned.
1232
1233 Either this method or :func:`bind_port` should be used for any tests
1234 where a server socket needs to be bound to a particular port for the
1235 duration of the test.
Andrés Delfino271818f2018-09-14 14:13:09 -03001236 Which one to use depends on whether the calling code is creating a Python
Eli Benderskye1689652011-05-06 09:29:27 +03001237 socket, or if an unused port needs to be provided in a constructor
1238 or passed to an external program (i.e. the ``-accept`` argument to
1239 openssl's s_server mode). Always prefer :func:`bind_port` over
1240 :func:`find_unused_port` where possible. Using a hard coded port is
Martin Panter8f265652016-04-19 04:03:41 +00001241 discouraged since it can make multiple instances of the test impossible to
Eli Benderskye1689652011-05-06 09:29:27 +03001242 run simultaneously, which is a problem for buildbots.
1243
1244
Zachary Waref012ba42014-07-23 12:00:29 -05001245.. function:: load_package_tests(pkg_dir, loader, standard_tests, pattern)
1246
1247 Generic implementation of the :mod:`unittest` ``load_tests`` protocol for
1248 use in test packages. *pkg_dir* is the root directory of the package;
1249 *loader*, *standard_tests*, and *pattern* are the arguments expected by
1250 ``load_tests``. In simple cases, the test package's ``__init__.py``
1251 can be the following::
1252
1253 import os
1254 from test.support import load_package_tests
1255
1256 def load_tests(*args):
1257 return load_package_tests(os.path.dirname(__file__), *args)
1258
Louie Lu7fae81e2017-04-22 14:46:18 +08001259
Cheryl Sabella988fb282018-02-11 08:10:42 -05001260.. function:: fs_is_case_insensitive(directory)
1261
1262 Return ``True`` if the file system for *directory* is case-insensitive.
1263
1264
Louie Lu7fae81e2017-04-22 14:46:18 +08001265.. function:: detect_api_mismatch(ref_api, other_api, *, ignore=())
Gregory P. Smith4e72cce2015-04-14 13:26:06 -07001266
Zachary Ware3d3aedc2015-07-07 00:07:25 -05001267 Returns the set of attributes, functions or methods of *ref_api* not
1268 found on *other_api*, except for a defined list of items to be
1269 ignored in this check specified in *ignore*.
Gregory P. Smith4e72cce2015-04-14 13:26:06 -07001270
1271 By default this skips private attributes beginning with '_' but
1272 includes all magic methods, i.e. those starting and ending in '__'.
1273
Gregory P. Smith7c63fd32015-04-14 15:25:01 -07001274 .. versionadded:: 3.5
1275
Zachary Waref012ba42014-07-23 12:00:29 -05001276
Cheryl Sabella988fb282018-02-11 08:10:42 -05001277.. function:: patch(test_instance, object_to_patch, attr_name, new_value)
1278
1279 Override *object_to_patch.attr_name* with *new_value*. Also add
1280 cleanup procedure to *test_instance* to restore *object_to_patch* for
1281 *attr_name*. The *attr_name* should be a valid attribute for
1282 *object_to_patch*.
1283
1284
1285.. function:: run_in_subinterp(code)
1286
1287 Run *code* in subinterpreter. Raise :exc:`unittest.SkipTest` if
1288 :mod:`tracemalloc` is enabled.
1289
1290
1291.. function:: check_free_after_iterating(test, iter, cls, args=())
1292
1293 Assert that *iter* is deallocated after iterating.
1294
1295
1296.. function:: missing_compiler_executable(cmd_names=[])
1297
1298 Check for the existence of the compiler executables whose names are listed
1299 in *cmd_names* or all the compiler executables when *cmd_names* is empty
1300 and return the first missing executable or ``None`` when none is found
1301 missing.
1302
1303
Martin Panterd226d302015-11-14 11:47:00 +00001304.. function:: check__all__(test_case, module, name_of_module=None, extra=(), blacklist=())
1305
1306 Assert that the ``__all__`` variable of *module* contains all public names.
1307
1308 The module's public names (its API) are detected automatically
1309 based on whether they match the public name convention and were defined in
1310 *module*.
1311
1312 The *name_of_module* argument can specify (as a string or tuple thereof) what
Serhiy Storchakabac2d5b2018-03-28 22:14:26 +03001313 module(s) an API could be defined in order to be detected as a public
Martin Panterd226d302015-11-14 11:47:00 +00001314 API. One case for this is when *module* imports part of its public API from
1315 other modules, possibly a C backend (like ``csv`` and its ``_csv``).
1316
1317 The *extra* argument can be a set of names that wouldn't otherwise be automatically
1318 detected as "public", like objects without a proper ``__module__``
1319 attribute. If provided, it will be added to the automatically detected ones.
1320
1321 The *blacklist* argument can be a set of names that must not be treated as part of
1322 the public API even though their names indicate otherwise.
1323
1324 Example use::
1325
1326 import bar
1327 import foo
1328 import unittest
1329 from test import support
1330
1331 class MiscTestCase(unittest.TestCase):
1332 def test__all__(self):
1333 support.check__all__(self, foo)
1334
1335 class OtherTestCase(unittest.TestCase):
1336 def test__all__(self):
1337 extra = {'BAR_CONST', 'FOO_CONST'}
1338 blacklist = {'baz'} # Undocumented name.
1339 # bar imports part of its API from _bar.
1340 support.check__all__(self, bar, ('bar', '_bar'),
1341 extra=extra, blacklist=blacklist)
1342
1343 .. versionadded:: 3.6
1344
1345
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001346The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +00001347
Georg Brandl7f01a132009-09-16 15:58:14 +00001348.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001349
1350 Instances are a context manager that raises :exc:`ResourceDenied` if the
1351 specified exception type is raised. Any keyword arguments are treated as
1352 attribute/value pairs to be compared against any exception raised within the
1353 :keyword:`with` statement. Only if all pairs match properly against
1354 attributes on the exception is :exc:`ResourceDenied` raised.
1355
Georg Brandl116aa622007-08-15 14:28:22 +00001356
1357.. class:: EnvironmentVarGuard()
1358
Florent Xicluna53b506be2010-03-18 20:00:57 +00001359 Class used to temporarily set or unset environment variables. Instances can
1360 be used as a context manager and have a complete dictionary interface for
1361 querying/modifying the underlying ``os.environ``. After exit from the
1362 context manager all changes to environment variables done through this
1363 instance will be rolled back.
Georg Brandl116aa622007-08-15 14:28:22 +00001364
Georg Brandl705d9d52009-05-05 09:29:50 +00001365 .. versionchanged:: 3.1
Walter Dörwald155374d2009-05-01 19:58:58 +00001366 Added dictionary interface.
Georg Brandl116aa622007-08-15 14:28:22 +00001367
1368.. method:: EnvironmentVarGuard.set(envvar, value)
1369
Florent Xicluna53b506be2010-03-18 20:00:57 +00001370 Temporarily set the environment variable ``envvar`` to the value of
1371 ``value``.
Georg Brandl116aa622007-08-15 14:28:22 +00001372
1373
1374.. method:: EnvironmentVarGuard.unset(envvar)
1375
1376 Temporarily unset the environment variable ``envvar``.
Nick Coghlanb1304932008-07-13 12:25:08 +00001377
Walter Dörwald155374d2009-05-01 19:58:58 +00001378
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001379.. class:: SuppressCrashReport()
1380
1381 A context manager used to try to prevent crash dialog popups on tests that
1382 are expected to crash a subprocess.
1383
1384 On Windows, it disables Windows Error Reporting dialogs using
Georg Brandl5d941342016-02-26 19:37:12 +01001385 `SetErrorMode <https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx>`_.
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001386
1387 On UNIX, :func:`resource.setrlimit` is used to set
1388 :attr:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file
1389 creation.
1390
1391 On both platforms, the old value is restored by :meth:`__exit__`.
1392
1393
Cheryl Sabella988fb282018-02-11 08:10:42 -05001394.. class:: CleanImport(*module_names)
1395
1396 A context manager to force import to return a new module reference. This
1397 is useful for testing module-level behaviors, such as the emission of a
1398 DeprecationWarning on import. Example usage::
1399
1400 with CleanImport('foo'):
1401 importlib.import_module('foo') # New reference.
1402
1403
1404.. class:: DirsOnSysPath(*paths)
1405
1406 A context manager to temporarily add directories to sys.path.
1407
1408 This makes a copy of :data:`sys.path`, appends any directories given
1409 as positional arguments, then reverts :data:`sys.path` to the copied
1410 settings when the context ends.
1411
1412 Note that *all* :data:`sys.path` modifications in the body of the
1413 context manager, including replacement of the object,
1414 will be reverted at the end of the block.
1415
1416
1417.. class:: SaveSignals()
1418
1419 Class to save and restore signal handlers registered by the Python signal
1420 handler.
1421
1422
1423.. class:: Matcher()
1424
1425 .. method:: matches(self, d, **kwargs)
1426
1427 Try to match a single dict with the supplied arguments.
1428
1429
1430 .. method:: match_value(self, k, dv, v)
1431
1432 Try to match a single stored value (*dv*) with a supplied value (*v*).
1433
1434
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001435.. class:: WarningsRecorder()
1436
1437 Class used to record warnings for unit tests. See documentation of
1438 :func:`check_warnings` above for more details.
Cheryl Sabella988fb282018-02-11 08:10:42 -05001439
1440
1441.. class:: BasicTestRunner()
1442
1443 .. method:: run(test)
1444
1445 Run *test* and return the result.
1446
1447
1448.. class:: TestHandler(logging.handlers.BufferingHandler)
1449
1450 Class for logging support.
1451
1452
Serhiy Storchakab21d1552018-03-02 11:53:51 +02001453.. class:: FakePath(path)
1454
1455 Simple :term:`path-like object`. It implements the :meth:`__fspath__`
1456 method which just returns the *path* argument. If *path* is an exception,
1457 it will be raised in :meth:`!__fspath__`.
1458
1459
Cheryl Sabella988fb282018-02-11 08:10:42 -05001460:mod:`test.support.script_helper` --- Utilities for the Python execution tests
1461==============================================================================
1462
1463.. module:: test.support.script_helper
1464 :synopsis: Support for Python's script execution tests.
1465
1466
1467The :mod:`test.support.script_helper` module provides support for Python's
1468script execution tests.
1469
1470.. function:: interpreter_requires_environment()
1471
1472 Return ``True`` if ``sys.executable interpreter`` requires environment
1473 variables in order to be able to run at all.
1474
1475 This is designed to be used with ``@unittest.skipIf()`` to annotate tests
1476 that need to use an ``assert_python*()`` function to launch an isolated
1477 mode (``-I``) or no environment mode (``-E``) sub-interpreter process.
1478
1479 A normal build & test does not run into this situation but it can happen
1480 when trying to run the standard library test suite from an interpreter that
1481 doesn't have an obvious home with Python's current home finding logic.
1482
1483 Setting :envvar:`PYTHONHOME` is one way to get most of the testsuite to run
1484 in that situation. :envvar:`PYTHONPATH` or :envvar:`PYTHONUSERSITE` are
1485 other common environment variables that might impact whether or not the
1486 interpreter can start.
1487
1488
1489.. function:: run_python_until_end(*args, **env_vars)
1490
1491 Set up the environment based on *env_vars* for running the interpreter
Nick Coghland5d9e022018-03-25 23:03:10 +10001492 in a subprocess. The values can include ``__isolated``, ``__cleanenv``,
1493 ``__cwd``, and ``TERM``.
Cheryl Sabella988fb282018-02-11 08:10:42 -05001494
Victor Stinner6cac1132019-12-08 08:38:16 +01001495 .. versionchanged:: 3.9
1496 The function no longer strips whitespaces from *stderr*.
1497
Cheryl Sabella988fb282018-02-11 08:10:42 -05001498
1499.. function:: assert_python_ok(*args, **env_vars)
1500
1501 Assert that running the interpreter with *args* and optional environment
1502 variables *env_vars* succeeds (``rc == 0``) and return a ``(return code,
1503 stdout, stderr)`` tuple.
1504
1505 If the ``__cleanenv`` keyword is set, *env_vars* is used as a fresh
1506 environment.
1507
1508 Python is started in isolated mode (command line option ``-I``),
1509 except if the ``__isolated`` keyword is set to ``False``.
1510
Victor Stinner6cac1132019-12-08 08:38:16 +01001511 .. versionchanged:: 3.9
1512 The function no longer strips whitespaces from *stderr*.
1513
Cheryl Sabella988fb282018-02-11 08:10:42 -05001514
1515.. function:: assert_python_failure(*args, **env_vars)
1516
1517 Assert that running the interpreter with *args* and optional environment
1518 variables *env_vars* fails (``rc != 0``) and return a ``(return code,
1519 stdout, stderr)`` tuple.
1520
1521 See :func:`assert_python_ok` for more options.
1522
Victor Stinner6cac1132019-12-08 08:38:16 +01001523 .. versionchanged:: 3.9
1524 The function no longer strips whitespaces from *stderr*.
1525
Cheryl Sabella988fb282018-02-11 08:10:42 -05001526
1527.. function:: spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw)
1528
1529 Run a Python subprocess with the given arguments.
1530
1531 *kw* is extra keyword args to pass to :func:`subprocess.Popen`. Returns a
1532 :class:`subprocess.Popen` object.
1533
1534
1535.. function:: kill_python(p)
1536
1537 Run the given :class:`subprocess.Popen` process until completion and return
1538 stdout.
1539
1540
1541.. function:: make_script(script_dir, script_basename, source, omit_suffix=False)
1542
1543 Create script containing *source* in path *script_dir* and *script_basename*.
1544 If *omit_suffix* is ``False``, append ``.py`` to the name. Return the full
1545 script path.
1546
1547
1548.. function:: make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None)
1549
1550 Create zip file at *zip_dir* and *zip_basename* with extension ``zip`` which
1551 contains the files in *script_name*. *name_in_zip* is the archive name.
1552 Return a tuple containing ``(full path, full path of archive name)``.
1553
1554
1555.. function:: make_pkg(pkg_dir, init_source='')
1556
1557 Create a directory named *pkg_dir* containing an ``__init__`` file with
1558 *init_source* as its contents.
1559
1560
1561.. function:: make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, \
1562 source, depth=1, compiled=False)
1563
1564 Create a zip package directory with a path of *zip_dir* and *zip_basename*
1565 containing an empty ``__init__`` file and a file *script_basename*
1566 containing the *source*. If *compiled* is ``True``, both source files will
1567 be compiled and added to the zip package. Return a tuple of the full zip
1568 path and the archive name for the zip file.
Joannah Nanjekye92777d52019-09-12 10:02:59 +01001569
1570
1571:mod:`test.support.bytecode_helper` --- Support tools for testing correct bytecode generation
1572=============================================================================================
1573
1574.. module:: test.support.bytecode_helper
1575 :synopsis: Support tools for testing correct bytecode generation.
1576
1577The :mod:`test.support.bytecode_helper` module provides support for testing
1578and inspecting bytecode generation.
1579
Gurupad Hegde6c7bb382019-12-28 17:16:02 -05001580The module defines the following class:
Joannah Nanjekye92777d52019-09-12 10:02:59 +01001581
1582.. class:: BytecodeTestCase(unittest.TestCase)
1583
1584 This class has custom assertion methods for inspecting bytecode.
1585
1586.. method:: BytecodeTestCase.get_disassembly_as_string(co)
1587
1588 Return the disassembly of *co* as string.
1589
1590
1591.. method:: BytecodeTestCase.assertInBytecode(x, opname, argval=_UNSPECIFIED)
1592
1593 Return instr if *opname* is found, otherwise throws :exc:`AssertionError`.
1594
1595
1596.. method:: BytecodeTestCase.assertNotInBytecode(x, opname, argval=_UNSPECIFIED)
1597
1598 Throws :exc:`AssertionError` if *opname* is found.