o
    f                    @   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mZ zddlmZ W n eyO   dZY nw g dZd	Zejd
krcdejv rcdZnejdkrjd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ZG dd dejZdd Z dd Z!dd  Z"dZ#dZ$da%da&dZ'd!Z(da)d"d# Z*d$d% Z+d&d' Z,d(d) Z-d*d+ Z.dd,d-Z/d.d/ Z0d0d1 Z1d2d3 Z2d4d5 Z3d!d!d!d6d7d8Z4dd!d!d!d6d9d:Z5d;d< Z6d=Z7d>Z8e9e:;d?<d@dAZ=d	dCdDZ>d
dFdGZ?ddIdJZ@ddLdMZAe9edNZBej<dOZCeDedPZEejdQvr<eEr9dRndSZFndZFdTZGd!ZHd!ZIejJKejJLeMZNejJKeNZOejJPeOdUZQdVdW ZRddXdYZSdZd[ ZTdddd]d^d_ZUd`da ZVejWdbdc ZXddde ZYdfdg ZZdhdi Z[djdk Z\ejWdldm Z]dndo Z^dpZ_dqZ`eDedrrdse_ Z_dtZ`e_du Zadvdw Zbdxdy ZcdzZdd{Zed|d} ZfejWd~d Zgdd ZhdZidei Zjdej Zkdej ZlejmZndd ZoG dd dZpdddZqdd ZrG dd dZsdd Ztdd Zudd ZvdddZwdd Zxdd Zydd Zzdd Z{dd Z|dd Z}da~dadadd Zdd ZdddZdd Zdd Zdd Zey oNejd
koNe	d Zej duoWe Ze9edZdddZdd Zd!add ZejWdd ZejWdd Zdd Zdd ZG dd deZdaddĄ ZG ddƄ dƃZddȄ Zddʜdd̄Z		ɐddd΄ZdddЄZG dd҄ d҃ZddԄ ZejWddք Zdd؄ ZdddڄZg fdd܄Zdaddބ ZejWdd ZG dd dZdd ZG dd dZe ZG dd dZe ZejG dd dZe ZejG dd dZe Zdd ZejjZedv s)J dd ZG dd dZddddZdd ZejWdddZdd Zdeded efddZded dfddZejWdd ZdS (  z7Supporting definitions for the Python regression tests.ztest.supportz.support must be imported from the test package    N   )get_test_runner)unicode_legacy_string)BPIPE_MAX_SIZEverbose
max_memuseuse_resourcesfailfastError
TestFailedTestDidNotRunResourceDeniedrecord_original_stdoutget_original_stdoutcaptured_stdoutcaptured_stdincaptured_stderris_resource_enabledrequiresrequires_freebsd_versionrequires_linux_versionrequires_mac_vercheck_syntax_errorBasicTestRunnerrun_unittestrun_doctestrequires_gziprequires_bz2requires_lzma
bigmemtestbigaddrspacetestcpython_onlyget_attributerequires_IEEE_754requires_zlibanticipate_failureload_package_testsdetect_api_mismatchcheck__all__skip_if_buggy_ucrt_strfptimecheck_disallow_instantiationcheck_sanitizerskip_if_sanitizer	is_jython
is_androidcheck_impl_detail
unix_shellsetswitchintervalopen_urlresourcereap_childrenrun_with_locale	swap_itemfindfile	swap_attrMatcherset_memlimitSuppressCrashReportsortdictrun_with_tzPGOmissing_compiler_executable	ALWAYS_EQNEVER_EQLARGESTSMALLESTLOOPBACK_TIMEOUTINTERNET_TIMEOUTSHORT_TIMEOUTLONG_TIMEOUTg      @win32z 32 bit (ARM)
   vxworksg      N@g      >@g     r@c                   @      e Zd ZdZdS )r
   z*Base class for regression test exceptions.N__name__
__module____qualname____doc__ rP   rP   ,/usr/lib/python3.10/test/support/__init__.pyr
   g       r
   c                   @   rJ   )r   Test failed.NrK   rP   rP   rP   rQ   r   j   rR   r   c                       s(   e Zd ZdZ fddZdd Z  ZS )TestFailedWithDetailsrS   c                    s&   || _ || _|| _t ||| d S N)msgerrorsfailuressuper__init__)selfrV   rW   rX   	__class__rP   rQ   rZ   o   s   zTestFailedWithDetails.__init__c                 C   s   | j S rU   )rV   r[   rP   rP   rQ   __str__u   s   zTestFailedWithDetails.__str__)rL   rM   rN   rO   rZ   r_   __classcell__rP   rP   r\   rQ   rT   m   s    rT   c                   @   rJ   )r   zTest did not run any subtests.NrK   rP   rP   rP   rQ   r   x   rR   r   c                   @   rJ   )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.
    NrK   rP   rP   rP   rQ   r   {   rR   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 rU   rP   frP   rP   rQ   <lambda>       z$anticipate_failure.<locals>.<lambda>)unittestexpectedFailure)	conditionrP   rP   rQ   r%      s   r%   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*)	start_dirtop_level_dirpattern)ospathdirname__file__discoveraddTests)pkg_dirloaderstandard_testsrk   top_dirpackage_testsrP   rP   rQ   r&      s   

r&   c                 C   s2   zt | |}W |S  ty   td| |f w )z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %r)getattrAttributeErrorrf   SkipTest)objname	attributerP   rP   rQ   r"      s   r"   Fc                 C   s   | a d S rU   )_original_stdout)stdoutrP   rP   rQ   r      s   r   c                   C   s
   t ptjS rU   )r}   sysr~   rP   rP   rP   rQ   r         
r   c              
   G   st   z|| W S  t y9 } z(tdkr$td|jj|f  td|j|f  t| tj || W  Y d }~S d }~ww )N   z%s: %szre-run %s%r)	OSErrorr   printr]   rL   rl   chmodstatS_IRWXU)rm   funcargserrrP   rP   rQ   
_force_run   s   
r   c               
      s  t tdrtjS dd l} d }tjdr|  rd}ntjdrpdd ldd ld}d}G fdddj	}j
j}| }|sF | }j }||||||}	|	sf t|j|@ sod}nHtjd	krdd
lm}
m m}m	} ddlm} |
|d}| dkrd}n!G  fddd|}| }||}||dk s||dk rd}|szddlm} | }|   |!  |"  W n- t#y } z!t$|}t%|dkr|d d d }d&t'|j(|}W Y d }~nd }~ww |t_)| t_tjS )Nresultr   winz(gui is not available on Windows IoT Corer   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>.USEROBJECTFLAGSfInherit	fReserveddwFlagsN)rL   rM   rN   wintypesBOOLDWORD_fields_rP   )ctypesrP   rQ   USEROBJECTFLAGS   s
    


r   z,gui not available (WSF_VISIBLE flag not set)darwin)cdllc_intpointer	Structure)find_library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>.ProcessSerialNumberhighLongOfPSNlowLongOfPSNN)rL   rM   rN   r   rP   )r   rP   rQ   ProcessSerialNumber   s    r   z#cannot run without OS X gui process)Tk2   z [...]zTk unavailable due to {}: {})*hasattr_is_gui_availabler   platformr   
startswithwin32_is_iotr   ctypes.wintypesr   windlluser32GetProcessWindowStationWinErrorr   r   GetUserObjectInformationWbyrefsizeofboolr   r   r   r   ctypes.utilr   LoadLibraryCGMainDisplayIDGetCurrentProcessSetFrontProcesstkinterr   withdrawupdatedestroy	ExceptionstrlenformattyperL   reason)r   r   	UOI_FLAGSWSF_VISIBLEr   dllhuofneededresr   r   r   r   app_servicesr   psnpsn_pr   roote
err_stringrP   )r   r   rQ   r      sx   


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   resourcerP   rP   rQ   r     s   r   c                 C   s@   t | s|du rd|  }t|| dkrt sttjdS 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   rV   rP   rP   rQ   r     s   
r   c                 C   s   ddl }dtt|}| ddd }| | kr9zttt|d}W n t	y3   d}Y nw ||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   N.-r   Fz	 version z or higher required, not )r   joinmapr   releasesplitsystemtupleint
ValueErrorrf   skipIf)sysnamemin_versionr   min_version_txtversion_txtversionskiprP   rP   rQ   _requires_unix_version(  s"   
r   c                  G   
   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.
    FreeBSDr   r   rP   rP   rQ   r   C     
r   c                  G   r   )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.
    Linuxr   r   rP   rP   rQ   r   L  r   r   c                         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                     s   t jdkr:dd l}| d }zttt|d}W n	 ty$   Y nw |k r:dtt	}t
d||f  | i |S )Nr   r   r   z&Mac OS X %s or higher required, not %s)r   r   mac_verr   r   r   r   r   r   r   rf   ry   )r   kwr   r   r   r   )r   r   rP   rQ   wrapper]  s    
z4requires_mac_ver.<locals>.decorator.<locals>.wrapper)	functoolswrapsr   r   r   r   r   rQ   	decorator\  s   z#requires_mac_ver.<locals>.decoratorrP   )r   r   rP   r   rQ   r   U  s   r   addressmemoryubc                 C   sx   | s
|s
|s
t dtdpd}tdpd}d|v pd|v }d|v p'd|v }d|v p/d	|v }|r4|p;| o7|p;|o;|S )
z9Returns True if Python is compiled with sanitizer supportz3At least one of address, memory, or ub must be TrueCFLAGS CONFIG_ARGSz-fsanitize=memoryz--with-memory-sanitizerz-fsanitize=addressz-fsanitize=undefinedz#--with-undefined-behavior-sanitizer)r   	sysconfigget_config_var)r   r   r   _cflags_config_argsmemory_sanitizeraddress_sanitizerub_sanitizerrP   rP   rQ   r+   r  s$   r+   c                C   s"   | sd} t |||d}t|| S )z>Decorator raising SkipTest if running with a sanitizer active.z"not working with sanitizers activer   )r+   rf   r   )r   r   r   r   r   rP   rP   rQ   r,     s   r,   c                    s   t   fdd}|S )z5Skip the test on TLS certificate validation failures.c               
      sF   z
 | i | W d S  t y" } zdt|v rtd d }~ww )NCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)r   r   rf   ry   )r   kwargsr   rb   rP   rQ   dec  s   
z&system_must_validate_cert.<locals>.dec)r   r   )rc   r   rP   rb   rQ   system_must_validate_cert  s   r  i @ i  doubleIEEEztest requires IEEE 754 doublesrequires zlibc                 C   0   zdd l }W n ty   d }Y nw t|| S Nr   )zlibImportErrorrf   
skipUnless)r   r  rP   rP   rQ   r$        r$   requires gzipc                 C   r  r  )gzipr  rf   r	  )r   r  rP   rP   rQ   r     r
  r   requires bz2c                 C   r  r  )bz2r  rf   r	  )r   r  rP   rP   rQ   r     r
  r   requires lzmac                 C   r  r  )lzmar  rf   r	  )r   r  rP   rP   rQ   r     r
  r   zrequires legacy Unicode C APIjavagetandroidapilevel)rG   rI   z/system/bin/shz/bin/shzhttp://www.pythontest.netdatac                 C   sX   t jdkrdS ddl}d}|  d}| \}}t||d t| td|  dS )zOAssure user that loud errors generated by macOS libc's malloc are
    expected.r   Nr   z NOTICE z may generate "malloc can't allocate region"
warnings on macOS systems. This behavior is known. Do not
report a bug unless tests are also failing. See bpo-40928.r   )r   r   shutilget_terminal_sizer   center)	test_namer  rV   detailpadding_rP   rP   rQ   darwin_malloc_err_warning  s   

r  c                 C   sb   t j| r| S |durt j|| } tgtj }|D ]}t j|| }t j|r.|  S q| 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)rl   rm   isabsr   TEST_HOME_DIRr   exists)filenamesubdirrm   dnfnrP   rP   rQ   r6     s   r6   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: %rrP   ).0pairrP   rP   rQ   
<listcomp>  s    zsortdict.<locals>.<listcomp>z, z{%s})sorteditemsr   )dictr'  	reprpairs
withcommasrP   rP   rQ   r;     s   
r;   r   )linenooffsetc                C   s   |  t|}t|dd W d    n1 sw   Y  |j}| |j |d ur0| |j| | |j |d urC| |j| d S d S )Nz<test string>exec)assertRaisesRegexSyntaxErrorcompile	exceptionassertIsNotNoner+  assertEqualr,  )testcase	statementerrtextr+  r,  cmr   rP   rP   rQ   r     s   r   c                    s  dd l }dd l}ddlm} zdd l}W n ty   d }Y nw dd |j| d 	dd }t
jt|} fdd	}t
j|rV||}	|	d urR|	S || td
 tretd|  t d |j }
|rr|
jd |
j| td}	|r|	jddkr|j|	d}	z,t|d}|	 }|r|| |	 }|sW d    n1 sw   Y  W |	  n|	  w ||}	|	d ur|	S td| )Nr   r   )unlinkcheckr   /c                    sD   t | g R i }d u r|S |r|d |S |  d S r  )openseekclose)r"  rc   r   r9  r   rP   rQ   check_valid_file8  s   
z*open_urlresource.<locals>.check_valid_fileurlfetchz	fetching %s ...file)zAccept-Encodingr  timeoutzContent-Encodingr  )fileobjwbzinvalid resource %r) urllib.requesturllib.parse	os_helperr8  r  r  popparseurlparser   rl   rm   r   TEST_DATA_DIRr  r   r   r   r   requestbuild_opener
addheadersappendr<  rD   headersgetGzipFilereadwriter>  r   )urlr   r   urllibr8  r  r  r"  r@  rc   openeroutsrP   r?  rQ   r2   *  sP   	

r2   c              
   c   sR    ddl }tt| }tt| |  ztt| V  W tt| | dS tt| | w )zReturn a context manager used by captured_stdout/stdin/stderr
    that temporarily replaces the sys stream *stream_name* with a StringIO.r   N)iorw   r   setattrStringIO)stream_namer]  orig_stdoutrP   rP   rQ   captured_outputa  s   
rb  c                   C      t dS )zCapture the output of sys.stdout:

       with captured_stdout() as stdout:
           print("hello")
       self.assertEqual(stdout.getvalue(), "hello\n")
    r~   rb  rP   rP   rP   rQ   r   m     r   c                   C   rc  )zCapture the output of sys.stderr:

       with captured_stderr() as stderr:
           print("hello", file=sys.stderr)
       self.assertEqual(stderr.getvalue(), "hello\n")
    stderrrd  rP   rP   rP   rQ   r   v  re  r   c                   C   rc  )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")
    stdinrd  rP   rP   rP   rQ   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皙?)gccollectr-   timesleep)ri  rP   rP   rQ   
gc_collect  s   

rm  c                  c   sH    dd l } |  }|   zd V  W |r|   d S d S |r#|   w w r  )ri  	isenableddisableenable)ri  have_gcrP   rP   rQ   
disable_gc  s   
rr  c                  C   s6   t dpd} d}|  D ]	}|dr|}q|dvS )z,Find if Python was built with optimizations.	PY_CFLAGSr   z-O)r   z-O0z-Og)r   r   r   r   )cflags	final_optoptrP   rP   rQ   python_is_optimized  s   
rw  nP0n
getobjects2P0Pnc                 C      dd l }|t|  t S r  )structcalcsize_header_alignfmtr  rP   rP   rQ   calcobjsize     r  c                 C   r~  r  )r  r  _vheaderr  r  rP   rP   rQ   calcvobjsize  r  r  i @  i   c                 C   sp   dd l }t|}t|tkr|jt@ s!t|tkr&t|jt@ r&||j7 }dt|||f }| ||| d S )Nr   z&wrong size for %s: got %d, expected %d)	_testinternalcapir   	getsizeofr   	__flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCSIZEOF_PYGC_HEADr3  )testosizer  r   rV   rP   rP   rQ   check_sizeof  s   

r  c              
   g   s    zdd l }t|| }||}W n ty       d  }}Y n|D ]}z	||| W  n   Y q$zd V  W |rF|rH||| d S d S d S |rU|rV||| w w w r  )localerw   	setlocalerx   )catstrlocalesr  categoryorig_localelocrP   rP   rQ   r4     s,   
r4   c                    r   )Nc                    s"    fdd} j |_  j|_|S )Nc               	      s   zt j}W n ty   tdw dtjv rtjd }nd }tjd< |  z | i |W |d u r8tjd= n|tjd< t   S |d u rKtjd= n|tjd< t   w )Nztzset requiredTZ)rk  tzsetrx   rf   ry   rl   environ)r   kwdsr  orig_tz)r   tzrP   rQ   inner  s(   









z-run_with_tz.<locals>.decorator.<locals>.inner)rL   rO   )r   r  r  r   rQ   r     s   zrun_with_tz.<locals>.decoratorrP   )r  r   rP   r  rQ   r<     s   r<   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r9t}|td k rFtd| f |ad S )Nr  )kmgtz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rr      z$Memory limit %r too low to be useful)_1M_1Grematch
IGNORECASEVERBOSEr   r   floatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr   )limitsizesr  memlimitrP   rP   rQ   r9     s"   
$r9   c                   @   (   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)pidF)r   rl   getpidprocfilestartedr^   rP   rP   rQ   rZ   7  s   
z_MemoryWatchdog.__init__c              
   C   s   dd l }zt| jd}W n! ty- } z|d|t tj	  W Y d }~d S d }~ww dd l
}| td}|jtj|g||jd| _W d    n1 sPw   Y  d| _d S )Nr   rz!/proc not available for stats: {}zmemory_watchdog.py)rg  rf  T)warningsr<  r  r   warnr   RuntimeWarningr   rf  flush
subprocessr6   Popen
executableDEVNULLmem_watchdogr  )r[   r  rc   r   r  watchdog_scriptrP   rP   rQ   start;  s(   


z_MemoryWatchdog.startc                 C   s"   | j r| j  | j  d S d S rU   )r  r  	terminatewaitr^   rP   rP   rQ   stopM  s   
z_MemoryWatchdog.stopN)rL   rM   rN   rO   rZ   r  r  rP   rP   rP   rQ   r  2  s
    r  Tc                    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 s"t|| k r"td|| d  tr=tr=t  tdj|| d d t }|	  nd }z| |W |rL|
  S S |rT|
  w w )Ni  'not enough memory: %.1fG minimum needed   @z* ... expected peak memory use: {peak:.1f}G)peak)r  memuser  rf   ry   r   r   r   r  r  r  )r[   r  r  maxsizewatchdog)dry_runrc   r   rP   rQ   r   a  s6   




z.bigmemtest.<locals>.decorator.<locals>.wrapper)r  r  rb   r  r  r  rc   r   rQ   r   `  s   zbigmemtest.<locals>.decoratorrP   )r  r  r  r   rP   r  rQ   r   S  s   !r   c                    r   )z0Decorator for tests that fill the address space.c                    s<   t tk rtdkrt dkrtdtdtd   | S )Nl    l        z-not enough memory: try a 32-bit build insteadr  r  )r   r  rf   ry   r^   rb   rP   rQ   r     s   z!bigaddrspacetest.<locals>.wrapperrP   r  rP   rb   rQ   r      s   r    c                   @   s   e Zd Zdd ZdS )r   c                 C   s   t  }|| |S rU   )rf   
TestResult)r[   r  r   rP   rP   rQ   run     zBasicTestRunner.runN)rL   rM   rN   r  rP   rP   rP   rQ   r     s    r   c                 C   ra   rU   rP   )rz   rP   rP   rQ   _id     r  c                 C   s6   | dkrt  stt jS t| rtS td| S )Nr   zresource {0!r} is not enabled)r   rf   r   r   r   r  r   r   rP   rP   rQ   requires_resource  s
   r  c                 C   s   t dd| S )z9
    Decorator for tests only applicable on CPython.
    T)cpython)impl_detailr  rP   rP   rQ   r!     s   r!   c                 K   sZ   t di |r	tS | d u r(t|\}}|rd} nd} t| }| d|} t| S )Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or rP   )	r/   r  _parse_guardsr&  keysr   r   rf   r   )rV   guards
