U
    gl                 b   @   s  d Z edkredddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl!Z!ddl"Z"ddl#Z#ddl$Z$ddl%Z&ddl'Z'ddl(m)Z) zddl*Z+W n ek
rN   dZ+Y nX zddl,Z,W n ek
rv   dZ,Y nX zddl-Z-W n ek
r   dZ-Y nX zddl.Z.W n ek
r   dZ.Y nX zddl/Z/W n ek
r   dZ/Y nX zddl0Z0W n ek
r   dZ0Y nX zddl1Z1W n ek
r>   dZ1Y nX ddd	d
dddddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhgbZ2G did de3Z4G djd de4Z5G dkd de4Z6G dld de$j7Z8ej9ddndoZ:dpdD Z;ddrdsdtdZ<dudv Z=dwdx Z>dyd> Z?dzd? Z@dd{dZAd|d: ZBdZCdZDdaEdaFdZGdqZHdaId}d ZJd~d ZKdd ZLdd ZMejNdr"dddZOdd ZPdd ZQdd ZRdd ZSnejTZPejUZQdd ZRdd ZSdd ZTdd ZUdd ZVdd ZWdd ZXdd ZYdd# ZZddd$Z[dd Z\dd% Z]dd& Z^dd' Z_ddd(Z`dZadZbdZcejdejefddLZfeafddMZgddO Zhdd Ziei Zjdd ZkdZldZme$neopdNddZqe$ne,dZre$ne-dZse$ne.dZte$ne/dZuejNdZvewedZxejdkrxexrrdndZyndZyejzdkrdZ{ndZ{d|e{e} Z{dZ~dZdD ]FZzeeeekreW n ek
r   Y nX eZ qqe{d ZejdkrddlZedeZe ZdZejzdkre jdkre{d Zzee W n ek
rr   Y nX edeef  dZnBejdkrzdĠe W n& ek
r   e{dŠedơ ZY nX dZdD ]BZzzeze W n, ek
r   ee{ez ZY  qY nX qer,e{d e ZndZe ZdqZdqZej9dddʄZej9ddd̄Zej9dddZewedσrej9ddP ZejejeZejeZejedѡZdddZdd  Zdda Zddք Zdddd؜dd)Zdddd؜dd*ZddN ZG dd݄ deZddd߄Zej9ddW Zej9dedqfddYZej9ddX ZG dd deZG ddZ dZejjZG dd deZG dd+ d+eZeeejdZeeejdZeeejdZdd Zej9ddrddd/Zej9dd Zdd Zdd Zdd Zdd Zej9dd Zdd ZdZdZewed	rPde ZdZed Zdd  ZȐdd ZɐdZʐdZːdd Z̐dd[ Z͐ddb Zΐd	Zϐd
e Zde Zѐde ZejZԐdd_ ZG dd dZ֐ddd7Zאdd8 ZG dd0 d0Zِdd Zڐdd Zېdd9 ZܐdddZݐdd ZސddG Zߐdd Zdd Zd d! Zd"d# Zdadadad$d% Zd&d' Zdd(d)Zd*d+ Zd,d1 Zd-d. Ze߃ 
oejdk
oed/ Zej dk	oe Ze$ned0Zdd1d2Zd2d3 Zd4d5 Zd6d7 Zdqad8dS Zd9dT Zd:dU Zej9dd<d=Zdd>d?Zd@dQ Zej9ddAdVZej9dBd] Zej9dCd\ ZdDdE Ze$ ewedFdGZdHdI ZdJdK ZG dLdR dRejjZG dMd^ d^eZdadNd! Z	dOd3 Z
dadPdC ZG dQdR dRZdadSdT ZdUd< ZdVdW ZdadXdB ZdYd" ZdrdZd[d@Zdd\dAZdd]d^ZG d_d` d`Zd`da Zdbdc ZddddeZg fdfddZdadgdI Zej9dhdi Zdjde Z G dkdl dlZ!dmdn Z"G dodp dpZ#G dqdr drZ$e$ Z%ej&G dsdt dtZ'e' Z(ej&G dudv dvZ)e) Z*dwdx Z+ej,j-Z.e.dyksft/dzd{ Z0G d|d} d}Z1G d~d dZ2ej9dd Z3dd Z4dS (  z7Supporting definitions for the Python regression tests.ztest.supportz.support must be imported from the test package    N   )get_test_runnerPIPE_MAX_SIZEverbose
max_memuseuse_resourcesfailfastError
TestFailedTestDidNotRun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requires_hashdigestcheck_syntax_errorcheck_syntax_warning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check__all__skip_unless_bind_unix_socketskip_if_buggy_ucrt_strfptimeignore_warnings	is_jython
is_androidcheck_impl_detail
unix_shellsetswitchintervalHOSTIPV6_ENABLEDfind_unused_port	bind_portopen_urlresourcebind_unix_socket
temp_umaskreap_childrenTestHandlerthreading_setupthreading_cleanupreap_threadsstart_threadscheck_warningscheck_no_resource_warningcheck_no_warningsEnvironmentVarGuardrun_with_locale	swap_item	swap_attrMatcherset_memlimitSuppressCrashReportsortdictrun_with_tzPGOmissing_compiler_executablefd_count	ALWAYS_EQLARGESTSMALLESTc                   @   s   e Zd ZdZdS )r	   z*Base class for regression test exceptions.N__name__
__module____qualname____doc__ rk   rk   +/usr/lib/python3.8/test/support/__init__.pyr	   }   s   c                   @   s   e Zd ZdZdS )r
   zTest failed.Nrf   rk   rk   rk   rl   r
      s   c                   @   s   e Zd ZdZdS )r   zTest did not run any subtests.Nrf   rk   rk   rk   rl   r      s   c                   @   s   e Zd ZdZdS )r   zTest 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.
    Nrf   rk   rk   rk   rl   r      s   Tc              	   c   s8   | r.t   t ddt dV  W 5 Q R X ndV  dS )zContext 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rm   rk   rk   rl   _ignore_deprecated_imports   s    
rs   c                    s    fdd}|S )zDecorator to suppress deprecation warnings.

    Use of context managers to hide warnings make diffs
    more noisy and tools like 'git blame' less useful.
    c                    s   t   fdd}|S )Nc              
      s>   t  , t jd d | f||W  5 Q R  S Q R X d S )Nrm   category)rn   ro   simplefilter)selfargskwargs)ru   testrk   rl   wrapper   s    
z3ignore_warnings.<locals>.decorator.<locals>.wrapper	functoolswraps)rz   r{   rt   rz   rl   	decorator   s    z"ignore_warnings.<locals>.decoratorrk   )ru   r   rk   rt   rl   rA      s    Frk   )required_onc                C   st   t |b zt| W W  5 Q R  S  tk
rd } z$tjt|rF t	t
|W 5 d}~X Y nX W 5 Q R X dS )ac  Import 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)rs   	importlibr   ImportErrorsysplatform
startswithtupleunittestSkipTeststr)name
deprecatedr   msgrk   rk   rl   r      s    	
c                 C   sZ   | t jkrt|  t j| = tt jD ]0}|| ks>|| d r$t j| ||< t j|= q$dS )zyHelper function to save and remove a module from sys.modules

    Raise ImportError if the module can't be imported.
    .N)r   modules
__import__listr   )r   orig_modulesmodnamerk   rk   rl   _save_and_remove_module   s    
r   c                 C   s>   d}zt j|  || < W n tk
r.   d}Y nX dt j| < |S )zHelper function to save and block a module in sys.modules

    Return True if the module was in sys.modules, False otherwise.
    TFNr   r   KeyError)r   r   Zsavedrk   rk   rl   _save_and_block_module   s    

r   c                 C   s   | r
t jS dd S )zDecorator 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.
    c                 S   s   | S Nrk   frk   rk   rl   <lambda>       z$anticipate_failure.<locals>.<lambda>)r   ZexpectedFailure)Z	conditionrk   rk   rl   r;      s    c                 C   sF   |dkrd}t jt jt jt}|j| ||d}|| |S )zGeneric 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)
    Nztest*)Z	start_dirZtop_level_dirpattern)ospathdirname__file__ZdiscoverZaddTests)Zpkg_dirloaderZstandard_testsr   Ztop_dirZpackage_testsrk   rk   rl   r<      s    

c                 C   s   t | i }g }t| | z^z@|D ]}	t|	| q$|D ]}
t|
|s8||
 q8t| }W n t	k
rv   d}Y nX W 5 | D ]\}}|tj|< q|D ]}tj|= qX |W  5 Q R  S Q R X dS )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)
rs   r   itemsr   r   r   appendr   r   r   )r   ZfreshZblockedr   r   Znames_to_removeZ	orig_namemoduleZname_to_removeZ
fresh_nameZblocked_nameZfresh_modulerk   rk   rl   r      s$    


c                 C   s>   zt | |}W n& tk
r4   td| |f Y nX |S dS )z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %rN)getattrAttributeErrorr   r   )objr   Z	attributerk   rk   rl   r7   ,  s
    c                 C   s   | a d S r   )_original_stdout)stdoutrk   rk   rl   r   A  s    c                   C   s
   t ptjS r   )r   r   r   rk   rk   rk   rl   r   E  s    c                 C   s&   zt j| = W n tk
r    Y nX d S r   r   )r   rk   rk   rl   r   H  s    c              
   G   sz   z
