AlkantarClanX12

Your IP : 18.219.207.115


Current Path : /proc/self/root/opt/alt/python35/lib64/python3.5/test/support/__pycache__/
Upload File :
Current File : //proc/self/root/opt/alt/python35/lib64/python3.5/test/support/__pycache__/__init__.cpython-35.pyc



��Yf
Q��@s�dZedkred��ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
ZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZyddl Z ddl!Z!Wnek
r�dZ dZ!YnXyddl"Z#Wnek
r�dZ#YnXyddl$Z$Wnek
r�dZ$YnXyddl%Z%Wnek
rdZ%YnXyddl&Z&Wnek
r>dZ&YnXyddl'Z'Wnek
ridZ'YnXyddl(Z(Wnek
r�dZ(YnXddddd	d
ddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUgQZ)GdVd
�d
e*�Z+GdWd�de+�Z,GdXd�dej-�Z.ej/dYdZd[��Z0d\d]fd^d
�Z1d_d`�Z2dadb�Z3dcd9�Z4ddd:�Z5ffd\ded�Z6dfd5�Z7dgZ8dZ9da:da;d\Z<da=da>dhd�Z?did�Z@djd�ZAdkdl�ZBejjCdm�r�d\dndo�ZDdpdq�ZEdrds�ZFdtdu�ZGnejHZEejIZFdvdu�ZGdwd�ZHdxdy�ZIdzd�ZJd{d|�ZKd}d�ZLd~d�ZMd�d �ZNdd�d!�ZOd�d��ZPd�d"�ZQd�d#�ZRd�d$�ZSd�ZTd�ZUejVejWd�dA�ZXeTd�dB�ZYd�d��ZZeZ�Z[d�d��Z\d;Z]d>Z^ej_e`jad��jCd��d��Zbej_e$d��Zcej_e%d��Zdej_e&d��Zeej_e'd��ZfejjCd��Zgejhd�kr�d�Zind�Zid�jjeiejk��ZidZlxDd?D]<Zmyejnejoem��Wnepk
r�Yq�XemZlPq�Weid�Zqejd�kr<ddlrZrerjsd�eq�Zqejt�ZudZvejhd@kr�ejw�jd�kr
eid�Zvyevjxeu�Wneyk
r�Yq
Xezd�eveuf�dZvnKejd�kr
yd�j{eu�Wn(e|k
r	eid�j{eud��ZvYnXdZ}xHdAD]@Zhyehj{eu�Wqe|k
rVejoei�ehZ}PYqXqWelrreid�elZ~ndZ~ej�Z�ej/dd\d�d���Z�ej/d\d�d���Z�ej/d�d\d�d��Z�e�ed��r�ej/d�dD��Z�ej�j�ej�j�e���Z�ej�j�e��Z�ej�j�e�d��Z�dd�d�Z�d�d�Z�d�dT�Z�d�d��Z�d�dd�dd�d%�Z�d�dC�Z�Gd�d��d�e��Z�d\d�d��Z�ej/d�dK��Z�ej/d�dL��Z�Gd�d�de��Z�Gd�dM�dMej�j��Z�Gd�d��d�e��Z�Gd�d&�d&e��Z�e�e�d�ej��Z�e�e�d�ej��Z�e�e�d�ej��Z�ej/d�d�d�fd�d*��Z�ej/d�d���Z�d�d�Z�d�d�Z�d�d�Z�d�d��Z�ej/d�d���Z�d�d��Z�d�Z�d�Z�e�ed��r0d�e�Z�d�Z�e�d�Z�d�d��Z�d�d��Z�dBZ�dCZ�d�d��Z�d�dN�Z�d�dU�Z�dDZ�d�e�Z�d�e�Z�d�e�Z�ej�Z�d�dR�Z�Gd�d��d��Z�dYd�d2�Z�d�d3�Z�Gd�d+�d+�Z�d�d��Z�d�d��Z�d�d4�Z�ddd�Z�da�dd<�Z�dd�Z�dd>�Z�dd�Z�dd	�Z�d
d�Z�dd
�Z�dd�Z�dd,�Z�dd�Z�e��o�ejdko�ej�d�Z�e�jdk	o�e�Z�ej_e�d�Z�dddd-�Z�dd�Z�dd�Z�ddG�Z�ddH�Z�ddI�Z�ddE�Z�ej/dddJ��Z�ej/d dP��Z�ej/d!dO��Z�d"d#�Z�ej�e�ed$�d%�Z�d&d'�Z�Gd(dF�dFej�j��Z�Gd)dQ�dQe��Z�da�d*d�Z�d+d.�Z�da�d,d-�Z�d.d7�Z�d/d�Z�d0fd1d;�Z�Gd2dS�dS�Z�d3d4�Z�d5d6�Z�fd7d8�Z�dS(Ez7Supporting definitions for the Python regression tests.ztest.supportz.support must be imported from the test package�N�
PIPE_MAX_SIZE�verbose�
max_memuse�
use_resources�failfast�Error�
TestFailed�ResourceDenied�
import_module�import_fresh_module�CleanImport�unload�forget�record_original_stdout�get_original_stdout�captured_stdout�captured_stdin�captured_stderr�TESTFN�SAVEDCWD�unlink�rmtree�temp_cwd�findfile�create_empty_file�can_symlink�fs_is_case_insensitive�is_resource_enabled�requires�requires_freebsd_version�requires_linux_version�requires_mac_ver�check_syntax_error�TransientResource�time_out�socket_peer_reset�ioerror_peer_reset�transient_internet�BasicTestRunner�run_unittest�run_doctest�skip_unless_symlink�
requires_gzip�requires_bz2�
requires_lzma�
bigmemtest�bigaddrspacetest�cpython_only�
get_attribute�requires_IEEE_754�skip_unless_xattr�
requires_zlib�anticipate_failure�load_package_tests�detect_api_mismatch�requires_multiprocessing_queue�	is_jython�check_impl_detail�HOST�IPV6_ENABLED�find_unused_port�	bind_port�open_urlresource�
temp_umask�
reap_children�TestHandler�threading_setup�threading_cleanup�reap_threads�
start_threads�check_warnings�check_no_resource_warning�EnvironmentVarGuard�run_with_locale�	swap_item�	swap_attr�Matcher�set_memlimit�SuppressCrashReport�sortdict�run_with_tzc@seZdZdZdS)rz*Base class for regression test exceptions.N)�__name__�
__module__�__qualname__�__doc__�rWrW�:/opt/alt/python35/lib64/python3.5/test/support/__init__.pyrnsc@seZdZdZdS)rzTest failed.N)rSrTrUrVrWrWrWrXrqsc@seZdZdZdS)r	z�Test skipped because it requested a disallowed resource.

    This is raised when a test calls requires() for a resource that
    has not be enabled.  It is used to distinguish between expected
    and unexpected skips.
    N)rSrTrUrVrWrWrWrXr	tsTccs>|r5tj��tjddt�dVWdQRXndVdS)z�Context manager to suppress package and module deprecation
    warnings when importing them.

    If ignore is False, this context manager has no effect.
    �ignorez.+ (module|package)N)�warnings�catch_warnings�filterwarnings�DeprecationWarning)rYrWrWrX�_ignore_deprecated_imports|s
r^F�required_oncCs�t|��nytj|�SWnUtk
ru}z5tjjt|��rN�tj	t
|���WYdd}~XnXWdQRXdS)acImport and return the module to be tested, raising SkipTest if
    it is not available.

    If deprecated is True, any module or package deprecation messages
    will be suppressed. 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.
    N)r^�	importlibr
