a
    kxg                 	   @   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mZ g dZdZejd	kre d
krdZdZdZ dZ!G dd de"Z#G dd de#Z$G dd de#Z%G dd dej&Z'ej(diddZ)dd Z*djdddd Z+d!d" Z,d#d$ Z-d%d& Z.d'd( Z/dkd)d*Z0d+d, Z1dZ2dZ3da4da5dZ6dZ7da8d-d. Z9d/d0 Z:d1d2 Z;d3d4 Z<ej=d5rdld6d7Z>d8d9 Z?d:d; Z@d<d= ZAd>d? ZBnejCZ?ejDZ@d@d= ZAdAd? ZBdBdC ZCdDdE ZDdFdG ZEdHdI ZFdJdK ZGdLdM ZHdNdO ZIdmdPdQZJdRdS ZKdTdU ZLdVdW ZMdXdY ZNdZd[ ZOd\ZPd]ZQeReSTd^=d_d`ZUdndbdcZVdodedfZWdpdhdiZXdqdkdlZYej=dmZZe[ednZ\ejd	kr&e\r dondpZ]ndZ]ej^dmkr<dqZ_ndrZ_ds`e_ea Z_dtZbduZcdvD ]DZdzeeefededkr|egW n egy   Y n0 edZc qq\e_dw ZhejdxkrddliZieijdyehZhek ZldZmej^dzkr4en jd{krte_d| Zmzemoel W n epy   Y n0 eqd}emelf  dZmn@ejdxkrtzd~rel W n$ esyr   e_dreld ZmY n0 dZtdD ]@Z^ze^rel W n* esy   efe_e^ ZtY  qY n0 q|ecre_ec ZundZueupe_Zvew ZxdZydZzej(drddZ{ej(dsddZ|ej(dtddZ}e[edr<ej(dd Z~ejejeZejeZejedZduddZdd Zdd Zdd ZdvdddddZdwdddddZdd ZG dd deZdxddZej(dd Zej(duedfddZej(dd ZG dd deZG dd dejjZG dd deZG dd deZeeejdZeeejdZeeejdZej(dd Zdd Zdd Zdd Zdd Zej(dd Zdd ZdZdZe[edrde ZdZed ZddĄ ZddƄ ZdZdZddʄ Zdd̄ Zdd΄ ZdZde Zd{e Zde ZejZddӄ ZG ddՄ dՃZdyddׄZddل ZG ddۄ dۃZdd݄ Zdd߄ Zdd ZdzddZdd Zdd Zdd Zdd Zdd Zdd Zdadadadd Zdd Zːd{ddZdd Zdd Zdd Ze o"ejd	ko"ed Zej duo4e ZeRedZӐd|ddZԐd d ZՐdd Z֐dd Zdaؐdd Zِdd	 Zڐd
d Zej(d}ddZܐd~ddZݐdd Zej(dddZej(dd Zej(dd Zdd Zdd ZG dd deZdadd Zd d! Zdad"d# ZG d$d% d%Zdad&d' Zd(d) Zd*d+ Zd,d- Zdd.d/d0Zdd1d2Zdd3d4ZG d5d6 d6Zd7d8 Zd9d: Zdd;d<Zg fd=d>Zdad?d@ Zej(dAdB ZdCdD ZG dEdF dFZdGdH ZG dIdJ dJZG dKdL dLZe Z G dMdN dNZe ZejG dOdP dPZe ZejG dQdR dRZe ZdSdT Zej	j
ZedUv sDJ dVdW ZG dXdY dYZG dZd[ d[Zdd\d]d^Zd_d` Zdadb Zej(dcdd Zdedf Zej(dgdh Zd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check_syntax_errorcheck_syntax_warningTransientResourcetime_outsocket_peer_resetioerror_peer_reset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_if_buggy_ucrt_strfptimeignore_warnings	is_jython
is_androidcheck_impl_detail
unix_shellsetswitchintervalopen_urlresource
temp_umaskreap_children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NEVER_EQLARGESTSMALLESTLOOPBACK_TIMEOUTINTERNET_TIMEOUTSHORT_TIMEOUTLONG_TIMEOUTg      @win32ZARM
   g      N@g      >@g     r@c                   @   s   e Zd ZdZdS )r	   z*Base class for regression test exceptions.N__name__
__module____qualname____doc__ ri   ri   +/usr/lib/python3.9/test/support/__init__.pyr	   v   s   r	   c                   @   s   e Zd ZdZdS )r
   zTest failed.Nrd   ri   ri   ri   rj   r
   y   s   r
   c                   @   s   e Zd ZdZdS )r   zTest did not run any subtests.Nrd   ri   ri   ri   rj   r   |   s   r   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.
    Nrd   ri   ri   ri   rj   r      s   r   Tc                 c   sL   | rBt  $ t ddt dV  W d   qH1 s60    Y  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rk   ri   ri   rj   _ignore_deprecated_imports   s    
&rq   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                    sP   t  4 t jd d | g|R i |W  d    S 1 sB0    Y  d S )Nrk   category)rl   rm   simplefilter)selfargskwargs)rs   testri   rj   wrapper   s    
z3ignore_warnings.<locals>.decorator.<locals>.wrapper	functoolswraps)rx   ry   rr   rx   rj   	decorator   s    z"ignore_warnings.<locals>.decoratorri   )rs   r~   ri   rr   rj   r>      s    r>   Fri   )required_onc                C   s   t |p zt| W W  d   S  tyh } z,tjt|rF t	t
|W Y d}~n
d}~0 0 W d   n1 s~0    Y  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)rq   	importlibr   ImportErrorsysplatform
startswithtupleunittestSkipTeststr)name
deprecatedr   msgri   ri   rj   r      s    	
r   c                 C   sZ   | t jv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modnameri   ri   rj   _save_and_remove_module   s    
r   c                 C   s<   d}zt j|  || < W n ty,   d}Y n0 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savedri   ri   rj   _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 Nri   fri   ri   rj   <lambda>       z$anticipate_failure.<locals>.<lambda>)r   ZexpectedFailure)Z	conditionri   ri   rj   r9      s    r9   c                 C   sF   |du 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_testsri   ri   rj   r:      s    

r:   c                 C   s   t | i }g }t| | zz@|D ]}t|| q$|D ]}t||s8|| q8t| }W n tyt   d}Y n0 W | D ]\}	}
|
tj	|	< q|D ]}tj	|= qn0| D ]\}	}
|
tj	|	< q|D ]}tj	|= q0 |W  d   S 1 s0    Y  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)
rq   r   r   appendr   r   r   itemsr   r   )r   ZfreshZblockedr   r   Znames_to_removeZ
fresh_nameZblocked_nameZfresh_moduleZ	orig_namemoduleZname_to_removeri   ri   rj   r      s,    


r   c                 C   s<   zt | |}W n$ ty2   td| |f Y n0 |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	attributeri   ri   rj   r5   %  s
    r5   c                 C   s   | a d S r   )_original_stdout)stdoutri   ri   rj   r   :  s    r   c                   C   s
   t ptjS r   )r   r   r   ri   ri   ri   rj   r   >  s    r   c                 C   s$   zt j| = W n ty   Y n0 d S r   r   )r   ri   ri   rj   r   A  s    r   c              
   G   sx   z
|| W S  t yr } zPtdkrHtd|jj|f  td|j|f  t| tj || W  Y d }~S d }~0 0 d S )N   z%s: %szre-run %s%r)	OSErrorr   print	__class__re   r   chmodstatS_IRWXU)r   funcrv   errri   ri   rj   
_force_runG  s    
r   winc                 C   s   | | |r|}nt j|\}}|p(d}d}|dk rjt |}|rJ|sVn||v sVd S t| |d9 }q.tjd| tdd d S )Nr   MbP?g      ?r   z)tests may fail, delete still pending for    
stacklevel)	r   r   splitlistdirtimesleeprl   warnRuntimeWarning)r   pathnamewaitallr   r   timeoutLri   ri   rj   _waitforR  s    



r   c                 C   s   t tj|  d S r   )r   r   r   filenameri   ri   rj   _unlinks  s    r   c                 C   s   t tj|  d S r   )r   r   rmdirr   ri   ri   rj   _rmdirv  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yn } z&td||f t	j
d d}W Y d }~n
d }~0 0 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_innerri   rj   r   z  s    
_rmtree.<locals>._rmtree_innerTr   c                 S   s   t | tj| S r   )r   r   r   )pri   ri   rj   r     r   z_rmtree.<locals>.<lambda>)r   r   ri   r   rj   _rmtreey  s    r   c                 C   s\   zdd l }W n ty   Y n:0 |t| d }|jj| |t|}|rX|d | S | S )Nr   r   )ctypesr   Zcreate_unicode_bufferlenwindllZkernel32ZGetLongPathNameW)r   r   bufferZlengthri   ri   rj   	_longpath  s    r   c                    sN   dd l }z||  W d S  ty*   Y n0  fdd  |  t|  d S )Nr   c              	      s~   t | tj| D ]j}tj| |}zt|j}W n tyF   d}Y n0 t	|rj | 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   ri   rj   r     s    

r   )shutilr   r   r   r   )r   r   ri   r   rj   r     s    
c                 C   s   | S r   ri   r   ri   ri   rj   r     s    c              	   C   s(   zt |  W n ttfy"   Y n0 d S r   )r   FileNotFoundErrorNotADirectoryErrorr   ri   ri   rj   r     s    r   c                 C   s$   zt |  W n ty   Y n0 d S r   )r   r   r   ri   ri   rj   r     s    r   c                 C   s$   zt |  W n ty   Y n0 d S r   )r   r   r   ri   ri   rj   r     s    r   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_pycri   ri   rj   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   optri   ri   rj   r     s    
r   c               
      s  t tdrtjS d } tjdr0t r0d} nBtjdrdd ldd ld}d}G fdddj	}j
j}| }|s | }j }||||||}|sƈ t|j|@ sd} ntjd	krrdd
lm}	m m}
m	} ddlm} |	|d}| dkr,d} nFG  fddd|}| }|
|}||dk sn||dk rrd} | sz.ddlm} | }|   |!  |"  W n^ t#y } zDt$|}t%|dkr|d d d }d&t'|j(|} W Y d }~n
d }~0 0 | t_)|  t_tjS )Nresultr   z(gui is not available on Windows IoT Corer   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)re   rf   rg   wintypesZBOOLDWORD_fields_ri   )r   ri   rj   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)re   rf   rg   r   ri   )r   ri   rj   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   Zwin32_is_iotr   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typere   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_stringri   )r   r   rj   r     sr    

r   c                 C   s   t du p| t v 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   resourceri   ri   rj   r    1  s    r    c                 C   s<   t | s |du 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   ri   ri   rj   r!   9  s    r!   c                 C   s   ddl }dtt|}| ddd }| | krrzttt|d}W n t	yf   d}Y qv0 ||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skipri   ri   rj   _requires_unix_versionB  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  ri   ri   rj   r"   ]  s    r"   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  ri   ri   rj   r#   f  s    r#   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                     sz   t jdkrlt d }zttt|d}W n ty@   Y n,0 |k rldtt	}t
d||f  | i |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   )rv   kwr  r  r  )r   r  ri   rj   ry   w  s    
z4requires_mac_ver.<locals>.decorator.<locals>.wrapper)r{   r|   r  r   ry   r  r   rj   r~   v  s    z#requires_mac_ver.<locals>.decoratorri   )r  r~   ri   r  rj   r$   o  s    r$   c                    s   t   fdd}|S )z5Skip the test on TLS certificate validation failures.c               
      sT   z | i | W n< t yN } z$dt|v r8td W Y d }~n
d }~0 0 d S )NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)r   r   r   r   )rv   rw   r  r   ri   rj   dec  s    
z&system_must_validate_cert.<locals>.decrz   )r   r  ri   r   rj   system_must_validate_cert  s    r   i @ i  ZdoubleZIEEEztest requires IEEE 754 doublesrequires zlibc                 C   s0   zdd l }W n ty"   d }Y n0 t|| S r   )zlibr   r   
skipUnless)r  r"  ri   ri   rj   r8     s
    
r8   requires gzipc                 C   s0   zdd l }W n ty"   d }Y n0 t|| S r   )gzipr   r   r#  )r  r%  ri   ri   rj   r/     s
    
r/   requires bz2c                 C   s0   zdd l }W n ty"   d }Y n0 t|| S r   )bz2r   r   r#  )r  r'  ri   ri   rj   r0     s
    
r0   requires lzmac                 C   s0   zdd l }W n ty"   d }Y n0 t|| S r   )lzmar   r   r#  )r  r)  ri   ri   rj   r1     s
    
r1   ZjavaZgetandroidapilevelz/system/bin/shz/bin/shz$testz@testz	{}_{}_tmpzhttp://www.pythontest.netr   )   æ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   c              
   c   s   ddl }d}| du r.| } d}tj| } nZzt|  d}W nF ty } z.|sV tjd| d| t	dd W Y d}~n
d}~0 0 |rt
 }z"| V  W |r|t
 krt|  n|r|t
 krt|  0 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.

    r   NFTz5tests may fail, unable to create temporary directory :    r   )tempfilemkdtempr   r   realpathmkdirr   rl   r   r   getpidr   )r   quietr1  Zdir_createdr   pidri   ri   rj   temp_diri  s6    

r8  c              
   c   s   t  }zt t j|  W nF tyd } z.|s4 tjd| d| tdd W Y d}~n
d}~0 0 zt  V  W t | nt | 0 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/  r0  r   N)	r   getcwdchdirr   r3  r   rl   r   r   )r   r6  Z	saved_dirr   ri   ri   rj   
change_cwd  s     r;  tempcwdc              	   c   sb   t | |dB}t||d}|V  W d   n1 s60    Y  W d   n1 sT0    Y  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   r6  )r6  N)r8  r;  )r   r6  Z	temp_pathZcwd_dirri   ri   rj   r     s    r   umaskc              	   c   s0   t | }zdV  W t | nt | 0 dS )z8Context manager that temporarily sets the process umask.N)r   r=  )r=  Zoldmaskri   ri   rj   rE     s    
rE   datac                 C   sb   t j| r| S |du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fnri   ri   rj   r     s    r   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_TRUNCclose)r   fdri   ri   rj   r     s    r   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: %rri   ).0Zpairri   ri   rj   
<listcomp>  r   zsortdict.<locals>.<listcomp>z, z{%s})sortedr   r   )dictr   Z	reprpairsZ
withcommasri   ri   rj   rU     s    
rU   c                  C   s<   t td} z|  W |   tt S |   tt 0 dS )z`
    Create an invalid file descriptor by opening and closing a file and return
    its fd.
    wbN)rD  r   filenorH  r   r   ri   ri   rj   make_bad_fd  s    
  rP  linenooffsetc                C   s   |  t|}t|dd W d    n1 s.0    Y  |j}| |j |d ur`| |j| | |j |d ur| |j| d S )Nz<test string>exec)ZassertRaisesRegexSyntaxErrorcompileZ	exceptionassertIsNotNonerR  assertEqualrS  )testcase	statementerrtextrR  rS  cmr   ri   ri   rj   r%     s    *r%   c                C   s  t jdd(}t dt t|dd W d    n1 s:0    Y  | t|d| |\}| t|j	t|j	 |r| 
t|j| | |jd | |j |d ur| |j| t jdd.}t dt t| ||||d W d    n1 s0    Y  | |g  d S )	NTrecordalwaysz
<testcase>rT  r   errorrQ  )rl   rm   rt   SyntaxWarningrV  rX  r   
assertTrue
issubclassrs   ZassertRegexr   messager   rW  rR  r%   )rY  rZ  r[  rR  rS  warnsr   ri   ri   rj   r&     s$    *$r&   c                    s  dd l }dd l}zdd l}W n ty2   d }Y n0 dd |j| d dd }tj	
t|} fdd}tj	|r||}|d ur|S t| td trtd	|  t d
 |j }	|r|	jd |	j| td}|r
|jddkr
|j|d}z\t|d4}
| }|r<|
| | }q W d    n1 sR0    Y  W |  n
|  0 ||}|d ur|S td| d S )Nr   checkr   /c                    sD   t | g R i }d u r"|S |r8|d |S |  d S r   )rD  seekrH  )rC  r   rv   rf  r  ri   rj   check_valid_file0  s    
z*open_urlresource.<locals>.check_valid_fileZurlfetchz	fetching %s ...r   )zAccept-Encodingr%  r   zContent-Encodingr%  )ZfileobjrN  zinvalid resource %r)Zurllib.requestZurllib.parser%  r   popparseZurlparser   r   r   r   TEST_DATA_DIRrA  r   r!   r   r   r   ZrequestZbuild_openerZ
addheadersr   rD  r_   ZheadersgetZGzipFilereadwriterH  r
   )Zurlrv   r  Zurllibr%  r   rC  rk  r   Zopeneroutsri   rj  rj   rD   #  sD    
	

.
rD   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)ru   Zwarnings_listri   ri   rj   __init__]  s    zWarningsRecorder.__init__c                 C   sD   t | j| jkr t| jd |S |tjjv r0d S td| |f d S )Nrh  z%r has no attribute %r)r   rw  rx  r   rl   WarningMessage_WARNING_DETAILSr   )ru   attrri   ri   rj   __getattr__a  s
    zWarningsRecorder.__getattr__c                 C   s   | j | jd  S r   rv  ru   ri   ri   rj   rl   h  s    zWarningsRecorder.warningsc                 C   s   t | j| _d S r   )r   rw  rx  r~  ri   ri   rj   resetl  s    zWarningsRecorder.resetN)	re   rf   rg   rh   ry  r}  propertyrl   r  ri   ri   ri   rj   ru  Y  s   
ru  c                 c   s  t d}|jd}|r"|  tjdd*}t jd d t	|V  W d   n1 s^0    Y  t
|}g }| D ]j\}}d}	|dd D ]8}|j}
t|t|
tjrt|
j|rd}	|| q|	sx|sx|||jf qx|rtd	|d
  |rt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__Tr]  rl   r_  NFzunhandled warning %sr   z)filter (%r, %s) did not catch any warning)r   	_getframe	f_globalsrp  clearrl   rm   r   rt   ru  r   rd  rematchr   Irc  r   remover   re   AssertionError)filtersr6  frameregistrywZreraiseZmissingr   catseenZwarningri   ri   rj   _filterwarningsp  s4    
(
r  c                  O   s.   | d}| s$dtff} |du 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)
    r6  r   NT)rp  Warningr  )r  rw   r6  ri   ri   rj   rK     s    

rK   c                 c   s\   t jdd0}t jd||d dV  |r.t  W d   n1 sB0    Y  | |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().
    Tr]  r_  )rd  rs   N)rl   rm   rn   
gc_collectrX  )rY  rd  rs   force_gcre  ri   ri   rj   rM     s    $rM   c                 c   s8   t | tdd dV  W d   n1 s*0    Y  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)rs   r  N)rM   ResourceWarning)rY  ri   ri   rj   rL     s    rL   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v rt j| }|j|kr<t j|j= t j|= qd S r   )r   r   copyoriginal_modulesre   )ru   Zmodule_namesZmodule_namer   ri   ri   rj   ry    s    



zCleanImport.__init__c                 C   s   | S r   ri   r~  ri   ri   rj   	__enter__  s    zCleanImport.__enter__c                 G   s   t j| j d S r   )r   r   r   r  ru   
ignore_excri   ri   rj   __exit__  s    zCleanImport.__exit__Nre   rf   rg   rh   ry  r  r  ri   ri   ri   rj   r     s   r   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 )rN   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~  ri   ri   rj   ry    s    zEnvironmentVarGuard.__init__c                 C   s
   | j | S r   )r  ru   envvarri   ri   rj   __getitem__  s    zEnvironmentVarGuard.__getitem__c                 C   s*   || j vr| j|| j |< || j|< d S r   r  r  rp  ru   r  valueri   ri   rj   __setitem__  s    
zEnvironmentVarGuard.__setitem__c                 C   s2   || j vr| j|| j |< || jv r.| j|= d S r   r  r  ri   ri   rj   __delitem__  s    

zEnvironmentVarGuard.__delitem__c                 C   s
   | j  S r   )r  keysr~  ri   ri   rj   r    s    zEnvironmentVarGuard.keysc                 C   s
   t | jS r   )iterr  r~  ri   ri   rj   __iter__  s    zEnvironmentVarGuard.__iter__c                 C   s
   t | jS r   )r   r  r~  ri   ri   rj   __len__  s    zEnvironmentVarGuard.__len__c                 C   s   || |< d S r   ri   r  ri   ri   rj   set  s    zEnvironmentVarGuard.setc                 C   s
   | |= d S r   ri   r  ri   ri   rj   unset  s    zEnvironmentVarGuard.unsetc                 C   s   | S r   ri   r~  ri   ri   rj   r  !  s    zEnvironmentVarGuard.__enter__c                 G   sF   | j  D ].\}}|d u r.|| jv r8| j|= q
|| j|< q
| jt_d S r   )r  r   r  r   r  )ru   r  kvri   ri   rj   r  $  s    

zEnvironmentVarGuard.__exit__N)re   rf   rg   rh   ry  r  r  r  r  r  r  r  r  r  r  ri   ri   ri   rj   rN     s   rN   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)ru   pathsri   ri   rj   ry  :  s    zDirsOnSysPath.__init__c                 C   s   | S r   ri   r~  ri   ri   rj   r  ?  s    zDirsOnSysPath.__enter__c                 G   s   | j t_| jtjd d < d S r   )r  r   r   r  r  ri   ri   rj   r  B  s    zDirsOnSysPath.__exit__Nr  ri   ri   ri   rj   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)ru   r   rw   ri   ri   rj   ry  L  s    zTransientResource.__init__c                 C   s   | S r   ri   r~  ri   ri   rj   r  P  s    zTransientResource.__enter__Nc                 C   sT   |du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)rc  r   r  r   r   r   r   )ru   type_r  	tracebackr|  Z
attr_valueri   ri   rj   r  S  s    
zTransientResource.__exit__)NNNr  ri   ri   ri   rj   r'   G  s   r'   )errnoc              
   c   sR   ddl }tt| }tt| |  ztt| V  W tt| | ntt| | 0 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_stdoutri   ri   rj   captured_outputh  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  ri   ri   ri   rj   r   t  s    r   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")
    stderrr  ri   ri   ri   rj   r   }  s    r   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  ri   ri   ri   rj   r     s    
r   c                  C   s2   ddl } |   trtd |   |   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.
    r   N皙?)gcZcollectr?   r   r   )r  ri   ri   rj   r    s    

r  c                  c   sB   dd l } |  }|   zd V  W |r>|   n|r<|   0 d S r   )r  Z	isenableddisableenable)r  Zhave_gcri   ri   rj   
disable_gc  s    
r  c                  C   s6   t dpd} d}|  D ]}|dr|}q|dv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   ri   ri   rj   python_is_optimized  s    
r  ZnPZ0nZ
getobjectsZ2PZ0Pnc                 C   s   t t|  t S r   )structcalcsize_header_alignZfmtri   ri   rj   calcobjsize  s    r  c                 C   s   t t|  t S r   )r  r  _vheaderr  r  ri   ri   rj   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)	_testinternalcapir   	getsizeofr  	__flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADrX  )rx   osizer  r   r   ri   ri   rj   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y4    Y nB   d  }}Y n00 D ](}z||| W  qvW qL   Y qL0 qLz&| i |W |r|r||| S n|r|r||| 0 d S r   )localer   	setlocaler   )rv   kwdsr  rs   Zorig_localeZloc)catstrr   localesri   rj   inner  s.    

 z1run_with_locale.<locals>.decorator.<locals>.innerre   rh   r   r  r  r  r  rj   r~     s    z"run_with_locale.<locals>.decoratorri   )r  r  r~   ri   r  rj   rO     s    rO   c                    s    fdd}|S )Nc                    s"    fdd} j |_  j|_|S )Nc               	      s   z
t j}W n ty&   tdY n0 dtjv r>tjd }nd }tjd< |  zH | i |W |d u rttjd= n
|tjd< t   S |tjd< t   n&|d u rtjd= n
|tjd< t   0 d S )Nztzset requiredZTZ)r   tzsetr   r   r   r   r  )rv   r  r  Zorig_tz)r   tzri   rj   r     s0    




  



z-run_with_tz.<locals>.decorator.<locals>.innerr  r  r  r  rj   r~     s    zrun_with_tz.<locals>.decoratorri   )r  r~   ri   r  rj   rV     s    rV   i      r   c                 C   s   dt tdt d}td| tjtjB }|d u 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   r0  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memlimitri   ri   rj   rS   (  s"    
$rS   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)r7  F)r  r   r5  procfilestartedr~  ri   ri   rj   ry  B  s    z_MemoryWatchdog.__init__c              
   C   s   zt | jd}W nB tyR } z*td|t tj	  W Y d }~d S d }~0 0 |2 t
d}tjtj|g|tjd| _W d    n1 s0    Y  d| _d S )Nrz!/proc not available for stats: {}zmemory_watchdog.py)r  r  T)rD  r  r   rl   r   r  r   r   r  flushr   
subprocessPopen
executableZDEVNULLmem_watchdogr  )ru   r   r  Zwatchdog_scriptri   ri   rj   startF  s    
&z_MemoryWatchdog.startc                 C   s   | j r| j  | j  d S r   )r  r  Z	terminatewaitr~  ri   ri   rj   stopV  s    
z_MemoryWatchdog.stopN)re   rf   rg   rh   ry  r  r  ri   ri   ri   rj   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 |r|
  S n|r|
  0 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  )ru   r  r   maxsizeZwatchdog)dry_runr   ry   ri   rj   ry   j  s<    




 z.bigmemtest.<locals>.decorator.<locals>.wrapper)r  r   r   r  r   r  r   ry   rj   r~   i  s    zbigmemtest.<locals>.decoratorri   )r  r   r  r~   ri   r  rj   r2   \  s    !r2   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   ri   rj   ry     s    z!bigaddrspacetest.<locals>.wrapperri   r  ri   r   rj   r3     s    r3   c                   @   s   e Zd Zdd ZdS )r+   c                 C   s   t  }|| |S r   )r   Z
TestResult)ru   rx   r   ri   ri   rj   run  s    zBasicTestRunner.runN)re   rf   rg   r  ri   ri   ri   rj   r+     s   r+   c                 C   s   | S r   ri   )r   ri   ri   rj   _id  s    r  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    r  r  r	  ri   ri   rj   requires_resource  s
    r  c                 C   s   t dd| S )z9
    Decorator for tests only applicable on CPython.
    T)cpython)impl_detailr}   ri   ri   rj   r4     s    r4   c                 K   sZ   t f i |rtS | d u rPt|\}}|r0d} nd} t| }| d|} t| S )Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or )	rA   r  _parse_guardsrL  r  r  r   r   r  )r   guardsZ
guardnamesdefaultri   ri   rj   r	    s    r	  c                 C   sH   | sddidfS t |  d }t |  |gt|  ks>J | | fS )Nr  TFr   )r   valuesr   )r  Zis_trueri   ri   rj   r
    s
    r
  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
    )r
  rp  r   Zpython_implementationr  )r  r  ri   ri   rj   rA     s    rA   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               	      s>   t  }z$t d   | i |W t | S t | 0 d S r   )r   r  settrace)rv   rw   Zoriginal_tracer  ri   rj   ry     s    

zno_tracing.<locals>.wrapperN)r   r   r{   r|   r  ri   r  rj   
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  r4   r}   ri   ri   rj   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_tests
isinstancer   	TestSuite_filter_suiter   )suiteZpredZnewtestsrx   ri   ri   rj   r    s    

r  c                 C   s   t tjttdud}|| }tdu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_listr  r   Zget_xml_elementZtestsRunZskippedr   ZwasSuccessfulr   errorsZfailuresr
   )r  Zrunnerr   r   ri   ri   rj   
_run_suite  s"    
r  c                 C   s   t d u rdS t |  S d S NT)_match_test_funcidr}   ri   ri   rj   
match_test  s    r  c                 C   s   d| v ot d|  S )Nr   z[?*\[\]])r  search)r   ri   ri   rj   _is_full_match_test%  s    r  c                    s~   | d u rd} |d u rd}d   | t kr4t| \}  |tkrHt|\}t| a t|a d ushd urz fdd}|ad S )Nri   c                    s*   d}d} r | }r | }|o(| S )NTFri   )test_idZacceptrk   Zaccept_funcZignore_funcri   rj   match_functionD  s    z'set_match_tests.<locals>.match_function)_accept_test_patterns_compile_match_function_ignore_test_patternsr   r  )Zaccept_patternsZignore_patternsr"  ri   r!  rj   set_match_tests/  s    	r&  c                    s^   | sd }d} nHt tt| r(t| j}n.dttj| }t	|j
  fdd}|}| |fS )Nri   |c                    s$    | rdS t t | dS d S )NTr   )anyr  r   )r   Zregex_matchri   rj   match_test_regex_  s    z1_compile_match_function.<locals>.match_test_regex)allr  r  r  __contains__r   fnmatch	translater  rV  r  )Zpatternsr   Zregexr*  ri   r)  rj   r$  P  s    r$  c                  G   s   t jt jf}t  }| D ]`}t|trR|tjv 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  r  r  )classesZvalid_typesr  clsri   ri   rj   r,   o  s    