|| W S  t k
rt } zLtdkrJtd|jj|f  td|j|f  t| tj ||  W Y S d }~X Y nX d S )N   z%s: %szre-run %s%r)	OSErrorr   print	__class__rg   r   chmodstatS_IRWXU)r   funcrx   errrk   rk   rl   
_force_runN  s    
r   winc                 C   s   | | |r|}nt j|\}}|p(d}d}|dk rjt |}|rJ|sVn||ksVd S t| |d9 }q.tjd| tdd d S )Nr   gMbP?g      ?r   z)tests may fail, delete still pending for    
stacklevel)	r   r   splitlistdirtimesleeprn   warnRuntimeWarning)r   pathnamewaitallr   r   timeoutLrk   rk   rl   _waitforY  s     



 r   c                 C   s   t tj|  d S r   )r   r   r   filenamerk   rk   rl   _unlinkz  s    r   c                 C   s   t tj|  d S r   )r   r   rmdirr   rk   rk   rl   _rmdir}  s    r   c                    s,    fdd t  | dd t dd |  d S )Nc                    s   t | tj| D ]}tj| |}zt|j}W n< tk
rl } ztd||f t	j
d d}W 5 d }~X Y nX t|rt |dd t |tj| qt |tj| qd S )Nz-support.rmtree(): os.lstat(%r) failed with %sfiler   Tr   )r   r   r   r   joinlstatst_moder   r   r   
__stderr__r   S_ISDIRr   r   r   )r   r   fullnamemodeexc_rmtree_innerrk   rl   r     s    
_rmtree.<locals>._rmtree_innerTr   c                 S   s   t | tj| S r   )r   r   r   )prk   rk   rl   r     r   z_rmtree.<locals>.<lambda>)r   r   rk   r   rl   _rmtree  s    r   c                 C   s^   zdd l }W n tk
r    Y n:X |t| d }|jj| |t|}|rZ|d | S | S )Nr   r   )ctypesr   Zcreate_unicode_bufferlenwindllZkernel32ZGetLongPathNameW)r   r   bufferZlengthrk   rk   rl   	_longpath  s    r   c                    sH   zt |  W d S  tk
r$   Y nX  fdd  |  t|  d S )Nc              	      s   t | tj| D ]l}tj| |}zt|j}W n tk
rH   d}Y nX t	|rl | t | tj
| qt | tj| qd S Nr   )r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   rk   rl   r     s    

r   )shutilr   r   r   r   r   rk   r   rl   r     s    
c                 C   s   | S r   rk   r   rk   rk   rl   r     s    c              	   C   s*   zt |  W n ttfk
r$   Y nX d S r   )r   FileNotFoundErrorNotADirectoryErrorr   rk   rk   rl   r     s    c                 C   s&   zt |  W n tk
r    Y nX d S r   )r   r   r   rk   rk   rl   r     s    r   c                 C   s&   zt |  W n tk
r    Y nX d S r   )r   r   r   rk   rk   rl   r     s    c                 C   sB   t j| }tjtj| }tj|| d }t|| |S )a  Move 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_sourcer   r   r   abspathr   rename)sourceZpyc_fileZup_oneZ
legacy_pycrk   rk   rl   make_legacy_pyc  s
    r   c                 C   sT   t |  tjD ]@}tj|| d }t|d  dD ]}ttjj||d q4qdS )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   r   r   r   r   r   )r   r   r   optrk   rk   rl   r     s    
c               
      s  t tdrtjS d } tjdrdd ldd ld}d}G fdddj}j	j
}| }|sj | }j }||||||}|s t|j|@ sd} ntjdkrVdd	lm}	m m}
m} dd
lm} |	|d}| dkrd} nFG  fddd|}| }|
|}||dk sR||dk rVd} | sz.ddlm} | }|  |   |!  W n\ t"k
r } z<t#|}t$|dkr|d d d }d%t&|j'|} W 5 d }~X Y nX | t_(|  t_tjS )Nresultr   r   r   c                       s.   e Zd Zd jjfd jjfd jjfgZdS )z*_is_gui_available.<locals>.USEROBJECTFLAGSZfInheritZ	fReserveddwFlagsN)rg   rh   ri   wintypesZBOOLDWORD_fields_rk   )r   rk   rl   USEROBJECTFLAGS  s   


r   z,gui not available (WSF_VISIBLE flag not set)darwin)cdllc_intpointer	Structure)find_libraryZApplicationServicesz0gui tests cannot run without OS X window managerc                       s   e Zd Zd fd fgZdS )z._is_gui_available.<locals>.ProcessSerialNumberZhighLongOfPSNZlowLongOfPSNN)rg   rh   ri   r   rk   )r   rk   rl   ProcessSerialNumber  s   r   z#cannot run without OS X gui process)Tk2   z [...]zTk unavailable due to {}: {}))hasattr_is_gui_availabler   r   r   r   r   Zctypes.wintypesr   r   Zuser32ZGetProcessWindowStationZWinErrorr   r   ZGetUserObjectInformationWZbyrefZsizeofboolr   r   r   r   Zctypes.utilr   ZLoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterr   ZwithdrawupdateZdestroy	Exceptionr   r   formattyperg   reason)r  Z	UOI_FLAGSZWSF_VISIBLEr   dllhZuofZneededresr   r   r   r   Zapp_servicesr   ZpsnZpsn_pr   rooteZ
err_stringrk   )r   r   rl   r     sn    

r   c                 C   s   t dkp| t kS )zTest 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   resourcerk   rk   rl   r    5  s    c                 C   s<   t | s |dkrd|  }t|| dkr8t s8ttjdS )z@Raise ResourceDenied if the specified resource is not available.Nz"Use of the %r resource not enabledgui)r    r   r   r  )r  r   rk   rk   rl   r!   =  s    c                 C   s   ddl }dtt|}| ddd }| | krtzttt|d}W n t	k
rh   d}Y qxX ||k }nd}t
||  d| d| S )	zDecorator 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.
    r   Nr   -r   Fz	 version z or higher required, not )r   r   mapr   releaser   systemr   int
ValueErrorr   skipIf)sysnamemin_versionr   min_version_txtversion_txtversionskiprk   rk   rl   _requires_unix_versionF  s    

r  c                  G   s
   t d| S )zDecorator 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.
    ZFreeBSDr  r  rk   rk   rl   r"   a  s    c                  G   s
   t d| S )zDecorator 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.
    ZLinuxr  r  rk   rk   rl   r#   j  s    c                     s    fdd}|S )zDecorator 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.
    c                    s"   t   fdd}|_|S )Nc                     sx   t jdkrnt d }zttt|d}W n tk
rB   Y n,X |k rndtt	}t
d||f  | |S )Nr   r   r   z&Mac OS X %s or higher required, not %s)r   r   Zmac_verr   r  r  r   r  r   r   r   r   )rx   kwr  r  r  )r   r  rk   rl   r{   {  s    
z4requires_mac_ver.<locals>.decorator.<locals>.wrapper)r}   r~   r  r   r{   r  r   rl   r   z  s    z#requires_mac_ver.<locals>.decoratorrk   )r  r   rk   r  rl   r$   s  s    c                    s    fdd}|S )a  Decorator raising SkipTest if a hashing algorithm is not available

    The hashing algorithm could be missing or blocked by a strict crypto
    policy.

    If 'openssl' is True, then the decorator checks that OpenSSL provides
    the algorithm. Otherwise the check falls back to built-in
    implementations.

    ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS
    ValueError: unsupported hash type md4
    c                    s   t   fdd}|S )Nc                     sX   z&rt d k	rt   n
t  W n& tk
rL   td  dY nX | |S )Nzhash digest 'z' is not available.)_hashlibnewhashlibr  r   r   )rx   ry   )
digestnamer   opensslrk   rl   r{     s    

z7requires_hashdigest.<locals>.decorator.<locals>.wrapperr|   r  r#  r$  r  rl   r     s    z&requires_hashdigest.<locals>.decoratorrk   )r#  r$  r   rk   r%  rl   r%     s    Z	localhostz	127.0.0.1z::1c              	   C   s&   t  | |}t|}W 5 Q R X ~|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.
    )socketrJ   )familyZsocktypeZtempsockportrk   rk   rl   rI     s    8c                 C   s   | j tjkr| jtjkrttdr>| tjtjdkr>t	dttdr~z | tjtj
dkrft	dW n tk
r|   Y nX ttdr| tjtjd | |df |  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_REUSEPORTzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!SO_EXCLUSIVEADDRUSEr   )r'  r&  AF_INETr  SOCK_STREAMr   Z
getsockoptZ
SOL_SOCKETr)  r
   r*  r   Z
setsockoptr+  bindZgetsockname)sockZhostr(  rk   rk   rl   rJ     s    


c                 C   sJ   | j tjkstz| | W n& tk
rD   |   tdY nX dS )zBBind a unix socket, raising SkipTest if PermissionError is raised.zcannot bind AF_UNIX socketsN)	r'  r&  AF_UNIXAssertionErrorr.  PermissionErrorcloser   r   )r/  Zaddrrk   rk   rl   rL     s    c                  C   s`   t jr\d} zBz(t  t jt j} | tdf W W dS  tk
rH   Y nX W 5 | rZ|   X dS )z+Check whether IPv6 is enabled on this host.Nr   TF)r&  Zhas_ipv6r3  ZAF_INET6r-  r.  HOSTv6r   )r/  rk   rk   rl   _is_ipv6_enabled  s    