�ImportError�sys�platform�
startswith�tuple�unittest�SkipTest�str)�name�
deprecatedr_�msgrWrWrXr
�s	
cCs{|tjkr#t|�tj|=xQttj�D]@}||ksX|j|d�r3tj|||<tj|=q3WdS)zyHelper function to save and remove a module from sys.modules

    Raise ImportError if the module can't be imported.
    �.N)rb�modules�
__import__�listrd)ri�orig_modules�modnamerWrWrX�_save_and_remove_module�s

rrcCsGd}ytj|||<Wntk
r5d}YnXdtj|<|S)z�Helper function to save and block a module in sys.modules

    Return True if the module was in sys.modules, False otherwise.
    TFN)rbrm�KeyError)rirpZsavedrWrWrX�_save_and_block_module�s

rtcCs|r
tjSdd�S)z�Decorator to mark a test that is known to be broken in some cases

       Any use of this decorator should have a comment identifying the
       associated tracker issue.
    cSs|S)NrW)�frWrWrX�<lambda>�sz$anticipate_failure.<locals>.<lambda>)rfZexpectedFailure)Z	conditionrWrWrXr6�scCsk|dkrd}tjjtjjtjjt���}|jd|d|d|�}|j|�|S)z�Generic load_tests implementation for simple test packages.

    Most packages can implement load_tests using this function as follows:

       def load_tests(*args):
           return load_package_tests(os.path.dirname(__file__), *args)
    Nztest*Z	start_dirZ
top_level_dir�pattern)�os�path�dirname�__file__ZdiscoverZaddTests)Zpkg_dir�loaderZstandard_testsrwZtop_dirZ
package_testsrWrWrXr7�s			
cCs�t|���i}g}t||�z}y^x|D]}t||�q3Wx*|D]"}t||�sQ|j|�qQWtj|�}Wntk
r�d}YnXWdx'|j�D]\}	}
|
tj	|	<q�Wx|D]}tj	|=q�WX|SWdQRXdS)a�Import and return a module, deliberately bypassing sys.modules.

    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.
    N)
r^rrrt�appendr`r
ra�itemsrbrm)riZfreshZblockedrjrpZnames_to_removeZ
fresh_nameZblocked_nameZfresh_moduleZ	orig_name�moduleZname_to_removerWrWrXr�s$





cCsIyt||�}Wn+tk
r@tjd||f��YnX|SdS)z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %rN)�getattr�AttributeErrorrfrg)�objriZ	attributerWrWrXr2
s

�cCs
|adS)N)�_original_stdout)�stdoutrWrWrXrscCs
tptjS)N)r�rbr�rWrWrWrXr#scCs'ytj|=Wntk
r"YnXdS)N)rbrmrs)rirWrWrXr
&s
cGs�y||�SWntk
r�}z_tdkr`td|jj|f�td|j|f�tj|tj�||�SWYdd}~XnXdS)N�z%s: %szre-run %s%r)	�OSErrorr�print�	__class__rSrx�chmod�stat�S_IRWXU)ry�func�args�errrWrWrX�
_force_run,sr��wincCs�||�|r|}n$tjj|�\}}|p:d}d}xR|dkr�tj|�}|rm|n	||ks}dStj|�|d9}qFWtjd|tdd�dS)Nrlg����MbP?g�?r�z)tests may fail, delete still pending for �
stacklevel�)	rxry�split�listdir�time�sleeprZ�warn�RuntimeWarning)r��pathname�waitallrzri�timeout�LrWrWrX�_waitfor7s
	

r�cCsttj|�dS)N)r�rxr)�filenamerWrWrX�_unlinkXsr�cCsttj|�dS)N)r�rx�rmdir)rzrWrWrX�_rmdir[sr�cs<�fdd��t�|dd�tdd�|�dS)Ncs�x�t|tj|�D]�}tjj||�}ytj|�j}WnHtk
r�}z(td||fdt	j
�d}WYdd}~XnXtj|�r�t
�|dd�t|tj|�qt|tj|�qWdS)Nz-support.rmtree(): os.lstat(%r) failed with %s�filerr�T)r�rxr�ry�join�lstat�st_moder�r�rb�
__stderr__r��S_ISDIRr�r�r)ryri�fullname�mode�exc)�
_rmtree_innerrWrXr�_s
z_rmtree.<locals>._rmtree_innerr�TcSst|tj|�S)N)r�rxr�)�prWrWrXrvnsz_rmtree.<locals>.<lambda>)r�)ryrW)r�rX�_rmtree^sr�csWytj|�dSWntk
r)YnX�fdd���|�tj|�dS)Nc
s�x�t|tj|�D]�}tjj||�}ytj|�j}Wntk
rad}YnXtj	|�r��|�t|tj
|�qt|tj|�qWdS)Nr)r�rxr�ryr�r�r�r�r�r�r�r)ryrir�r�)r�rWrXr�zs

z_rmtree.<locals>._rmtree_inner)�shutilrr�rxr�)ryrW)r�rXr�ss


cCs-yt|�Wnttfk
r(YnXdS)N)r��FileNotFoundError�NotADirectoryError)r�rWrWrXr�scCs'yt|�Wntk
r"YnXdS)N)r�r�)rzrWrWrXr��s
r�cCs'yt|�Wntk
r"YnXdS)N)r�r�)ryrWrWrXr�s
cCs]tjj|�}tjjtjj|��}tjj||d�}tj||�|S)aMove a PEP 3147/488 pyc file to its legacy pyc location.

    :param source: The file system path to the source file.  The source file
        does not need to exist, however the PEP 3147/488 pyc file must exist.
    :return: The file system path to the legacy pyc file.
    �c)	r`�util�cache_from_sourcerxryrz�abspathr��rename)�sourceZpyc_fileZup_oneZ
legacy_pycrWrWrX�make_legacy_pyc�s
r�cCsvt|�xetjD]Z}tjj||d�}t|d�x*dD]"}ttjj|d|��qHWqWdS)	z�'Forget' a module was ever imported.

    This removes the module from sys.modules and deletes any PEP 3147/488 or
    legacy .pyc files.
    z.pyr��r�r��optimizationN)r�r�r�)	r
rbryrxr�rr`r�r�)rqrzr��optrWrWrXr�s

cs�ttd�rtjSd}tjjd�rddl�ddl�d}d}G�fdd�d�j�}�j	j
}|j�}|s��j��|�}�j
j�}|j||�j|��j|��j|��}|s��j��t|j|@�s�d}n�tjdkr�dd	lm}	m�m}
m}dd
lm}|	j|d��}
|
j�dkr�d}naG�fd
d�d|�}|�}|
|�}|
j|�dks�|
j|�dkr�d}|s�y;ddlm}|�}|j�|j �|j!�Wnrt"k
r�}zRt#|�}t$|�dkrq|dd�d}dj%t&|�j'|�}WYdd}~XnX|t_(|t_tjS)N�resultr�rr�csCeZdZd�jjfd�jjfd�jjfgZdS)z*_is_gui_available.<locals>.USEROBJECTFLAGSZfInheritZ	fReserved�dwFlagsN)rSrTrU�wintypesZBOOL�DWORD�_fields_rW)�ctypesrWrX�USEROBJECTFLAGS�sr�z,gui not available (WSF_VISIBLE flag not set)�darwin)�cdll�c_int�pointer�	Structure)�find_libraryZApplicationServicesz0gui tests cannot run without OS X window managercs(eZdZd�fd�fgZdS)z._is_gui_available.<locals>.ProcessSerialNumberZ
highLongOfPSNZlowLongOfPSNN)rSrTrUr�rW)r�rWrX�ProcessSerialNumber�s	r�z#cannot run without OS X gui process)�Tk�2z [...]zTk unavailable due to {}: {}))�hasattr�_is_gui_availabler�rbrcrdr�Zctypes.wintypesr��windllZuser32ZGetProcessWindowStationZWinErrorr�r�ZGetUserObjectInformationWZbyrefZsizeof�boolr�r�r�r�Zctypes.utilr�ZLoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterr�Zwithdraw�updateZdestroy�	Exceptionrh�len�format�typerS�reason)r�Z	UOI_FLAGSZWSF_VISIBLEr�Zdll�hZuofZneeded�resr�r�r�r�Zapp_servicesr�ZpsnZpsn_pr��root�eZ
err_stringrW)r�r�rXr��sh			"			

	
r�cCstdkp|tkS)z�Test whether a resource is enabled.

    Known resources are set by regrtest.py.  If not running under regrtest.py,
    all resources are assumed enabled unless use_resources has been set.
    N)r)�resourcerWrWrXrscCsWt|�s.|dkr"d|}t|��|dkrSt�rSttj��dS)z@Raise ResourceDenied if the specified resource is not available.Nz"Use of the %r resource not enabled�gui)rr	r�r�)r�rkrWrWrXr