r,   c                   C   s   dS )z,Just used to check if docstrings are enabledNri   ri   ri   ri   rj   _check_docstrings  s    r1  ZWITH_DOC_STRINGSztest requires docstringsc                 C   s`   ddl }|du 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   re   )r   r  r2  r3  r   r  ri   ri   rj   r-     s    r-   c                 C   s(   |   D ]}td| tjdd qd S )NzWarning -- T)r   r  )
splitlinesr   r   r   )r   lineri   ri   rj   print_warning  s    r6  c                   C   s   t j fS r   )r   r   r  ri   ri   ri   rj   modules_setup  s    r7  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   )rJ  r  r  ri   ri   rj   rK    s   
z#modules_cleanup.<locals>.<listcomp>)r   r   r   r  r   )Z
oldmodulesZ	encodingsri   ri   rj   modules_cleanup  s    
r8  c                   C   s   t  tj fS r   )_thread_count	threading	_danglingr  ri   ri   ri   rj   rG     s    rG   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?)ranger9  r:  r;  r<  environment_alteredr6  r   r   r   r  )Zoriginal_valuesZ
_MAX_COUNTcountr  Zdangling_threadsthreadri   ri   rj   rH     s*    

rH   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 t|  S t|  0 d S r   )rG   rH   )rv   keyr  ri   rj   r~     s    zreap_threads.<locals>.decoratorrz   )r   r~   ri   r  rj   rI     s    rI   c                 c   s  | du rt } t }zdV  W t }||  }t }||kr@qt |krt | }d||  d|dd| d| d	}t|td t  q.n~t }||  }t }||krqt |krt | }d||  d|dd| d| d	}t|td t  q0 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.
    Nz!wait_threads() failed to cleanup z threads after .1fz seconds (count: z, old count: r>  r?  )r`   r9  r:  r   	monotonicr  r   r  )r   Z	old_countZ