r5  c                    s   t   fdd}|S )z5Skip the test on TLS certificate validation failures.c               
      sN   z | | W n: t k
rH } zdt|kr6td W 5 d }~X Y nX d S )NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)r   r   r   r   )rx   ry   r	  r   rk   rl   dec0  s    
z&system_must_validate_cert.<locals>.decr|   )r   r6  rk   r   rl   system_must_validate_cert.  s    r7  i @ i  ZdoubleZIEEEztest requires IEEE 754 doubleszrequires zlibzrequires gzipzrequires bz2zrequires lzmaZjavaZgetandroidapilevelwin32z/system/bin/shz/bin/shz$testz@testz	{}_{}_tmpzhttp://www.pythontest.net)   æu   İu   Łu   φu   Кu   אu   ،u   تu   ก    u   €u   -àòɘŁğr   ZNFDntr   u   -共Ł♡ͣztWARNING: The filename %r CAN be encoded by the filesystem encoding (%s). Unicode filename tests may not be effective   s   -surrogateescape)s   wr<  s   s   s   r  c              
   c   s   d}| dkr&t  } d}tj| } nXzt|  d}W nD tk
r| } z&|sP tjd| d| t	dd W 5 d}~X Y nX |rt
 }z
| V  W 5 |r|t
 krt|  X dS )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.

    FNTz5tests may fail, unable to create temporary directory :    r   )tempfilemkdtempr   r   realpathmkdirr   rn   r   r   getpidr   )r   quietZdir_createdr   pidrk   rk   rl   temp_dir  s*    
 
rG  c              
   c   s   t  }zt t j|  W nD tk
rb } z&|s6 tjd| d| tdd W 5 d}~X Y nX zt  V  W 5 t | X dS )ag  Return 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.

    zBtests may fail, unable to change the current working directory to r>  r?  r   N)	r   getcwdchdirr   rB  r   rn   r   r   )r   rE  Z	saved_dirr   rk   rk   rl   
change_cwd  s     rJ  tempcwdc              
   c   s:   t | |d$}t||d}|V  W 5 Q R X W 5 Q R X dS )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.

    )r   rE  )rE  N)rG  rJ  )r   rE  Z	temp_pathZcwd_dirrk   rk   rl   r   :  s    umaskc              	   c   s&   t | }z
dV  W 5 t | X dS )z8Context manager that temporarily sets the process umask.N)r   rL  )rL  Zoldmaskrk   rk   rl   rM   N  s    

datac                 C   sb   t j| r| S |dk	r&t j|| } tgtj }|D ]&}t j|| }t j|r6|  S q6| 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)r   r   isabsr   TEST_HOME_DIRr   exists)r   Zsubdirr   dnfnrk   rk   rl   r   _  s     
c                 C   s(   t | t jt jB t jB }t | dS )z>Create an empty file. If the file already exists, truncate it.N)r   openO_WRONLYO_CREATO_TRUNCr3  )r   fdrk   rk   rl   r   q  s    c                 C   s,   t |  }dd |D }d|}d| S )z%Like repr(dict), but in sorted order.c                 S   s   g | ]}d | qS )z%r: %rrk   ).0Zpairrk   rk   rl   
<listcomp>y  s     zsortdict.<locals>.<listcomp>z, z{%s})sortedr   r   )dictr   Z	reprpairsZ
withcommasrk   rk   rl   r^   v  s    
c                  C   s.   t td} z|  W S |   tt X dS )z`
    Create an invalid file descriptor by opening and closing a file and return
    its fd.
    wbN)rS  r   r3  r   filenor   rk   rk   rl   make_bad_fd}  s
    
r^  r   linenooffsetc             	   C   sr   |  t|}t|dd W 5 Q R X |j}| |j |d k	rL| |j| | |j |d k	rn| |j| d S )Nz<test string>exec)ZassertRaisesRegexSyntaxErrorcompileZ	exceptionassertIsNotNoner`  assertEqualra  )testcase	statementerrtextr`  ra  cmr   rk   rk   rl   r&     s    c             	   C   s   t jdd}t dt t|dd W 5 Q R X | t|d| |\}| t|j	t|j	 |rt| 
t|j| | |jd | |j |d k	r| |j| t jdd$}t dt t| ||||d W 5 Q R X | |g  d S )	NTrecordalwaysz
<testcase>rb  r   errorr_  )rn   ro   rv   SyntaxWarningrd  rf  r   
assertTrue
issubclassru   ZassertRegexr   messager   re  r`  r&   )rg  rh  ri  r`  ra  warnsr   rk   rk   rl   r'     s&     c              	      sP  dd l }dd l}dd |j| d dd }tjt	|} fdd}tj
|r|||}|d k	rt|S t| td trtd	|  t d
 |j }tr|jd |j| dd}tr|jddkrtj|d}z<t|d(}	| }
|
r|	|
 | }
qW 5 Q R X W 5 |  X ||}|d k	r@|S td| d S )Nr   checkr   /c                    s>   t | f }d kr|S |r2|d |S |  d S r   )rS  seekr3  )rR  r   rx   rt  r  rk   rl   check_valid_file  s    
z*open_urlresource.<locals>.check_valid_fileZurlfetchz	fetching %s ...r   )zAccept-Encodinggzip   )r   zContent-Encodingrz  )Zfileobjr\  zinvalid resource %r)Zurllib.requestZurllib.parsepopparseZurlparser   r   r   r   TEST_DATA_DIRrP  r   r!   r   r   r   ZrequestZbuild_openerrz  Z
addheadersr   rS  ZheadersgetZGzipFiler3  readwriter
   )Zurlrx   r  urllibr   rR  ry  r   Zopeneroutsrk   rx  rl   rK     s<    	



c                   @   s4   e Zd ZdZdd Zdd Zedd Zdd	 Zd
S )WarningsRecorderzyConvenience wrapper for the warnings list returned on
       entry to the warnings.catch_warnings() context manager.
    c                 C   s   || _ d| _d S r   	_warnings_last)rw   Zwarnings_listrk   rk   rl   __init__  s    zWarningsRecorder.__init__c                 C   sD   t | j| jkr t| jd |S |tjjkr0d S td| |f d S )Nrv  z%r has no attribute %r)r   r  r  r   rn   WarningMessage_WARNING_DETAILSr   )rw   attrrk   rk   rl   __getattr__  s
    zWarningsRecorder.__getattr__c                 C   s   | j | jd  S r   r  rw   rk   rk   rl   rn     s    zWarningsRecorder.warningsc                 C   s   t | j| _d S r   )r   r  r  r  rk   rk   rl   reset  s    zWarningsRecorder.resetN)	rg   rh   ri   rj   r  r  propertyrn   r  rk   rk   rk   rl   r    s   
r  c              	   c   s   t d}|jd}|r"|  tjdd }t jd d t	|V  W 5 Q R X t
|}g }| D ]j\}}d}	|dd D ]8}|j}
t|t|
tjr|t|
j|r|d}	|| q||	sd|sd|||jf qd|rtd	|d
  |rtd|d
  dS )zCatch 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__Trk  rn   rm  FNzunhandled warning %sr   z)filter (%r, %s) did not catch any warning)r   	_getframe	f_globalsr  clearrn   ro   r   rv   r  r   rr  rematchr   Irq  r   remover   rg   r1  )filtersrE  frameregistrywZreraiseZmissingr   catseenZwarningrk   rk   rl   _filterwarnings  s4    

r  c                  O   s.   | d}| s$dtff} |dkr$d}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)
    rE  r   NT)r  Warningr  )r  ry   rE  rk   rk   rl   rT      s    

c              	   c   sH   t jdd&}t jd||d dV  |r.t  W 5 Q R X | |g  dS )a  Context manager to check that no warnings are emitted.

    This context manager enables a given warning within its scope
    and checks that no warnings are emitted even with that warning
    enabled.

    If force_gc is True, a garbage collection is attempted before checking
    for warnings. This may help to catch warnings emitted when objects
    are deleted, such as ResourceWarning.

    Other keyword arguments are passed to warnings.filterwarnings().
    Trk  rm  )rr  ru   N)rn   ro   rp   
gc_collectrf  )rg  rr  ru   force_gcrs  rk   rk   rl   rV   8  s    c              	   c   s$   t | tdd dV  W 5 Q R X dS )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.
    T)ru   r  N)rV   ResourceWarning)rg  rk   rk   rl   rU   P  s    c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	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
    c                 G   sJ   t j | _|D ]4}|t jkrt j| }|j|kr<t j|j= t j|= qd S r   )r   r   copyoriginal_modulesrg   )rw   Zmodule_namesZmodule_namer   rk   rk   rl   r  n  s    



zCleanImport.__init__c                 C   s   | S r   rk   r  rk   rk   rl   	__enter__{  s    zCleanImport.__enter__c                 G   s   t j| j d S r   )r   r   r   r  rw   
ignore_excrk   rk   rl   __exit__~  s    zCleanImport.__exit__Nrg   rh   ri   rj   r  r  r  rk   rk   rk   rl   r   b  s   c                   @   sh   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd ZdS )rW   z_Class to help protect the environment variable properly.  Can be used as
    a context manager.c                 C   s   t j| _i | _d S r   )r   environ_environ_changedr  rk   rk   rl   r    s    zEnvironmentVarGuard.__init__c                 C   s
   | j | S r   )r  rw   envvarrk   rk   rl   __getitem__  s    zEnvironmentVarGuard.__getitem__c                 C   s*   || j kr| j|| j |< || j|< d S r   r  r  r  rw   r  valuerk   rk   rl   __setitem__  s    
zEnvironmentVarGuard.__setitem__c                 C   s2   || j kr| j|| j |< || jkr.| j|= d S r   r  r  rk   rk   rl   __delitem__  s    

zEnvironmentVarGuard.__delitem__c                 C   s
   | j  S r   )r  keysr  rk   rk   rl   r    s    zEnvironmentVarGuard.keysc                 C   s
   t | jS r   )iterr  r  rk   rk   rl   __iter__  s    zEnvironmentVarGuard.__iter__c                 C   s
   t | jS r   )r   r  r  rk   rk   rl   __len__  s    zEnvironmentVarGuard.__len__c                 C   s   || |< d S r   rk   r  rk   rk   rl   set  s    zEnvironmentVarGuard.setc                 C   s
   | |= d S r   rk   r  rk   rk   rl   unset  s    zEnvironmentVarGuard.unsetc                 C   s   | S r   rk   r  rk   rk   rl   r    s    zEnvironmentVarGuard.__enter__c                 G   sF   | j  D ].\}}|d kr.|| jkr8| j|= q
|| j|< q
| jt_d S r   )r  r   r  r   r  )rw   r  kvrk   rk   rl   r    s    

zEnvironmentVarGuard.__exit__N)rg   rh   ri   rj   r  r  r  r  r  r  r  r  r  r  r  rk   rk   rk   rl   rW     s   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	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.
    c                 G   s(   t jd d  | _t j| _t j| d S r   )r   r   original_valueoriginal_objectextend)rw   pathsrk   rk   rl   r    s    zDirsOnSysPath.__init__c                 C   s   | S r   rk   r  rk   rk   rl   r    s    zDirsOnSysPath.__enter__c                 G   s   | j t_| jtjd d < d S r   )r  r   r   r  r  rk   rk   rl   r    s    zDirsOnSysPath.__exit__Nr  rk   rk   rk   rl   r    s   r  c                   @   s*   e Zd ZdZdd Zdd Zd	ddZdS )
r(   zRaise ResourceDenied if an exception is raised while the context manager
    is in effect that matches the specified exception and attributes.c                 K   s   || _ || _d S r   )r   attrs)rw   r   ry   rk   rk   rl   r    s    zTransientResource.__init__c                 C   s   | S r   rk   r  rk   rk   rl   r    s    zTransientResource.__enter__Nc                 C   sT   |dk	rPt | j|rP| j D ](\}}t||s4 qPt|||kr qPqtddS )zIf 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)rq  r   r  r   r   r   r   )rw   Ztype_r  	tracebackr  Z
attr_valuerk   rk   rl   r    s    
zTransientResource.__exit__)NNNr  rk   rk   rk   rl   r(     s   )errnoc                  C   s^   t jg} tt dr| t j tt dr4| t j tt drJ| t j tsZ| t j | S )zr
    Get the different socket error numbers ('errno') which can be received
    when a connection is refused.
    ENETUNREACHEADDRNOTAVAILEHOSTUNREACH)	r  ECONNREFUSEDr   r   r  r  r  rH   ZEAFNOSUPPORT)errorsrk   rk   rl   get_socket_conn_refused_errs  s    


r        >@)r   errnosc          	   
   #   sj  ddddddg}ddd	d
dg}t d|  | g  sRdd |D  dd |D  fdd}t }zz|dk	rt| dV  W n tjk
r } z$trtj	j
d d  |W 5 d}~X Y n tk
rT } zj|j
}t|dkrt|d tr|d }qt|dkr:t|d tr:|d }qސq:q||  W 5 d}~X Y nX W 5 t| X dS )zReturn a context manager that raises ResourceDenied when various issues
    with the Internet connection manifest themselves as exceptions.)r  o   )
ECONNRESETh   )r  q   )r  e   )	ETIMEDOUTn   )r  c   )Z	EAI_AGAIN)ZEAI_FAIL)Z
EAI_NONAME)Z
EAI_NODATA)Z
WSANO_DATAi*  zResource %r is not availablec                 S   s   g | ]\}}t t||qS rk   )r   r  rX  r   Znumrk   rk   rl   rY  !  s   z&transient_internet.<locals>.<listcomp>c                 S   s   g | ]\}}t t||qS rk   )r   r&  r  rk   rk   rl   rY  #  s   c                    s   t | dd }t| tjst| tjr,|kst| tjjrRd| j  krPdksn t| tjj	r~d| j
ksd| j
ksd| j
ks| krtstjjd d  | d S )	Nr  i  iW  ConnectionRefusedErrorTimeoutErrorEOFErrorr   
)r   
isinstancer&  r   Zgaierrorr  rn  Z	HTTPErrorcodeZURLErrorr  r   r   stderrr  rx   )r   nZcaptured_errnosZdeniedZ
gai_errnosrk   rl   filter_error&  s4    
 	z(transient_internet.<locals>.filter_errorNr   r  r   r   )r   r&  ZgetdefaulttimeoutZsetdefaulttimeoutnntplibZNNTPTemporaryErrorr   r   r  r  rx   r   r   r  )	Zresource_namer   r  Zdefault_errnosZdefault_gai_errnosr  Zold_timeoutr   ark   r  rl   r,     sV    	



c              
   c   sF   ddl }tt| }tt| |  ztt| V  W 5 tt| | X dS )zReturn a context manager used by captured_stdout/stdin/stderr
    that temporarily replaces the sys stream *stream_name* with a StringIO.r   N)ior   r   setattrStringIO)Zstream_namer  Zorig_stdoutrk   rk   rl   captured_outputT  s    
r  c                   C   s   t dS )zCapture the output of sys.stdout:

       with captured_stdout() as stdout:
           print("hello")
       self.assertEqual(stdout.getvalue(), "hello\n")
    r   r  rk   rk   rk   rl   r   `  s    c                   C   s   t dS )zCapture the output of sys.stderr:

       with captured_stderr() as stderr:
           print("hello", file=sys.stderr)
       self.assertEqual(stderr.getvalue(), "hello\n")
    r  r  rk   rk   rk   rl   r   i  s    c                   C   s   t d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")
    stdinr  rk   rk   rk   rl   r   r  s    
