Read until one from a list of a regular expressions matches.
The first argument is a list of regular expressions, either compiled (regex objects) or uncompiled (byte strings). The optional second argument is a timeout, in seconds; the default is to block indefinitely.
Return a tuple of three items: the index in the list of the first regular expression that matches; the match object returned; and the bytes read up till and including the match.
If end of file is found and no bytes were read, raise EOFError. Otherwise, when nothing matches, return (-1, None, data) where data is the bytes received so far (may be empty bytes if a timeout happened).
If a regular expression ends with a greedy match (such as .*) or if more than one expression can match the same input, the results are non-deterministic, and may depend on the I/O timing.


Return the file descriptor of the socket object used internally.


Return the socket object used internally.


Interaction function, emulates a very dumb Telnet client.


Print a debug message when the debug level is > 0. If extra arguments are present, they are substituted in the message using the standard string formatting operator.


Connect to a host. The optional second argument is the port number, which defaults to the standard Telnet port (23). The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used).
Do not try to reopen an already connected instance.
Raises an auditing event telnetlib.Telnet.open with arguments self, host, port.


Read all data until EOF as bytes; block until connection closed.


Read readily available data.
Raise EOFError if connection closed and no cooked data available. Return b'' if no cooked data available otherwise. Do not block unless in the midst of an IAC sequence.


Process and return data already in the queues (lazy).
Raise EOFError if connection closed and no data available. Return b'' if no cooked data available otherwise. Do not block unless in the midst of an IAC sequence.


Return the data collected between a SB/SE pair (suboption begin/end). The callback should access these data when it was invoked with a SE command. This method never blocks.


Read at least one byte of cooked data unless EOF is hit. Return b'' if EOF is hit. Block if no data is immediately available.


Read until a given byte string, expected, is encountered or until timeout seconds have passed.
When no match is found, return whatever is available instead, possibly empty bytes. Raise EOFError if the connection is closed and no cooked data is available.


Read everything that can be without blocking in I/O (eager).
Raise EOFError if connection closed and no cooked data available. Return b'' if no cooked data available otherwise. Do not block unless in the midst of an IAC sequence.


Return any data available in the cooked queue (very lazy).
Raise EOFError if connection closed and no data available. Return b'' if no cooked data available otherwise. This method never blocks.


Set the debug level. The higher the value of debuglevel, the more debug output you get (on sys.stdout).


Each time a telnet option is read on the input flow, this callback (if set) is called with the following parameters: callback(telnet socket, command (DO/DONT/WILL/WONT), option). No other action is done afterwards by telnetlib.


Write a byte string to the socket, doubling any IAC characters. This can block if the connection is blocked. May raise OSError if the connection is closed.
Raises an auditing event telnetlib.Telnet.write with arguments self, buffer.
Changed in version 3.3: This method used to raise socket.error, which is now an alias of OSError.


Source code: Lib/tempfile.py
This module creates temporary files and directories. It works on all supported platforms. TemporaryFile, NamedTemporaryFile, TemporaryDirectory, and SpooledTemporaryFile are high-level interfaces which provide automatic cleanup and can be used as context managers. mkstemp() and mkdtemp() are lower-level functions which require manual cleanup.
All the user-callable functions and constructors take additional arguments which allow direct control over the location and name of temporary files and directories. Files names used by this module include a string of random characters which allows those files to be securely created in shared temporary directories. To maintain backward compatibility, the argument order is somewhat odd; it is recommended to use keyword arguments for clarity.
The module defines the following user-callable items:
Return a file-like object that can be used as a temporary storage area. The file is created securely, using the same rules as mkstemp(). It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected). Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.
The resulting object can be used as a context manager (see Examples). On completion of the context or destruction of the file object the temporary file will be removed from the filesystem.
The mode parameter defaults to 'w+b' so that the file created can be read and written without being closed. Binary mode is used so that it behaves consistently on all platforms without regard for the data that is stored. buffering, encoding, errors and newline are interpreted as for open().
The dir, prefix and suffix parameters have the same meaning and defaults as with mkstemp().
The returned object is a true file object on POSIX platforms. On other platforms, it is a file-like object whose file attribute is the underlying true file object.
The os.O_TMPFILE flag is used if it is available and works (Linux-specific, requires Linux kernel 3.11 or later).
Raises an auditing event tempfile.mkstemp with argument fullpath.
Changed in version 3.5: The os.O_TMPFILE flag is now used if available.
Changed in version 3.8: Added errors parameter.
This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the returned file-like object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later). If delete is true (the default), the file is deleted as soon as it is closed. The returned object is always a file-like object whose file attribute is the underlying true file object. This file-like object can be used in a with statement, just like a normal file.
Raises an auditing event tempfile.mkstemp with argument fullpath.
Changed in version 3.8: Added errors parameter.
This function operates exactly as TemporaryFile() does, except that data is spooled in memory until the file size exceeds max_size, or until the file’s fileno() method is called, at which point the contents are written to disk and operation proceeds as with TemporaryFile().
The resulting file has one additional method, rollover(), which causes the file to roll over to an on-disk file regardless of its size.
The returned object is a file-like object whose _file attribute is either an io.BytesIO or io.TextIOWrapper object (depending on whether binary or text mode was specified) or a true file object, depending on whether rollover() has been called. This file-like object can be used in a with statement, just like a normal file.
Changed in version 3.3: the truncate method now accepts a size argument.
Changed in version 3.8: Added errors parameter.
This function securely creates a temporary directory using the same rules as mkdtemp(). The resulting object can be used as a context manager (see Examples). On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.
The directory name can be retrieved from the name attribute of the returned object. When the returned object is used as a context manager, the name will be assigned to the target of the as clause in the with statement, if there is one.
The directory can be explicitly cleaned up by calling the cleanup() method.
Raises an auditing event tempfile.mkdtemp with argument fullpath.
New in version 3.2.
Creates a temporary file in the most secure manner possible. There are no race conditions in the file’s creation, assuming that the platform properly implements the os.O_EXCL flag for os.open(). The file is readable and writable only by the creating user ID. If the platform uses permission bits to indicate whether a file is executable, the file is executable by no one. The file descriptor is not inherited by child processes.
Unlike TemporaryFile(), the user of mkstemp() is responsible for deleting the temporary file when done with it.
If suffix is not None, the file name will end with that suffix, otherwise there will be no suffix. mkstemp() does not put a dot between the file name and the suffix; if you need one, put it at the beginning of suffix.
If prefix is not None, the file name will begin with that prefix; otherwise, a default prefix is used. The default is the return value of gettempprefix() or gettempprefixb(), as appropriate.
If dir is not None, the file will be created in that directory; otherwise, a default directory is used. The default directory is chosen from a platform-dependent list, but the user of the application can control the directory location by setting the TMPDIR, TEMP or TMP environment variables. There is thus no guarantee that the generated filename will have any nice properties, such as not requiring quoting when passed to external commands via os.popen().
If any of suffix, prefix, and dir are not None, they must be the same type. If they are bytes, the returned name will be bytes instead of str. If you want to force a bytes return value with otherwise default behavior, pass suffix=b''.
If text is specified and true, the file is opened in text mode. Otherwise, (the default) the file is opened in binary mode.
mkstemp() returns a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.
Raises an auditing event tempfile.mkstemp with argument fullpath.
Changed in version 3.5: suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value. Prior to this, only str was allowed. suffix and prefix now accept and default to None to cause an appropriate default value to be used.
Changed in version 3.6: The dir parameter now accepts a path-like object.
Creates a temporary directory in the most secure manner possible. There are no race conditions in the directory’s creation. The directory is readable, writable, and searchable only by the creating user ID.
The user of mkdtemp() is responsible for deleting the temporary directory and its contents when done with it.
The prefix, suffix, and dir arguments are the same as for mkstemp().
mkdtemp() returns the absolute pathname of the new directory.
Raises an auditing event tempfile.mkdtemp with argument fullpath.
Changed in version 3.5: suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value. Prior to this, only str was allowed. suffix and prefix now accept and default to None to cause an appropriate default value to be used.
Changed in version 3.6: The dir parameter now accepts a path-like object.
Return the name of the directory used for temporary files. This defines the default value for the dir argument to all functions in this module.
Python searches a standard list of directories to find one which the calling user can create files in. The list is:
A platform-specific location:
The result of this search is cached, see the description of tempdir below.
Same as gettempdir() but the return value is in bytes.
New in version 3.5.
Return the filename prefix used to create temporary files. This does not contain the directory component.
Same as gettempprefix() but the return value is in bytes.
New in version 3.5.
The module uses a global variable to store the name of the directory used for temporary files returned by gettempdir(). It can be set directly to override the selection process, but this is discouraged. All functions in this module take a dir argument which can be used to specify the directory and this is the recommended approach.
When set to a value other than None, this variable defines the default value for the dir argument to the functions defined in this module.
If tempdir is None (the default) at any call to any of the above functions except gettempprefix() it is initialized following the algorithm described in gettempdir().
Here are some examples of typical usage of the tempfile module:
A historical way to create temporary files was to first generate a file name with the mktemp() function and then create a file using this name. Unfortunately this is not secure, because a different process may create a file with this name in the time between the call to mktemp() and the subsequent attempt to create the file by the first process. The solution is to combine the two steps and create the file immediately. This approach is used by mkstemp() and the other functions described above.
Deprecated since version 2.3: Use mkstemp() instead.
Return an absolute pathname of a file that did not exist at the time the call is made. The prefix, suffix, and dir arguments are similar to those of mkstemp(), except that bytes file names, suffix=None and prefix=None are not supported.
Warning
Use of this function may introduce a security hole in your program. By the time you get around to doing anything with the file name it returns, someone else may have beaten you to the punch. mktemp() usage can be replaced easily with NamedTemporaryFile(), passing it the delete=False parameter:


Return the name of the directory used for temporary files. This defines the default value for the dir argument to all functions in this module.
Python searches a standard list of directories to find one which the calling user can create files in. The list is:
A platform-specific location:
The result of this search is cached, see the description of tempdir below.


Same as gettempdir() but the return value is in bytes.
New in version 3.5.


Return the filename prefix used to create temporary files. This does not contain the directory component.


Same as gettempprefix() but the return value is in bytes.
New in version 3.5.


Creates a temporary directory in the most secure manner possible. There are no race conditions in the directory’s creation. The directory is readable, writable, and searchable only by the creating user ID.
The user of mkdtemp() is responsible for deleting the temporary directory and its contents when done with it.
The prefix, suffix, and dir arguments are the same as for mkstemp().
mkdtemp() returns the absolute pathname of the new directory.
Raises an auditing event tempfile.mkdtemp with argument fullpath.
Changed in version 3.5: suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value. Prior to this, only str was allowed. suffix and prefix now accept and default to None to cause an appropriate default value to be used.
Changed in version 3.6: The dir parameter now accepts a path-like object.


Creates a temporary file in the most secure manner possible. There are no race conditions in the file’s creation, assuming that the platform properly implements the os.O_EXCL flag for os.open(). The file is readable and writable only by the creating user ID. If the platform uses permission bits to indicate whether a file is executable, the file is executable by no one. The file descriptor is not inherited by child processes.
Unlike TemporaryFile(), the user of mkstemp() is responsible for deleting the temporary file when done with it.
If suffix is not None, the file name will end with that suffix, otherwise there will be no suffix. mkstemp() does not put a dot between the file name and the suffix; if you need one, put it at the beginning of suffix.
If prefix is not None, the file name will begin with that prefix; otherwise, a default prefix is used. The default is the return value of gettempprefix() or gettempprefixb(), as appropriate.
If dir is not None, the file will be created in that directory; otherwise, a default directory is used. The default directory is chosen from a platform-dependent list, but the user of the application can control the directory location by setting the TMPDIR, TEMP or TMP environment variables. There is thus no guarantee that the generated filename will have any nice properties, such as not requiring quoting when passed to external commands via os.popen().
If any of suffix, prefix, and dir are not None, they must be the same type. If they are bytes, the returned name will be bytes instead of str. If you want to force a bytes return value with otherwise default behavior, pass suffix=b''.
If text is specified and true, the file is opened in text mode. Otherwise, (the default) the file is opened in binary mode.
mkstemp() returns a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.
Raises an auditing event tempfile.mkstemp with argument fullpath.
Changed in version 3.5: suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value. Prior to this, only str was allowed. suffix and prefix now accept and default to None to cause an appropriate default value to be used.
Changed in version 3.6: The dir parameter now accepts a path-like object.


Deprecated since version 2.3: Use mkstemp() instead.
Return an absolute pathname of a file that did not exist at the time the call is made. The prefix, suffix, and dir arguments are similar to those of mkstemp(), except that bytes file names, suffix=None and prefix=None are not supported.
Warning
Use of this function may introduce a security hole in your program. By the time you get around to doing anything with the file name it returns, someone else may have beaten you to the punch. mktemp() usage can be replaced easily with NamedTemporaryFile(), passing it the delete=False parameter:


This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the returned file-like object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later). If delete is true (the default), the file is deleted as soon as it is closed. The returned object is always a file-like object whose file attribute is the underlying true file object. This file-like object can be used in a with statement, just like a normal file.
Raises an auditing event tempfile.mkstemp with argument fullpath.
Changed in version 3.8: Added errors parameter.


This function operates exactly as TemporaryFile() does, except that data is spooled in memory until the file size exceeds max_size, or until the file’s fileno() method is called, at which point the contents are written to disk and operation proceeds as with TemporaryFile().
The resulting file has one additional method, rollover(), which causes the file to roll over to an on-disk file regardless of its size.
The returned object is a file-like object whose _file attribute is either an io.BytesIO or io.TextIOWrapper object (depending on whether binary or text mode was specified) or a true file object, depending on whether rollover() has been called. This file-like object can be used in a with statement, just like a normal file.
Changed in version 3.3: the truncate method now accepts a size argument.
Changed in version 3.8: Added errors parameter.


When set to a value other than None, this variable defines the default value for the dir argument to the functions defined in this module.
If tempdir is None (the default) at any call to any of the above functions except gettempprefix() it is initialized following the algorithm described in gettempdir().


This function securely creates a temporary directory using the same rules as mkdtemp(). The resulting object can be used as a context manager (see Examples). On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.
The directory name can be retrieved from the name attribute of the returned object. When the returned object is used as a context manager, the name will be assigned to the target of the as clause in the with statement, if there is one.
The directory can be explicitly cleaned up by calling the cleanup() method.
Raises an auditing event tempfile.mkdtemp with argument fullpath.
New in version 3.2.


Return a file-like object that can be used as a temporary storage area. The file is created securely, using the same rules as mkstemp(). It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected). Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.
The resulting object can be used as a context manager (see Examples). On completion of the context or destruction of the file object the temporary file will be removed from the filesystem.
The mode parameter defaults to 'w+b' so that the file created can be read and written without being closed. Binary mode is used so that it behaves consistently on all platforms without regard for the data that is stored. buffering, encoding, errors and newline are interpreted as for open().
The dir, prefix and suffix parameters have the same meaning and defaults as with mkstemp().
The returned object is a true file object on POSIX platforms. On other platforms, it is a file-like object whose file attribute is the underlying true file object.
The os.O_TMPFILE flag is used if it is available and works (Linux-specific, requires Linux kernel 3.11 or later).
Raises an auditing event tempfile.mkstemp with argument fullpath.
Changed in version 3.5: The os.O_TMPFILE flag is now used if available.
Changed in version 3.8: Added errors parameter.


This module provides an interface to the POSIX calls for tty I/O control. For a complete description of these calls, see termios(3) Unix manual page. It is only available for those Unix versions that support POSIX termios style tty I/O control configured during installation.
All functions in this module take a file descriptor fd as their first argument. This can be an integer file descriptor, such as returned by sys.stdin.fileno(), or a file object, such as sys.stdin itself.
This module also defines all the constants needed to work with the functions provided here; these have the same name as their counterparts in C. Please refer to your system documentation for more information on using these terminal control interfaces.
The module defines the following functions:
Return a list containing the tty attributes for file descriptor fd, as follows: [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] where cc is a list of the tty special characters (each a string of length 1, except the items with indices VMIN and VTIME, which are integers when these fields are defined). The interpretation of the flags and the speeds as well as the indexing in the cc array must be done using the symbolic constants defined in the termios module.
Set the tty attributes for file descriptor fd from the attributes, which is a list like the one returned by tcgetattr(). The when argument determines when the attributes are changed: TCSANOW to change immediately, TCSADRAIN to change after transmitting all queued output, or TCSAFLUSH to change after transmitting all queued output and discarding all queued input.
Send a break on file descriptor fd. A zero duration sends a break for 0.25–0.5 seconds; a nonzero duration has a system dependent meaning.
Wait until all output written to file descriptor fd has been transmitted.
Discard queued data on file descriptor fd. The queue selector specifies which queue: TCIFLUSH for the input queue, TCOFLUSH for the output queue, or TCIOFLUSH for both queues.
Suspend or resume input or output on file descriptor fd. The action argument can be TCOOFF to suspend output, TCOON to restart output, TCIOFF to suspend input, or TCION to restart input.
See also
Convenience functions for common terminal control operations.
Here’s a function that prompts for a password with echoing turned off. Note the technique using a separate tcgetattr() call and a try … finally statement to ensure that the old tty attributes are restored exactly no matter what happens:


Wait until all output written to file descriptor fd has been transmitted.


Suspend or resume input or output on file descriptor fd. The action argument can be TCOOFF to suspend output, TCOON to restart output, TCIOFF to suspend input, or TCION to restart input.


Discard queued data on file descriptor fd. The queue selector specifies which queue: TCIFLUSH for the input queue, TCOFLUSH for the output queue, or TCIOFLUSH for both queues.


Return a list containing the tty attributes for file descriptor fd, as follows: [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] where cc is a list of the tty special characters (each a string of length 1, except the items with indices VMIN and VTIME, which are integers when these fields are defined). The interpretation of the flags and the speeds as well as the indexing in the cc array must be done using the symbolic constants defined in the termios module.


Send a break on file descriptor fd. A zero duration sends a break for 0.25–0.5 seconds; a nonzero duration has a system dependent meaning.


Set the tty attributes for file descriptor fd from the attributes, which is a list like the one returned by tcgetattr(). The when argument determines when the attributes are changed: TCSANOW to change immediately, TCSADRAIN to change after transmitting all queued output, or TCSAFLUSH to change after transmitting all queued output and discarding all queued input.