start_timeZdeadlinerB  dtr   ri   ri   rj   wait_threads_exit  sN    


rH  c                 C   s8   |du rt }| | |  r4d|dd}t|dS )zcJoin a thread. Raise an AssertionError if the thread is still alive
    after timeout seconds.
    Nzfailed to join the thread in rE   seconds)r`   r   is_aliver  )rC  r   r   ri   ri   rj   join_thread1  s    
rK  c                  C   sh   t tdrt tdsdS ztdtj\} }W n tyD   Y qdY n0 | dkrPqdt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WNOHANGNrh  r   z%reap_children() reaped child process T)r   r   rL  rM  r   r6  rA  )r7  statusri   ri   rj   rF   =  s    	
rF   c                 c   sL  dd l }t| } g }z<z | D ]}|  || qW n*   tr\tdt| t|f   Y n0 d V  W z|rx|  t  }}t	ddD ]\}|d7 }|D ]}|
t|t  d qdd |D }|s qtrtd	t||f  qW d
d |D }|rR|tj tdt| n2d
d |D }|rP|tj tdt| 0 nz|rb|  t  }}t	ddD ]f}|d7 }|D ]}|
t|t  d qdd |D }|s qtrxtd	t||f  qxW d
d |D }|rF|tj tdt| n2d
d |D }|rD|tj tdt| 0 0 d S )Nr   z/Can't start %d threads, only %d threads startedr      <   r?  c                 S   s   g | ]}|  r|qS ri   rJ  rJ  r  ri   ri   rj   rK  r  r   z!start_threads.<locals>.<listcomp>z7Unable to join %d threads during a period of %d minutesc                 S   s   g | ]}|  r|qS ri   rQ  rR  ri   ri   rj   rK  y  r   zUnable to join %d threads)faulthandlerr   r  r   r   r   r   r   rF  r@  r   maxZdump_tracebackr   r   r  )ZthreadsZunlockrS  r  r  ZendtimeZ	starttimer   ri   ri   rj   rJ   Y  sz    


rJ   c              
   c   s   t | |rHt| |}t| || z|V  W t| || qt| || 0 nBt| || zdV  W t | |rt| | nt | |rt| | 0 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_valri   ri   rj   rQ   ~  s    



rQ   c              	   c   sn   || v r8| | }|| |< z|V  W || |< qj|| |< 0 n2|| |< zdV  W || v rj| |= n|| v rh| |= 0 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.
    Nri   )r   itemrV  rW  ri   ri   rj   rP     s    rP   c                   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_flagsri   ri   ri   rj   args_from_interpreter_flags  s    rY  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_flagsri   ri   ri   rj   !optim_args_from_interpreter_flags  s    rZ  c                   @   s    e Zd ZdZdd Zdd ZdS )rR   )r   rd  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)rp  match_value)ru   drw   r   r  r  dvri   ri   rj   matches  s    
zMatcher.matchesc                 C   sH   t |t |krd}n.t |tus,|| jv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)ru   r  r]  r  r   ri   ri   rj   r[    s    
zMatcher.match_valueN)re   rf   rg   r_  r^  r[  ri   ri   ri   rj   rR     s   rR   c               
   C   sX   t d urt S td } ztt|  d}W n tttfyD   d}Y n0 t|  |a |S )Nr   TF)_can_symlinkr   r   symlinkr   NotImplementedErrorr   r  )Zsymlink_pathcanri   ri   rj   r     s    

r   c                 C   s    t  }d}|r| S t|| S )z8Skip decorator for tests that require functional symlinkz*Requires functional symlink implementation)r   r   r  rx   okr   ri   ri   rj   r.     s    r.   c                 C   sX   ddl }tdu rBtjdkr>| d dkr>t jdkr>dandatrTt	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
    r   Nrb   r   cp65001r   TFz!buggy MSVC UCRT strptime/strftime)
r  _buggy_ucrtr   r   Zgetdefaultlocaler   	localtimetm_zoner   r  )rx   r  ri   ri   rj   r=    	  s    

r=   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_linkedr3  r   r  real
_also_link_env_platform_specific)ru   rl  ri   ri   rj   ry  	  s    zPythonSymlink.__init__c                 C   s   d S r   ri   r~  ri   ri   rj   rq  !	  s    z PythonSymlink._platform_specificrb   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 ri   )upperr   getenv)rJ  r  ri   ri   rj   
<dictcomp>:	  r   z4PythonSymlink._platform_specific.<locals>.<dictcomp>Z
PYTHONHOMETZ
PYTHONPATH)_winapir   r   lexistsrn  rA  ZGetModuleFileNamer   Z	dllhandler   rl  ro  r   r   basenameglobescaper  rp  r  Zis_python_buildr   )ru   ru  r  Zsrc_dirZdest_dirZruntimeri   ri   rj   rq  %	  s&    
c                 C   sJ   t | j| j | j| j | jD ] \}}t || | j| q$| S r   )r   rb  rn  rl  rm  r   ro  )ru   rn  rl  ri   ri   rj   r  ?	  s    zPythonSymlink.__enter__c                 C   sX   | j D ]L}zt| W q tyP } z tr<td|| W Y d }~qd }~0 0 qd S )Nzfailed to clean up {}: {})rm  r   r  IOErrorr   r   r  )ru   exc_type	exc_valueZexc_tbrl  Zexri   ri   rj   r  G	  s    
zPythonSymlink.__exit__c                 C   sp   |g|}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  )ru   Zpythonrv   r}  r  cmdr   r  ri   ri   rj   _callO	  s    



zPythonSymlink._callr   )r  c                G   s   |  | j|d |S r   )r  rn  ru   r  rv   ri   ri   rj   	call_real\	  s    zPythonSymlink.call_realc                G   s   |  | j|| j|S r   )r  rl  rp  r  ri   ri   rj   	call_link_	  s    zPythonSymlink.call_link)N)re   rf   rg   rh   ry  rq  r   r   r  r  r  r  r  ri   ri   ri   rj   rk  	  s   


rk  c               	   C   s  dd l } td urtS ttds$d}n|  }| j|d\}}zttd}z`t|dd t|dd	 t|	 dd t
 }td