c                   C   s*   t   trtd t   t   dS )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)gcZcollectrB   r   r   rk   rk   rk   rl   r    s
    

r  c                  c   s.   t  } t   z
d V  W 5 | r(t   X d S r   )r  Z	isenableddisableenable)Zhave_gcrk   rk   rl   
disable_gc  s    
r  c                  C   s6   t dpd} d}|  D ]}|dr|}q|dkS )z,Find if Python was built with optimizations.Z	PY_CFLAGSr   z-O)r   z-O0z-Og)	sysconfigget_config_varr   r   )ZcflagsZ	final_optr   rk   rk   rl   python_is_optimized  s    
r  ZnPZ0nZ
getobjectsZ2PZ0Pr  c                 C   s   t t|  t S r   )structcalcsize_header_alignZfmtrk   rk   rl   calcobjsize  s    r  c                 C   s   t t|  t S r   )r  r  _vheaderr  r  rk   rk   rl   calcvobjsize  s    r  i @  i   c                 C   sp   dd l }t|}t|tkr(|jt@ sBt|tkrLt|jt@ rL||j7 }dt|||f }| ||| d S )Nr   z&wrong size for %s: got %d, expected %d)		_testcapir   	getsizeofr  	__flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADrf  )rz   osizer  r   r   rk   rk   rl   check_sizeof  s    


r  c                    s    fdd}|S )Nc                    s$    fdd} j |_  j|_|S )Nc               
      s   z dd l }t| }||}W n( tk
r6    Y nB   d  }}Y n0X D ](}z||| W  qxW qN   Y qNX qNz| |W S |r|r||| X d S r   )localer   	setlocaler   )rx   kwdsr  ru   Zorig_localeZloc)catstrr   localesrk   rl   inner  s$    

z1run_with_locale.<locals>.decorator.<locals>.innerrg   rj   r   r  r  r  r  rl   r     s    z"run_with_locale.<locals>.decoratorrk   )r  r  r   rk   r  rl   rX     s    c                    s    fdd}|S )Nc                    s"    fdd} j |_  j|_|S )Nc               	      s   z
t j}W n tk
r(   tdY nX dtjkr@tjd }nd }tjd< |  z | |W S |d krvtjd= n
|tjd< t   X d S )Nztzset requiredZTZ)r   tzsetr   r   r   r   r  )rx   r  r  Zorig_tz)r   tzrk   rl   r    s    




z-run_with_tz.<locals>.decorator.<locals>.innerr	  r
  r  r  rl   r     s    zrun_with_tz.<locals>.decoratorrk   )r  r   rk   r  rl   r_     s    i      r   c                 C   s   dt tdt d}td| tjtjB }|d kr>td| f tt|	d||	d
   }|a|tkrrt}|td k rtd| f |ad S )Nr  )r  mgtz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rr   r?  z$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   )limitZsizesr  Zmemlimitrk   rk   rl   r\     s"    