s
cs��fdd�}|S)z�Decorator raising SkipTest if the OS is `sysname` and the version is less
    than `min_version`.

    For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
    the FreeBSD version is less than 7.2.
    cs4tj�����fdd��}�|_|S)Nc
s�tj��kr�tj�jdd�d}y"ttt|jd���}Wntk
rdYnAX|�kr�djtt	���}t
jd�||f���||�S)N�-r�rrlz(%s version %s or higher required, not %s)rc�system�releaser�re�map�int�
ValueErrorr�rhrfrg)r��kw�version_txt�version�min_version_txt)r��min_version�sysnamerWrX�wrappers"
z:_requires_unix_version.<locals>.decorator.<locals>.wrapper)�	functools�wrapsr�)r�r�)r�r�)r�rX�	decorators'	z)_requires_unix_version.<locals>.decoratorrW)r�r�r�rW)r�r�rX�_requires_unix_versionsr�cGs
td|�S)z�Decorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is
    less than `min_version`.

    For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD
    version is less than 7.2.
    ZFreeBSD)r�)r�rWrWrXr.scGs
td|�S)z�Decorator raising SkipTest if the OS is Linux and the Linux version is
    less than `min_version`.

    For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux
    version is less than 2.6.32.
    ZLinux)r�)r�rWrWrXr 7scs�fdd�}|S)z�Decorator raising SkipTest if the OS is Mac OS X and the OS X
    version if less than min_version.

    For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
    is lesser than 10.5.
    cs1tj����fdd��}�|_|S)Ncs�tjdkr�tj�d}y"ttt|jd���}Wntk
rUYn>X|�kr�djtt	���}t
jd||f���||�S)Nr�rrlz&Mac OS X %s or higher required, not %s)rbrcZmac_verrer�r�r�r�r�rhrfrg)r�r�r�r�r�)r�r�rWrXr�Hs"
z4requires_mac_ver.<locals>.decorator.<locals>.wrapper)r�r�r�)r�r�)r�)r�rXr�Gs$	z#requires_mac_ver.<locals>.decoratorrW)r�r�rW)r�rXr!@sz	127.0.0.1z::1cCs/tj||�}t|�}|j�~|S)a�
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.  Hard coded ports should *NEVER* be used.  As soon as a server
    socket is bound to a hard coded port, the ability to run multiple instances
    of the test simultaneously on the same host is compromised, which makes the
    test a ticking time bomb in a buildbot environment. On Unix buildbots, this
    may simply manifest as a failed test, which can be recovered from without
    intervention in most cases, but on Windows, the entire python process can
    completely and utterly wedge, requiring someone to log in to the buildbot
    and manually kill the affected process.

    (This is easy to reproduce on Windows, unfortunately, and can be traced to
    the SO_REUSEADDR socket option having different semantics on Windows versus
    Unix/Linux.  On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
    listen and then accept connections on identical host/ports.  An EADDRINUSE
    OSError will be raised at some point (depending on the platform and
    the order bind and listen were called on each socket).

    However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
    will ever be raised when attempting to bind two identical host/ports. When
    accept() is called on each socket, the second caller's process will steal
    the port from the first caller, leaving them both in an awkwardly wedged
    state where they'll no longer respond to any signals or graceful kills, and
    must be forcibly killed via OpenProcess()/TerminateProcess().

    The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
    instead of SO_REUSEADDR, which effectively affords the same semantics as
    SO_REUSEADDR on Unix.  Given the propensity of Unix developers in the Open
    Source world compared to Windows ones, this is a common mistake.  A quick
    look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
    openssl.exe is called with the 's_server' option, for example. See
    http://bugs.python.org/issue2550 for more info.  The following site also
    has a very thorough description about the implications of both REUSEADDR
    and EXCLUSIVEADDRUSE on Windows:
    http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)

    XXX: although this approach is a vast improvement on previous attempts to
    elicit unused ports, it rests heavily on the assumption that the ephemeral
    port returned to us by the OS won't immediately be dished back out to some
    other process when we close and delete our temporary socket but before our
    calling code has a chance to bind the returned port.  We can deal with this
    issue if/when we come across it.
    )�socketr?�close)�familyZsocktypeZtempsock�portrWrWrXr>bs
8
cCs
|jtjkr�|jtjkr�ttd�r]|jtjtj�dkr]t	d��ttd�r�dt
jkr�y.|jtjtj�dkr�t	d��Wnt
k
r�YnXttd�r�|jtjtjd�|j|df�|j�d}|S)	a%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 bind()'ing to our host/port for the duration of the test.
    �SO_REUSEADDRr�zHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets!�SO_REUSEPORTZWITHIN_PYTHON_RPM_BUILDzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!�SO_EXCLUSIVEADDRUSEr)r�r��AF_INETr��SOCK_STREAMr�Z
getsockoptZ
SOL_SOCKETr�rrx�environr�r�Z
setsockoptr��bindZgetsockname)�sock�hostr�rWrWrXr?�s $
cCsstjrod}zLy3tjtjtj�}|jtdf�dSWntk
rYYnXWd|rn|j�XdS)z+Check whether IPv6 is enabled on this host.NrTF)r�Zhas_ipv6ZAF_INET6r�r��HOSTv6r�r�)r�rWrWrX�_is_ipv6_enabled�s	
	r�cs%tj���fdd��}|S)z5Skip the test on TLS certificate validation failures.csay�||�WnItk
r\}z)dt|�krGtjd���WYdd}~XnXdS)NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)�IOErrorrhrfrg)r��kwargsr�)rurWrX�dec�sz&system_must_validate_cert.<locals>.dec)r�r�)rur�rW)rurX�system_must_validate_cert�s!	r�r�i�ZdoubleZIEEEztest requires IEEE 754 doublesz
requires zlibz
requires gzipzrequires bz2z
requires lzma�javaz$testz@testz	{}_{}_tmp�æ�İ�Ł�φ�К�א�،�ت�ก� �€u-àòɘŁğr�ZNFD�nt�cer�u-共Ł♡ͣ�ztWARNING: The filename %r CAN be encoded by the filesystem encoding (%s). Unicode filename tests may not be effective��s-��surrogateescape��w����������r�ccs�d}|dkr9tj�}d}tjj|�}nOytj|�d}Wn5tk
r�|si�tjd|t	dd�YnXz	|VWd|r�t
|�XdS)a�Return a context manager that creates a temporary directory.

    Arguments:

      path: the directory to create temporarily.  If omitted or None,
        defaults to creating a temporary directory using tempfile.mkdtemp.

      quiet: if False (the default), the context manager raises an exception
        on error.  Otherwise, if the path is specified and cannot be
        created, only a warning is issued.

    FNTz+tests may fail, unable to create temp dir: r��)�tempfileZmkdtemprxry�realpath�mkdirr�rZr�r�r)ry�quietZdir_createdrWrWrX�temp_dir�s"



	rccsytj�}ytj|�Wn5tk