|}|d u pt|ddk}W n ty   d}Y n0 W d    n1 s0    Y  W tt t| t| ntt t| t| 0 |a|S )Nr   setxattrFdirrN  s	   user.testr   s   trusted.foos   42z2.6.(\d{1,2})r   '   )r1  
_can_xattrr   r   r2  ZmkstemprD  r   r  rO  r   r  r  r  r  r  r   r   r   )r1  rd  Ztmp_dirZtmp_fpZtmp_namefpZkernel_versionr  ri   ri   rj   	can_xattrd	  s4    
*

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  re  ri   ri   rj   r7   	  s    r7   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)rW   PGO_EXTENDEDr   r  re  ri   ri   rj   skip_if_pgo_task	  s    
r  c              	   C   s   ddl }|j| dn}|j}| }||kr4| }ztj||W W  d   S  tyr   Y W d   dS 0 W d   n1 s0    Y  dS )zKDetects if the file system for the specified directory is case-insensitive.r   Nr  F)	r1  ZNamedTemporaryFiler   rr  r  r   r   samefiler   )Z	directoryr1  base	base_pathZ	case_pathri   ri   rj   r   	  s    r   rp   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)rJ  r  ri   ri   rj   	<genexpr>	  s   z&detect_api_mismatch.<locals>.<genexpr>)r  r  )Zref_apiZ	other_apirk   Zmissing_itemsri   ri   rj   r;   	  s
    r;   c                 C   s   |du r|j f}nt|tr"|f}t|}t|D ]R}|ds2||v rJq2t||}t|dd|v 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  rf   )re   r  r   r  r  r   r   r   types