$c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_MemoryWatchdogz`An object which periodically watches the process' memory consumption
    and prints it out.
    c                 C   s   dj t d| _d| _d S )Nz/proc/{pid}/statm)rF  F)r  r   rD  procfilestartedr  rk   rk   rl   r  ,  s    z_MemoryWatchdog.__init__c              
   C   s   zt | jd}W nD tk
rT } z&td|t tj	  W Y d S d }~X Y nX |( t
d}tjtj|g|tjd| _W 5 Q R X d| _d S )Nrz!/proc not available for stats: {}zmemory_watchdog.py)r  r  T)rS  r  r   rn   r   r  r   r   r  flushr   
subprocessPopen
executableZDEVNULLmem_watchdogr   )rw   r   r	  Zwatchdog_scriptrk   rk   rl   start0  s    
z_MemoryWatchdog.startc                 C   s   | j r| j  | j  d S r   )r   r&  Z	terminatewaitr  rk   rk   rl   stop@  s    
z_MemoryWatchdog.stopN)rg   rh   ri   rj   r  r'  r)  rk   rk   rk   rl   r  '  s   r  c                    s    fdd}|S )at  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.
    c                    s     fdd_ _S )Nc                    s   j }j}tsd}n|}ts" sDt|| k rDtd|| d  trztrzt  tdj|| d d t }|	  nd }z| |W S |r|
  X d S )Ni  'not enough memory: %.1fG minimum needed   @z* ... expected peak memory use: {peak:.1f}G)Zpeak)r  memuser  r   r   r   r   r  r  r'  r)  )rw   r  r,  maxsizeZwatchdog)dry_runr   r{   rk   rl   r{   T  s2    



z.bigmemtest.<locals>.decorator.<locals>.wrapper)r  r,  r   r.  r,  r  r   r{   rl   r   S  s    zbigmemtest.<locals>.decoratorrk   )r  r,  r.  r   rk   r/  rl   r4   F  s    !c                    s    fdd}|S )z0Decorator for tests that fill the address space.c                    sD   t tk r8tdkr$t dkr$tdq@tdtd  n | S d S )Nl    l        z-not enough memory: try a 32-bit build insteadr*  r+  )r   r  r   r   r  r   rk   rl   r{   x  s    z!bigaddrspacetest.<locals>.wrapperrk   r0  rk   r   rl   r5   v  s    c                   @   s   e Zd Zdd ZdS )r-   c                 C   s   t  }|| |S r   )r   Z
TestResult)rw   rz   r   rk   rk   rl   run  s    zBasicTestRunner.runN)rg   rh   ri   r1  rk   rk   rk   rl   r-     s   c                 C   s   | S r   rk   )r   rk   rk   rl   _id  s    r2  c                 C   s:   | dkrt  stt jS t| r&tS td| S d S )Nr  zresource {0!r} is not enabled)r   r   r  r  r    r2  r  r
  rk   rk   rl   requires_resource  s
    r3  c                 C   s   t dd| S )z9
    Decorator for tests only applicable on CPython.
    T)cpython)impl_detailr   rk   rk   rl   r6     s    c                 K   sV   t f |rtS | d krLt|\}}|r,d} nd} t| }| d|} t| S )Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or )	rD   r2  _parse_guardsrZ  r  r  r   r   r  )r   guardsZ
guardnamesdefaultrk   rk   rl   r5    s    
r5  c                 C   sH   | sddidfS t |  d }t |  |gt|  ks>t| | fS )Nr4  TFr   )r   valuesr   r1  )r7  Zis_truerk   rk   rl   r6    s
    r6  c                  K   s    t | \} }| t  |S )a5  This 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
    )r6  r  r   Zpython_implementationr  )r7  r8  rk   rk   rl   rD     s    c                    s,   t tds S t  fdd}|S dS )zEDecorator to temporarily turn off tracing for the duration of a test.gettracec               	      s2   t  }zt d   | |W S t | X d S r   )r   r:  settrace)rx   ry   Zoriginal_tracer  rk   rl   r{     s
    
zno_tracing.<locals>.wrapperN)r   r   r}   r~   r  rk   r  rl   
no_tracing  s
    
r<  c                 C   s   t t| S )a  Decorator 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.

    )r<  r6   r   rk   rk   rl   refcount_test  s    r=  c                 C   sN   g }| j D ]8}t|tjr0t|| || q
||r
|| q
|| _ dS )z>Recursively filter test cases in a suite based on a predicate.N)Z_testsr  r   	TestSuite_filter_suiter   )suiteZpredZnewtestsrz   rk   rk   rl   r?    s    

r?  c                 C   s   t tjttdk	d}|| }tdk	r4t|  |jsD|j	sDt
| st|jdkrp|jsp|jd d }n4t|jdkr|js|jd d }nd}ts|d7 }t|dS )z2Run tests from a unittest.TestSuite-derived class.N)	verbosityZcapture_outputr   r   zmultiple errors occurredz!; run in verbose mode for details)r   r   r   r   junit_xml_listr1  r   Zget_xml_elementZtestsRunZskippedr   ZwasSuccessfulr   r  Zfailuresr
   )r@  Zrunnerr   r   rk   rk   rl   
_run_suite  s$    
 rC  c                 C   s   t d krdS t |  S d S NT)_match_test_funcidr   rk   rk   rl   
match_test  s    rG  c                 C   s   d| kot d|  S )Nr   z[?*\[\]])r  search)r   rk   rk   rl   _is_full_match_test  s    rI  c                    s~   | d krd} |d krd}d   | t kr4t| \}  |tkrHt|\}t| a t|a d k	shd k	rz fdd}|ad S )Nrk   c                    s*   d}d} r | }r | }|o(| S )NTFrk   )test_idZacceptrm   Zaccept_funcZignore_funcrk   rl   match_function.  s    z'set_match_tests.<locals>.match_function)_accept_test_patterns_compile_match_function_ignore_test_patternsr   rE  )Zaccept_patternsZignore_patternsrL  rk   rK  rl   set_match_tests  s    	rP  c                    s^   | sd }d} nHt tt| r(t| j}n.dttj| }t	|j
  fdd}|}| |fS )Nrk   |c                    s$    | rdS t t | dS d S )NTr   )anyr  r   )rJ  Zregex_matchrk   rl   match_test_regexI  s    z1_compile_match_function.<locals>.match_test_regex)allr  rI  r  __contains__r   fnmatch	translater  rd  r  )Zpatternsr   ZregexrT  rk   rS  rl   rN  :  s    rN  c                  G   s   t jt jf}t  }| D ]`}t|trR|tjkrH|t tj|  qxt	dqt||rh|| q|t 
| qt|t t| dS )z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesN)r   r>  ZTestCaser  r   r   r   ZaddTestZfindTestCasesr  Z	makeSuiter?  rG  rC  )classesZvalid_typesr@  clsrk   rk   rl   r.   Y  s    




c                   C   s   dS )z,Just used to check if docstrings are enabledNrk   rk   rk   rk   rl   _check_docstringsp  s    r[  ZWITH_DOC_STRINGSztest requires docstringsc                 C   s`   ddl }|dkrt}nd}|j| ||d\}}|rBtd||f trXtd| j|f  ||fS )a  Run 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).
    r   N)r   optionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)doctestr   Ztestmodr
   r   rg   )r   rA  r\  r]  r   r  rk   rk   rl   r/     s    c                 C   s(   |   D ]}td| tjdd qd S )NzWarning -- T)r   r"  )
splitlinesr   r   r   )r   linerk   rk   rl   print_warning  s    r`  c                   C   s   t j fS r   )r   r   r  rk   rk   rk   rl   modules_setup  s    ra  c                 C   s:   dd t j D }t j  t j| t j|  d S )Nc                 S   s"   g | ]\}}| d r||fqS )z
encodings.)r   )rX  r  r  rk   rk   rl   rY    s    
z#modules_cleanup.<locals>.<listcomp>)r   r   r   r  r   )Z
oldmodulesZ	encodingsrk   rk   rl   modules_cleanup  s    
rb  c                   C   s   t  tj fS r   )_thread_count	threading	_danglingr  rk   rk   rk   rl   rP     s    c               	   G   s   d}t |D ]}t tjf}|| kr* q|sda|d }td|d | d   d|d  dt| d |D ]}td	| qnd }d }t	d
 t
  qd S )Nd   Tr   z&threading_cleanup() failed to cleanup r   z threads (count: z, dangling: )zDangling thread: {Gz?)rangerc  rd  re  rf  environment_alteredr`  r   r   r   r  )Zoriginal_valuesZ
_MAX_COUNTcountr9  Zdangling_threadsthreadrk   rk   rl   rQ     s    0
c                    s   t   fdd}|S )zUse this function when threads are being used.  This will
    ensure that the threads are cleaned up even when the test fails.
    c                     s"   t  }z |  W S t|  X d S r   )rP   rQ   )rx   keyr  rk   rl   r     s    zreap_threads.<locals>.decoratorr|   )r   r   rk   r  rl   rR     s          N@c                 c   s   t  }z
dV  W 5 t }||  }t  }||kr6qt |krzt | }d||  d|dd| d| d	}t|td t  q$X dS )	aH  
    bpo-31234: Context manager to wait until all threads created in the with
    statement exit.

    Use _thread.count() to check if threads exited. Indirectly, wait until
    threads exit the internal t_bootstrap() C function of the _thread module.

    threading_setup() and threading_cleanup() are designed to emit a warning
    if a test leaves running threads in the background. This context manager
    is designed to cleanup threads started by the _thread.start_new_thread()
    which doesn't allow to wait for thread exit, whereas thread.Thread has a
    join() method.
    z!wait_threads() failed to cleanup z threads after .1fz seconds (count: z, old count: rh  ri  N)rc  rd  r   	monotonicr1  r   r  )r   Z	old_countZ
start_timeZdeadlinerl  Zdtr   rk   rk   rl   wait_threads_exit  s    
$
rr  c                 C   s,   |  | |  r(d|dd}t|dS )zcJoin a thread. Raise an AssertionError if the thread is still alive
    after timeout seconds.
    zfailed to join the thread in rp  z secondsN)r   is_aliver1  )rm  r   r   rk   rk   rl   join_thread	  s    
rt  c                  C   sj   t tdrt tdsdS ztdtj\} }W n tk
rF   Y qfY nX | dkrRqftd|   daqdS )zUse 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.
    waitpidWNOHANGNrv  r   z%reap_children() reaped child process T)r   r   ru  rv  r   r`  rk  )rF  Zstatusrk   rk   rl   rN   #	  s    	