rT|s6�tjd|tdd�YnXztj�VWdtj|�XdS)agReturn a context manager that changes the current working directory.

    Arguments:

      path: the directory to use as the temporary current working directory.

      quiet: if False (the default), the context manager raises an exception
        on error.  Otherwise, it issues only a warning and keeps the current
        working directory the same.

    z)tests may fail, unable to change CWD to: r�rN)rx�getcwd�chdirr�rZr�r�)ryrZ	saved_dirrWrWrX�
change_cwd�s


rZtempcwdccsDtd|d|��(}t|d|��}|VWdQRXWdQRXdS)a�
    Context manager that temporarily creates and changes the CWD.

    The function temporarily changes the current working directory
    after creating a temporary directory in the current directory with
    name *name*.  If *name* is None, the temporary directory is
    created using tempfile.mkdtemp.

    If *quiet* is False (default) and it is not possible to
    create or change the CWD, an error is raised.  If *quiet* is True,
    only a warning is raised and the original CWD is used.

    ryrN)rr)rirZ	temp_pathZcwd_dirrWrWrXr�s�umaskccs-tj|�}z	dVWdtj|�XdS)z8Context manager that temporarily sets the process umask.N)rxr)rZoldmaskrWrWrXrA�s	�datacCs�tjj|�r|S|dk	r7tjj||�}tgtj}x9|D]1}tjj||�}tjj|�rN|SqNW|S)a[Try to find a file on sys.path or in the test directory.  If it is not
    found the argument passed to the function is returned (this does not
    necessarily signal failure; could still be the legitimate path).

    Setting *subdir* indicates a relative path to use to find the file
    rather than looking directly in the path directories.
    N)rxry�isabsr��
TEST_HOME_DIRrb�exists)r�ZsubdirryZdn�fnrWrWrXr�s
cCs4tj|tjtjBtjB�}tj|�dS)z>Create an empty file. If the file already exists, truncate it.N)rx�open�O_WRONLY�O_CREAT�O_TRUNCr�)r��fdrWrWrXr�s#cCs<t|j��}dd�|D�}dj|�}d|S)z%Like repr(dict), but in sorted order.cSsg|]}d|�qS)z%r: %rrW)�.0ZpairrWrWrX�
<listcomp>s	zsortdict.<locals>.<listcomp>z, z{%s})�sortedr~r�)�dictr~Z	reprpairsZ
withcommasrWrWrXrQscCs9ttd�}z|j�SWd|j�tt�XdS)z`
    Create an invalid file descriptor by opening and closing a file and return
    its fd.
    �wbN)r$r�filenor�r)r�rWrWrX�make_bad_fd	s

r/�lineno�offsetcCs�|jt��}t|dd�WdQRX|j}|j|j�|dk	ra|j|j|�|j|j�|dk	r�|j|j|�dS)Nz
<test string>�exec)�assertRaises�SyntaxError�compileZ	exceptionZassertIsNotNoner0�assertEqualr1)�testcaseZ	statementr0r1�cmr�rWrWrXr"s	cs�ddl}ddl}�jdd��|jj|�djd�d}tjjt	|�}���fdd�}tjj
|�r�||�}|dk	r�|St|�td�t
r�td	|d
t��|jj�}tr�|jjd�|j|d
d�}trC|jjd�dkrCtjd|�}zOt|d��9}	|j�}
x#|
r�|	j|
�|j�}
qgWWdQRXWd|j�X||�}|dk	r�|Std|��dS)Nr�checkr��/r�csMt|���}�dkr"|S�|�r?|jd�|S|j�dS)Nr)r$�seekr�)r#ru)r�r9r�rWrX�check_valid_file)s
z*open_urlresource.<locals>.check_valid_fileZurlfetchz	fetching %s ...r��Accept-Encoding�gzipr��zContent-EncodingZfileobjr-zinvalid resource %r���)r=r>)Zurllib.requestZurllib.parse�pop�parseZurlparser�rxryr��
TEST_DATA_DIRr"rrrr�rZrequestZbuild_openerr>Z
addheadersr}r$Zheaders�getZGzipFile�read�writer�r)Zurlr�r��urllibr�r#r<ruZopener�out�srW)r�r9r�rXr@ s<#	

	
c@sLeZdZdZdd�Zdd�Zedd��Zdd	�Zd
S)�WarningsRecorderzyConvenience wrapper for the warnings list returned on
       entry to the warnings.catch_warnings() context manager.
    cCs||_d|_dS)Nr)�	_warnings�_last)�selfZ
warnings_listrWrWrX�__init__Vs	zWarningsRecorder.__init__cCs\t|j�|jkr,t|jd|�S|tjjkrBdStd||f��dS)Nr�z%r has no attribute %rr@)r�rKrLr�rZ�WarningMessage�_WARNING_DETAILSr�)rM�attrrWrWrX�__getattr__Zs
zWarningsRecorder.__getattr__cCs|j|jd�S)N)rKrL)rMrWrWrXrZaszWarningsRecorder.warningscCst|j�|_dS)N)r�rKrL)rMrWrWrX�reseteszWarningsRecorder.resetN)	rSrTrUrVrNrR�propertyrZrSrWrWrWrXrJRs
rJc
cs^tjd�}|jjd�}|r1|j�tjdd��&}tjdjd�t	|�VWdQRXt
|�}g}x�|D]�\}}d}	xd|dd�D]R}|j}
tj
|t|
�tj�r�t|
j|�r�d}	|j|�q�W|	r�|r�|j||jf�q�W|r@td	|d
��|rZtd|d
��dS)z�Catch the warnings, then check if all the expected
    warnings have been raised and re-raise unexpected warnings.
    If 'quiet' is True, only re-raise the unexpected warnings.
    r�Z__warningregistry__�recordTrZ�alwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)rb�	_getframe�	f_globalsrD�clearrZr[rm�simplefilterrJro�message�re�matchrh�I�
issubclassr��remover}rS�AssertionError)�filtersr�frame�registry�wZreraiseZmissingrk�cat�seenZwarningrWrWrX�_filterwarningsis0
	rhcOsC|jd�}|s6dtff}|dkr6d}t||�S)a�Context manager to silence warnings.

    Accept 2-tuples as positional arguments:
        ("message regexp", WarningCategory)

    Optional argument:
     - if 'quiet' is True, it does not fail if a filter catches nothing
        (default True without argument,
         default False if some filters are defined)

    Without argument, it defaults to:
        check_warnings(("", Warning), quiet=True)
    rr�NT)rD�Warningrh)rbr�rrWrWrXrH�sccsOtjdd��&}tjddt�dVt�WdQRX|j|g�dS)a"Context manager to check that no ResourceWarning is emitted.

    Usage:

        with check_no_resource_warning(self):
            f = open(...)
            ...
            del f

    You must remove the object which may emit ResourceWarning before
    the end of the context manager.
    rUTrV�categoryN)rZr[r\�ResourceWarning�
gc_collectr6)r7ZwarnsrWrWrXrI�s
c@s:eZdZdZdd�Zdd�Zdd�ZdS)	ra,Context manager to force import to return a new module reference.

    This is useful for testing module-level behaviours, such as
    the emission of a DeprecationWarning on import.

    Use like this:

        with CleanImport("foo"):
            importlib.import_module("foo") # new reference
    cGsitjj�|_xP|D]H}|tjkrtj|}|j|krWtj|j=tj|=qWdS)N)rbrm�copy�original_modulesrS)rMZmodule_namesZmodule_namerrWrWrXrN�s


zCleanImport.__init__cCs|S)NrW)rMrWrWrX�	__enter__�szCleanImport.__enter__cGstjj|j�dS)N)rbrmr�rn)rM�
ignore_excrWrWrX�__exit__�szCleanImport.__exit__N)rSrTrUrVrNrorqrWrWrWrXr�s

c@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZdS)rJz_Class to help protect the environment variable properly.  Can be used as
    a context manager.cCstj|_i|_dS)N)rxr��_environ�_changed)rMrWrWrXrN�szEnvironmentVarGuard.__init__cCs|j|S)N)rr)rM�envvarrWrWrX�__getitem__�szEnvironmentVarGuard.__getitem__cCs9||jkr(|jj|�|j|<||j|<dS)N)rsrrrD)rMrt�valuerWrWrX�__setitem__�szEnvironmentVarGuard.__setitem__cCsE||jkr(|jj|�|j|<||jkrA|j|=dS)N)rsrrrD)rMrtrWrWrX�__delitem__�szEnvironmentVarGuard.__delitem__cCs
|jj�S)N)rr�keys)rMrWrWrXry�szEnvironmentVarGuard.keyscCs
t|j�S)N)�iterrr)rMrWrWrX�__iter__�szEnvironmentVarGuard.__iter__cCs
t|j�S)N)r�rr)rMrWrWrX�__len__�szEnvironmentVarGuard.__len__cCs|||<dS)NrW)rMrtrvrWrWrX�set�szEnvironmentVarGuard.setcCs||=dS)NrW)rMrtrWrWrX�unsetszEnvironmentVarGuard.unsetcCs|S)NrW)rMrWrWrXroszEnvironmentVarGuard.__enter__cGsexR|jj�D]A\}}|dkrD||jkrQ|j|=q||j|<qW|jt_dS)N)rsr~rrrxr�)rMrp�k�vrWrWrXrqs
zEnvironmentVarGuard.__exit__N)rSrTrUrVrNrurwrxryr{r|r}r~rorqrWrWrWrXrJ�sc@s:eZdZdZdd�Zdd�Zdd�ZdS)	�
DirsOnSysPatha�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.
    cGs6tjdd�|_tj|_tjj|�dS)N)rbry�original_value�original_object�extend)rM�pathsrWrWrXrNszDirsOnSysPath.__init__cCs|S)NrW)rMrWrWrXro#szDirsOnSysPath.__enter__cGs&|jt_|jtjdd�<dS)N)r�rbryr�)rMrprWrWrXrq&szDirsOnSysPath.__exit__N)rSrTrUrVrNrorqrWrWrWrXr�s
r�c@sCeZdZdZdd�Zdd�Zddddd�ZdS)	r#z�Raise ResourceDenied if an exception is raised while the context manager
    is in effect that matches the specified exception and attributes.cKs||_||_dS)N)r��attrs)rMr�r�rWrWrXrN0s	zTransientResource.__init__cCs|S)NrW)rMrWrWrXro4szTransientResource.__enter__NcCst|dk	rpt|j|�rpxO|jj�D]2\}}t||�sJPt||�|kr.Pq.Wtd��dS)z�If type_ is a subclass of self.exc and value has attributes matching
        self.attrs, raise ResourceDenied.  Otherwise let the exception
        propagate (if any).Nz%an optional resource is not available)r_r�r�r~r�r�r	)rMZtype_rv�	tracebackrQZ
attr_valuerWrWrXrq7szTransientResource.__exit__)rSrTrUrVrNrorqrWrWrWrXr#+s�errnor�g>@�errnosc	#s�dd d!d"d#g}d%d'd)d+d,g}td|��|�g��srdd�|D��dd�|D�����fdd�}tj�}z!y"|dk	r�tj|�dVWn�tjk
r}z/tr�tjj	�j
dd��|�WYdd}~Xn�tk
r�}z�xr|j
}t|�dkr_t
|dt�r_|d}q$t|�dkr�t
|dt�r�|d}q$Pq$W||��WYdd}~XnXWdtj|�XdS)-z�Return a context manager that raises ResourceDenied when various issues
    with the Internet connection manifest themselves as exceptions.�ECONNREFUSED�o�
ECONNRESET�h�EHOSTUNREACH�q�ENETUNREACH�e�	ETIMEDOUT�n�	EAI_AGAINr�EAI_FAILr��
EAI_NONAMEr��
EAI_NODATA��
WSANO_DATA�*zResource %r is not availablecSs(g|]\}}tt||��qSrW)r�r�)r)ri�numrWrWrXr*ds	z&transient_internet.<locals>.<listcomp>cSs(g|]\}}tt||��qSrW)r�r�)r)rir�rWrWrXr*fs	cs�t|dd�}t|tj�s�t|tj�rB|�ks�t|tjj�rvd|jkoqdkns�t|tjj	�r�d|j
ks�d|j
ks�d|j
ks�|�kr�ts�tj
j�jdd��|�dS)	Nr�i�iW�ConnectionRefusedError�TimeoutError�EOFErrorr�
)r��
isinstancer�r�ZgaierrorrG�errorZ	HTTPError�codeZURLErrorr�rrb�stderrrFr�)r��n)�captured_errnos�denied�
gai_errnosrWrX�filter_errorisz(transient_internet.<locals>.filter_errorNrr�r�)r�r�)r�r�)r�r�)r�r�)r�r����)r�r����)r�r����)r�r����)r�r�)r�r�)r	r�ZgetdefaulttimeoutZsetdefaulttimeout�nntplibZNNTPTemporaryErrorrrbr�rFr�r�r�r�)	Z
resource_namer�r�Zdefault_errnosZdefault_gai_errnosr�Zold_timeoutr��arW)r�r�r�rXr'LsN			
	

		%
%

c
cs[ddl}tt|�}tt||j��ztt|�VWdtt||�XdS)z�Return a context manager used by captured_stdout/stdin/stderr
    that temporarily replaces the sys stream *stream_name* with a StringIO.rN)�ior�rb�setattr�StringIO)Zstream_namer�Zorig_stdoutrWrWrX�captured_output�sr�cCs
td�S)z�Capture the output of sys.stdout:

       with captured_stdout() as stdout:
           print("hello")
       self.assertEqual(stdout.getvalue(), "hello\n")
    r�)r�rWrWrWrXr�scCs
td�S)z�Capture the output of sys.stderr:

       with captured_stderr() as stderr:
           print("hello", file=sys.stderr)
       self.assertEqual(stderr.getvalue(), "hello\n")
    r�)r�rWrWrWrXr�scCs
td�S)a	Capture the input to sys.stdin:

       with captured_stdin() as stdin:
           stdin.write('hello\n')
           stdin.seek(0)
           # call test code that consumes from sys.stdin
           captured = input()
       self.assertEqual(captured, "hello")
    �stdin)r�rWrWrWrXr�s
cCs5tj�trtjd�tj�tj�dS)a�Force as many objects as possible to be collected.

    In non-CPython implementations of Python, this is needed because timely
    deallocation is not guaranteed by the garbage collector.  (Even in CPython
    this can be the case in case of reference cycles.)  This means that __del__
    methods may be called later than expected and weakrefs may remain alive for
    longer than expected.  This function tries its best to force all garbage
    objects to disappear.
    g�������?N)�gcZcollectr:r�r�rWrWrWrXrl�s




rlc
cs7tj�}tj�z	dVWd|r2tj�XdS)N)r��	isenabled�disable�enable)Zhave_gcrWrWrX�
disable_gc�s
	r�cCsQtjd�pd}d}x)|j�D]}|jd�r(|}q(W|dkS)z,Find if Python was built with optimizations.�	PY_CFLAGSr�z-O�-O0�-Og)r�r�r�)�	sysconfig�get_config_varr�rd)ZcflagsZ	final_optr�rWrWrX�python_is_optimized�s
r�ZnPZ0n�gettotalrefcountZ2PZ0Pr�cCstjt|t�S)N)�struct�calcsize�_header�_align)�fmtrWrWrX�calcobjsize�sr�cCstjt|t�S)N)r�r��_vheaderr�)r�rWrWrX�calcvobjsize�sr���	cCs�ddl}tj|�}t|�tkr:|jt@s_t|�tkrlt|�jt@rl||j7}dt|�||f}|j|||�dS)Nrz&wrong size for %s: got %d, expected %d)	�	_testcapirb�	getsizeofr��	__flags__�_TPFLAGS_HEAPTYPE�_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADr6)�test�o�sizer�r�rkrWrWrX�check_sizeof�s%
r�cs��fdd�}|S)Ncs4���fdd�}�j|_�j|_|S)Ncs�y.ddl}t|��}|j|�}Wn&tk
rE�YnCd}}Yn2Xx.�D]&}y|j||�PWq^Yq^Xq^Wz�||�SWd|r�|r�|j||�XdS)Nr)�localer��	setlocaler�)r��kwdsr�rjZorig_locale�loc)�catstrr��localesrWrX�inner	s$

	z1run_with_locale.<locals>.decorator.<locals>.inner)rSrV)r�r�)r�r�)r�rXr�sz"run_with_locale.<locals>.decoratorrW)r�r�r�rW)r�r�rXrKscs�fdd�}|S)Ncs1��fdd�}�j|_�j|_|S)Ncs�y
tj}Wn!tk
r0tjd��YnXdtjkrPtjd}nd}�tjd<|�z�||�SWd|dkr�tjd=n
|tjd<tj�XdS)Nztzset requiredZTZ)r��tzsetr�rfrgrxr�)r�r�r�Zorig_tz)r��tzrWrXr�-s




z-run_with_tz.<locals>.decorator.<locals>.inner)rSrV)r�r�)r�)r�rXr�,szrun_with_tz.<locals>.decoratorrW)r�r�rW)r�rXrR+sc	Cs�dddtdtddti}tjd|tjtjB�}|dkr`td|f��tt|j	d��||j	d	�j
��}|a|tkr�t}|t
dkr�td
|f��|adS)Nri�m�g�tz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rr�rz$Memory limit %r too low to be useful)�_1M�_1Gr\r]�
IGNORECASE�VERBOSEr�r��float�group�lower�real_max_memuse�MAX_Py_ssize_t�_2Gr)�limitZsizesr�ZmemlimitrWrWrXrOUs2c@s:eZdZdZdd�Zdd�Zdd�ZdS)	�_MemoryWatchdogz`An object which periodically watches the process' memory consumption
    and prints it out.
    cCs(djdtj��|_d|_dS)Nz/proc/{pid}/statm�pidF)r�rx�getpid�procfile�started)rMrWrWrXrNosz_MemoryWatchdog.__init__cCs�yt|jd�}WnOtk
rg}z/tjdj|�t�tjj	�dSWYdd}~XnXt
d�}tjtj
|gd|dtj�|_|j�d|_dS)N�rz!/proc not available for stats: {}zmemory_watchdog.pyr�r�T)r$r�r�rZr�r�r�rbr��flushr�
subprocess�Popen�
executableZDEVNULL�mem_watchdogr�r�)rMrur�Zwatchdog_scriptrWrWrX�startss

z_MemoryWatchdog.startcCs'|jr#|jj�|jj�dS)N)r�r�Z	terminate�wait)rMrWrWrX�stop�s	
z_MemoryWatchdog.stopN)rSrTrUrVrNr�r�rWrWrWrXr�jsr�cs���fdd�}|S)atDecorator 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.
    cs.���fdd����_��_�S)Nc
s��j}�j}ts!d}n|}ts4�r_t||kr_tjd||d��tr�tr�t�tdjd||d��t�}|j	�nd}z�||�SWd|r�|j
�XdS)	Niz'not enough memory: %.1fG minimum neededirz* ... expected peak memory use: {peak:.1f}GZpeaki@i@)r��memuser�rfrgrr�r�r�r�r�)rMr�r��maxsizeZwatchdog)�dry_runrur�rWrXr��s*			
	
z.bigmemtest.<locals>.decorator.<locals>.wrapper)r�r�)ru)r�r�r�)rur�rXr��s		zbigmemtest.<locals>.decoratorrW)r�r�r�r�rW)r�r�r�rXr/�s
!cs�fdd�}|S)z0Decorator for tests that fill the address space.cs^ttkrPtd
kr6tdkr6tjd��qZtjdtd��n
�|�SdS)
Nr��?r��z-not enough memory: try a 32-bit build insteadz'not enough memory: %.1fG minimum neededirll����li@)rr�rfrg)rM)rurWrXr��sz!bigaddrspacetest.<locals>.wrapperrW)rur�rW)rurXr0�sc@seZdZdd�ZdS)r(cCstj�}||�|S)N)rfZ
TestResult)rMr�r�rWrWrX�run�s
zBasicTestRunner.runN)rSrTrUr�rWrWrWrXr(�scCs|S)NrW)r�rWrWrX�_id�sr�cCsP|dkr&t�r&tjtj�St|�r6tStjdj|��SdS)Nr�zresource {0!r} is not enabled)r�rf�skipr�rr�r�)r�rWrWrX�requires_resource�s
rcCstdd�|�S)z9
    Decorator for tests only applicable on CPython.
    �cpythonT)�impl_detail)r�rWrWrXr1�scKszt|�rtS|dkrmt|�\}}|r=d}nd}t|j��}|jdj|��}tj|�S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or )	r;r��
_parse_guardsr+ryr�r�rfr�)rk�guardsZ
guardnames�defaultrWrWrXr�s	rcCsjtdkrGddl}y|j�daWntk
rFdaYnXd}trW|Stj|�|�S)z8Skip decorator for tests that use multiprocessing.Queue.NrTFz6requires a functioning shared semaphore implementation)�_have_mp_queue�multiprocessingZQueuerarfr�)r�rrkrWrWrXr9�s


cCsb|sddidfSt|j��d}t|j��|gt|�ksWt�||fS)NrTFr)ro�valuesr�ra)rZis_truerWrWrXr�s
+rcKs.t|�\}}|jtj�j�|�S)a5This function returns True or False depending on the host platform.
       Examples:
          if check_impl_detail():               # only on CPython (default)
          if check_impl_detail(jython=True):    # only on Jython
          if check_impl_detail(cpython=False):  # everywhere except on CPython
    )rrDrcZpython_implementationr�)rrrWrWrXr;scs<ttd�s�Stj���fdd��}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.�gettracecs?tj�}ztjd��||�SWdtj|�XdS)N)rbr	�settrace)r�r�Zoriginal_trace)r�rWrXr�s

zno_tracing.<locals>.wrapperN)r�rbr�r�)r�r�rW)r�rX�
no_tracings!rcCstt|��S)aDecorator for tests which involve reference counting.

    To start, the decorator does not run the test if is not run by CPython.
    After that, any trace function is unset during the test to prevent
    unexpected refcounts caused by the trace function.

    )rr1)r�rWrWrX�
refcount_test#srcCsog}xY|jD]N}t|tj�rEt||�|j|�q||�r|j|�qW||_dS)z>Recursively filter test cases in a suite based on a predicate.N)Z_testsr�rf�	TestSuite�
_filter_suiter})�suiteZpredZnewtestsr�rWrWrXr.s
rcCs�tr'tjtjdddt�}n	t�}|j|�}|j�s�t	|j
�dkr~|jr~|j
dd}nIt	|j�dkr�|j
r�|jdd}nd}ts�|d7}t|��dS)	z2Run tests from a unittest.TestSuite-derived class.�	verbosityr�rr�rzmultiple errors occurredz!; run in verbose mode for detailsN)
rrfZTextTestRunnerrbr�rr(r�Z
wasSuccessfulr��errorsZfailuresr)rZrunnerr�r�rWrWrX�
_run_suite:s	
rcCswtdkrdS|j�}xTtD]L}tj||�r?dSx-|jd�D]}tj||�rOdSqOWq#WdS)NTrlF)�match_tests�id�fnmatchZfnmatchcaser�)r�Ztest_idZ
match_testrirWrWrX�_match_testNs
rcGs�tjtjf}tj�}x�|D]�}t|t�rx|tjkri|jtjtj|��q�t	d��q%t||�r�|j|�q%|jtj
|��q%Wt|t�t
|�dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesN)rfr
ZTestCaser�rhrbrmZaddTestZ
findTestCasesr�Z	makeSuiterrr)�classesZvalid_typesr�clsrWrWrXr)_s
 
cCsdS)z,Just used to check if docstrings are enabledNrWrWrWrWrX�_check_docstringsvsr�win32�WITH_DOC_STRINGSztest requires docstringscCs�ddl}|dkr!t}nd}|j|d|d|�\}}|rdtd||f��tr�td|j|f�||fS)aRun doctest on the given module.  Return (#failures, #tests).

    If optional argument verbosity is not specified (or is None), pass
    support's belief about verbosity on to doctest.  Else doctest's
    usual behavior is used (it searches sys.argv for -v).
    rNr�optionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)�doctestrZtestmodrr�rS)rrrrrur�rWrWrXr*�s	!cCstjj�fS)N)rbrmrmrWrWrWrX�
modules_setup�srcCsMdd�tjj�D�}tjj�tjj|�tjj|�dS)NcSs1g|]'\}}|jd�r||f�qS)z
encodings.)rd)r)rr�rWrWrXr*�s		z#modules_cleanup.<locals>.<listcomp>)rbrmr~rYr�)Z
oldmodules�	encodingsrWrWrX�modules_cleanup�s
r cCs-trtj�tjj�fSdffSdS)Nr�)�_thread�_count�	threading�	_danglingrmrWrWrWrXrD�scGsats
dSd}xJt|�D]<}tj�tjf}||krEPtjd�t�qWdS)N�dg{�G�z�?)r!�ranger"r#r$r�r�rl)Zoriginal_valuesZ
_MAX_COUNT�countrrWrWrXrE�s
cs/ts
�Stj���fdd��}|S)z�Use this function when threads are being used.  This will
    ensure that the threads are cleaned up even when the test fails.
    If threading is unavailable this function does nothing.
    cs)t�}z�|�SWdt|�XdS)N)rDrE)r��key)r�rWrXr��s	zreap_threads.<locals>.decorator)r!r�r�)r�r�rW)r�rXrF�s!c	CsXttd�rTd}x<y,tj|tj�\}}|dkrCPWqPYqXqWdS)z�Use this function 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.
    �waitpidr�rNr@)r�rxr)�WNOHANG)Zany_processr�ZstatusrWrWrXrB�s	ccsvt|�}g}ziy,x%|D]}|j�|j|�qWWn1trmtdt|�t|�f��YnXdVWdz�|r�|�tj�}}x�tdd�D]{}|d7}x.|D]&}|jt	|tj�d��q�Wdd�|D�}|s	Ptr�tdt|�|f�q�WWdd	d�|D�}|rpt
jtj
�td
t|���XXdS)Nz/Can't start %d threads, only %d threads startedr�r�<g{�G�z�?cSs"g|]}|j�r|�qSrW)�isAlive)r)r�rWrWrXr*s	z!start_threads.<locals>.<listcomp>z7Unable to join %d threads during a period of %d minutescSs"g|]}|j�r|�qSrW)r,)r)r�rWrWrXr*s	zUnable to join %d threads)ror�r}rr�r�r�r&r��max�faulthandlerZdump_tracebackrbr�ra)ZthreadsZunlockr�r�ZendtimeZ	starttimer�rWrWrXrG�s>

	

$c
cs�t||�rNt||�}t|||�z	|VWdt|||�Xn9t|||�z	dVWdt||�r�t||�XdS)a�Temporary swap out an attribute with a new object.

    Usage:
        with swap_attr(obj, "attr", 5):
            ...

        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.
    N)r�r�r��delattr)r�rQ�new_val�real_valrWrWrXrMs		ccsh||kr:||}|||<z	|VWd|||<Xn*|||<z	dVWd||krc||=XdS)a�Temporary swap out an item with a new object.

    Usage:
        with swap_item(obj, "item", 5):
            ...

        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.
    NrW)r��itemr0r1rWrWrXrL:s

	
	cCstjdd|�j�}|S)z�Strip the stderr of a Python process from potential debug output
    emitted by the interpreter.

    This will typically be run on the result of the communicate() method
    of a subprocess.Popen object.
    s\[\d+ refs, \d+ blocks\]\r?\n?�)r\�sub�strip)r�rWrWrX�strip_python_stderrYsr6Z	getcountsz-types are immortal if COUNT_ALLOCS is definedcCs
tj�S)znReturn a list of command-line arguments reproducing the current
    settings in sys.flags and sys.warnoptions.)r�Z_args_from_interpreter_flagsrWrWrWrX�args_from_interpreter_flagsfsr7c@s@eZdZdd�Zdd�Zdd�Zdd�Zd	S)
rCcCs#tjjj|d�||_dS)Nr)�logging�handlers�BufferingHandlerrN�matcher)rMr;rWrWrXrNpszTestHandler.__init__cCsdS)NFrW)rMrWrWrX�shouldFlushyszTestHandler.shouldFlushcCs$|j|�|jj|j�dS)N)r��bufferr}�__dict__)rMrUrWrWrX�emit|s
zTestHandler.emitcKs:d}x-|jD]"}|jj||�rd}PqW|S)zW
        Look for a saved dict whose keys/values match the supplied arguments.
        FT)r=r;�matches)rMr�r��drWrWrXr@�szTestHandler.matchesN)rSrTrUrNr<r?r@rWrWrWrXrCos	c@s.eZdZdZdd�Zdd�ZdS)	rNrkr[cKsPd}xC|D];}||}|j|�}|j|||�s
d}Pq
W|S)a.
        Try to match a single dict with the supplied arguments.

        Keys whose values are strings and which are in self._partial_matches
        will be checked for partial (i.e. substring) matches. You can extend
        this scheme to (for example) do regular expression matching, etc.
        TF)rD�match_value)rMrAr�r�rr��dvrWrWrXr@�s

zMatcher.matchescCsjt|�t|�kr!d}nEt|�tk	sB||jkrQ||k}n|j|�dk}|S)zT
        Try to match a single stored value (dv) with a supplied value (v).
        Fr)r�rh�_partial_matches�find)rMrrCr�r�rWrWrXrB�s	!zMatcher.match_valueN)rkr[)rSrTrUrDr@rBrWrWrWrXrN�sc
Csotdk	rtStd}ytjt|�d}Wn!tttfk
rWd}YnXtj|�|a|S)NrTF)�_can_symlinkrrx�symlinkr��NotImplementedErrorr�r`)Zsymlink_path�canrWrWrXr�s