Note
The test package is meant for internal use by Python only. It is documented for the benefit of the core developers of Python. Any use of this package outside of Python’s standard library is discouraged as code mentioned here can change or be removed without notice between releases of Python.
The test package contains all regression tests for Python as well as the modules test.support and test.regrtest. test.support is used to enhance your tests while test.regrtest drives the testing suite.
Each module in the test package whose name starts with test_ is a testing suite for a specific module or feature. All new tests should be written using the unittest or doctest module. Some older tests are written using a “traditional” testing style that compares output printed to sys.stdout; this style of test is considered deprecated.
See also
Writing PyUnit regression tests.
Tests embedded in documentation strings.
It is preferred that tests that use the unittest module follow a few guidelines. One is to name the test module by starting it with test_ and end it with the name of the module being tested. The test methods in the test module should start with test_ and end with a description of what the method is testing. This is needed so that the methods are recognized by the test driver as test methods. Also, no documentation string for the method should be included. A comment (such as # Tests function returns only True or False) should be used to provide documentation for test methods. This is done because documentation strings get printed out if they exist and thus what test is being run is not stated.
A basic boilerplate is often used:
This code pattern allows the testing suite to be run by test.regrtest, on its own as a script that supports the unittest CLI, or via the python -m unittest CLI.
The goal for regression testing is to try to break code. This leads to a few guidelines to be followed:
Try to maximize code reuse. On occasion, tests will vary by something as small as what type of input is used. Minimize code duplication by subclassing a basic test class with a class that specifies the input:
When using this pattern, remember that all classes that inherit from unittest.TestCase are run as tests. The Mixin class in the example above does not have any data and so can’t be run by itself, thus it does not inherit from unittest.TestCase.
See also
A book by Kent Beck on writing tests before code.
The test package can be run as a script to drive Python’s regression test suite, thanks to the -m option: python -m test. Under the hood, it uses test.regrtest; the call python -m test.regrtest used in previous Python versions still works. Running the script by itself automatically starts running all regression tests in the test package. It does this by finding all modules in the package whose name starts with test_, importing them, and executing the function test_main() if present or loading the tests via unittest.TestLoader.loadTestsFromModule if test_main does not exist. The names of tests to execute may also be passed to the script. Specifying a single regression test (python -m test test_spam) will minimize output and only print whether the test passed or failed.
Running test directly allows what resources are available for tests to use to be set. You do this by using the -u command-line option. Specifying all as the value for the -u option enables all possible resources: python -m test -uall. If all but one resource is desired (a more common case), a comma-separated list of resources that are not desired may be listed after all. The command python -m test -uall,-audio,-largefile will run test with all resources except the audio and largefile resources. For a list of all resources and more command-line options, run python -m test -h.
Some other ways to execute the regression tests depend on what platform the tests are being executed on. On Unix, you can run make test at the top-level directory where Python was built. On Windows, executing rt.bat from your PCbuild directory will run all regression tests.
The test.support module provides support for Python’s regression test suite.
Note
test.support is not a public module. It is documented here to help Python developers write tests. The API of this module is subject to change without backwards compatibility concerns between releases.
This module defines the following exceptions:
Exception to be raised when a test fails. This is deprecated in favor of unittest-based tests and unittest.TestCase’s assertion methods.
Subclass of unittest.SkipTest. Raised when a resource (such as a network connection) is not available. Raised by the requires() function.
The test.support module defines the following constants:
True when verbose output is enabled. Should be checked when more detailed information is desired about a running test. verbose is set by test.regrtest.
True if the running interpreter is Jython.
True if the system is Android.
Path for shell if not on Windows; otherwise None.
A non-ASCII character encodable by os.fsencode().
Set to a name that is safe to use as the name of a temporary file. Any temporary file that is created should be closed and unlinked (removed).
Set to a non-ASCII name for a temporary file.
Set to sys.getfilesystemencoding().
Set to a filename (str type) that should not be able to be encoded by file system encoding in strict mode. It may be None if it’s not possible to generate such a filename.
Set to a filename (bytes type) that should not be able to be decoded by file system encoding in strict mode. It may be None if it’s not possible to generate such a filename.
Set to a filename containing the FS_NONASCII character.
Timeout in seconds for tests using a network server listening on the network local loopback interface like 127.0.0.1.
The timeout is long enough to prevent test failure: it takes into account that the client and the server can run in different threads or even different processes.
The timeout should be long enough for connect(), recv() and send() methods of socket.socket.
Its default value is 5 seconds.
See also INTERNET_TIMEOUT.
Timeout in seconds for network requests going to the Internet.
The timeout is short enough to prevent a test to wait for too long if the Internet request is blocked for whatever reason.
Usually, a timeout using INTERNET_TIMEOUT should not mark a test as failed, but skip the test instead: see transient_internet().
Its default value is 1 minute.
See also LOOPBACK_TIMEOUT.
Timeout in seconds to mark a test as failed if the test takes “too long”.
The timeout value depends on the regrtest --timeout command line option.
If a test using SHORT_TIMEOUT starts to fail randomly on slow buildbots, use LONG_TIMEOUT instead.
Its default value is 30 seconds.
Timeout in seconds to detect when a test hangs.
It is long enough to reduce the risk of test failure on the slowest Python buildbots. It should not be used to mark a test as failed if the test takes “too long”. The timeout value depends on the regrtest --timeout command line option.
Its default value is 5 minutes.
See also LOOPBACK_TIMEOUT, INTERNET_TIMEOUT and SHORT_TIMEOUT.
Set to os.getcwd().
Set when tests can be skipped when they are not useful for PGO.
A constant that is likely larger than the underlying OS pipe buffer size, to make writes blocking.
A constant that is likely larger than the underlying OS socket buffer size, to make writes blocking.
Set to the top level directory that contains test.support.
Set to the top level directory for the test package.
Set to the data directory within the test package.
Set to sys.maxsize for big memory tests.
Set by set_memlimit() as the memory limit for big memory tests. Limited by MAX_Py_ssize_t.
Set by set_memlimit() as the memory limit for big memory tests. Not limited by MAX_Py_ssize_t.
Return True if running on CPython, not on Windows, and configuration not set with WITH_DOC_STRINGS.
Check for presence of docstrings.
Define the URL of a dedicated HTTP server for the network tests.
Object that is equal to anything. Used to test mixed type comparison.
Object that is not equal to anything (even to ALWAYS_EQ). Used to test mixed type comparison.
Object that is greater than anything (except itself). Used to test mixed type comparison.
Object that is less than anything (except itself). Used to test mixed type comparison.
The test.support module defines the following functions:
Remove the module named module_name from sys.modules and delete any byte-compiled files of the module.
Delete name from sys.modules.
Call os.unlink() on filename. On Windows platforms, this is wrapped with a wait loop that checks for the existence fo the file.
Call os.rmdir() on filename. On Windows platforms, this is wrapped with a wait loop that checks for the existence of the file.
Call shutil.rmtree() on path or call os.lstat() and os.rmdir() to remove a path and its contents. On Windows platforms, this is wrapped with a wait loop that checks for the existence of the files.
Move a PEP 3147/PEP 488 pyc file to its legacy pyc location and return the file system path to the legacy pyc file. The source value is the file system path to the source file. It does not need to exist, however the PEP 3147/488 pyc file must exist.
Return True if resource is enabled and available. The list of available resources is only set when test.regrtest is executing the tests.
Return True if Python was not built with -O0 or -Og.
Return _testcapi.WITH_PYMALLOC.
Raise ResourceDenied if resource is not available. msg is the argument to ResourceDenied if it is raised. Always returns True if called by a function whose __name__ is '__main__'. Used when tests are executed by test.regrtest.
Raise unittest.SkipTest on TLS certification validation failures.
Return a repr of dict with keys sorted.
Return the path to the file named filename. If no match is found filename is returned. This does not equal a failure since it could be the path to the file.
Setting subdir indicates a relative path to use to find the file rather than looking directly in the path directories.
Create an empty file with filename. If it already exists, truncate it.
Count the number of open file descriptors.
Match test to patterns set in set_match_tests().
Define match test with regular expression patterns.
Execute unittest.TestCase subclasses passed to the function. The function scans the classes for methods starting with the prefix test_ and executes the tests individually.
It is also legal to pass strings as parameters; these should be keys in sys.modules. Each associated module will be scanned by unittest.TestLoader.loadTestsFromModule(). This is usually seen in the following test_main() function:
This will run all tests defined in the named module.
Run doctest.testmod() on the given module. Return (failure_count, test_count).
If verbosity is None, doctest.testmod() is run with verbosity set to verbose. Otherwise, it is run with verbosity set to None. optionflags is passed as optionflags to doctest.testmod().
Set the sys.setswitchinterval() to the given interval. Defines a minimum interval for Android systems to prevent the system from hanging.
Use this check to guard CPython’s implementation-specific tests or to run them only on the implementations guarded by the arguments:
A convenience wrapper for warnings.catch_warnings() that makes it easier to test that a warning was correctly raised. It is approximately equivalent to calling warnings.catch_warnings(record=True) with warnings.simplefilter() set to always and with the option to automatically validate the results that are recorded.
check_warnings accepts 2-tuples of the form ("message regexp",
WarningCategory) as positional arguments. If one or more filters are provided, or if the optional keyword argument quiet is False, it checks to make sure the warnings are as expected: each specified filter must match at least one of the warnings raised by the enclosed code or the test fails, and if any warnings are raised that do not match any of the specified filters the test fails. To disable the first of these checks, set quiet to True.
If no arguments are specified, it defaults to:
In this case all warnings are caught and no errors are raised.
On entry to the context manager, a WarningRecorder instance is returned. The underlying warnings list from catch_warnings() is available via the recorder object’s warnings attribute. As a convenience, the attributes of the object representing the most recent warning can also be accessed directly through the recorder object (see example below). If no warning has been raised, then any of the attributes that would otherwise be expected on an object representing a warning will return None.
The recorder object also has a reset() method, which clears the warnings list.
The context manager is designed to be used like this:
In this case if either warning was not raised, or some other warning was raised, check_warnings() would raise an error.
When a test needs to look more deeply into the warnings, rather than just checking whether or not they occurred, code like this can be used:
Here all warnings will be caught, and the test code tests the captured warnings directly.
Changed in version 3.2: New optional arguments filters and quiet.
Context manager to check that no ResourceWarning was raised. You must remove the object which may emit ResourceWarning before the end of the context manager.
Set the values for max_memuse and real_max_memuse for big memory tests.
Store the value from stdout. It is meant to hold the stdout at the time the regrtest began.
Return the original stdout set by record_original_stdout() or sys.stdout if it’s not set.
Return a list of command line arguments reproducing the current settings in sys.flags and sys.warnoptions.
Return a list of command line arguments reproducing the current optimization settings in sys.flags.
A context managers that temporarily replaces the named stream with io.StringIO object.
Example use with output streams:
Example use with input stream:
A context manager that creates a temporary directory at path and yields the directory.
If path is None, the temporary directory is created using tempfile.mkdtemp(). If quiet is False, the context manager raises an exception on error. Otherwise, if path is specified and cannot be created, only a warning is issued.
A context manager that temporarily changes the current working directory to path and yields the directory.
If quiet is False, the context manager raises an exception on error. Otherwise, it issues only a warning and keeps the current working directory the same.
A context manager that temporarily creates a new directory and changes the current working directory (CWD).
The context manager creates a temporary directory in the current directory with name name before temporarily changing the current working directory. If name is None, the temporary directory is created using tempfile.mkdtemp().
If quiet is False and it is not possible to create or change the CWD, an error is raised. Otherwise, only a warning is raised and the original CWD is used.
A context manager that temporarily sets the process umask.
A context manager that replaces sys.stderr with sys.__stderr__.
Force as many objects as possible to be collected. This is needed because timely deallocation is not guaranteed by the garbage collector. This means that __del__ methods may be called later than expected and weakrefs may remain alive for longer than expected.
A context manager that disables the garbage collector upon entry and reenables it upon exit.
Context manager to swap out an attribute with a new object.
Usage:
This will set obj.attr to 5 for the duration of the with block, restoring the old value at the end of the block. If attr doesn’t exist on obj, it will be created and then deleted at the end of the block.
The old value (or None if it doesn’t exist) will be assigned to the target of the “as” clause, if there is one.
Context manager to swap out an item with a new object.
Usage:
This will set obj["item"] to 5 for the duration of the with block, restoring the old value at the end of the block. If item doesn’t exist on obj, it will be created and then deleted at the end of the block.
The old value (or None if it doesn’t exist) will be assigned to the target of the “as” clause, if there is one.
Print a warning into sys.__stderr__. Format the message as: f"Warning -- {msg}". If msg is made of multiple lines, add "Warning -- " prefix to each line.
New in version 3.9.
Wait until process pid completes and check that the process exit code is exitcode.
Raise an AssertionError if the process exit code is not equal to exitcode.
If the process runs longer than timeout seconds (SHORT_TIMEOUT by default), kill the process and raise an AssertionError. The timeout feature is not available on Windows.
New in version 3.9.
Context manager to wait until all threads created in the with statement exit.
Context manager to start threads. It attempts to join the threads upon exit.
Return struct.calcsize() for nP{fmt}0n or, if gettotalrefcount exists, 2PnP{fmt}0P.
Return struct.calcsize() for nPn{fmt}0n or, if gettotalrefcount exists, 2PnPn{fmt}0P.
For testcase test, assert that the sys.getsizeof for o plus the GC header size equals size.
Return True if the OS supports symbolic links, False otherwise.
Return True if the OS supports xattr, False otherwise.
A decorator for running tests that require support for symbolic links.
A decorator for running tests that require support for xattr.
A decorator to conditionally mark tests with unittest.expectedFailure(). Any use of this decorator should have an associated comment identifying the relevant tracker issue.
A decorator for running a function in a different locale, correctly resetting it after it has finished. catstr is the locale category as a string (for example "LC_ALL"). The locales passed will be tried sequentially, and the first valid locale will be used.
A decorator for running a function in a specific timezone, correctly resetting it after it has finished.
Decorator for the minimum version when running test on FreeBSD. If the FreeBSD version is less than the minimum, raise unittest.SkipTest.
Decorator for the minimum version when running test on Linux. If the Linux version is less than the minimum, raise unittest.SkipTest.
Decorator for the minimum version when running test on Mac OS X. If the MAC OS X version is less than the minimum, raise unittest.SkipTest.
Decorator for skipping tests on non-IEEE 754 platforms.
Decorator for skipping tests if zlib doesn’t exist.
Decorator for skipping tests if gzip doesn’t exist.
Decorator for skipping tests if bz2 doesn’t exist.
Decorator for skipping tests if lzma doesn’t exist.
Decorator for skipping tests if resource is not available.
Decorator for only running the test if HAVE_DOCSTRINGS.
Decorator for tests only applicable to CPython.
Decorator for invoking check_impl_detail() on guards. If that returns False, then uses msg as the reason for skipping the test.
Decorator to temporarily turn off tracing for the duration of the test.
Decorator for tests which involve reference counting. The decorator does not run the test if it is not run by CPython. Any trace function is unset for the duration of the test to prevent unexpected refcounts caused by the trace function.
Decorator to ensure the threads are cleaned up even if the test fails.
Decorator for bigmem tests.
size is a requested size for the test (in arbitrary, test-interpreted units.) memuse is the number of bytes per unit for the test, or a good estimate of it. For example, a test that needs two byte buffers, of 4 GiB each, could be decorated with @bigmemtest(size=_4G, memuse=2).
The size argument is normally passed to the decorated test method as an extra argument. If dry_run is True, the value passed to the test method may be less than the requested value. If dry_run is False, it means the test doesn’t support dummy runs when -M is not specified.
Decorator for tests that fill the address space. f is the function to wrap.
Create an invalid file descriptor by opening and closing a temporary file, and returning its descriptor.
Test for syntax errors in statement by attempting to compile statement. testcase is the unittest instance for the test. errtext is the regular expression which should match the string representation of the raised SyntaxError. If lineno is not None, compares to the line of the exception. If offset is not None, compares to the offset of the exception.
Test for syntax warning in statement by attempting to compile statement. Test also that the SyntaxWarning is emitted only once, and that it will be converted to a SyntaxError when turned into error. testcase is the unittest instance for the test. errtext is the regular expression which should match the string representation of the emitted SyntaxWarning and raised SyntaxError. If lineno is not None, compares to the line of the warning and exception. If offset is not None, compares to the offset of the exception.
New in version 3.8.
Open url. If open fails, raises TestFailed.
This function imports and returns the named module. Unlike a normal import, this function raises unittest.SkipTest if the module cannot be imported.
Module and package deprecation messages are suppressed during this import if deprecated is True. If a module is required on a platform but optional for others, set required_on to an iterable of platform prefixes which will be compared against sys.platform.
New in version 3.1.
This function imports and returns a fresh copy of the named Python module by removing the named module from sys.modules before doing the import. Note that unlike reload(), the original module is not affected by this operation.
fresh is an iterable of additional module names that are also removed from the sys.modules cache before doing the import.
blocked is an iterable of module names that are replaced with None in the module cache during the import to ensure that attempts to import them raise ImportError.
The named module and any modules named in the fresh and blocked parameters are saved before starting the import and then reinserted into sys.modules when the fresh import is complete.
Module and package deprecation messages are suppressed during this import if deprecated is True.
This function will raise ImportError if the named module cannot be imported.
Example use:
New in version 3.1.
Return a copy of sys.modules.
Remove modules except for oldmodules and encodings in order to preserve internal cache.
Return current thread count and copy of dangling threads.
Cleanup up threads not specified in original_values. Designed to emit a warning if a test leaves running threads in the background.
Join a thread within timeout. Raise an AssertionError if thread is still alive after timeout seconds.
Use this at the end of test_main whenever sub-processes are started. This will help ensure that no extra children (zombies) stick around to hog resources and create problems when looking for refleaks.
Get an attribute, raising unittest.SkipTest if AttributeError is raised.
Context manager catching threading.Thread exception using threading.excepthook().
Attributes set when an exception is catched:
See threading.excepthook() documentation.
These attributes are deleted at the context manager exit.
Usage:
New in version 3.8.
Context manager catching unraisable exception using sys.unraisablehook().
Storing the exception value (cm.unraisable.exc_value) creates a reference cycle. The reference cycle is broken explicitly when the context manager exits.
Storing the object (cm.unraisable.object) can resurrect it if it is set to an object which is being finalized. Exiting the context manager clears the stored object.
Usage:
New in version 3.8.
Generic implementation of the unittest load_tests protocol for use in test packages. pkg_dir is the root directory of the package; loader, standard_tests, and pattern are the arguments expected by load_tests. In simple cases, the test package’s __init__.py can be the following:
Return True if the file system for directory is case-insensitive.
Returns the set of attributes, functions or methods of ref_api not found on other_api, except for a defined list of items to be ignored in this check specified in ignore.
By default this skips private attributes beginning with ‘_’ but includes all magic methods, i.e. those starting and ending in ‘__’.
New in version 3.5.
Override object_to_patch.attr_name with new_value. Also add cleanup procedure to test_instance to restore object_to_patch for attr_name. The attr_name should be a valid attribute for object_to_patch.
Run code in subinterpreter. Raise unittest.SkipTest if tracemalloc is enabled.
Assert that iter is deallocated after iterating.
Check for the existence of the compiler executables whose names are listed in cmd_names or all the compiler executables when cmd_names is empty and return the first missing executable or None when none is found missing.
Assert that the __all__ variable of module contains all public names.
The module’s public names (its API) are detected automatically based on whether they match the public name convention and were defined in module.
The name_of_module argument can specify (as a string or tuple thereof) what module(s) an API could be defined in order to be detected as a public API. One case for this is when module imports part of its public API from other modules, possibly a C backend (like csv and its _csv).
The extra argument can be a set of names that wouldn’t otherwise be automatically detected as “public”, like objects without a proper __module__ attribute. If provided, it will be added to the automatically detected ones.
The blacklist argument can be a set of names that must not be treated as part of the public API even though their names indicate otherwise.
Example use:
New in version 3.6.
The test.support module defines the following classes:
Instances are a context manager that raises ResourceDenied if the specified exception type is raised. Any keyword arguments are treated as attribute/value pairs to be compared against any exception raised within the with statement. Only if all pairs match properly against attributes on the exception is ResourceDenied raised.
Class used to temporarily set or unset environment variables. Instances can be used as a context manager and have a complete dictionary interface for querying/modifying the underlying os.environ. After exit from the context manager all changes to environment variables done through this instance will be rolled back.
Changed in version 3.1: Added dictionary interface.
Temporarily set the environment variable envvar to the value of value.
Temporarily unset the environment variable envvar.
A context manager used to try to prevent crash dialog popups on tests that are expected to crash a subprocess.
On Windows, it disables Windows Error Reporting dialogs using SetErrorMode.
On UNIX, resource.setrlimit() is used to set resource.RLIMIT_CORE’s soft limit to 0 to prevent coredump file creation.
On both platforms, the old value is restored by __exit__().
A context manager to force import to return a new module reference. This is useful for testing module-level behaviors, such as the emission of a DeprecationWarning on import. Example usage:
A context manager to temporarily add directories to sys.path.
This makes a copy of sys.path, appends any directories given as positional arguments, then reverts sys.path to the copied settings when the context ends.
Note that all sys.path modifications in the body of the context manager, including replacement of the object, will be reverted at the end of the block.
Class to save and restore signal handlers registered by the Python signal handler.
Try to match a single dict with the supplied arguments.
Try to match a single stored value (dv) with a supplied value (v).
Class used to record warnings for unit tests. See documentation of check_warnings() above for more details.
Run test and return the result.
Simple path-like object. It implements the __fspath__() method which just returns the path argument. If path is an exception, it will be raised in __fspath__().
The test.support.socket_helper module provides support for socket tests.
New in version 3.9.
Set to True if IPv6 is enabled on this host, False otherwise.
Returns an unused port that should be suitable for binding. This is achieved by creating a temporary socket with the same family and type as the sock parameter (default is AF_INET, SOCK_STREAM), and binding it to the specified host address (defaults to 0.0.0.0) with the port set to 0, eliciting an unused ephemeral port from the OS. The temporary socket is then closed and deleted, and the ephemeral port is returned.
Either this method or bind_port() should be used for any tests where a server socket needs to be bound to a particular port for the duration of the test. Which one to use depends on whether the calling code is creating a Python socket, or if an unused port needs to be provided in a constructor or passed to an external program (i.e. the -accept argument to openssl’s s_server mode). Always prefer bind_port() over find_unused_port() where possible. Using a hard coded port is discouraged since it can make multiple instances of the test impossible to run simultaneously, which is a problem for buildbots.
Bind the socket to a free port and return the port number. Relies on ephemeral ports in order to ensure we are using an unbound port. This is important as many tests may be running simultaneously, especially in a buildbot environment. This method raises an exception if the sock.family is AF_INET and sock.type is SOCK_STREAM, and the socket has SO_REUSEADDR or SO_REUSEPORT set on it. Tests should never set these socket options for TCP/IP sockets. The only case for setting these options is testing multicasting via multiple UDP sockets.
Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. on Windows), it will be set on the socket. This will prevent anyone else from binding to our host/port for the duration of the test.
Bind a unix socket, raising unittest.SkipTest if PermissionError is raised.
A decorator for running tests that require a functional bind() for Unix sockets.
A context manager that raises ResourceDenied when various issues with the internet connection manifest themselves as exceptions.
The test.support.script_helper module provides support for Python’s script execution tests.
Return True if sys.executable interpreter requires environment variables in order to be able to run at all.
This is designed to be used with @unittest.skipIf() to annotate tests that need to use an assert_python*() function to launch an isolated mode (-I) or no environment mode (-E) sub-interpreter process.
A normal build & test does not run into this situation but it can happen when trying to run the standard library test suite from an interpreter that doesn’t have an obvious home with Python’s current home finding logic.
Setting PYTHONHOME is one way to get most of the testsuite to run in that situation. PYTHONPATH or PYTHONUSERSITE are other common environment variables that might impact whether or not the interpreter can start.
Set up the environment based on env_vars for running the interpreter in a subprocess. The values can include __isolated, __cleanenv, __cwd, and TERM.
Changed in version 3.9: The function no longer strips whitespaces from stderr.
Assert that running the interpreter with args and optional environment variables env_vars succeeds (rc == 0) and return a (return code,
stdout, stderr) tuple.
If the __cleanenv keyword is set, env_vars is used as a fresh environment.
Python is started in isolated mode (command line option -I), except if the __isolated keyword is set to False.
Changed in version 3.9: The function no longer strips whitespaces from stderr.
Assert that running the interpreter with args and optional environment variables env_vars fails (rc != 0) and return a (return code,
stdout, stderr) tuple.
See assert_python_ok() for more options.
Changed in version 3.9: The function no longer strips whitespaces from stderr.
Run a Python subprocess with the given arguments.
kw is extra keyword args to pass to subprocess.Popen(). Returns a subprocess.Popen object.
Run the given subprocess.Popen process until completion and return stdout.
Create script containing source in path script_dir and script_basename. If omit_suffix is False, append .py to the name. Return the full script path.
Create zip file at zip_dir and zip_basename with extension zip which contains the files in script_name. name_in_zip is the archive name. Return a tuple containing (full path, full path of archive name).
Create a directory named pkg_dir containing an __init__ file with init_source as its contents.
Create a zip package directory with a path of zip_dir and zip_basename containing an empty __init__ file and a file script_basename containing the source. If compiled is True, both source files will be compiled and added to the zip package. Return a tuple of the full zip path and the archive name for the zip file.
The test.support.bytecode_helper module provides support for testing and inspecting bytecode generation.
New in version 3.9.
The module defines the following class:
This class has custom assertion methods for inspecting bytecode.
Return the disassembly of co as string.
Return instr if opname is found, otherwise throws AssertionError.
Throws AssertionError if opname is found.