ModuleTypeaddZassertCountEqual__all__)Z	test_caser   Zname_of_moduleZextraZ	blacklistZexpectedr   r   ri   ri   rj   r<   	  s     )



r<   c                 C   s   zdd l }W n ty    Y d S 0 ||j|jB |jB |jB  t|dr|j|j	|j
fD ]2}| r|||j |||j qZ||d qZd 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  ri   ri   rj   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 )rT   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   s  t jdrzddl}W n ty,   Y dS 0 ||j| _|| j|jB  t|dri | _	|j
|j|jfD ].}|||j}|||j}||f| j	|< qnnzddl}|| _W n ty   d| _Y n0 | jdur$z2| j| jj| _| j| jjd| jd f W n ttfy"   Y n0 t jdkrg d}tj|tjtjd}| | d }W d   n1 st0    Y  | d	krt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/defaultsrq  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  stripr   )	ru   r  report_typeold_modeold_filer
  r  procr   ri   ri   rj   r  
  s\    

,zSuppressCrashReport.__enter__c              	   G   s   | j du rdS tjdrfddl}|| j  | jr| j D ]$\}\}}||| |	|| q>n:| j
durz| j
| j
j| j  W n ttfy   Y n0 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   )ru   r  r  r  r  r  ri   ri   rj   r  I
  s    