cCs,t�}d}|r|Stj|�|�S)z8Skip decorator for tests that require functional symlinkz*Requires functional symlink implementation)rrfr�)r��okrkrWrWrXr+�s	cCs	tdk	rtSttd�s(d}n�tj�\}}z�ttd���}yutj|dd�tj|j�dd�t	j
�}tjd|�}|dkp�t
|jd��dk}Wntk
r�d}YnXWdQRXWdtt�t|�X|a|S)	N�setxattrFr-s	user.testr3z
2.6.(\d{1,2})r��')�
_can_xattrr�rxrZmkstempr$rrKr.rcr�r\r]r�r�r�r)rIZtmp_fpZtmp_name�fpZkernel_versionr�rWrWrX�	can_xattr�s&	+

rOcCs,t�}d}|r|Stj|�|�S)zDSkip decorator for tests that require functional extended attributesz(no non-broken extended attribute support)rOrfr�)r�rJrkrWrWrXr4�s	cCs}tjd|��d}|j}|j�}||krB|j�}ytjj||�SWntk
rqdSYnXWdQRXdS)zKDetects if the file system for the specified directory is case-insensitive.�dirFN)	rZNamedTemporaryFileri�upperr�rxry�samefiler�)Z	directory�base�	base_pathZ	case_pathrWrWrXr�s	
rYcCsUtt|��tt|��}|r8|t|�8}tdd�|D��}|S)aReturns the set of items in ref_api not in other_api, except for a
    defined list of items to be ignored in this check.

    By default this skips private attributes beginning with '_' but
    includes all magic methods, i.e. those starting and ending in '__'.
    css4|]*}|jd�s(|jd�r|VqdS)�_�__N)rd�endswith)r)r�rWrWrX�	<genexpr>�sz&detect_api_mismatch.<locals>.<genexpr>)r}rP)Zref_apiZ	other_apirYZ