Object that is equal to anything. Used to test mixed type comparison.


A decorator to conditionally mark tests with unittest.expectedFailure(). Any use of this decorator should have an associated comment identifying the relevant tracker issue.


Return a list of command line arguments reproducing the current settings in sys.flags and sys.warnoptions.


Decorator for tests that fill the address space. f is the function to wrap.


Decorator for bigmem tests.
size is a requested size for the test (in arbitrary, test-interpreted units.) memuse is the number of bytes per unit for the test, or a good estimate of it. For example, a test that needs two byte buffers, of 4 GiB each, could be decorated with @bigmemtest(size=_4G, memuse=2).
The size argument is normally passed to the decorated test method as an extra argument. If dry_run is True, the value passed to the test method may be less than the requested value. If dry_run is False, it means the test doesn’t support dummy runs when -M is not specified.


This class has custom assertion methods for inspecting bytecode.


Return instr if opname is found, otherwise throws AssertionError.


Throws AssertionError if opname is found.


Return struct.calcsize() for nP{fmt}0n or, if gettotalrefcount exists, 2PnP{fmt}0P.


Return struct.calcsize() for nPn{fmt}0n or, if gettotalrefcount exists, 2PnPn{fmt}0P.


Return True if the OS supports symbolic links, False otherwise.