guardnamesdefaultrP   rP   rQ   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   )listvaluesr   )r  is_truerP   rP   rQ   r    s
   
r  c                  K   s   t | \} }| tjj|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  rT  r   implementationr{   )r  r  rP   rP   rQ   r/     s   r/   c                    s(   t tds S t  fd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 | w rU   )r   r  settrace)r   r   original_tracer   rP   rQ   r     s
   
zno_tracing.<locals>.wrapper)r   r   r   r   r   rP   r   rQ   
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  r!   r  rP   rP   rQ   refcount_test  s   r  c                 C   sN   g }| j D ]}t|tjrt|| || q||r!|| q|| _ dS )z>Recursively filter test cases in a suite based on a predicate.N)_tests
isinstancerf   	TestSuite_filter_suiterR  )suiteprednewtestsr  rP   rP   rQ   r    s   



r  c                 C   s   t tjttdud}|| }tdurt|  |js"|j	s"t
| sht|jdkr8|js8|jd d }nt|jdkrJ|jsJ|jd d }nd}tsR|d7 }dd |jD }d	d |jD }t|||dS )
z2Run tests from a unittest.TestSuite-derived class.N)	verbositycapture_outputr   r   zmultiple errors occurredz!; run in verbose mode for detailsc                 S      g | ]
\}}t ||fqS rP   r   r#  tcexc_strrP   rP   rQ   r%  
      z_run_suite.<locals>.<listcomp>c                 S   r  rP   r  r  rP   rP   rQ   r%    r  )r   r   r~   r   junit_xml_listr  rR  get_xml_elementtestsRunskippedr   wasSuccessfulr   rW   rX   rT   )r  runnerr   r   rW   rX   rP   rP   rQ   