missing_itemsrWrWrXr8�s
"c@s:eZdZdZdZdZdd�Zdd�ZdS)rPz�Try to prevent a crash report from popping up.

    On Windows, don't display the Windows Error Reporting dialog.  On UNIX,
    disable the creation of coredump file.
    Nc
Cs�tjjd�r�ddl}|jj|_d}|jj|�|_|jj|j|B�yddl	}|j
Wnttfk
r�Yq�Xi|_
xH|j|j|jgD]C}|j
||j�}|j||j�}||f|j
|<q�Wn�tdk	r]y9tjtj�|_tjtjd|jdf�Wnttfk
r\YnXtjdkr�ddd	d
g}tj|dtjdtj�}|�|j�d}	WdQRX|	j�d
kr�tddddd�|S)z�On Windows, disable Windows Error Reporting dialogs using
        SetErrorMode.

        On UNIX, try to save the previous core file size limit, then set
        soft limit to 0.
        r�rNr�r�r�z/usr/bin/defaultsrEzcom.apple.CrashReporterZ
DialogTyper�r�s	developerz:this test triggers the Crash Reporter, that is intentional�endr�r�T) rbrcrdr�r�Zkernel32�_k32�SetErrorMode�	old_value�msvcrt�CrtSetReportModer�ra�	old_modesZCRT_WARNZ	CRT_ERRORZ
CRT_ASSERTZCRTDBG_MODE_FILE�CrtSetReportFileZCRTDBG_FILE_STDERRr�Z	getrlimit�RLIMIT_CORE�	setrlimitr�r�r�r��PIPEZcommunicater5r�)
rMr�ZSEM_NOGPFAULTERRORBOXr]�report_type�old_mode�old_file�cmd�procr�rWrWrXro	sN						
zSuppressCrashReport.__enter__cGs�|jdkrdStjjd�r�|jj|j�|jr�ddl}x�|jj�D]2\}\}}|j	||�|j
||�q]WnAtdk	r�ytjtj
|j�Wnttfk
r�YnXdS)zARestore Windows ErrorMode or core file behavior to initial value.Nr�r)r\rbrcrdrZr[r_r]r~r^r`r�rbrar�r�)rMrpr]rdrerfrWrWrXrqL	s	"zSuppressCrashReport.__exit__)rSrTrUrVr\r_rorqrWrWrWrXrP	s
Acs�t���d�y�j��Wn*ttfk
rPt��d��YnXd�����fdd�}|j|�t��|�dS)z�Override 'object_to_patch'.'attr_name' with 'new_value'.

    Also, add a cleanup procedure to 'test_instance' to restore
    'object_to_patch' value for 'attr_name'.
    The 'attr_name' should be a valid attribute for 'object_to_patch'.

    FNTcs*�rt����n
t���dS)N)r�r/rW)�
attr_is_local�	attr_name�object_to_patchr\rWrX�cleanupw	szpatch.<locals>.cleanup)r�r>r�rsZ
addCleanupr�)Z
test_instancerkrjZ	new_valuerlrW)rirjrkr\rX�patcha	s


rmcCsYyddl}Wntk
r$YnX|j�r@tjd��ddl}|j|�S)zi
    Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
    module is enabled.
    rNzUrun_in_subinterp() cannot be used if tracemalloc module is tracing memory allocations)�tracemallocraZ
is_tracingrfrgr��run_in_subinterp)r�rnr�rWrWrXro�	s
rocsbG��fdd�d|�}d�|||���|jtt��t�|j��dS)Ncs%eZdZ��fdd�ZdS)z%check_free_after_iterating.<locals>.Acs-d�yt��Wntk
r(YnXdS)NT)�next�
StopIteration)rM)�done�itrWrX�__del__�	s

z-check_free_after_iterating.<locals>.A.__del__N)rSrTrUrtrW)rrrsrWrX�A�	sruF)r3rqrprlZ
assertTrue)r�rzrr�rurW)rrrsrX�check_free_after_iterating�	s	rvii@i@i@ii)rrrrrrrr	r
rr)r
r)rrrrri@ii)�rVrSra�collections.abc�collections�
contextlibr�r.rr�r�r`�importlib.utilZlogging.handlersr8r�rxrcr\r�r�r�r�r�rbr�rr�rfZurllib.errorrGrZr!r#Zmultiprocessing.processr�zlibr>�bz2Zlzmar��__all__r�rrrgr	�contextmanagerr^r
rrrtr6r7rr2rrrr�rrr�rrr
r�rdr�r�r�r�rr�rr�rr�rrr�rr r!r<r�r�r�r>r?r�r=r�rZ
SOCK_MAX_SIZEZ
skipUnlessr��
__getformat__r3r5r,r-r.r:rirr�r�ZFS_NONASCII�	character�fsdecode�fsencode�UnicodeErrorZTESTFN_UNICODEZunicodedata�	normalize�getfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversion�encode�UnicodeEncodeErrorr��decode�UnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIrrrrrr�rAryrzr�r{ZTEST_SUPPORT_DIRr!r�rCrrrQr/r"r@�objectrJrhrHrIr�abc�MutableMappingrJr�r#r�r�r$r�r%r&r'r�rrrrlr�r�r�r�r�r�r�r�r�r�rKrRr�r�r�Z_4Gr�r�rOr�r/r0r(r�rr1rrr9rr;rrrrrr)rr�ZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr*rr rDrErFrBrGrMrLr6ZskipIfZrequires_type_collectingr7r9r:rCrNrFrr+rMrOr4rr8rPrmrorvrWrWrWrX�<module>sv






										
2	
!		
J			>&			




	



!2' 5	J		



$#


	0

			#
		"
_"