Return True if the OS supports xattr, False otherwise.


A context managers that temporarily replaces the named stream with io.StringIO object.
Example use with output streams:
Example use with input stream:


Context manager catching threading.Thread exception using threading.excepthook().
Attributes set when an exception is catched:
See threading.excepthook() documentation.
These attributes are deleted at the context manager exit.
Usage:
New in version 3.8.


Context manager catching unraisable exception using sys.unraisablehook().
Storing the exception value (cm.unraisable.exc_value) creates a reference cycle. The reference cycle is broken explicitly when the context manager exits.
Storing the object (cm.unraisable.object) can resurrect it if it is set to an object which is being finalized. Exiting the context manager clears the stored object.
Usage:
New in version 3.8.


A context manager that temporarily changes the current working directory to path and yields the directory.
If quiet is False, the context manager raises an exception on error. Otherwise, it issues only a warning and keeps the current working directory the same.


For testcase test, assert that the sys.getsizeof for o plus the GC header size equals size.


Assert that iter is deallocated after iterating.


Use this check to guard CPython’s implementation-specific tests or to run them only on the implementations guarded by the arguments:


Context manager to check that no ResourceWarning was raised. You must remove the object which may emit ResourceWarning before the end of the context manager.


Test for syntax errors in statement by attempting to compile statement. testcase is the unittest instance for the test. errtext is the regular expression which should match the string representation of the raised SyntaxError. If lineno is not None, compares to the line of the exception. If offset is not None, compares to the offset of the exception.