zSuppressCrashReport.__exit__)re   rf   rg   rh   r  r  r  r  ri   ri   ri   rj   rT   	  s
   CrT   c              	      sp   t  d zj W n" ttfy>   t dY n0 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  rU  ri   Zattr_is_local	attr_nameobject_to_patchr  ri   rj   cleanupt
  s    zpatch.<locals>.cleanup)r   __dict__r   r   Z
addCleanupr  )Ztest_instancer  r  Z	new_valuer  ri   r  rj   patch^
  s    


r  c                 C   sD   zddl }W n ty   Y n0 | r2t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   	_testcapirun_in_subinterp)coder  r  ri   ri   rj   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y"   Y n0 d S r  )nextStopIterationr~  Zdoneitri   rj   __del__
  s
    z-check_free_after_iterating.<locals>.A.__del__N)re   rf   rg   r  ri   r  ri   rj   A
  s   r  F)ZassertRaisesr  r  r  rb  )rx   r  r0  rv   r  ri   r  rj   check_free_after_iterating
  s    	r  c                 C   s   ddl m}m}m}m} | }|| |jdkrXz|  W n |j	yV   Y dS 0 |j
D ]Z}| rp|| vrpq^t||}| r|dusJ d| n|sq^||d du 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  spawnr  ZmsvcNz%the '%s' executable is not configured)Z	distutilsr  r  r  r  Znew_compilerZcustomize_compilerZcompiler_typeZ
initializeZDistutilsPlatformErrorZexecutablesr   Zfind_executable)Z	cmd_namesr  r  r  r  Zcompilerr   r  ri   ri   rj   rX   
  s(    	




rX   c                 C   s@   d}t r6| |k r6td u r.tddg dkatr6|} t| S )Ngh㈵>Zgetpropzro.kernel.qemu   1)r@   _is_android_emulatorr  Zcheck_outputr  r   rC   )ZintervalZminimum_intervalri   ri   rj   rC   
  s    rC   c               
   c   sX   dd l } tj }|  }z$|   d V  W |rT| j|dd n|rR| j|dd 0 d S )Nr   T)r   Zall_threads)rS  r   r   rO  