c                 c   s   t | } g }zVz | D ]}|  || qW n*   trRtd
t| t|f   Y nX d V  W 5 z|rp|  t  }}t	ddD ]\}|d7 }|D ]}|
t|t  d qdd |D }|s qtrtd	t||f  qW 5 dd |D }|rttj tdt| X X d S )Nc                 S   s   g | ]}|  r|qS rk   rs  rX  r  rk   rk   rl   rY  ^	  s      z!start_threads.<locals>.<listcomp>zUnable to join %d threadsr      <   ri  c                 S   s   g | ]}|  r|qS rk   rw  rx  rk   rk   rl   rY  W	  s      z7Unable to join %d threads during a period of %d minutesz/Can't start %d threads, only %d threads started)r   faulthandlerZdump_tracebackr   r   r1  r   r   rq  rj  r   maxr   r   r'  r   )ZthreadsZunlockr   ZendtimeZ	starttimer   r  rk   rk   rl   rS   ?	  sB    

c              
   c   sn   t | |r<t| |}t| || z
|V  W 5 t| || X n.t| || z
dV  W 5 t | |rht| | X dS )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   r  new_valreal_valrk   rk   rl   rZ   c	  s    




c              	   c   sX   || kr0| | }|| |< z
|V  W 5 || |< X n$|| |< z
dV  W 5 || krR| |= X dS )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.
    Nrk   )r   itemr~  r  rk   rk   rl   rY   	  s    

c                 C   s   t dd|  } | S )zStrip 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   )r  substrip)r  rk   rk   rl   strip_python_stderr	  s    r  Z	getcountsz-types are immortal if COUNT_ALLOCS is definedc                   C   s   t  S )znReturn a list of command-line arguments reproducing the current
    settings in sys.flags and sys.warnoptions.)r#  Z_args_from_interpreter_flagsrk   rk   rk   rl   args_from_interpreter_flags	  s    r  c                   C   s   t  S )zgReturn a list of command-line arguments reproducing the current
    optimization settings in sys.flags.)r#  Z"_optim_args_from_interpreter_flagsrk   rk   rk   rl   !optim_args_from_interpreter_flags	  s    r  c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
rO   c                 C   s   t jj| d || _d S r   )logginghandlersBufferingHandlerr  matcher)rw   r  rk   rk   rl   r  	  s    zTestHandler.__init__c                 C   s   dS NFrk   r  rk   rk   rl   shouldFlush	  s    zTestHandler.shouldFlushc                 C   s   |  | | j|j d S r   )r  r   r   __dict__)rw   rl  rk   rk   rl   emit	  s    
zTestHandler.emitc                 K   s,   d}| j D ]}| jj|f|r
d} q(q
|S )zW
        Look for a saved dict whose keys/values match the supplied arguments.
        FT)r   r  matches)rw   ry   r   drk   rk   rl   r  	  s    
zTestHandler.matchesN)rg   rh   ri   r  r  r  r  rk   rk   rk   rl   rO   	  s   	c                   @   s    e Zd ZdZdd Zdd ZdS )r[   )r   rr  c                 K   s:   d}|D ],}|| }| |}| |||sd} q6q|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)r  match_value)rw   r  ry   r   r  r  dvrk   rk   rl   r  	  s    
zMatcher.matchesc                 C   sH   t |t |krd}n.t |tk	s,|| jkr6||k}n||dk}|S )zT
        Try to match a single stored value (dv) with a supplied value (v).
        Fr   )r  r   _partial_matchesfind)rw   r  r  r  r   rk   rk   rl   r  	  s    
zMatcher.match_valueN)rg   rh   ri   r  r  r  rk   rk   rk   rl   r[   	  s   c               
   C   sZ   t d k	rt S td } ztt|  d}W n tttfk
rF   d}Y nX t|  |a |S )Nr   TF)_can_symlinkr   r   symlinkr   NotImplementedErrorr   r  )Zsymlink_pathcanrk   rk   rl   r   	  s    

c                 C   s    t  }d}|r| S t|| S )z8Skip decorator for tests that require functional symlinkz*Requires functional symlink implementation)r   r   r  rz   okr   rk   rk   rl   r0   

  s    c                 C   sP   t dkr:tjdkr6t d dkr6t jdkr6da nda t rLt	d| S | S )	a-  
    Skip decorator for tests that use buggy strptime/strftime

    If the UCRT bugs are present time.localtime().tm_zone will be
    an empty string, otherwise we assume the UCRT bugs are fixed

    See bpo-37552 [Windows] strptime/strftime return invalid
    results with UCRT version 17763.615
    Nr8  r   cp65001r   TFz!buggy MSVC UCRT strptime/strftime)
_buggy_ucrtr   r   r  Zgetdefaultlocaler   	localtimetm_zoner   r  r   rk   rk   rl   r@   
  s    
c                   @   sh   e Zd ZdZdddZdd Zejdkr0dd Zd	d
 Zdd Z	dd Z
ddddZddddZdS )PythonSymlinkz3Creates a symlink for the current Python executableNc                 C   s@   |pt jt| _g | _t jtj| _	g | _
d | _|   d S r   )r   r   r   r   link_linkedrB  r   r%  real
_also_link_env_platform_specific)rw   r  rk   rk   rl   r  '
  s    zPythonSymlink.__init__c                 C   s   d S r   rk   r  rk   rk   rl   r  1
  s    z PythonSymlink._platform_specificr8  c              
   C   s  dd l }tj| jr0tj| js0|d| _|tj}tj	|}tj	| j
}| j|tj|tj|f ttjt|dD ]&}| j|tj|tj|f qdd tjD | _tj	| j| jd< tdrtj	tj| jd< d S )Nr   zvcruntime*.dllc                 S   s   i | ]}|  t|qS rk   )upperr   getenv)rX  r  rk   rk   rl   
<dictcomp>J
  s      z4PythonSymlink._platform_specific.<locals>.<dictcomp>Z
PYTHONHOMETZ
PYTHONPATH)_winapir   r   lexistsr  rP  ZGetModuleFileNamer   Z	dllhandler   r  r  r   r   basenameglobescaper  r  r  Zis_python_buildr   )rw   r  r  Zsrc_dirZdest_dirZruntimerk   rk   rl   r  5
  s&    
c                 C   sJ   t | j| j | j| j | jD ] \}}t || | j| q$| S r   )r   r  r  r  r  r   r  )rw   r  r  rk   rk   rl   r  O
  s    zPythonSymlink.__enter__c                 C   sV   | j D ]J}zt| W q tk
rN } ztr>td|| W 5 d }~X Y qX qd S )Nzfailed to clean up {}: {})r  r   r  IOErrorr   r   r  )rw   exc_type	exc_valueZexc_tbr  Zexrk   rk   rl   r  W
  s    
zPythonSymlink.__exit__c                 C   sp   |f|}t j|t jt j|d}| }|j|krltr\tt|d  tt|d tj	d t
d|j|S )N)r   r  envr   r   r   z'unexpected return code: {0} (0x{0:08X}))r#  r$  PIPEcommunicate
returncoder   r   reprr   r  RuntimeErrorr  )rw   Zpythonrx   r  r  cmdr   r!  rk   rk   rl   _call_
  s    

 

zPythonSymlink._callr   )r  c                G   s   |  | j|d |S r   )r  r  rw   r  rx   rk   rk   rl   	call_reall
  s    zPythonSymlink.call_realc                G   s   |  | j|| j|S r   )r  r  r  r  rk   rk   rl   	call_linko
  s    zPythonSymlink.call_link)N)rg   rh   ri   rj   r  r  r   r   r  r  r  r  r  rk   rk   rk   rl   r  %
  s   