Test for syntax warning in statement by attempting to compile statement. Test also that the SyntaxWarning is emitted only once, and that it will be converted to a SyntaxError when turned into error. testcase is the unittest instance for the test. errtext is the regular expression which should match the string representation of the emitted SyntaxWarning and raised SyntaxError. If lineno is not None, compares to the line of the warning and exception. If offset is not None, compares to the offset of the exception.
New in version 3.8.


A convenience wrapper for warnings.catch_warnings() that makes it easier to test that a warning was correctly raised. It is approximately equivalent to calling warnings.catch_warnings(record=True) with warnings.simplefilter() set to always and with the option to automatically validate the results that are recorded.
check_warnings accepts 2-tuples of the form ("message regexp",
WarningCategory) as positional arguments. If one or more filters are provided, or if the optional keyword argument quiet is False, it checks to make sure the warnings are as expected: each specified filter must match at least one of the warnings raised by the enclosed code or the test fails, and if any warnings are raised that do not match any of the specified filters the test fails. To disable the first of these checks, set quiet to True.
If no arguments are specified, it defaults to:
In this case all warnings are caught and no errors are raised.
On entry to the context manager, a WarningRecorder instance is returned. The underlying warnings list from catch_warnings() is available via the recorder object’s warnings attribute. As a convenience, the attributes of the object representing the most recent warning can also be accessed directly through the recorder object (see example below). If no warning has been raised, then any of the attributes that would otherwise be expected on an object representing a warning will return None.
The recorder object also has a reset() method, which clears the warnings list.
The context manager is designed to be used like this:
In this case if either warning was not raised, or some other warning was raised, check_warnings() would raise an error.
When a test needs to look more deeply into the warnings, rather than just checking whether or not they occurred, code like this can be used:
Here all warnings will be caught, and the test code tests the captured warnings directly.
Changed in version 3.2: New optional arguments filters and quiet.


Assert that the __all__ variable of module contains all public names.
The module’s public names (its API) are detected automatically based on whether they match the public name convention and were defined in module.
The name_of_module argument can specify (as a string or tuple thereof) what module(s) an API could be defined in order to be detected as a public API. One case for this is when module imports part of its public API from other modules, possibly a C backend (like csv and its _csv).
The extra argument can be a set of names that wouldn’t otherwise be automatically detected as “public”, like objects without a proper __module__ attribute. If provided, it will be added to the automatically detected ones.
The blacklist argument can be a set of names that must not be treated as part of the public API even though their names indicate otherwise.
Example use:
New in version 3.6.


A context manager to force import to return a new module reference. This is useful for testing module-level behaviors, such as the emission of a DeprecationWarning on import. Example usage:


Decorator for tests only applicable to CPython.


Create an empty file with filename. If it already exists, truncate it.


Returns the set of attributes, functions or methods of ref_api not found on other_api, except for a defined list of items to be ignored in this check specified in ignore.
By default this skips private attributes beginning with ‘_’ but includes all magic methods, i.e. those starting and ending in ‘__’.
New in version 3.5.


A context manager to temporarily add directories to sys.path.
This makes a copy of sys.path, appends any directories given as positional arguments, then reverts sys.path to the copied settings when the context ends.
Note that all sys.path modifications in the body of the context manager, including replacement of the object, will be reverted at the end of the block.


A context manager that replaces sys.stderr with sys.__stderr__.


A context manager that disables the garbage collector upon entry and reenables it upon exit.


Class used to temporarily set or unset environment variables. Instances can be used as a context manager and have a complete dictionary interface for querying/modifying the underlying os.environ. After exit from the context manager all changes to environment variables done through this instance will be rolled back.
Changed in version 3.1: Added dictionary interface.


Temporarily set the environment variable envvar to the value of value.


Temporarily unset the environment variable envvar.


Simple path-like object. It implements the __fspath__() method which just returns the path argument. If path is an exception, it will be raised in __fspath__().


Count the number of open file descriptors.


Return the path to the file named filename. If no match is found filename is returned. This does not equal a failure since it could be the path to the file.
Setting subdir indicates a relative path to use to find the file rather than looking directly in the path directories.


Remove the module named module_name from sys.modules and delete any byte-compiled files of the module.


Return True if the file system for directory is case-insensitive.


A non-ASCII character encodable by os.fsencode().


Force as many objects as possible to be collected. This is needed because timely deallocation is not guaranteed by the garbage collector. This means that __del__ methods may be called later than expected and weakrefs may remain alive for longer than expected.


Get an attribute, raising unittest.SkipTest if AttributeError is raised.


Return the original stdout set by record_original_stdout() or sys.stdout if it’s not set.


Decorator for invoking check_impl_detail() on guards. If that returns False, then uses msg as the reason for skipping the test.


This function imports and returns a fresh copy of the named Python module by removing the named module from sys.modules before doing the import. Note that unlike reload(), the original module is not affected by this operation.
fresh is an iterable of additional module names that are also removed from the sys.modules cache before doing the import.
blocked is an iterable of module names that are replaced with None in the module cache during the import to ensure that attempts to import them raise ImportError.
The named module and any modules named in the fresh and blocked parameters are saved before starting the import and then reinserted into sys.modules when the fresh import is complete.
Module and package deprecation messages are suppressed during this import if deprecated is True.
This function will raise ImportError if the named module cannot be imported.
Example use:
New in version 3.1.


This function imports and returns the named module. Unlike a normal import, this function raises unittest.SkipTest if the module cannot be imported.
Module and package deprecation messages are suppressed during this import if deprecated is True. If a module is required on a platform but optional for others, set required_on to an iterable of platform prefixes which will be compared against sys.platform.
New in version 3.1.


Timeout in seconds for network requests going to the Internet.
The timeout is short enough to prevent a test to wait for too long if the Internet request is blocked for whatever reason.
Usually, a timeout using INTERNET_TIMEOUT should not mark a test as failed, but skip the test instead: see transient_internet().
Its default value is 1 minute.
See also LOOPBACK_TIMEOUT.


True if the running interpreter is Jython.


Return True if resource is enabled and available. The list of available resources is only set when test.regrtest is executing the tests.


Join a thread within timeout. Raise an AssertionError if thread is still alive after timeout seconds.


Object that is greater than anything (except itself). Used to test mixed type comparison.


Generic implementation of the unittest load_tests protocol for use in test packages. pkg_dir is the root directory of the package; loader, standard_tests, and pattern are the arguments expected by load_tests. In simple cases, the test package’s __init__.py can be the following:


Timeout in seconds to detect when a test hangs.
It is long enough to reduce the risk of test failure on the slowest Python buildbots. It should not be used to mark a test as failed if the test takes “too long”. The timeout value depends on the regrtest --timeout command line option.
Its default value is 5 minutes.
See also LOOPBACK_TIMEOUT, INTERNET_TIMEOUT and SHORT_TIMEOUT.


Timeout in seconds for tests using a network server listening on the network local loopback interface like 127.0.0.1.
The timeout is long enough to prevent test failure: it takes into account that the client and the server can run in different threads or even different processes.
The timeout should be long enough for connect(), recv() and send() methods of socket.socket.
Its default value is 5 seconds.
See also INTERNET_TIMEOUT.


Create an invalid file descriptor by opening and closing a temporary file, and returning its descriptor.


Move a PEP 3147/PEP 488 pyc file to its legacy pyc location and return the file system path to the legacy pyc file. The source value is the file system path to the source file. It does not need to exist, however the PEP 3147/488 pyc file must exist.


Try to match a single dict with the supplied arguments.
Try to match a single stored value (dv) with a supplied value (v).


Try to match a single dict with the supplied arguments.


Try to match a single stored value (dv) with a supplied value (v).


Match test to patterns set in set_match_tests().


Set by set_memlimit() as the memory limit for big memory tests. Limited by MAX_Py_ssize_t.


Set to sys.maxsize for big memory tests.


Check for the existence of the compiler executables whose names are listed in cmd_names or all the compiler executables when cmd_names is empty and return the first missing executable or None when none is found missing.