is_enabledr  r  )rS  rI  r  ri   ri   rj   disable_faulthandler
  s    
r  c            	      C   s  t jdr8ztd} t| d W S  ty6   Y n0 d}ttdrhztd}W n t	yf   Y n0 d}t jdkrzd	dl
}|j W n ttfy   Y n,0 i }|j|j|jfD ]}||d	||< qzd	}t|D ]\}zt|}W n6 t	y  } z|jtjkr W Y d}~qd}~0 0 t| |d7 }qW |dur|j|j|jfD ]}||||  qRn4|dur|j|j|jfD ]}||||  q0 |S )
z/Count the number of open file descriptors.
    )linuxZfreebsdz/proc/self/fdr      sysconfSC_OPEN_MAXNrb   r   )r   r   r   r   r   r   r   r   r  r   r  r  r   r   r  r  r  r@  dupr  ZEBADFrH  )	namesZMAXFDr  r  r  rB  rI  Zfd2r  ri   ri   rj   rY   
  s`    






rY   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 ]6}zt||}W n tyD   Y qY n0 | j| qi | _d S )Nr   )SIGKILLSIGSTOP)signalvalid_signalssignalsr   r   r  handlers)ru   r  Zsignamesignumri   ri   rj   ry  +  s    

zSaveSignals.__init__c                 C   s0   | j D ]$}| j|}|d u r q|| j|< qd S r   )r  r  	getsignalr  ru   r  Zhandlerri   ri   rj   save8  s
    
zSaveSignals.savec                 C   s&   | j  D ]\}}| j|| q
d S r   )r  r   r  r  ri   ri   rj   restoreD  s    zSaveSignals.restoreN)re   rf   rg   rh   ry  r  r  ri   ri   ri   rj   r  "  s   r  c                  C   s   dd l } | jS r   )r  ZWITH_PYMALLOC)r  ri   ri   rj   with_pymallocI  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   )ru   r   ri   ri   rj   ry  Q  s    zFakePath.__init__c                 C   s   d| j dS )Nz
<FakePath >r   r~  ri   ri   rj   __repr__T  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  rc  r~  ri   ri   rj   
__fspath__W  s    

zFakePath.__fspath__N)re   rf   rg   rh   ry  r  r  ri   ri   ri   rj   r  N  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 r  ri   ru   otherri   ri   rj   __eq__d  s    z_ALWAYS_EQ.__eq__c                 C   s   dS NFri   r  ri   ri   rj   __ne__f  s    z_ALWAYS_EQ.__ne__N)re   rf   rg   rh   r  r  ri   ri   ri   rj   r  `  s   r  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )		_NEVER_EQz/
    Object that is not equal to anything.
    c                 C   s   dS r  ri   r  ri   ri   rj   r  o  s    z_NEVER_EQ.__eq__c                 C   s   dS r  ri   r  ri   ri   rj   r  q  s    z_NEVER_EQ.__ne__c                 C   s   dS )Nr   ri   r~  ri   ri   rj   __hash__s  s    z_NEVER_EQ.__hash__N)re   rf   rg   rh   r  r  r  ri   ri   ri   rj   r  k  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  ri   ri   rj   r  }  s    z_LARGEST.__eq__c                 C   s   dS r  ri   r  ri   ri   rj   __lt__  s    z_LARGEST.__lt__N)re   rf   rg   rh   r  r  ri   ri   ri   rj   r  x  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  ri   ri   rj   r    s    z_SMALLEST.__eq__c                 C   s   dS r  ri   r  ri   ri   rj   __gt__  s    z_SMALLEST.__gt__N)re   rf   rg   rh   r  r  ri   ri   ri   rj   r    s   r  c                  C   s   ddl } | jjS )zDReturn the global event loop policy if one is set, else return None.r   N)Zasyncio.eventsZeventsZ_event_loop_policy)Zasynciori   ri   rj   maybe_get_event_loop_policy  s    r  )    @   c                 C   s   | | }}dd l }| }| d }t|d|_||}|d | | }|| }	||	 }