_run_suite  s(   
r  c                 C   s   t d u rdS t |  S NT)_match_test_funcidr  rP   rP   rQ   
match_test  s   r  c                 C   s   d| v o
t d|  S )Nr   z[?*\[\]])r  search)rk   rP   rP   rQ   _is_full_match_test  s   r  c                    s   | d u rd} |d u rd}d   | t krt| \}  |tkr$t|\}t| a t|a d us4d ur? fdd}|ad S d S )NrP   c                    s*   d}d} r
 | }r| }|o| S )NTFrP   )test_idacceptignoreaccept_funcignore_funcrP   rQ   match_function=  s   
z'set_match_tests.<locals>.match_function)_accept_test_patterns_compile_match_function_ignore_test_patternsr   r  )accept_patternsignore_patternsr  rP   r  rQ   set_match_tests(  s   	r  c                    sr   | s
d }d} | |fS t tt| rt| j}| |fS dd l}dt|j| }t	|j
  fdd}|}| |fS )NrP   r   |c                    s     | rdS t t | dS )NTr   )anyr   r   )r	  regex_matchrP   rQ   match_test_regexY  s   z1_compile_match_function.<locals>.match_test_regex)allr   r  set__contains__fnmatchr   	translater  r0  r  )patternsr   r  regexr  rP   r  rQ   r  I  s   