Return True if running on CPython, not on Windows, and configuration not set with WITH_DOC_STRINGS.


Remove modules except for oldmodules and encodings in order to preserve internal cache.


Object that is not equal to anything (even to ALWAYS_EQ). Used to test mixed type comparison.


Decorator to temporarily turn off tracing for the duration of the test.


Open url. If open fails, raises TestFailed.


Return a list of command line arguments reproducing the current optimization settings in sys.flags.


Override object_to_patch.attr_name with new_value. Also add cleanup procedure to test_instance to restore object_to_patch for attr_name. The attr_name should be a valid attribute for object_to_patch.


Set when tests can be skipped when they are not useful for PGO.


A constant that is likely larger than the underlying OS pipe buffer size, to make writes blocking.


Print a warning into sys.__stderr__. Format the message as: f"Warning -- {msg}". If msg is made of multiple lines, add "Warning -- " prefix to each line.
New in version 3.9.


Return True if Python was not built with -O0 or -Og.


Set by set_memlimit() as the memory limit for big memory tests. Not limited by MAX_Py_ssize_t.


Use this at the end of test_main whenever sub-processes are started. This will help ensure that no extra children (zombies) stick around to hog resources and create problems when looking for refleaks.


Decorator to ensure the threads are cleaned up even if the test fails.


Store the value from stdout. It is meant to hold the stdout at the time the regrtest began.


Decorator for tests which involve reference counting. The decorator does not run the test if it is not run by CPython. Any trace function is unset for the duration of the test to prevent unexpected refcounts caused by the trace function.


Raise ResourceDenied if resource is not available. msg is the argument to ResourceDenied if it is raised. Always returns True if called by a function whose __name__ is '__main__'. Used when tests are executed by test.regrtest.


Decorator for skipping tests if bz2 doesn’t exist.


Decorator for only running the test if HAVE_DOCSTRINGS.


Decorator for the minimum version when running test on FreeBSD. If the FreeBSD version is less than the minimum, raise unittest.SkipTest.


Decorator for skipping tests if gzip doesn’t exist.


Decorator for skipping tests on non-IEEE 754 platforms.


Decorator for the minimum version when running test on Linux. If the Linux version is less than the minimum, raise unittest.SkipTest.


Decorator for skipping tests if lzma doesn’t exist.


Decorator for the minimum version when running test on Mac OS X. If the MAC OS X version is less than the minimum, raise unittest.SkipTest.


Decorator for skipping tests if resource is not available.


Decorator for skipping tests if zlib doesn’t exist.


Subclass of unittest.SkipTest. Raised when a resource (such as a network connection) is not available. Raised by the requires() function.


Call os.rmdir() on filename. On Windows platforms, this is wrapped with a wait loop that checks for the existence of the file.


Call shutil.rmtree() on path or call os.lstat() and os.rmdir() to remove a path and its contents. On Windows platforms, this is wrapped with a wait loop that checks for the existence of the files.


Run doctest.testmod() on the given module. Return (failure_count, test_count).
If verbosity is None, doctest.testmod() is run with verbosity set to verbose. Otherwise, it is run with verbosity set to None. optionflags is passed as optionflags to doctest.testmod().


Run code in subinterpreter. Raise unittest.SkipTest if tracemalloc is enabled.


Execute unittest.TestCase subclasses passed to the function. The function scans the classes for methods starting with the prefix test_ and executes the tests individually.
It is also legal to pass strings as parameters; these should be keys in sys.modules. Each associated module will be scanned by unittest.TestLoader.loadTestsFromModule(). This is usually seen in the following test_main() function:
This will run all tests defined in the named module.


A decorator for running a function in a different locale, correctly resetting it after it has finished. catstr is the locale category as a string (for example "LC_ALL"). The locales passed will be tried sequentially, and the first valid locale will be used.


A decorator for running a function in a specific timezone, correctly resetting it after it has finished.


Class to save and restore signal handlers registered by the Python signal handler.


Assert that running the interpreter with args and optional environment variables env_vars fails (rc != 0) and return a (return code,
stdout, stderr) tuple.
See assert_python_ok() for more options.
Changed in version 3.9: The function no longer strips whitespaces from stderr.


Assert that running the interpreter with args and optional environment variables env_vars succeeds (rc == 0) and return a (return code,
stdout, stderr) tuple.
If the __cleanenv keyword is set, env_vars is used as a fresh environment.
Python is started in isolated mode (command line option -I), except if the __isolated keyword is set to False.
Changed in version 3.9: The function no longer strips whitespaces from stderr.


Return True if sys.executable interpreter requires environment variables in order to be able to run at all.
This is designed to be used with @unittest.skipIf() to annotate tests that need to use an assert_python*() function to launch an isolated mode (-I) or no environment mode (-E) sub-interpreter process.
A normal build & test does not run into this situation but it can happen when trying to run the standard library test suite from an interpreter that doesn’t have an obvious home with Python’s current home finding logic.
Setting PYTHONHOME is one way to get most of the testsuite to run in that situation. PYTHONPATH or PYTHONUSERSITE are other common environment variables that might impact whether or not the interpreter can start.


Run the given subprocess.Popen process until completion and return stdout.


Create a directory named pkg_dir containing an __init__ file with init_source as its contents.


Create script containing source in path script_dir and script_basename. If omit_suffix is False, append .py to the name. Return the full script path.


Create a zip package directory with a path of zip_dir and zip_basename containing an empty __init__ file and a file script_basename containing the source. If compiled is True, both source files will be compiled and added to the zip package. Return a tuple of the full zip path and the archive name for the zip file.


Create zip file at zip_dir and zip_basename with extension zip which contains the files in script_name. name_in_zip is the archive name. Return a tuple containing (full path, full path of archive name).


Set up the environment based on env_vars for running the interpreter in a subprocess. The values can include __isolated, __cleanenv, __cwd, and TERM.
Changed in version 3.9: The function no longer strips whitespaces from stderr.


Run a Python subprocess with the given arguments.
kw is extra keyword args to pass to subprocess.Popen(). Returns a subprocess.Popen object.


Set the sys.setswitchinterval() to the given interval. Defines a minimum interval for Android systems to prevent the system from hanging.


Define match test with regular expression patterns.


Set the values for max_memuse and real_max_memuse for big memory tests.


Timeout in seconds to mark a test as failed if the test takes “too long”.
The timeout value depends on the regrtest --timeout command line option.
If a test using SHORT_TIMEOUT starts to fail randomly on slow buildbots, use LONG_TIMEOUT instead.
Its default value is 30 seconds.


A decorator for running tests that require support for symbolic links.


A decorator for running tests that require support for xattr.


Object that is less than anything (except itself). Used to test mixed type comparison.


Bind the socket to a free port and return the port number. Relies on ephemeral ports in order to ensure we are using an unbound port. This is important as many tests may be running simultaneously, especially in a buildbot environment. This method raises an exception if the sock.family is AF_INET and sock.type is SOCK_STREAM, and the socket has SO_REUSEADDR or SO_REUSEPORT set on it. Tests should never set these socket options for TCP/IP sockets. The only case for setting these options is testing multicasting via multiple UDP sockets.
Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. on Windows), it will be set on the socket. This will prevent anyone else from binding to our host/port for the duration of the test.


Bind a unix socket, raising unittest.SkipTest if PermissionError is raised.


Returns an unused port that should be suitable for binding. This is achieved by creating a temporary socket with the same family and type as the sock parameter (default is AF_INET, SOCK_STREAM), and binding it to the specified host address (defaults to 0.0.0.0) with the port set to 0, eliciting an unused ephemeral port from the OS. The temporary socket is then closed and deleted, and the ephemeral port is returned.
Either this method or bind_port() should be used for any tests where a server socket needs to be bound to a particular port for the duration of the test. Which one to use depends on whether the calling code is creating a Python socket, or if an unused port needs to be provided in a constructor or passed to an external program (i.e. the -accept argument to openssl’s s_server mode). Always prefer bind_port() over find_unused_port() where possible. Using a hard coded port is discouraged since it can make multiple instances of the test impossible to run simultaneously, which is a problem for buildbots.


Set to True if IPv6 is enabled on this host, False otherwise.


A decorator for running tests that require a functional bind() for Unix sockets.


A context manager that raises ResourceDenied when various issues with the internet connection manifest themselves as exceptions.


A constant that is likely larger than the underlying OS socket buffer size, to make writes blocking.


Context manager to start threads. It attempts to join the threads upon exit.


A context manager used to try to prevent crash dialog popups on tests that are expected to crash a subprocess.
On Windows, it disables Windows Error Reporting dialogs using SetErrorMode.
On UNIX, resource.setrlimit() is used to set resource.RLIMIT_CORE’s soft limit to 0 to prevent coredump file creation.
On both platforms, the old value is restored by __exit__().


Context manager to swap out an attribute with a new object.
Usage:
This will set obj.attr to 5 for the duration of the with block, restoring the old value at the end of the block. If attr doesn’t exist on obj, it will be created and then deleted at the end of the block.
The old value (or None if it doesn’t exist) will be assigned to the target of the “as” clause, if there is one.


Context manager to swap out an item with a new object.
Usage:
This will set obj["item"] to 5 for the duration of the with block, restoring the old value at the end of the block. If item doesn’t exist on obj, it will be created and then deleted at the end of the block.
The old value (or None if it doesn’t exist) will be assigned to the target of the “as” clause, if there is one.