||
 }||d  |d | |  |	d|	   }t|t| fW  d    S 1 s0    Y  d S )Nr   r      r   )decimalZlocalcontext
bit_lengthrT  ZprecZDecimalr  Zsqrt)ZnbinsZnballsr  r  r  ctxbitsrB  Zp1emptyZ	meanemptyZoccupiedZ
collisionsvarri   ri   rj   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~  ri   ri   rj   ry    s    z#catch_unraisable_exception.__init__c                 C   s
   || _ d S r   )r  )ru   r  ri   ri   rj   _hook  s    z catch_unraisable_exception._hookc                 C   s   t j| _| jt _| S r   )r   unraisablehookr  r  r~  ri   ri   rj   r    s    z$catch_unraisable_exception.__enter__c                 G   s   | j t_| `d S r   )r  r   r  r  ru   exc_infori   ri   rj   r    s    z#catch_unraisable_exception.__exit__Nre   rf   rg   rh   ry  r  r  r  ri   ri   ri   rj   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_tracebackrC  r  r~  ri   ri   rj   ry  
  s
    z"catch_threading_exception.__init__c                 C   s$   |j | _ |j| _|j| _|j| _d S r   )r{  r|  r   rC  )ru   rv   ri   ri   rj   r    s    zcatch_threading_exception._hookc                 C   s   t j| _| jt _| S r   )r;  
excepthookr  r  r~  ri   ri   rj   r    s    z#catch_threading_exception.__enter__c                 G   s   | j t_| `| `| `| `d S r   )r  r;  r  r{  r|  r   rC  r  ri   ri   rj   r    s
    z"catch_threading_exception.__exit__Nr  ri   ri   ri   rj   r    s
   r  rl  c                C   s&  t jdkrddl}|du rt}t }d}d}t | t j\}}|dkrJqt | }	|	tkrzt | |j	 t | d W n t
y   Y n0 td|  d|	dd	t|d
 |}t| q.nt | d\}}t |}
|
|krtd|  d|
 d| d|| kr"td| d|  dS )a  
    Wait until process pid completes and check that the process exit code is
    exitcode.

    Raise an AssertionError if the process exit code is not equal to exitcode.

    If the process runs longer than timeout seconds (SHORT_TIMEOUT by default),
    kill the process (if signal.SIGKILL is available) and raise an
    AssertionError. The timeout feature is not available on Windows.
    r,  r   Nr   r  zprocess z is still running after rE  rI  r   z exited with code z, but exit code z is expectedzpid z != pid )r   r   r  r`   r   rF  rL  rM  killr  r   r  minr   waitstatus_to_exitcode)r7  Zexitcoder   r  Zt0r   Z	max_sleepZpid2rN  rG  Z	exitcode2ri   ri   rj   wait_process$  s<    






r  c                  C   s    dd l } |  }|d d dkS )Nr   configZ_use_peg_parser)r  Zget_configs)r  r  ri   ri   rj   use_old_parserY  s    r  c                 C   s   t t  | S r   )r   r  r  )r   ri   ri   rj   skip_if_new_parser_  s    r  c               
   c   s<   t jd d  } zd V  W | t jd d < n| t jd d < 0 d S r   )rl   r  )Zold_filtersri   ri   rj   save_restore_warnings_filtersc  s    r	  c               
   C   sd   t d t d} tjdkr`z| jdd W n4 ty^ } ztd|W Y d}~n
d}~0 0 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   ri   ri   rj   *skip_if_broken_multiprocessing_synchronizel  s    
r
  c              	   c   s8   t  }zt |  dV  W t | nt | 0 dS )z>Temporarily change the integer string conversion length limit.N)r   get_int_max_str_digitsset_int_max_str_digits)Z
max_digitsZcurrentri   ri   rj   adjust_int_max_str_digits  s
    
r  )T)F)ri   ri   F)F)N)r!  )r$  )r&  )r(  )NF)F)r<  F)N)r   )r   )F)T)N)NN)Nr   )N)N)N)Nri   ri   )F)ri   (  rh   re   r   collections.abccollections
contextlibr  r-  r{   rx  r   importlib.utilr   r   r  r   r  r  r   r  r9  r;  r   r  r   rl   Z
testresultr   r  r^   machiner_   r`   ra   r   r	   r
   r   r   r   contextmanagerrq   r>   r   r   r   r9   r:   r   r5   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!   r  r"   r#   r$   r   r   ZSOCK_MAX_SIZEr#  r  __getformat__r6   r8   r/   r0   r1   r?   r   r@   rB   r   ZTESTFN_ASCIIr  r5  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_NONASCIIr   r9  r   rW   r  r8  r;  r   rE   r   r   r   r   ZTEST_SUPPORT_DIRr@  r   ro  r   r   rU   rP  r%   r&   rD   objectru  r  rK   r  rM   rL   r   abcMutableMappingrN   r  r'   r   Z	ETIMEDOUTr(   Z
ECONNRESETr)   r*   r  r   r   r   r  r  r  r  r  r  r  r  r  r  r  rO   rV   r  r  r  Z_4Gr  r  rS   r  r2   r3   r+   r  r  r4   r	  r
  rA   r  r  r  r  r  r#  r%  r  r  r&  r$  r,   r1  r  ZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr-   r6  r7  r8  rA  rG   rH   rI   rH  rK  rF   rJ   rQ   rP   rY  rZ  rR   ra  r   r.   rh  r=   rk  r  r  r7   r  r   r;   r<   r  rT   r  r  r  rX   r  rC   r  rY   r  r  r  r  rZ   r  r[   total_orderingr  r\   r  r]   r  	hash_infowidthZ	NHASHBITSr  r  r  r  r  r  r	  r
  r  ri   ri   ri   rj   <module>   sz  8
2	
!
L			
!




'

6'

 5
		

$#0

!

$$"N ;a";'	
	
	
",95