r  c               	   C   s   t d k	rt S ttdsd} nt }tj|d\}}zt	td}z`t
|dd t
|dd t
| dd t }td	|}|d kpt|d
dk} W n tk
r   d} Y nX W 5 Q R X W 5 tt t| t| X | a | S )NsetxattrFdirr\  s	   user.testr   s   trusted.foos   42z2.6.(\d{1,2})r   '   )
_can_xattrr   r   r@  rA  Zmkstempr   r   r   rS  r  r]  r   r  r  r  r  r  r   )r  Ztmp_dirZtmp_fpZtmp_namefpZkernel_versionr  rk   rk   rl   	can_xattrt
  s,    

r  c                 C   s    t  }d}|r| S t|| S )zDSkip decorator for tests that require functional extended attributesz(no non-broken extended attribute support)r  r   r  r  rk   rk   rl   r9   
  s    c                 C   s$   t  pt}d}|r| S t|| S )z;Skip decorator for tests not run in (non-extended) PGO taskz#Not run for (non-extended) PGO task)r`   PGO_EXTENDEDr   r  r  rk   rk   rl   skip_if_pgo_task
  s    
r  c                 C   s   t tdstd| S tdkrtd }ttjP}z>z|| daW n& t	k
rp } z|aW 5 d}~X Y nX W 5 t| X W 5 Q R X trdt }t|| S | S dS )zCDecorator for tests requiring a functional bind() for unix sockets.r0  zNo UNIX SocketsNZcan_bind_unix_socketFz%Requires a functional unix bind(): %s)
r   r&  r   r  _bind_nix_socket_errorr   r0  r   r.  r   )rz   r   r/  r	  r   rk   rk   rl   r?   
  s    

c              
   C   sx   t j| db}|j}| }||kr,| }ztj||W W  5 Q R  S  tk
rh   Y W 5 Q R  dS X W 5 Q R X dS )zKDetects if the file system for the specified directory is case-insensitive.r  FN)	r@  ZNamedTemporaryFiler   r  r  r   r   samefiler   )Z	directorybase	base_pathZ	case_pathrk   rk   rl   r   
  s    rr   c                C   s>   t t| t t| }|r(|t |8 }t dd |D }|S )a  Returns 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 '__'.
    c                 s   s&   | ]}| d r|dr|V  qdS )___N)r   endswith)rX  r  rk   rk   rl   	<genexpr>
  s    
 
z&detect_api_mismatch.<locals>.<genexpr>)r  r  )Zref_apiZ	other_apirm   Zmissing_itemsrk   rk   rl   r=   
  s
    c                 C   s   |dkr|j f}nt|tr"|f}t|}t|D ]R}|ds2||krJq2t||}t|dd|kszt|ds2t|tj	s2|
| q2| |j| dS )a  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 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.

    Usage:
        import bar
        import foo
        import unittest
        from test import support

        class MiscTestCase(unittest.TestCase):
            def test__all__(self):
                support.check__all__(self, foo)

        class OtherTestCase(unittest.TestCase):
            def test__all__(self):
                extra = {'BAR_CONST', 'FOO_CONST'}
                blacklist = {'baz'}  # Undocumented name.
                # bar imports part of its API from _bar.
                support.check__all__(self, bar, ('bar', '_bar'),
                                     extra=extra, blacklist=blacklist)

    Nr  rh   )rg   r  r   r  r  r   r   r   types
ModuleTypeaddZassertCountEqual__all__)Z	test_caser   Zname_of_moduleZextraZ	blacklistZexpectedr   r   rk   rk   rl   r>   
  s     )



c                 C   s   zdd l }W n tk
r"   Y d S X ||j|jB |jB |jB  t|dr|j|j	|j
fD ]2}| r|||j |||j q\||d q\d S )Nr   CrtSetReportMode)msvcrtr   SetErrorModeZSEM_FAILCRITICALERRORSZSEM_NOALIGNMENTFAULTEXCEPTSEM_NOGPFAULTERRORBOXZSEM_NOOPENFILEERRORBOXr   CRT_WARN	CRT_ERROR
CRT_ASSERTr  CRTDBG_MODE_FILECrtSetReportFileCRTDBG_FILE_STDERR)r   r  r  rk   rk   rl   suppress_msvcrt_asserts  s"    
r  c                   @   s(   e Zd ZdZdZdZdd Zdd ZdS )r]   zTry 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              	   C   sV  t jdrzddl}W n tk
r.   Y dS X ||j| _|| j|jB  t|dri | _	|j
|j|jfD ].}|||j}|||j}||f| j	|< qpntdk	rz*ttj| _ttjd| jd f W n ttfk
r   Y nX t jdkrRddd	d
g}tj|tjtjd}| | d }W 5 Q R X | dkrRtdddd | S )zOn Windows, disable Windows Error Reporting dialogs using
        SetErrorMode() and CrtSetReportMode().

        On UNIX, try to save the previous core file size limit, then set
        soft limit to 0.
        r   r   Nr  r   r   z/usr/bin/defaultsr  zcom.apple.CrashReporterZ
DialogType)r   r  s	   developerz:this test triggers the Crash Reporter, that is intentionalr   T)endr"  )r   r   r   r  r   r  r  	old_valuer   	old_modesr  r  r  r  r  r  r  r  Z	getrlimitRLIMIT_CORE	setrlimitr  r   r#  r$  r  r  r  r   )rw   r  report_typeold_modeold_filer  procr   rk   rk   rl   r  *  sZ    
  zSuppressCrashReport.__enter__c              	   G   s   | j dkrdS tjdrfddl}|| j  | jr| j D ]$\}\}}||| |	|| q>n6t
dk	rzt
t
j| j  W n ttfk
r   Y nX dS )zARestore Windows ErrorMode or core file behavior to initial value.Nr   r   )r  r   r   r   r  r  r  r   r  r  r  r  r  r  r   )rw   r  r  r  r  r  rk   rk   rl   r  h  s    
zSuppressCrashReport.__exit__)rg   rh   ri   rj   r  r  r  r  rk   rk   rk   rl   r]   !  s
   >c              	      sr   t  d zj W n$ ttfk
r@   t dY nX d  fdd}| | t| dS )zOverride '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'.

    FNTc                      s     rt  n
t d S r   )r  r}  rk   Zattr_is_local	attr_nameobject_to_patchr  rk   rl   cleanup  s    zpatch.<locals>.cleanup)r   r  r   r   Z
addCleanupr  )Ztest_instancer  r  Z	new_valuer  rk   r  rl   patch}  s    


r  c                 C   sF   zddl }W n tk
r    Y nX | r4tdddl}|| S )zi
    Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
    module is enabled.
    r   NzUrun_in_subinterp() cannot be used if tracemalloc module is tracing memory allocations)tracemallocr   
is_tracingr   r   r  run_in_subinterp)r  r  r  rk   rk   rl   r    s    
r  c                    sH   G  fddd|}d ||| |  tt t  |   d S )Nc                       s   e Zd Z fddZdS )z%check_free_after_iterating.<locals>.Ac                    s*   d zt  W n tk
r$   Y nX d S rD  )nextStopIterationr  Zdoneitrk   rl   __del__  s
    z-check_free_after_iterating.<locals>.A.__del__N)rg   rh   ri   r  rk   r  rk   rl   A  s   r  F)ZassertRaisesr  r  r  rp  )rz   r  rZ  rx   r  rk   r  rl   check_free_after_iterating  s    	r  c                 C   s   ddl m}m}m} | }|| |jD ]Z}| r>|| kr>q,t||}| rb|dk	shtd| n|shq,|	|d dkr,|d   S q,dS )a<  Check if the compiler components used to build the interpreter exist.

    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.

    r   )	ccompilerr  spawnNz%the '%s' executable is not configured)
Z	distutilsr  r  r  Znew_compilerZcustomize_compilerZexecutablesr   r1  Zfind_executable)Z	cmd_namesr  r  r  Zcompilerr   r  rk   rk   rl   ra     s    	



c                 C   s@   d}t r6| |k r6td kr.tddg dkatr6|} t| S )Ngh㈵>Zgetpropzro.kernel.qemu   1)rC   _is_android_emulatorr#  Zcheck_outputr  r   rF   )ZintervalZminimum_intervalrk   rk   rl   rF     s    c               
   c   s>   t j } t }zt  d V  W 5 |r8tj| dd X d S )NT)r   Zall_threads)r   r   r]  r{  
is_enabledr  r  )rW  r  rk   rk   rl   disable_faulthandler  s    

r  c            	      C   sv  t jdr:ztd} t| d W S  tk
r8   Y nX d}ttdrlztd}W n t	k
rj   Y nX d}t jdkrzd	dl
}|j W n ttfk
r   Y n,X i }|j|j|jfD ]}||d	||< qzld	}t|D ]Z}zt|}W n4 t	k
r$ } z|jtjkr W 5 d}~X Y qX t| |d7 }qW 5 |dk	rp|j|j|jfD ]}||||  qXX |S )
z/Count the number of open file descriptors.
    )linuxZfreebsdz/proc/self/fdr      sysconfSC_OPEN_MAXNr8  r   )r   r   r   r   r   r   r   r   r  r   r  r  r   r   r  r  r  rj  dupr  ZEBADFr3  )	namesZMAXFDr  r  r  rl  rW  Zfd2r	  rk   rk   rl   rb     sT    