Raise unittest.SkipTest on TLS certification validation failures.


A context manager that temporarily creates a new directory and changes the current working directory (CWD).
The context manager creates a temporary directory in the current directory with name name before temporarily changing the current working directory. If name is None, the temporary directory is created using tempfile.mkdtemp().
If quiet is False and it is not possible to create or change the CWD, an error is raised. Otherwise, only a warning is raised and the original CWD is used.


A context manager that creates a temporary directory at path and yields the directory.
If path is None, the temporary directory is created using tempfile.mkdtemp(). If quiet is False, the context manager raises an exception on error. Otherwise, if path is specified and cannot be created, only a warning is issued.


A context manager that temporarily sets the process umask.


Exception to be raised when a test fails. This is deprecated in favor of unittest-based tests and unittest.TestCase’s assertion methods.


Set to a name that is safe to use as the name of a temporary file. Any temporary file that is created should be closed and unlinked (removed).


Set to a filename containing the FS_NONASCII character.


Set to a filename (bytes type) that should not be able to be decoded by file system encoding in strict mode. It may be None if it’s not possible to generate such a filename.


Set to a filename (str type) that should not be able to be encoded by file system encoding in strict mode. It may be None if it’s not possible to generate such a filename.


Set to a non-ASCII name for a temporary file.


Set to the data directory within the test package.


Set to the top level directory for the test package.


Define the URL of a dedicated HTTP server for the network tests.


Set to the top level directory that contains test.support.


Cleanup up threads not specified in original_values. Designed to emit a warning if a test leaves running threads in the background.


Return current thread count and copy of dangling threads.


Instances are a context manager that raises ResourceDenied if the specified exception type is raised. Any keyword arguments are treated as attribute/value pairs to be compared against any exception raised within the with statement. Only if all pairs match properly against attributes on the exception is ResourceDenied raised.


Path for shell if not on Windows; otherwise None.


Call os.unlink() on filename. On Windows platforms, this is wrapped with a wait loop that checks for the existence fo the file.


True when verbose output is enabled. Should be checked when more detailed information is desired about a running test. verbose is set by test.regrtest.


Wait until process pid completes and check that the process exit code is exitcode.
Raise an AssertionError if the process exit code is not equal to exitcode.
If the process runs longer than timeout seconds (SHORT_TIMEOUT by default), kill the process and raise an AssertionError. The timeout feature is not available on Windows.
New in version 3.9.


Context manager to wait until all threads created in the with statement exit.


Class used to record warnings for unit tests. See documentation of check_warnings() above for more details.


Source code: Lib/textwrap.py
The textwrap module provides some convenience functions, as well as TextWrapper, the class that does all the work. If you’re just wrapping or filling one or two text strings, the convenience functions should be good enough; otherwise, you should use an instance of TextWrapper for efficiency.
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.
Optional keyword arguments correspond to the instance attributes of TextWrapper, documented below. width defaults to 70.
See the TextWrapper.wrap() method for additional details on how wrap() behaves.
Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. fill() is shorthand for
In particular, fill() accepts exactly the same keyword arguments as wrap().
Collapse and truncate the given text to fit in the given width.
First the whitespace in text is collapsed (all whitespace is replaced by single spaces). If the result fits in the width, it is returned. Otherwise, enough words are dropped from the end so that the remaining words plus the placeholder fit within width:
Optional keyword arguments correspond to the instance attributes of TextWrapper, documented below. Note that the whitespace is collapsed before the text is passed to the TextWrapper fill() function, so changing the value of tabsize, expand_tabs, drop_whitespace, and replace_whitespace will have no effect.
New in version 3.4.
Remove any common leading whitespace from every line in text.
This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form.
Note that tabs and spaces are both treated as whitespace, but they are not equal: the lines "  hello" and "\thello" are considered to have no common leading whitespace.
Lines containing only whitespace are ignored in the input and normalized to a single newline character in the output.
For example:
Add prefix to the beginning of selected lines in text.
Lines are separated by calling text.splitlines(True).
By default, prefix is added to all lines that do not consist solely of whitespace (including any line endings).
For example:
The optional predicate argument can be used to control which lines are indented. For example, it is easy to add prefix to even empty and whitespace-only lines:
New in version 3.3.
wrap(), fill() and shorten() work by creating a TextWrapper instance and calling a single method on it. That instance is not reused, so for applications that process many text strings using wrap() and/or fill(), it may be more efficient to create your own TextWrapper object.
Text is preferably wrapped on whitespaces and right after the hyphens in hyphenated words; only then will long words be broken if necessary, unless TextWrapper.break_long_words is set to false.
The TextWrapper constructor accepts a number of optional keyword arguments. Each keyword argument corresponds to an instance attribute, so for example
is the same as
You can re-use the same TextWrapper object many times, and you can change any of its options through direct assignment to instance attributes between uses.
The TextWrapper instance attributes (and keyword arguments to the constructor) are as follows:
(default: 70) The maximum length of wrapped lines. As long as there are no individual words in the input text longer than width, TextWrapper guarantees that no output line will be longer than width characters.
(default: True) If true, then all tab characters in text will be expanded to spaces using the expandtabs() method of text.
(default: 8) If expand_tabs is true, then all tab characters in text will be expanded to zero or more spaces, depending on the current column and the given tab size.
New in version 3.3.
(default: True) If true, after tab expansion but before wrapping, the wrap() method will replace each whitespace character with a single space. The whitespace characters replaced are as follows: tab, newline, vertical tab, formfeed, and carriage return ('\t\n\v\f\r').
Note
If expand_tabs is false and replace_whitespace is true, each tab character will be replaced by a single space, which is not the same as tab expansion.
Note
If replace_whitespace is false, newlines may appear in the middle of a line and cause strange output. For this reason, text should be split into paragraphs (using str.splitlines() or similar) which are wrapped separately.
(default: True) If true, whitespace at the beginning and ending of every line (after wrapping but before indenting) is dropped. Whitespace at the beginning of the paragraph, however, is not dropped if non-whitespace follows it. If whitespace being dropped takes up an entire line, the whole line is dropped.
(default: '') String that will be prepended to the first line of wrapped output. Counts towards the length of the first line. The empty string is not indented.
(default: '') String that will be prepended to all lines of wrapped output except the first. Counts towards the length of each line except the first.
(default: False) If true, TextWrapper attempts to detect sentence endings and ensure that sentences are always separated by exactly two spaces. This is generally desired for text in a monospaced font. However, the sentence detection algorithm is imperfect: it assumes that a sentence ending consists of a lowercase letter followed by one of '.', '!', or '?', possibly followed by one of '"' or "'", followed by a space. One problem with this is algorithm is that it is unable to detect the difference between “Dr.” in
and “Spot.” in
fix_sentence_endings is false by default.
Since the sentence detection algorithm relies on string.lowercase for the definition of “lowercase letter”, and a convention of using two spaces after a period to separate sentences on the same line, it is specific to English-language texts.
(default: True) If true, then words longer than width will be broken in order to ensure that no lines are longer than width. If it is false, long words will not be broken, and some lines may be longer than width. (Long words will be put on a line by themselves, in order to minimize the amount by which width is exceeded.)
(default: True) If true, wrapping will occur preferably on whitespaces and right after hyphens in compound words, as it is customary in English. If false, only whitespaces will be considered as potentially good places for line breaks, but you need to set break_long_words to false if you want truly insecable words. Default behaviour in previous versions was to always allow breaking hyphenated words.
(default: None) If not None, then the output will contain at most max_lines lines, with placeholder appearing at the end of the output.
New in version 3.4.
(default: ' [...]') String that will appear at the end of the output text if it has been truncated.
New in version 3.4.
TextWrapper also provides some public methods, analogous to the module-level convenience functions:
Wraps the single paragraph in text (a string) so every line is at most width characters long. All wrapping options are taken from instance attributes of the TextWrapper instance. Returns a list of output lines, without final newlines. If the wrapped output has no content, the returned list is empty.
Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph.


Remove any common leading whitespace from every line in text.
This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form.
Note that tabs and spaces are both treated as whitespace, but they are not equal: the lines "  hello" and "\thello" are considered to have no common leading whitespace.
Lines containing only whitespace are ignored in the input and normalized to a single newline character in the output.
For example:


Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. fill() is shorthand for
In particular, fill() accepts exactly the same keyword arguments as wrap().


Add prefix to the beginning of selected lines in text.
Lines are separated by calling text.splitlines(True).
By default, prefix is added to all lines that do not consist solely of whitespace (including any line endings).
For example:
The optional predicate argument can be used to control which lines are indented. For example, it is easy to add prefix to even empty and whitespace-only lines:
New in version 3.3.


Collapse and truncate the given text to fit in the given width.
First the whitespace in text is collapsed (all whitespace is replaced by single spaces). If the result fits in the width, it is returned. Otherwise, enough words are dropped from the end so that the remaining words plus the placeholder fit within width:
Optional keyword arguments correspond to the instance attributes of TextWrapper, documented below. Note that the whitespace is collapsed before the text is passed to the TextWrapper fill() function, so changing the value of tabsize, expand_tabs, drop_whitespace, and replace_whitespace will have no effect.
New in version 3.4.