r  c                  G   s   t jt jf}t  }| D ]/}t|tr(|tjv r$|t tj|  qt	dt||r3|| q|t 
| qt|t t| dS )z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesN)rf   r  TestCaser  r   r   modulesaddTestfindTestCasesr   	makeSuiter  r  r  )classesvalid_typesr  clsrP   rP   rQ   r   i  s   



r   c                   C      dS )z,Just used to check if docstrings are enabledNrP   rP   rP   rP   rQ   _check_docstrings  re   r+  WITH_DOC_STRINGSztest requires docstringsc                 C   s`   ddl }|du rt}nd}|j| ||d\}}|r!td||f tr,t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   testmodr   r   rL   )moduler  r-  r.  rc   r  rP   rP   rQ   r     s   r   c                 C   s(   |   D ]}td| tjdd qd S )NzWarning -- T)rC  r  )
splitlinesr   r   
__stderr__)rV   linerP   rP   rQ   print_warning  s   r4  c                  C   sf   t tdr
t tdsdS 	 ztdtj\} }W n
 ty"   Y dS w | dkr)dS td|   daq)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WNOHANGNTr;  r   z%reap_children() reaped child process )r   rl   r5  r6  r   r4  environment_altered)r  statusrP   rP   rQ   r3     s   	r3   c              
   c   s    t | |r%t| |}t| || z|V  W t| || dS t| || w t| || zdV  W t | |r<t| | dS dS t | |rIt| | w w )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   rw   r^  delattr)rz   attrnew_valreal_valrP   rP   rQ   r7     s   


r7   c              	   c   sr    || v r| | }|| |< z
|V  W || |< dS || |< w || |< zdV  W || v r/| |= dS dS || v r8| |= w )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.
    NrP   )rz   itemr;  r<  rP   rP   rQ   r5     s   
r5   c                  C      ddl } |  S )znReturn a list of command-line arguments reproducing the current
    settings in sys.flags and sys.warnoptions.r   N)r  _args_from_interpreter_flagsr  rP   rP   rQ   args_from_interpreter_flags     rA  c                  C   r>  )zgReturn a list of command-line arguments reproducing the current
    optimization settings in sys.flags.r   N)r  "_optim_args_from_interpreter_flagsr@  rP   rP   rQ   !optim_args_from_interpreter_flags  rB  rD  c                   @       e Zd ZdZdd Zdd ZdS )r8   )rV   messagec                 K   s<   d}|D ]}|| }| |}| |||sd} |S q|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)rT  match_value)r[   dr   r   r  vdvrP   rP   rQ   matches&  s   
zMatcher.matchesc                 C   sL   t |t |krd}|S t |tus|| jvr||k}|S ||dk}|S )zT
        Try to match a single stored value (dv) with a supplied value (v).
        Fr   )r   r   _partial_matchesfind)r[   r  rJ  rI  r   rP   rP   rQ   rG  7  s   zMatcher.match_valueN)rL   rM   rN   rL  rK  rG  rP   rP   rP   rQ   r8   "  s    r8   c                 C   sX   ddl }tdu r!tjdkr| d dkrt jdkrdandatr*t	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   NrG   r   cp65001r   TFz!buggy MSVC UCRT strptime/strftime)
r  _buggy_ucrtr   r   getdefaultlocalerk  	localtimetm_zonerf   r   )r  r  rP   rP   rQ   r)   E  s   

r)   c                   @   sj   e Zd ZdZdddZejdkrdd Znd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   sL   ddl m} |ptj|| _g | _tjtj	| _
g | _d | _|   d S )Nr   )TESTFN)rJ  rT  rl   rm   abspathlink_linkedrealpathr   r  real
_also_link_env_platform_specific)r[   rV  rT  rP   rP   rQ   rZ   \  s   zPythonSymlink.__init__rG   c              
   C   s  dd l }dd l}tj| jrtj| js|d| _|tj	}tj
|}tj
| j}| j|tj|tj|f | tj||dD ]}| j|tj|tj|f qMdd tjD | _tj
| j| jd< tdrtj
tj| jd< d S d S )Nr   zvcruntime*.dllc                 S   s   i | ]
}|  t|qS rP   )upperrl   getenv)r#  r  rP   rP   rQ   
<dictcomp>  r  z4PythonSymlink._platform_specific.<locals>.<dictcomp>
PYTHONHOMET
PYTHONPATH)glob_winapirl   rm   lexistsrY  r  GetModuleFileNamer   	dllhandlern   rV  rZ  rR  r   basenameescaper  r[  r   is_python_buildro   )r[   rb  rc  r   src_dirdest_dirruntimerP   rP   rQ   r\  i  s*   
z PythonSymlink._platform_specificc                 C   s   d S rU   rP   r^   rP   rP   rQ   r\    r  c                 C   sJ   t | j| j | j| j | jD ]\}}t || | j| q| S rU   )rl   symlinkrY  rV  rW  rR  rZ  )r[   rY  rV  rP   rP   rQ   	__enter__  s   zPythonSymlink.__enter__c                 C   sV   | j D ]%}zt| W q ty( } ztrtd|| W Y d }~qd }~ww d S )Nzfailed to clean up {}: {})rW  rl   removeIOErrorr   r   r   )r[   exc_type	exc_valueexc_tbrV  exrP   rP   rQ   __exit__  s   
zPythonSymlink.__exit__c           	      C   sx   dd l }|g|}|j||j|j|d}| }|j|kr:tr2tt|d  tt|d tj	d t
d|j|S )Nr   )r~   rf  envr   rB  z'unexpected return code: {0} (0x{0:08X}))r  r  PIPEcommunicate
returncoder   r   reprr   rf  RuntimeErrorr   )	r[   pythonr   rv  ry  r  cmdpr  rP   rP   rQ   _call  s   



zPythonSymlink._callr   )ry  c                G   s   |  | j|d |S rU   )r  rY  r[   ry  r   rP   rP   rQ   	call_real  s   zPythonSymlink.call_realc                G   s   |  | j|| j|S rU   )r  rV  r[  r  rP   rP   rQ   	call_link  s   zPythonSymlink.call_linkrU   )rL   rM   rN   rO   rZ   r   r   r\  rn  ru  r  r  r  rP   rP   rP   rQ   rS  Z  s    


rS  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_EXTENDEDrf   r   )r  okrV   rP   rP   rQ   skip_if_pgo_task  s   
r  rP   )r  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 )r  __N)r   endswith)r#  r  rP   rP   rQ   	<genexpr>  s    z&detect_api_mismatch.<locals>.<genexpr>)r  dir)ref_api	other_apir  missing_itemsrP   rP   rQ   r'     s
   r'   c                 C   s   |du r	|j f}nt|tr|f}t|}t|D ])}|ds$||v r%qt||}t|dd|v s=t|dsBt|tj	sB|
| q| |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 'not_exported' 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'}
                not_exported = {'baz'}  # Undocumented name.
                # bar imports part of its API from _bar.
                support.check__all__(self, bar, ('bar', '_bar'),
                                     extra=extra, not_exported=not_exported)

    Nr  rM   )rL   r  r   r  r  r   rw   r   types
ModuleTypeaddassertCountEqual__all__)	test_caser0  name_of_moduleextranot_exportedexpectedr{   rz   rP   rP   rQ   r(     s"   )




r(   c                 C   s   zdd l }W n
 ty   Y d S w ||j|jB |jB |jB  t|drG|j|j	|j
fD ]}| r@|||j |||j q-||d q-d S d S )Nr   CrtSetReportMode)msvcrtr  SetErrorModeSEM_FAILCRITICALERRORSSEM_NOALIGNMENTFAULTEXCEPTSEM_NOGPFAULTERRORBOXSEM_NOOPENFILEERRORBOXr   CRT_WARN	CRT_ERROR
CRT_ASSERTr  CRTDBG_MODE_FILECrtSetReportFileCRTDBG_FILE_STDERR)r   r  r  rP   rP   rQ   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   s  t jdrOzddl}W n
 ty   Y dS w | | _|| j|jB  t	|drMi | _
|j|j|jfD ]}|||j}|||j}||f| j
|< q5| S z	ddl}|| _W n tyd   d| _Y nw | jdurz| j| jj| _| j| jjd| jd f W n ttfy   Y nw t jdkrddl}g d}|j||j|jd}| | d }	W d   n1 sw   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/defaultsrV  zcom.apple.CrashReporter
DialogType)r~   rf  s	   developerz:this test triggers the Crash Reporter, that is intentionalr   T)endr  )r   r   r   r  r  GetErrorMode	old_valuer  r  r   	old_modesr  r  r  r  r  r  r  r   	getrlimitRLIMIT_CORE	setrlimitr   r   r  r  rw  rx  stripr   )
r[   r  report_typeold_modeold_filer   r  r}  procr~   rP   rP   rQ   rn    sh   

#



zSuppressCrashReport.__enter__c              	   G   s   | j du rdS tjdr6ddl}|| j  | jr2| j D ]\}\}}||| |	|| qdS dS | j
durUz| j
| j
j| j  W dS  ttfyT   Y dS w 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   )r[   
ignore_excr  r  r  r  rP   rP   rQ   ru  ]  s$   

zSuppressCrashReport.__exit__)rL   rM   rN   rO   r  r  rn  ru  rP   rP   rP   rQ   r:     s    Br:   c              	      sp   t  d zj W n ttfy   t dY nw 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  d S t d S rU   )r^  r9  rP   attr_is_local	attr_nameobject_to_patchr  rP   rQ   cleanup  s   zpatch.<locals>.cleanup)rw   __dict__rx   KeyError
addCleanupr^  )test_instancer  r  	new_valuer  rP   r  rQ   patchr  s   


r  c              
   c   s6    z| dd }dV  W || dd< dS || dd< w )z-Like unittest.mock.patch.dict, but for lists.NrP   )origsavedrP   rP   rQ   
patch_list  s
   r  c                 C   sD   zddl }W n	 ty   Y n
w | rt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_tracingrf   ry   	_testcapirun_in_subinterp)coder  r  rP   rP   rQ   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 d S  ty   Y d S w r  )nextStopIterationr^   doneitrP   rQ   __del__  s   z-check_free_after_iterating.<locals>.A.__del__N)rL   rM   rN   r  rP   r  rP   rQ   A  s    r  F)assertRaisesr  r  rm  
assertTrue)r  iterr)  r   r  rP   r  rQ   check_free_after_iterating  s   	r  c                 C   s   ddl m}m}m}m} | }|| |jdkr,z|  W n |j	y+   Y dS w |j
D ]-}| r8|| vr8q/t||}| rJ|dusIJ d| n|sMq/||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   spawnrW   msvcNz%the '%s' executable is not configured)	distutilsr  r   r  rW   new_compilercustomize_compilercompiler_type
initializeDistutilsPlatformErrorexecutablesrw   find_executable)	cmd_namesr  r   r  rW   compilerr{   r}  rP   rP   rQ   r>     s.   





r>   c                 C   sH   d}t r| |k rtd u rdd l}|ddg dkatr|} t| S )Ngh㈵>r   getpropzro.kernel.qemu   1)r.   _is_android_emulatorr  check_outputr  r   r1   )intervalminimum_intervalr  rP   rP   rQ   r1     s   
r1   c               
   c   s^    dd l } tj }|  }z|   d V  W |r"| j|dd d S d S |r.| j|dd w w )Nr   T)rC  all_threads)faulthandlerr   r2  fileno
is_enabledro  rp  )r  fdr  rP   rP   rQ   disable_faulthandler  s   
r  c                   @   r  )	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   sZ   dd l }|| _ | | _dD ]}zt||}W n	 ty    Y qw | j| qi | _d S )Nr   )SIGKILLSIGSTOP)signalvalid_signalssignalsrw   rx   ro  handlers)r[   r  signamesignumrP   rP   rQ   rZ     s   

zSaveSignals.__init__c                 C   s0   | j D ]}| j|}|d u rq|| j|< qd S rU   )r  r  	getsignalr  r[   r  handlerrP   rP   rQ   save  s   
zSaveSignals.savec                 C   s&   | j  D ]\}}| j|| qd S rU   )r  r'  r  r  rP   rP   rQ   restore)  s   zSaveSignals.restoreN)rL   rM   rN   rO   rZ   r  r  rP   rP   rP   rQ   r    s
    r  c                  C   s   dd l } | jS r  )r  WITH_PYMALLOC)r  rP   rP   rQ   with_pymalloc.  s   r  c                   @   rE  )
_ALWAYS_EQz+
    Object that is equal to anything.
    c                 C   r*  r  rP   r[   otherrP   rP   rQ   __eq__7  r  z_ALWAYS_EQ.__eq__c                 C   r*  NFrP   r  rP   rP   rQ   __ne__9  r  z_ALWAYS_EQ.__ne__N)rL   rM   rN   rO   r  r  rP   rP   rP   rQ   r  3  s    r  c                   @   r  )		_NEVER_EQz/
    Object that is not equal to anything.
    c                 C   r*  r  rP   r  rP   rP   rQ   r  B  r  z_NEVER_EQ.__eq__c                 C   r*  r  rP   r  rP   rP   rQ   r  D  r  z_NEVER_EQ.__ne__c                 C   r*  )Nr   rP   r^   rP   rP   rQ   __hash__F  r  z_NEVER_EQ.__hash__N)rL   rM   rN   rO   r  r  r  rP   rP   rP   rQ   r   >  s
    r   c                   @   rE  )_LARGESTz?
    Object that is greater than anything (except itself).
    c                 C   
   t |tS rU   )r  r  r  rP   rP   rQ   r  P  r   z_LARGEST.__eq__c                 C   r*  r  rP   r  rP   rP   rQ   __lt__R  r  z_LARGEST.__lt__N)rL   rM   rN   rO   r  r  rP   rP   rP   rQ   r  K      r  c                   @   rE  )	_SMALLESTz<
    Object that is less than anything (except itself).
    c                 C   r  rU   )r  r  r  rP   rP   rQ   r  \  r   z_SMALLEST.__eq__c                 C   r*  r  rP   r  rP   rP   rQ   __gt__^  r  z_SMALLEST.__gt__N)rL   rM   rN   rO   r  r  rP   rP   rP   rQ   r  W  r  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)asyncio.eventsevents_event_loop_policy)asynciorP   rP   rQ   maybe_get_event_loop_policyc  s   r  )    @   c                 C   s   | |}}dd l }| K}| d }t|d|_||}|d | | }|| }	||	 }
||
 }||d  |d | |  |	d|	   }t|t| fW  d    S 1 s[w   Y  d S )Nr   r      r   )decimallocalcontext
bit_lengthmaxprecDecimalr  sqrt)nbinsnballsr}  r  r  ctxbitsr!  p1empty	meanemptyoccupied
collisionsvarrP   rP   rQ   collision_statsp  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 rU   )
unraisable	_old_hookr^   rP   rP   rQ   rZ     s   
z#catch_unraisable_exception.__init__c                 C   s
   || _ d S rU   )r"  )r[   r"  rP   rP   rQ   _hook  s   
z catch_unraisable_exception._hookc                 C   s   t j| _| jt _| S rU   )r   unraisablehookr#  r$  r^   rP   rP   rQ   rn    r  z$catch_unraisable_exception.__enter__c                 G   s   | j t_| `d S rU   )r#  r   r%  r"  )r[   exc_inforP   rP   rQ   ru    s   z#catch_unraisable_exception.__exit__N)rL   rM   rN   rO   rZ   r$  rn  ru  rP   rP   rP   rQ   r!    s    r!  rD  c                C   s$  t jdkrcddl}|du rt}t }d}d}	 t | t j\}}|dkr&n<t | }	|	|krUzt | |j	 t | d W n	 t
yH   Y nw td|  d|	d	d
t|d |}t| qnt | d\}}t |}
|
|krtd|  d|
 d| d|| krt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 (LONG_TIMEOUT by default),
    kill the process (if signal.SIGKILL is available) and raise an
    AssertionError. The timeout feature is not available on Windows.
    ntr   NgMbP?rh  Tzprocess z is still running after z.1fz secondsr   z exited with code z, but exit code z is expectedzpid z != pid )rl   r{   r  rF   rk  	monotonicr5  r6  killr  r   AssertionErrorminrl  waitstatus_to_exitcode)r  exitcoderE  r  t0rl  	max_sleeppid2r8  dt	exitcode2rP   rP   rQ   wait_process  sF   