c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	SaveSignalsz
    Save and restore signal handlers.

    This class is only able to save/restore signal handlers registered
    by the Python signal module: see bpo-13285 for "external" signal
    handlers.
    c              	   C   s`   dd l }|| _ | | _dD ]8}zt||}W n tk
rF   Y qY nX | j| qi | _d S )Nr   )SIGKILLSIGSTOP)signalvalid_signalssignalsr   r   r  r  )rw   r  Zsignamesignumrk   rk   rl   r  B  s    

zSaveSignals.__init__c                 C   s0   | j D ]$}| j|}|d kr q|| j|< qd S r   )r  r  	getsignalr  rw   r  Zhandlerrk   rk   rl   saveO  s
    
zSaveSignals.savec                 C   s&   | j  D ]\}}| j|| q
d S r   )r  r   r  r  rk   rk   rl   restore[  s    zSaveSignals.restoreN)rg   rh   ri   rj   r  r  r	  rk   rk   rk   rl   r  9  s   r  c                  C   s   dd l } | jS r   )r  ZWITH_PYMALLOC)r  rk   rk   rl   with_pymalloc`  s    r
  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	FakePathz.Simple implementing of the path protocol.
    c                 C   s
   || _ d S r   r   )rw   r   rk   rk   rl   r  h  s    zFakePath.__init__c                 C   s   d| j dS )Nz
<FakePath >r   r  rk   rk   rl   __repr__k  s    zFakePath.__repr__c                 C   s6   t | jts$t | jtr,t| jtr,| jn| jS d S r   )r  r   BaseExceptionr  rq  r  rk   rk   rl   
__fspath__n  s    

zFakePath.__fspath__N)rg   rh   ri   rj   r  r  r  rk   rk   rk   rl   r  e  s   r  c                   @   s    e Zd ZdZdd Zdd ZdS )
_ALWAYS_EQz+
    Object that is equal to anything.
    c                 C   s   dS rD  rk   rw   otherrk   rk   rl   __eq__{  s    z_ALWAYS_EQ.__eq__c                 C   s   dS r  rk   r  rk   rk   rl   __ne__}  s    z_ALWAYS_EQ.__ne__N)rg   rh   ri   rj   r  r  rk   rk   rk   rl   r  w  s   r  c                   @   s    e Zd ZdZdd Zdd ZdS )_LARGESTz?
    Object that is greater than anything (except itself).
    c                 C   s
   t |tS r   )r  r  r  rk   rk   rl   r    s    z_LARGEST.__eq__c                 C   s   dS r  rk   r  rk   rk   rl   __lt__  s    z_LARGEST.__lt__N)rg   rh   ri   rj   r  r  rk   rk   rk   rl   r    s   r  c                   @   s    e Zd ZdZdd Zdd ZdS )	_SMALLESTz<
    Object that is less than anything (except itself).
    c                 C   s
   t |tS r   )r  r  r  rk   rk   rl   r    s    z_SMALLEST.__eq__c                 C   s   dS r  rk   r  rk   rk   rl   __gt__  s    z_SMALLEST.__gt__N)rg   rh   ri   rj   r  r  rk   rk   rk   rl   r    s   r  c                   C   s   t jjS )zDReturn the global event loop policy if one is set, else return None.)asyncioZeventsZ_event_loop_policyrk   rk   rk   rl   maybe_get_event_loop_policy  s    r  )    @   c              
   C   s   | | }}dd l }| }| d }t|d|_||}|d | | }|| }	||	 }
||
 }||d  |d | |  |	d|	   }t|t| fW  5 Q R  S Q R X d S )Nr   r      r   )decimalZlocalcontext
bit_lengthr|  ZprecZDecimalr  Zsqrt)ZnbinsZnballsr  r  r  ctxbitsrQ  Zp1emptyZ	meanemptyZoccupiedZ
collisionsvarrk   rk   rl   collision_stats  s    


(r#  c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )catch_unraisable_exceptiona  
    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:

        with support.catch_unraisable_exception() as cm:
            # code creating an "unraisable exception"
            ...

            # check the unraisable exception: use cm.unraisable
            ...

        # cm.unraisable attribute no longer exists at this point
        # (to break a reference cycle)
    c                 C   s   d | _ d | _d S r   )
unraisable	_old_hookr  rk   rk   rl   r    s    z#catch_unraisable_exception.__init__c                 C   s
   || _ d S r   )r%  )rw   r%  rk   rk   rl   _hook  s    z catch_unraisable_exception._hookc                 C   s   t j| _| jt _| S r   )r   unraisablehookr&  r'  r  rk   rk   rl   r    s    z$catch_unraisable_exception.__enter__c                 G   s   | j t_| `d S r   )r&  r   r(  r%  rw   exc_infork   rk   rl   r    s    z#catch_unraisable_exception.__exit__Nrg   rh   ri   rj   r  r'  r  r  rk   rk   rk   rl   r$    s
   r$  c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )catch_threading_exceptiona  
    Context manager catching threading.Thread exception using
    threading.excepthook.

    Attributes set when an exception is catched:

    * exc_type
    * exc_value
    * exc_traceback
    * thread

    See threading.excepthook() documentation for these attributes.

    These attributes are deleted at the context manager exit.

    Usage:

        with support.catch_threading_exception() as cm:
            # code spawning a thread which raises an exception
            ...

            # check the thread exception, use cm attributes:
            # exc_type, exc_value, exc_traceback, thread
            ...

        # exc_type, exc_value, exc_traceback, thread attributes of cm no longer
        # exists at this point
        # (to avoid reference cycles)
    c                 C   s"   d | _ d | _d | _d | _d | _d S r   )r  r  exc_tracebackrm  r&  r  rk   rk   rl   r    s
    z"catch_threading_exception.__init__c                 C   s$   |j | _ |j| _|j| _|j| _d S r   )r  r  r-  rm  )rw   rx   rk   rk   rl   r'    s    zcatch_threading_exception._hookc                 C   s   t j| _| jt _| S r   )re  
excepthookr&  r'  r  rk   rk   rl   r     s    z#catch_threading_exception.__enter__c                 G   s   | j t_| `| `| `| `d S r   )r&  re  r.  r  r  r-  rm  r)  rk   rk   rl   r  %  s
    z"catch_threading_exception.__exit__Nr+  rk   rk   rk   rl   r,    s
   r,  c               
   c   s.   t jd d  } z
d V  W 5 | t jd d < X d S r   )rn   r  )Zold_filtersrk   rk   rl   save_restore_warnings_filters-  s    
r/  c               
   C   sb   t d t d} tjdkr^z| jdd W n2 tk
r\ } ztd|W 5 d}~X Y nX dS )z
    Skip tests if the multiprocessing.synchronize module is missing, if there
    is no available semaphore implementation, or if creating a lock raises an
    OSError (on Linux only).
    Z_multiprocessingzmultiprocessing.synchronizer  N)r   z broken multiprocessing SemLock: )r   r   r   ZLockr   r   r   )Zsynchronizer   rk   rk   rl   *skip_if_broken_multiprocessing_synchronize6  s    
r0  )T)F)rk   rk   F)F)N)N)NF)F)rK  F)N)r   )r   )F)T)N)NN)Nr   )ro  )r  )N)Nrk   rk   )F)rk   (5  rj   rg   r   Zasyncio.eventsr  Zcollections.abccollections
contextlibr  r{  rW  r}   r  r  r"  r   importlib.utilr  Zlogging.handlersr  r  r   r   r  r   r&  r   r  r#  r   r  r@  rc  re  r   r  r   Zurllib.errorr  rn   Z
testresultr   Zmultiprocessing.processZmultiprocessingzlibrz  bz2Zlzmar  r   r  r  r	   r
   r   r   r   contextmanagerrs   rA   r   r   r   r;   r<   r   r7   r   r   r   r  rB  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r  r"   r#   r$   r%   rG   ZHOSTv4r4  r,  r-  rI   rJ   rL   r5  rH   r7  r   ZSOCK_MAX_SIZEZ
skipUnlessr  __getformat__r8   r:   r1   r2   r3   rB   r   rC   rE   r   r   r  rD  ZTEST_HTTP_URLZFS_NONASCII	characterfsdecodefsencodeUnicodeErrorZTESTFN_UNICODEunicodedataZ	normalizegetfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversionencodeUnicodeEncodeErrorr   decodeUnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIrH  r   r`   r  rG  rJ  r   rM   r   r   r   r   ZTEST_SUPPORT_DIRrO  r   r~  r   r   r^   r^  r&   r'   rK   objectr  r  rT   r  rV   rU   r   abcMutableMappingrW   r  r(   r   r  r)   r  r*   r+   r  r,   r  r   r   r   r  r  r  r  r  r  r  r  r  r  r  rX   r_   r  r  r  Z_4Gr-  r  r\   r  r4   r5   r-   r2  r3  r6   r5  r6  rD   r<  r=  r?  rC  rE  rM  rO  rG  rI  rP  rN  r.   r[  r  ZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr/   r`  ra  rb  rk  rP   rQ   rR   rr  rt  rN   rS   rZ   rY   r  r  Zrequires_type_collectingr  r  r  r  rO   r[   r  r   r0   r  r@   r  r  r  r9   r  r  r?   r   r=   r>   r  r]   r  r  r  ra   r  rF   r  rb   r  r
  r  r  rc   total_orderingr  rd   r  re   r  	hash_infowidthZ	NHASHBITSr1  r#  r$  r,  r/  r0  rk   rk   rk   rl   <module>   s  






                                                                  0
2	
!
J			=%	
!


&

2'

 5M
		




$
#


0




!




"

#
	"N ;\";'	
	
	
",9