r3  c               
   C   sf   ddl m}  | d | d}tjdkr1z	|jdd W dS  ty0 } ztd|d}~ww 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).
    r   )import_module_multiprocessingzmultiprocessing.synchronizelinuxN)r  z broken multiprocessing SemLock: )import_helperr4  r   r   Lockr   rf   ry   )r4  synchronizeexcrP   rP   rQ   *skip_if_broken_multiprocessing_synchronize  s   
r;  K   c              	   c   s8    t  }zt |  d V  W t | d S t | w rU   )r   getrecursionlimitsetrecursionlimit)	max_depthoriginal_depthrP   rP   rQ   infinite_recursion  s   
rA  c                 O   s\   |j }|j}|dkr| d| }n| }dt| d}| jt||g|R i | dS )z
    Check that given type cannot be instantiated using *args and **kwds.

    See bpo-43916: Add Py_TPFLAGS_DISALLOW_INSTANTIATION type flag.
    builtinsr   zcannot create 'z' instancesN)rM   rL   r  rh  r.  	TypeError)r4  tpr   r  modr{   qualnamerV   rP   rP   rQ   r*     s    r*   r0  likereturnc                C   s,   t  }tjdt| |dt| d d |S )Nr  
(?#support))r  r0  rF  )objectr  filterwarningsDeprecationWarningr  )r0  rG  tokenrP   rP   rQ   ignore_deprecations_from%  s   rO  tokensc            	      G   s   | st dg }tdd | D }tjD ]-\}}}}}|dkr7|tu r7t|tjr-|j}n|p0d}|	|r7q|
|||||f qtj|krT|tjd d < t  d S d S )Nz<Provide token or tokens returned by ignore_deprecations_fromc                 s   s     | ]}d t | dV  qdS )rI  rJ  N)r  )r#  rN  rP   rP   rQ   r  5  s    z-clear_ignored_deprecations.<locals>.<genexpr>r  r   )r   r   r  filtersrM  r  r  Patternrk   r  rR  _filters_mutated)	rP  new_filtersr  actionrF  r  r0  r+  rV   rP   rP   rQ   clear_ignored_deprecations0  s    

rV  c              	   c   s8    t  }zt |  dV  W t | dS t | w )z>Temporarily change the integer string conversion length limit.N)r   get_int_max_str_digitsset_int_max_str_digits)
max_digitscurrentrP   rP   rQ   adjust_int_max_str_digitsD  s   
r[  rU   )r  )r  )r  )r  )r   )T)NNr  )NrP   rP   )F)rP   )r<  )rO   rL   r  
contextlibr   rl   r  r   r   r   rk  r  rf   r  
testresultr   r  r   r  rC   r   r   rD   rE   rF   r   r
   r   rT   r   ry   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   SOCK_MAX_SIZEr	  r  __getformat__r   r#   r$   r   r   r   requires_legacy_unicode_capir-   r   r.   r0   TEST_HTTP_URLr=   r  rm   rn   rU  ro   TEST_SUPPORT_DIRr  r   rN  r  r6   r;   r   r2   contextmanagerrb  r   r   r   rm  rr  rw  r  r  r  r  r  r  r  r  r4   r<   r  r  r  _4Gr  r  r9   r  r   r    r   r  r  r!   r  r  r/   r  r  r  r  r  r  r  r  r  r  r  r   r+  r   MISSING_C_DOCSTRINGSHAVE_DOCSTRINGSrequires_docstringsr   r4  r7  r3   r7   r5   rA  rD  rK  r8   rO  r)   rS  r  r'   r(   r  r:   r  r  r  r  r>   r  r1   r  r  r  r  r?   r   r@   total_orderingr  rA   r  rB   r  	hash_infowidth	NHASHBITSr   r!  r3  r;  rA  r*   r   rO  rV  r[  rP   rP   rP   rQ   <module>   s   ,

	M			
7
		


#!0

! 


"R;`"
	 
'			",4	