MINI MINI MANI MO

Path : /lib64/python3.6/test/support/__pycache__/
File Upload :
Current File : //lib64/python3.6/test/support/__pycache__/__init__.cpython-36.pyc

3


 \/@sdZedkredddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
ZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z!ddl"Z"ddl#m$Z$yddl%Z%ddl&Z&Wnek
r:dZ%dZ&YnXyddl'Z(Wnek
rbdZ(YnXyddl)Z)Wnek
rdZ)YnXyddl*Z*Wnek
rdZ*YnXyddl+Z+Wnek
rdZ+YnXyddl,Z,Wnek
rdZ,YnXyddl-Z-Wnek
r*dZ-YnXddd	d
ddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dag[Z.Gdbdde/Z0Gdcd
d
e0Z1Gdddde0Z2Gdeddej3Z4ej5d]dgdhZ6d^fdjdkdZ7dldmZ8dndoZ9dpd<Z:dqd=Z;ffdifdrdZ<dsd8Z=dZ>dZ?da@daAdZBdiZCdaDdtdZEdudZFdvdZGdwdxZHejjIdyrd_dzd{ZJd|d}ZKd~dZLddZMddZNnejOZKejPZLddZMddZNddZOddZPddZQddZRddZSddZTdd#ZUd`dd$ZVddZWdd%ZXdd&ZYdd'ZZdZ[dZ\ej]ej^fddIZ_e[fddJZ`ddLZaddZbebZcddZddcZedfZfejgehjidjIddZjejge)dZkejge*dZlejge+dZmejge,dZnejjIdZoejpdZqeqdk	o:eqdkZrejdkrXerrRdndZsndZsejtdkrndZundZudjveuejwZudZxxLdgD]BZyyejzej{eyeykre|Wne|k
rYnXeyZxPqWeudZ}ejdkrddl~Z~e~jde}Z}ejZdZejtdkrhejjdkreudZyejeWnek
rPYnXedeefdZnBejdkrydjeWn&ek
reudjedŃZYnXdZxFdhD]<ZtyetjeWn&ek
rej{euetZPYnXqWexr
eudexZndZejZdiZej5didd̄Zej5djdd΄Zej5dkddZeedуrjej5ddMZejjejjeZejjeZejjedӃZdlddZdd Zdd]Zdd؄Zdddٜdd(ZddKZGdd݄deZdmdd߄Zej5ddTZej5ddUZGdddeZGddVdVejjZGdddeZGdd)d)eZeeejdZeeejdZeeejdZej5dfddd-Zej5ddZddZddZddZddZej5ddZddZdZdZeedrdeZdZedZddZddZdnZdoZddZddWZdd^ZÐdpZdeZdeZdeZejZɐdd[ZGdddZːdqd	d5Z̐d
d6ZGdd.d.Zΐdd
ZϐddZАdd@Zѐdd7ZҐdrddZdaԐddAZՐddZ֐ddDZאddZؐddZِddZڐddZdadaݐd d!Zސd"d#Zߐd$d%Zd&d/Zd'd(Ze׃
oejdk
oejpd)Zejdk	
oeZejged*Zdsd+d0Zd,d-Zd.d/ZdiZd0dPZd1dQZd2dRZej5dtd4d5Zd6dNZej5dud7dSZej5d8dYZej5d9dXZd:d;Zejeed<d=Zd>d?Zd@dAZGdBdOdOejjZGdCdZdZeZdadDd!ZdEd1ZdadFdGZdHd:ZdId"ZfdJdKd>ZdfffdLd?ZGdMd\d\ZdNdOZdPdQZffdRdSZgfdTd`Zda	dUdFZ
ej5dVdWZdXdaZGdYdZdZZ
Gd[d\d\ZdS(vz7Supporting definitions for the Python regression tests.ztest.supportz.support must be imported from the test packageN)get_test_runner
PIPE_MAX_SIZEverbose
max_memuse
use_resourcesfailfastError
TestFailed
TestDidNotRunResourceDenied
import_moduleimport_fresh_moduleCleanImportunloadforgetrecord_original_stdoutget_original_stdoutcaptured_stdoutcaptured_stdincaptured_stderrTESTFNSAVEDCWDunlinkrmtreetemp_cwdfindfilecreate_empty_filecan_symlinkfs_is_case_insensitiveis_resource_enabledrequiresrequires_freebsd_versionrequires_linux_versionrequires_mac_vercheck_syntax_errorTransientResourcetime_outsocket_peer_resetioerror_peer_resettransient_internetBasicTestRunnerrun_unittestrun_doctestskip_unless_symlink
requires_gziprequires_bz2
requires_lzma
bigmemtestbigaddrspacetestcpython_only
get_attributerequires_IEEE_754skip_unless_xattr
requires_zlibanticipate_failureload_package_testsdetect_api_mismatchcheck__all__requires_android_levelrequires_multiprocessing_queue	is_jython
is_androidcheck_impl_detail
unix_shellsetswitchintervalHOSTIPV6_ENABLEDfind_unused_port	bind_portopen_urlresourcebind_unix_socket
temp_umask
reap_childrenTestHandlerthreading_setupthreading_cleanupreap_threads
start_threadscheck_warningscheck_no_resource_warningEnvironmentVarGuardrun_with_locale	swap_item	swap_attrMatcherset_memlimitSuppressCrashReportsortdictrun_with_tzPGOmissing_compiler_executablefd_countc@seZdZdZdS)r	z*Base class for regression test exceptions.N)__name__
__module____qualname____doc__rcrc-/usr/lib64/python3.6/test/support/__init__.pyr	usc@seZdZdZdS)r
zTest failed.N)r_r`rarbrcrcrcrdr
xsc@seZdZdZdS)rzTest did not run any subtests.N)r_r`rarbrcrcrcrdr{sc@seZdZdZdS)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.
    N)r_r`rarbrcrcrcrdr~sTccs8|r.tjtjddtdVWdQRXndVdS)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)warningscatch_warningsfilterwarningsDeprecationWarning)rercrcrd_ignore_deprecated_importss
rjF)required_oncCsft|Ty
tj|Stk
rV}z&tjjt|r8tj	t
|WYdd}~XnXWdQRXdS)acImport and return the module to be tested, raising SkipTest if
    it is not available.

    If deprecated is True, any module or package deprecation messages
    will be suppressed. If a module is required on a platform but optional for
    others, set required_on to an iterable of platform prefixes which will be
    compared against sys.platform.
    N)rj	importlibr
ImportErrorsysplatform
startswithtupleunittestSkipTeststr)name
deprecatedrkmsgrcrcrdr
s	

cCs^|tjkrt|tj|=x>ttjD]0}||ks@|j|dr&tj|||<tj|=q&WdS)zyHelper function to save and remove a module from sys.modules

    Raise ImportError if the module can't be imported.
    .N)rnmodules
__import__listrp)ruorig_modulesmodnamercrcrd_save_and_remove_modules
r~cCs>d}ytj|||<Wntk
r.d}YnXdtj|<|S)zHelper function to save and block a module in sys.modules

    Return True if the module was in sys.modules, False otherwise.
    TFN)rnryKeyError)rur|Zsavedrcrcrd_save_and_block_modules

rcCs|r
tjSddS)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.
    cSs|S)Nrc)frcrcrd<lambda>sz$anticipate_failure.<locals>.<lambda>)rrZexpectedFailure)Z	conditionrcrcrdr9scCsF|dkrd}tjjtjjtjjt}|j|||d}|j||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)
    Nztest*)Z	start_dirZ
top_level_dirpattern)ospathdirname__file__ZdiscoverZaddTests)Zpkg_dirloaderZstandard_testsrZtop_dirZ
package_testsrcrcrdr:s
cCst|i}g}t||zfyHx|D]}t||q&Wx |D]}t||s>|j|q>Wtj|}Wntk
r~d}YnXWdx|jD]\}	}
|
tj	|	<qWx|D]}tj	|=qWX|SQRXdS)aImport 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)
rjr~rappendrlr
rmitemsrnry)ruZfreshZblockedrvr|Znames_to_removeZ
fresh_nameZblocked_nameZfresh_moduleZ	orig_namemoduleZname_to_removercrcrdrs$





cCs>yt||}Wn&tk
r4tjd||fYnX|SdS)z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %rN)getattrAttributeErrorrrrs)objruZ	attributercrcrdr5s
cCs|adS)N)_original_stdout)stdoutrcrcrdr)scCs
tptjS)N)rrnrrcrcrcrdr-scCs&ytj|=Wntk
r YnXdS)N)rnryr)rurcrcrdr0scGsny||Stk
rh}zDtdkrHtd|jj|ftd|j|ftj|tj||Sd}~XnXdS)Nz%s: %szre-run %s%r)	OSErrorrprint	__class__r_rchmodstatS_IRWXU)rfuncargserrrcrcrd
_force_run6srwincCs|||r|}ntjj|\}}|p(d}d}x<|dkrjtj|}|rJ|n||ksVdStj||d9}q0Wtjd|tdddS)NrxgMbP?g?rz)tests may fail, delete still pending for )
stacklevel)	rrsplitlistdirtimesleeprfwarnRuntimeWarning)rpathnamewaitallrrutimeoutLrcrcrd_waitforAs



rcCsttj|dS)N)rrr)filenamercrcrd_unlinkbsrcCsttj|dS)N)rrrmdir)rrcrcrd_rmdiresrcs,fddt|ddtdd|dS)Ncsxt|tj|D]}tjj||}ytj|j}Wn<tk
rn}z td||ft	j
dd}WYdd}~XnXtj|rt
|ddt|tj|qt|tj|qWdS)Nz-support.rmtree(): os.lstat(%r) failed with %s)filerT)r)rrrrjoinlstatst_moderrrn
__stderr__rS_ISDIRrrr)rrufullnamemodeexc)
_rmtree_innerrcrdris

z_rmtree.<locals>._rmtree_innerT)rcSst|tj|S)N)rrr)prcrcrdrxsz_rmtree.<locals>.<lambda>)r)rrc)rrd_rmtreehsrc
Cs^yddl}Wntk
r Yn:X|jt|d}|jjj||t|}|rZ|d|S|S)Nrr)ctypesrmZcreate_unicode_bufferlenwindllkernel32ZGetLongPathNameW)rrbufferZlengthrcrcrd	_longpathzs
rcsFytj|dStk
r"YnXfdd|tj|dS)Nc
sx~t|tj|D]l}tjj||}ytj|j}Wntk
rJd}YnXtj	|rn|t|tj
|qt|tj|qWdS)Nr)rrrrrrrrrrrr)rrurr)rrcrdrs

z_rmtree.<locals>._rmtree_inner)shutilrrrr)rrc)rrdrs
cCs|S)Nrc)rrcrcrdrscCs*yt|Wnttfk
r$YnXdS)N)rFileNotFoundErrorNotADirectoryError)rrcrcrdrscCs&yt|Wntk
r YnXdS)N)rr)rrcrcrdrsrcCs&yt|Wntk
r YnXdS)N)rr)rrcrcrdrscCsBtjj|}tjjtjj|}tjj||d}tj|||S)aMove a PEP 3147/488 pyc file to its legacy pyc location.

    :param source: The file system path to the source file.  The source file
        does not need to exist, however the PEP 3147/488 pyc file must exist.
    :return: The file system path to the legacy pyc file.
    c)	rlutilcache_from_sourcerrrabspathrrename)sourceZpyc_fileZup_oneZ
legacy_pycrcrcrdmake_legacy_pycs
rcCs\t|xNtjD]D}tjj||d}t|dx dD]}ttjj||dq8WqWdS)	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.pyrrr)optimizationN)rrr)	rrnrrrrrlrr)r}rroptrcrcrdrs
csttdrtjSd}tjjdrddlddld}d}Gfdddj}j	j
}|j}|sjj|}j
j}|j||j|j|j|}|sjt|j|@sd}ntjdkrVdd	lm}	mm}
m}dd
lm}|	j|d}
|
jdkrd}nFGfd
dd|}|}|
|}|
j|dksR|
j|dkrVd}|sy.ddlm}|}|j|j |j!Wn\t"k
r}z>t#|}t$|dkr|ddd}dj%t&|j'|}WYdd}~XnX|t_(|t_tjS)Nresultrrrcs.eZdZdjjfdjjfdjjfgZdS)z*_is_gui_available.<locals>.USEROBJECTFLAGSZfInheritZ	fReserveddwFlagsN)r_r`rawintypesZBOOLDWORD_fields_rc)rrcrdUSEROBJECTFLAGSs

rz,gui not available (WSF_VISIBLE flag not set)darwin)cdllc_intpointer	Structure)find_libraryZApplicationServicesz0gui tests cannot run without OS X window managercseZdZdfdfgZdS)z._is_gui_available.<locals>.ProcessSerialNumberZ
highLongOfPSNZlowLongOfPSNN)r_r`rarrc)rrcrdProcessSerialNumbersrz#cannot run without OS X gui process)Tk2z [...]zTk unavailable due to {}: {}))hasattr_is_gui_availablerrnrorprZctypes.wintypesrrZuser32ZGetProcessWindowStationZWinErrorrrZGetUserObjectInformationWZbyrefZsizeofboolrrrrZctypes.utilrZLoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterrZwithdrawupdateZdestroy	Exceptionrtrformattyper_reason)rZ	UOI_FLAGSZWSF_VISIBLErZdllhZuofZneededresrrrrZapp_servicesrZpsnZpsn_prrooteZ
err_stringrc)rrrdrsh

rcCstdkp|tkS)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)resourcercrcrdr scCs>t|s |dkrd|}t||dkr:tr:ttjdS)z@Raise ResourceDenied if the specified resource is not available.Nz"Use of the %r resource not enabledgui)r rrr)rrwrcrcrdr!%scsfdd}|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.
    cs$tjfdd}|_|S)Nc
stjkrztjjddd}yttt|jd}Wntk
rLYn.X|krzdjtt	}t
jd||f||S)N-rrrxz(%s version %s or higher required, not %s)rosystemreleaserrqmapint
ValueErrorrrtrrrs)rkwversion_txtversionmin_version_txt)rmin_versionsysnamercrdwrapper6sz:_requires_unix_version.<locals>.decorator.<locals>.wrapper)	functoolswrapsr)rr)rr)rrd	decorator5sz)_requires_unix_version.<locals>.decoratorrc)rrrrc)rrrd_requires_unix_version.srcGs
td|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.
    ZFreeBSD)r)rrcrcrdr"IscGs
td|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.
    ZLinux)r)rrcrcrdr#Rscsfdd}|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.
    cs"tjfdd}|_|S)Ncsxtjdkrntjd}yttt|jd}Wntk
rBYn,X|krndjtt	}t
jd||f||S)Nrrrxz&Mac OS X %s or higher required, not %s)rnroZmac_verrqrrrrrrtrrrs)rrrrr)rrrcrdrcs
z4requires_mac_ver.<locals>.decorator.<locals>.wrapper)rrr)rr)r)rrdrbsz#requires_mac_ver.<locals>.decoratorrc)rrrc)rrdr$[sz	127.0.0.1z::1cCs"tj||}t|}|j~|S)a
Returns an unused port that should be suitable for binding.  This is
    achieved by creating a temporary socket with the same family and type as
    the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
    the specified host address (defaults to 0.0.0.0) with the port set to 0,
    eliciting an unused ephemeral port from the OS.  The temporary socket is
    then closed and deleted, and the ephemeral port is returned.

    Either this method or bind_port() should be used for any tests where a
    server socket needs to be bound to a particular port for the duration of
    the test.  Which one to use depends on whether the calling code is creating
    a python socket, or if an unused port needs to be provided in a constructor
    or passed to an external program (i.e. the -accept argument to openssl's
    s_server mode).  Always prefer bind_port() over find_unused_port() where
    possible.  Hard coded ports should *NEVER* be used.  As soon as a server
    socket is bound to a hard coded port, the ability to run multiple instances
    of the test simultaneously on the same host is compromised, which makes the
    test a ticking time bomb in a buildbot environment. On Unix buildbots, this
    may simply manifest as a failed test, which can be recovered from without
    intervention in most cases, but on Windows, the entire python process can
    completely and utterly wedge, requiring someone to log in to the buildbot
    and manually kill the affected process.

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

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

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

    XXX: although this approach is a vast improvement on previous attempts to
    elicit unused ports, it rests heavily on the assumption that the ephemeral
    port returned to us by the OS won't immediately be dished back out to some
    other process when we close and delete our temporary socket but before our
    calling code has a chance to bind the returned port.  We can deal with this
    issue if/when we come across it.
    )socketrGclose)familyZsocktypeZtempsockportrcrcrdrF}s
8cCs|jtjkr|jtjkrttdr>|jtjtjdkr>t	dttdr~y |jtjtj
dkrft	dWntk
r|YnXttdr|jtjtj
d|j|df|jd}|S)a%Bind the socket to a free port and return the port number.  Relies on
    ephemeral ports in order to ensure we are using an unbound port.  This is
    important as many tests may be running simultaneously, especially in a
    buildbot environment.  This method raises an exception if the sock.family
    is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
    or SO_REUSEPORT set on it.  Tests should *never* set these socket options
    for TCP/IP sockets.  The only case for setting these options is testing
    multicasting via multiple UDP sockets.

    Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
    on Windows), it will be set on the socket.  This will prevent anyone else
    from bind()'ing to our host/port for the duration of the test.
    SO_REUSEADDRrzHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets!SO_REUSEPORTzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!SO_EXCLUSIVEADDRUSEr)rrAF_INETrSOCK_STREAMrZ
getsockoptZ
SOL_SOCKETrr
rrZ
setsockoptrbindZgetsockname)sockhostrrcrcrdrGs


cCsJ|jtjksty|j|Wn&tk
rD|jtjdYnXdS)zBBind a unix socket, raising SkipTest if PermissionError is raised.zcannot bind AF_UNIX socketsN)	rrZAF_UNIXAssertionErrorrPermissionErrorrrrrs)rZaddrrcrcrdrIscCsZtjrVd}z<y"tjtjtj}|jtdfdStk
rBYnXWd|rT|jXdS)z+Check whether IPv6 is enabled on this host.NrTF)rZhas_ipv6ZAF_INET6rrHOSTv6rr)rrcrcrd_is_ipv6_enableds

r
cstjfdd}|S)z5Skip the test on TLS certificate validation failures.csNy||Wn:tk
rH}zdt|kr6tjdWYdd}~XnXdS)NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)IOErrorrtrrrs)rkwargsr)rrcrddecs
z&system_must_validate_cert.<locals>.dec)rr)rr
rc)rrdsystem_must_validate_certs	rriZdoubleZIEEEztest requires IEEE 754 doublesz
requires zlibz
requires gzipzrequires bz2z
requires lzmajavaANDROID_API_LEVELwin32z/system/bin/shz/bin/shz$testz@testz	{}_{}_tmpæİŁφКא،تก €u-àòɘŁğrZNFDntru-共Ł♡ͣztWARNING: The filename %r CAN be encoded by the filesystem encoding (%s). Unicode filename tests may not be effectives-surrogateescapewrccsd}|dkr&tj}d}tjj|}nBytj|d}Wn.tk
rf|sNtjd|t	ddYnX|rttj
}z
|VWd|r|tj
krt|XdS)aReturn a context manager that creates a temporary directory.

    Arguments:

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

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

    FNTz+tests may fail, unable to create temp dir: )r)tempfilemkdtemprrrealpathmkdirrrfrrgetpidr)rquietZdir_createdpidrcrcrdtemp_dirs&


r-ccsftj}ytj|Wn.tk
rD|s,tjd|tddYnXztjVWdtj|XdS)agReturn a context manager that changes the current working directory.

    Arguments:

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

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

    z)tests may fail, unable to change CWD to: r%)rN)rgetcwdchdirrrfrr)rr+Z	saved_dirrcrcrd
change_cwds

r0tempcwdccs:t||d$}t||d}|VWdQRXWdQRXdS)a
    Context manager that temporarily creates and changes the CWD.

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

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

    )rr+)r+N)r-r0)rur+Z	temp_pathZcwd_dirrcrcrdrsumaskccs&tj|}z
dVWdtj|XdS)z8Context manager that temporarily sets the process umask.N)rr2)r2ZoldmaskrcrcrdrJs

datacCsbtjj|r|S|dk	r&tjj||}tgtj}x*|D]"}tjj||}tjj|r8|Sq8W|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)rrisabsr
TEST_HOME_DIRrnexists)rZsubdirrZdnfnrcrcrdr"s
cCs(tj|tjtjBtjB}tj|dS)z>Create an empty file. If the file already exists, truncate it.N)ropenO_WRONLYO_CREATO_TRUNCr)rfdrcrcrdr4scCs,t|j}dd|D}dj|}d|S)z%Like repr(dict), but in sorted order.cSsg|]}d|qS)z%r: %rrc).0Zpairrcrcrd
<listcomp><szsortdict.<locals>.<listcomp>z, z{%s})sortedrr)dictrZ	reprpairsZ
withcommasrcrcrdrZ9s
cCs*ttd}z|jS|jttXdS)z`
    Create an invalid file descriptor by opening and closing a file and return
    its fd.
    wbN)r8rfilenorr)rrcrcrdmake_bad_fd@s

rC)linenooffsetcCsp|jt}t|ddWdQRX|j}|j|j|dk	rJ|j|j||j|j|dk	rl|j|j|dS)Nz
<test string>exec)assertRaisesSyntaxErrorcompileZ	exceptionZassertIsNotNonerDassertEqualrE)testcaseZ	statementrDrEcmrrcrcrdr%LscsVddl}ddl}jdd|jj|djdd}tjjt	|}fdd}tjj
|r|||}|dk	rt|St|tdt
rtd	|td
|jj}tr|jjd|j|d
d}tr|jjddkrtj|d}zBt|d.}	|j}
x|
r|	j|
|j}
qWWdQRXWd|jX||}|dk	rF|Std|dS)Nrcheckr/rcs>t|f}dkr|S|r2|jd|S|jdS)Nr)r8seekr)r7r)rrMrrcrdcheck_valid_file`s
z*open_urlresource.<locals>.check_valid_fileZurlfetchz	fetching %s ...)rAccept-Encodinggzip)rzContent-Encoding)ZfileobjrAzinvalid resource %r)rQrR)Zurllib.requestZurllib.parsepopparseZurlparserrrr
TEST_DATA_DIRr6rr!rrrZrequestZbuild_openerrRZ
addheadersrr8ZheadersgetZGzipFilereadwriterr
)Zurlrrurllibrr7rPropeneroutsrc)rrMrrdrHWs<	



c@s4eZdZdZddZddZeddZdd	Zd
S)WarningsRecorderzyConvenience wrapper for the warnings list returned on
       entry to the warnings.catch_warnings() context manager.
    cCs||_d|_dS)Nr)	_warnings_last)selfZ
warnings_listrcrcrd__init__szWarningsRecorder.__init__cCsDt|j|jkr t|jd|S|tjjkr0dStd||fdS)Nrz%r has no attribute %rrT)rr`rarrfWarningMessage_WARNING_DETAILSr)rbattrrcrcrd__getattr__s
zWarningsRecorder.__getattr__cCs|j|jdS)N)r`ra)rbrcrcrdrfszWarningsRecorder.warningscCst|j|_dS)N)rr`ra)rbrcrcrdresetszWarningsRecorder.resetN)	r_r`rarbrcrgpropertyrfrhrcrcrcrdr_s
r_c
cs
tjd}|jjd}|r"|jtjdd }tjdjdt	|VWdQRXt
|}g}xz|D]r\}}d}	xH|ddD]8}|j}
tj
|t|
tjrt|
j|rd}	|j|qW|	rf|rf|j||jfqfW|rtd	|d
|rtd|d
dS)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.
    rZ__warningregistry__T)recordrfalwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)rn	_getframe	f_globalsrXclearrfrgrysimplefilterr_r{messagerematchrtI
issubclassrremoverr_r)filtersr+frameregistrywZreraiseZmissingrwcatseenZwarningrcrcrd_filterwarningss0
r|cOs.|jd}|s$dtff}|dkr$d}t||S)aContext 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)
    r+rNT)rXWarningr|)rvrr+rcrcrdrQs

ccsBtjdd }tjdtddVtWdQRX|j|gdS)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)rjrk)categoryN)rfrgrhResourceWarning
gc_collectrJ)rKZwarnsrcrcrdrRs
c@s(eZdZdZddZddZddZdS)	ra,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
    cGsNtjj|_x<|D]4}|tjkrtj|}|j|kr>tj|j=tj|=qWdS)N)rnrycopyoriginal_modulesr_)rbZmodule_namesZmodule_namerrcrcrdrcs




zCleanImport.__init__cCs|S)Nrc)rbrcrcrd	__enter__
szCleanImport.__enter__cGstjj|jdS)N)rnryrr)rb
ignore_excrcrcrd__exit__szCleanImport.__exit__N)r_r`rarbrcrrrcrcrcrdrs

c@sheZdZdZddZddZddZdd	Zd
dZdd
Z	ddZ
ddZddZddZ
ddZdS)rSz_Class to help protect the environment variable properly.  Can be used as
    a context manager.cCstj|_i|_dS)N)renviron_environ_changed)rbrcrcrdrcszEnvironmentVarGuard.__init__cCs
|j|S)N)r)rbenvvarrcrcrd__getitem__szEnvironmentVarGuard.__getitem__cCs*||jkr|jj||j|<||j|<dS)N)rrrX)rbrvaluercrcrd__setitem__ s
zEnvironmentVarGuard.__setitem__cCs2||jkr|jj||j|<||jkr.|j|=dS)N)rrrX)rbrrcrcrd__delitem__&s

zEnvironmentVarGuard.__delitem__cCs
|jjS)N)rkeys)rbrcrcrdr-szEnvironmentVarGuard.keyscCs
t|jS)N)iterr)rbrcrcrd__iter__0szEnvironmentVarGuard.__iter__cCs
t|jS)N)rr)rbrcrcrd__len__3szEnvironmentVarGuard.__len__cCs|||<dS)Nrc)rbrrrcrcrdset6szEnvironmentVarGuard.setcCs
||=dS)Nrc)rbrrcrcrdunset9szEnvironmentVarGuard.unsetcCs|S)Nrc)rbrcrcrdr<szEnvironmentVarGuard.__enter__cGsJx<|jjD].\}}|dkr0||jkr:|j|=q||j|<qW|jt_dS)N)rrrrr)rbrkvrcrcrdr?s

zEnvironmentVarGuard.__exit__N)r_r`rarbrcrrrrrrrrrrrcrcrcrdrSsc@s(eZdZdZddZddZddZdS)	
DirsOnSysPathaContext 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.
    cGs(tjdd|_tj|_tjj|dS)N)rnroriginal_valueoriginal_objectextend)rbpathsrcrcrdrcUszDirsOnSysPath.__init__cCs|S)Nrc)rbrcrcrdrZszDirsOnSysPath.__enter__cGs|jt_|jtjdd<dS)N)rrnrr)rbrrcrcrdr]szDirsOnSysPath.__exit__N)r_r`rarbrcrrrcrcrcrdrIs
rc@s*eZdZdZddZddZd	ddZdS)
r&zRaise ResourceDenied if an exception is raised while the context manager
    is in effect that matches the specified exception and attributes.cKs||_||_dS)N)rattrs)rbrrrcrcrdrcgszTransientResource.__init__cCs|S)Nrc)rbrcrcrdrkszTransientResource.__enter__NcCsT|dk	rPt|j|rPx:|jjD]$\}}t||s4Pt|||kr Pq WtddS)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)rtrrrrrr)rbZtype_r	tracebackrfZ
attr_valuercrcrdrns
zTransientResource.__exit__)NNN)r_r`rarbrcrrrcrcrcrdr&bs)errnog>@)rerrnosc	#spd!d"d#d$d%d&g}d(d*d,d.d/g}td||gsRdd|Ddd|Dfdd}tj}zy|dk	rtj|dVWntjk
r}z&trtjj	j
dd|WYdd}~Xntk
rZ}zpx^|j
}t|d krt
|dtr|d}n*t|dkr8t
|d tr8|d }nPqW||WYdd}~XnXWdtj|XdS)0zReturn a context manager that raises ResourceDenied when various issues
    with the Internet connection manifest themselves as exceptions.ECONNREFUSEDo
ECONNRESEThEHOSTUNREACHqENETUNREACHe	ETIMEDOUTn
EADDRNOTAVAILc	EAI_AGAINr%EAI_FAILr
EAI_NONAMEr
EAI_NODATA
WSANO_DATA*zResource %r is not availablecSsg|]\}}tt||qSrc)rr)r=runumrcrcrdr>sz&transient_internet.<locals>.<listcomp>cSsg|]\}}tt||qSrc)rr)r=rurrcrcrdr>scst|dd}t|tjst|tjr,|kst|tjjrTd|jkoNdknst|tjj	rd|j
ksd|j
ksd|j
ks|krtstj
jjdd|dS)	NriiWConnectionRefusedErrorTimeoutErrorEOFErrorr
)r
isinstancerrZgaierrorr[errorZ	HTTPErrorcodeZURLErrorrrrnstderrrZr)rn)captured_errnosdenied
gai_errnosrcrdfilter_errors


z(transient_internet.<locals>.filter_errorNrrr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rrZgetdefaulttimeoutZsetdefaulttimeoutnntplibZNNTPTemporaryErrorrrnrrZrrrr)	Z
resource_namerrZdefault_errnosZdefault_gai_errnosrZold_timeoutrarc)rrrrdr*sP



c
csFddl}tt|}tt||jztt|VWdtt||XdS)zReturn a context manager used by captured_stdout/stdin/stderr
    that temporarily replaces the sys stream *stream_name* with a StringIO.rN)iorrnsetattrStringIO)Zstream_namerZorig_stdoutrcrcrdcaptured_outputs
rcCstdS)zCapture the output of sys.stdout:

       with captured_stdout() as stdout:
           print("hello")
       self.assertEqual(stdout.getvalue(), "hello\n")
    r)rrcrcrcrdrscCstdS)zCapture the output of sys.stderr:

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

       with captured_stdin() as stdin:
           stdin.write('hello\n')
           stdin.seek(0)
           # call test code that consumes from sys.stdin
           captured = input()
       self.assertEqual(captured, "hello")
    stdin)rrcrcrcrdrs
cCs*tjtrtjdtjtjdS)aForce as many objects as possible to be collected.

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


rc
cs.tj}tjz
dVWd|r(tjXdS)N)r	isenableddisableenable)Zhave_gcrcrcrd
disable_gcs
rcCs:tjdpd}d}x|jD]}|jdr|}qW|dkS)z,Find if Python was built with optimizations.	PY_CFLAGSrz-O-O0-Og)rrr)	sysconfigget_config_varrrp)ZcflagsZ	final_optrrcrcrdpython_is_optimizeds
rZnPZ0ngettotalrefcountZ2PZ0PrcCstjt|tS)N)structcalcsize_header_align)fmtrcrcrdcalcobjsize(srcCstjt|tS)N)rr_vheaderr)rrcrcrdcalcvobjsize+sr	cCspddl}tj|}t|tkr(|jt@sBt|tkrLt|jt@rL||j7}dt|||f}|j|||dS)Nrz&wrong size for %s: got %d, expected %d)		_testcapirn	getsizeofr	__flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADrJ)testosizerrrwrcrcrdcheck_sizeof2s

rcsfdd}|S)Ncs$fdd}j|_j|_|S)Ncsy ddl}t|}|j|}Wn(tk
r6YnBd}}Yn0Xx,D]$}y|j||PWqPYqPXqPWz
||S|r|r|j||XdS)Nr)localer	setlocaler)rkwdsrr~Zorig_localeloc)catstrrlocalesrcrdinnerCs$



z1run_with_locale.<locals>.decorator.<locals>.inner)r_rb)rr)rr)rrdrBsz"run_with_locale.<locals>.decoratorrc)rrrrc)rrrdrTAscsfdd}|S)Ncs"fdd}j|_j|_|S)Ncsy
tj}Wntk
r(tjdYnXdtjkr@tjd}nd}tjd<|z
||S|dkrrtjd=n
|tjd<tjXdS)Nztzset requiredZTZ)rtzsetrrrrsrr)rrrZorig_tz)rtzrcrdrgs





z-run_with_tz.<locals>.decorator.<locals>.inner)r_rb)rr)r)rrdrfszrun_with_tz.<locals>.decoratorrc)rrrc)rrdr[escCsdttdtd}tjd|tjtjB}|dkr>td|ftt|j	d||j	dj
}|a|tkrrt}|t
dkrtd|f|adS)Ni)rmgtz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rrr%z$Memory limit %r too low to be useful)_1M_1Grqrr
IGNORECASEVERBOSErrfloatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitZsizesrZmemlimitrcrcrdrXs$c@s(eZdZdZddZddZddZdS)	_MemoryWatchdogz`An object which periodically watches the process' memory consumption
    and prints it out.
    cCsdjtjd|_d|_dS)Nz/proc/{pid}/statm)r,F)rrr*procfilestarted)rbrcrcrdrcsz_MemoryWatchdog.__init__cCsyt|jd}Wn<tk
rL}z tjdj|ttjj	dSd}~XnXt
d}tjtj
|g|tjd|_|jd|_dS)Nrz!/proc not available for stats: {}zmemory_watchdog.py)rrT)r8rrrfrrrrnrflushr
subprocessPopen
executableZDEVNULLmem_watchdogrr)rbrrZwatchdog_scriptrcrcrdstarts
z_MemoryWatchdog.startcCs|jr|jj|jjdS)N)rr	Z	terminatewait)rbrcrcrdstops
z_MemoryWatchdog.stopN)r_r`rarbrcr
rrcrcrcrdrsrcsfdd}|S)atDecorator for bigmem tests.

    'size' is a requested size for the test (in arbitrary, test-interpreted
    units.) 'memuse' is the number of bytes per unit for the test, or a good
    estimate of it. For example, a test that needs two byte buffers, of 4 GiB
    each, could be decorated with @bigmemtest(size=_4G, memuse=2).

    The 'size' argument is normally passed to the decorated test method as an
    extra argument. If 'dry_run' is true, the value passed to the test method
    may be less than the requested value. If 'dry_run' is false, it means the
    test doesn't support dummy runs when -M is not specified.
    cs fdd__S)Nc
sj}j}tsd}n|}ts$rFt||krFtjd||dtr|tr|ttdj||ddt}|j	nd}z
||S|r|j
XdS)	Niz'not enough memory: %.1fG minimum neededir%z* ... expected peak memory use: {peak:.1f}G)Zpeaki@i@)rmemuserrrrsrrrrr
r)rbrr
maxsizeZwatchdog)dry_runrrrcrdrs*


z.bigmemtest.<locals>.decorator.<locals>.wrapper)rr
)r)rr
r)rrrdrszbigmemtest.<locals>.decoratorrc)rr
rrrc)rr
rrdr2s
!csfdd}|S)z0Decorator for tests that fill the address space.csDttkr8td
kr$tdkr$tjdq@tjdtdn|SdS)
Nr?rz-not enough memory: try a 32-bit build insteadz'not enough memory: %.1fG minimum neededir%llli@)rrrrrs)rb)rrcrdrsz!bigaddrspacetest.<locals>.wrapperrc)rrrc)rrdr3sc@seZdZddZdS)r+cCstj}|||S)N)rrZ
TestResult)rbrrrcrcrdrunszBasicTestRunner.runN)r_r`rarrcrcrcrdr+scCs|S)Nrc)rrcrcrd_id
srcCs<|dkrtrtjtjSt|r(tStjdj|SdS)Nrzresource {0!r} is not enabled)rrrskiprr rr)rrcrcrdrequires_resource
s
rcCs&trt|krtjd|tfStSdS)Nz%s at Android API level %d)r@_ANDROID_API_LEVELrrrr)levelrrcrcrdr=scCstdd|S)z9
    Decorator for tests only applicable on CPython.
    T)cpython)impl_detail)rrcrcrdr4scKsVtf|rtS|dkrLt|\}}|r,d}nd}t|j}|jdj|}tj|S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or )	rAr
_parse_guardsr?rrrrrr)rwguardsZ
guardnamesdefaultrcrcrdr"s
rcCsTtdkr:ddl}y|jdaWntk
r8daYnXd}trF|Stj||S)z8Skip decorator for tests that use multiprocessing.Queue.NrTFz6requires a functioning shared semaphore implementation)_have_mp_queuemultiprocessingZQueuermrrr)rrrwrcrcrdr>0s
cCsH|sddidfSt|jd}t|j|gt|ks>t||fS)NrTFr)r{valuesrr)rZis_truercrcrdr?s
rcKs t|\}}|jtjj|S)a5This function returns True or False depending on the host platform.
       Examples:
          if check_impl_detail():               # only on CPython (default)
          if check_impl_detail(jython=True):    # only on Jython
          if check_impl_detail(cpython=False):  # everywhere except on CPython
    )rrXroZpython_implementationr)rrrcrcrdrAIscs,ttdsStjfdd}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.gettracecs.tj}ztjd||Stj|XdS)N)rnr settrace)rrZoriginal_trace)rrcrdrYs


zno_tracing.<locals>.wrapperN)rrnrr)rrrc)rrd
no_tracingTs
r"cCstt|S)aDecorator for tests which involve reference counting.

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

    )r"r4)rrcrcrd
refcount_testdsr#cCsRg}xB|jD]8}t|tjr2t|||j|q||r|j|qW||_dS)z>Recursively filter test cases in a suite based on a predicate.N)Z_testsrrr	TestSuite
_filter_suiter)suiteZpredZnewtestsrrcrcrdr%os
r%cCsttjttdk	d}|j|}tdk	r4tj|j|js>t	|j
st|jdkrl|j
rl|jdd}n6t|j
dkr|jr|j
dd}nd}ts|d7}t|dS)z2Run tests from a unittest.TestSuite-derived class.N)	verbosityZcapture_outputrrzmultiple errors occurredz!; run in verbose mode for details)rrnrrjunit_xml_listrrZget_xml_elementZtestsRunrZ
wasSuccessfulrerrorsZfailuresr
)r&Zrunnerrrrcrcrd
_run_suite{s"
r*cCstdkrdSt|jSdS)NT)_match_test_funcid)rrcrcrd
match_testsr-cCsd|kotjd|S)Nrxz[?*\[\]])rqsearch)rrcrcrd_is_full_match_testsr/csr|tkrdS|sd}f}nHttt|r4t|j}n.djttj|}t	j
|jfdd}|}t|a|a
dS)N|cs$|rdStt|jdSdS)NTrx)anyrr)Ztest_id)regex_matchrcrdmatch_test_regexsz)set_match_tests.<locals>.match_test_regex)_match_test_patternsallrr/r__contains__rfnmatch	translaterqrIrrrqr+)ZpatternsrZregexr3rc)r2rdset_match_testssr9cGstjtjf}tj}xh|D]`}t|trT|tjkrJ|jtjtj|qzt	dqt||rj|j|q|jtj
|qWt|tt
|dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesN)rrr$ZTestCaserrtrnryZaddTestZ
findTestCasesrZ	makeSuiter%r-r*)classesZvalid_typesr&clsrcrcrdr,s





cCsdS)z,Just used to check if docstrings are enabledNrcrcrcrcrd_check_docstringssr<WITH_DOC_STRINGSztest requires docstringscCs`ddl}|dkrt}nd}|j|||d\}}|rBtd||ftrXtd|j|f||fS)aRun doctest on the given module.  Return (#failures, #tests).

    If optional argument verbosity is not specified (or is None), pass
    support's belief about verbosity on to doctest.  Else doctest's
    usual behavior is used (it searches sys.argv for -v).
    rN)roptionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)doctestrZtestmodr
rr_)rr'r>r?rrrcrcrdr-scCstjjfS)N)rnryrrcrcrcrd
modules_setupsr@cCs:ddtjjD}tjjtjj|tjj|dS)NcSs"g|]\}}|jdr||fqS)z
encodings.)rp)r=rrrcrcrdr>sz#modules_cleanup.<locals>.<listcomp>)rnryrrnr)Z
oldmodulesZ	encodingsrcrcrdmodules_cleanups
rAcCs"trtjtjjfSdffSdS)Nr)_thread_count	threading	_danglingrrcrcrcrdrM;scGsJtsdSd}x8t|D],}tjtjf}||kr2PtjdtqWdS)Ndg{Gz?)rBrangerCrDrErrr)Zoriginal_valuesZ
_MAX_COUNTcountrrcrcrdrNAs
cs"tsStjfdd}|S)zUse this function when threads are being used.  This will
    ensure that the threads are cleaned up even when the test fails.
    If threading is unavailable this function does nothing.
    cst}z|St|XdS)N)rMrN)rkey)rrcrdrUszreap_threads.<locals>.decorator)rBrr)rrrc)rrdrOMsN@ccstj}z
dVWdtj}||}xjtj}||kr8Ptj|kr|tj|}d||d|dd|d|d	}t|tjdtq&WXdS)	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 z.1fz seconds (count: z
, old count: )g{Gz?)rBrCrZ	monotonicrrr)rZ	old_countZ
start_timeZdeadlinerHZdtrwrcrcrdwait_threads_exit_s
$
rLc
CsZttdrVd}xFy2tj|tj\}}|dkr.Ptd|tjdWqPYqXqWdS)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.
    waitpidrrz2Warning -- reap_children() reaped child process %s)rNrT)rrrMWNOHANGrrnr)Zany_processr,ZstatusrcrcrdrKs
ccs*t|}g}zZy$x|D]}|j|j|qWWn*trVtdt|t|fYnXdVWdz|rt|tj}}xltddD]^}|d7}x$|D]}|jt	|tjdqWdd|D}|sPtrtdt||fqWWdd	d|D}|r"t
jtj
td
t|XXdS)Nz/Can't start %d threads, only %d threads startedrr<g{Gz?cSsg|]}|jr|qSrc)isAlive)r=rrcrcrdr>sz!start_threads.<locals>.<listcomp>z7Unable to join %d threads during a period of %d minutescSsg|]}|jr|qSrc)rP)r=rrcrcrdr>szUnable to join %d threads)r{r
rrrrrrGrmaxfaulthandlerZdump_tracebackrnrr)ZthreadsZunlockrrZendtimeZ	starttimerrcrcrdrPs>


c
csnt||r<t||}t|||z
|VWdt|||Xn.t|||z
dVWdt||rht||XdS)aTemporary 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)rrrdelattr)rrfnew_valreal_valrcrcrdrVs




ccsX||kr0||}|||<z
|VWd|||<Xn$|||<z
dVWd||krR||=XdS)aTemporary 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.
    Nrc)ritemrTrUrcrcrdrUs

cCstjdd|j}|S)zStrip the stderr of a Python process from potential debug output
    emitted by the interpreter.

    This will typically be run on the result of the communicate() method
    of a subprocess.Popen object.
    s\[\d+ refs, \d+ blocks\]\r?\n?)rqsubstrip)rrcrcrdstrip_python_stderrsrZZ	getcountsz-types are immortal if COUNT_ALLOCS is definedcCstjS)znReturn a list of command-line arguments reproducing the current
    settings in sys.flags and sys.warnoptions.)rZ_args_from_interpreter_flagsrcrcrcrdargs_from_interpreter_flags	sr[cCstjS)zgReturn a list of command-line arguments reproducing the current
    optimization settings in sys.flags.)rZ"_optim_args_from_interpreter_flagsrcrcrcrd!optim_args_from_interpreter_flags	sr\c@s,eZdZddZddZddZddZd	S)
rLcCstjjj|d||_dS)Nr)logginghandlersBufferingHandlerrcmatcher)rbr`rcrcrdrc	szTestHandler.__init__cCsdS)NFrc)rbrcrcrdshouldFlush	szTestHandler.shouldFlushcCs|j||jj|jdS)N)rrr__dict__)rbrjrcrcrdemit!	s
zTestHandler.emitcKs.d}x$|jD]}|jj|f|rd}PqW|S)zW
        Look for a saved dict whose keys/values match the supplied arguments.
        FT)rr`matches)rbrrdrcrcrdrd%	szTestHandler.matchesN)r_r`rarcrarcrdrcrcrcrdrL	s	c@s eZdZdZddZddZdS)	rWrwrpcKs<d}x2|D]*}||}|j|}|j|||s
d}Pq
W|S)a.
        Try to match a single dict with the supplied arguments.

        Keys whose values are strings and which are in self._partial_matches
        will be checked for partial (i.e. substring) matches. You can extend
        this scheme to (for example) do regular expression matching, etc.
        TF)rXmatch_value)rbrerrrrdvrcrcrdrd4	s

zMatcher.matchescCsHt|t|krd}n.t|tk	s,||jkr6||k}n|j|dk}|S)zT
        Try to match a single stored value (dv) with a supplied value (v).
        Fr)rrt_partial_matchesfind)rbrrgrrrcrcrdrfE	s
zMatcher.match_valueN)rwrp)r_r`rarhrdrfrcrcrcrdrW0	sc
CsZtdk	rtStd}ytjt|d}Wntttfk
rFd}YnXtj||a|S)NrTF)_can_symlinkrrsymlinkrNotImplementedErrorrru)Zsymlink_pathcanrcrcrdrS	s

cCs t}d}|r|Stj||S)z8Skip decorator for tests that require functional symlinkz*Requires functional symlink implementation)rrrr)rokrwrcrcrdr.b	scCstdk	rtSttdsd}ntj}tj|d\}}zttd}y`tj|ddtj|ddtj|j	ddt
j}tj
d	|}|dkpt|jd
dk}Wntk
rd}YnXWdQRXWdttt|t|X|a|S)NsetxattrF)dirrAs	user.testrWstrusted.foos42z
2.6.(\d{1,2})r')
_can_xattrrrr&r'Zmkstempr8rrorBrorrqrrrrrrr)rmZtmp_dirZtmp_fpZtmp_namefpZkernel_versionrrcrcrd	can_xattri	s,

rtcCs t}d}|r|Stj||S)zDSkip decorator for tests that require functional extended attributesz(no non-broken extended attribute support)rtrrr)rrnrwrcrcrdr7	scCs^tj|dH}|j}|j}||kr,|j}ytjj||Stk
rNdSXWdQRXdS)zKDetects if the file system for the specified directory is case-insensitive.)rpFN)	r&ZNamedTemporaryFileruupperrrrsamefiler)Z	directorybase	base_pathZ	case_pathrcrcrdr	s)recCs>tt|tt|}|r(|t|8}tdd|D}|S)aReturns the set of items in ref_api not in other_api, except for a
    defined list of items to be ignored in this check.

    By default this skips private attributes beginning with '_' but
    includes all magic methods, i.e. those starting and ending in '__'.
    css(|] }|jds|jdr|VqdS)___N)rpendswith)r=rrcrcrd	<genexpr>	sz&detect_api_mismatch.<locals>.<genexpr>)rrp)Zref_apiZ	other_apireZ
missing_itemsrcrcrdr;	s
cCs|dkr|jf}nt|tr"|f}t|}xbt|D]V}|jds4||krLq4t||}t|dd|kst|dr4t|tj	r4|j
|q4W|j|j|dS)aAssert 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)

    Nryr`)
r_rrtrrprprrtypes
ModuleTypeaddZassertCountEqual__all__)Z	test_caserZname_of_moduleZextraZ	blacklistZexpectedrurrcrcrdr<	s)


c@s(eZdZdZdZdZddZddZdS)rYzTry 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
Csrtjjdrddl}|jj|_d}|jj||_|jj|j|Byddl	}|j
Wnttfk
rlYnLXi|_
x|j|j|jgD].}|j
||j}|j||j}||f|j
|<qWntdk	r
y*tjtj|_tjtjd|jdfWnttfk
rYnXtjdkrnddd	d
g}tj|tjtjd}||jd}	WdQRX|	jdkrntd
ddd|S)zOn Windows, disable Windows Error Reporting dialogs using
        SetErrorMode.

        On UNIX, try to save the previous core file size limit, then set
        soft limit to 0.
        rrNrrrz/usr/bin/defaultsrYzcom.apple.CrashReporterZ
DialogType)rrs	developerz:this test triggers the Crash Reporter, that is intentionalrT)endr) rnrorprrr_k32SetErrorMode	old_valuemsvcrtCrtSetReportModerrm	old_modesCRT_WARN	CRT_ERROR
CRT_ASSERTZCRTDBG_MODE_FILECrtSetReportFileZCRTDBG_FILE_STDERRrZ	getrlimitRLIMIT_CORE	setrlimitrrrrPIPEZcommunicaterYr)
rbrZSEM_NOGPFAULTERRORBOXrreport_typeold_modeold_filecmdprocrrcrcrdr	sN




zSuppressCrashReport.__enter__cGs|jdkrdStjjdrl|jj|j|jrddl}xj|jjD]$\}\}}|j	|||j
||qBWn6tdk	rytjtj
|jWnttfk
rYnXdS)zARestore Windows ErrorMode or core file behavior to initial value.Nrr)rrnrorprrrrrrrrrrrr)rbrrrrrrcrcrdr/
s
zSuppressCrashReport.__exit__)r_r`rarbrrrrrcrcrcrdrY	s
AcsrtdyjWn$ttfk
r@tdYnXdfdd}|j|t|dS)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'.

    FNTcs rtn
tdS)N)rrSrc)
attr_is_local	attr_nameobject_to_patchrrcrdcleanupZ
szpatch.<locals>.cleanup)rrbrrZ
addCleanupr)Z
test_instancerrZ	new_valuerrc)rrrrrdpatchD
s


rcCsFyddl}Wntk
r YnX|jr4tjdddl}|j|S)zi
    Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
    module is enabled.
    rNzUrun_in_subinterp() cannot be used if tracemalloc module is tracing memory allocations)tracemallocrmZ
is_tracingrrrsrrun_in_subinterp)rrrrcrcrdrf
s
rcsHGfddd|}d||||jttt|jdS)NcseZdZfddZdS)z%check_free_after_iterating.<locals>.Acs*dytWntk
r$YnXdS)NT)next
StopIteration)rb)doneitrcrd__del__|
s
z-check_free_after_iterating.<locals>.A.__del__N)r_r`rarrc)rrrcrdA{
srF)rGrrrZ
assertTrue)rrr;rrrc)rrrdcheck_free_after_iteratingz
s	rcCsddlm}m}m}|j}|j|xd|jD]Z}|r@||kr@q.t||}|rd|dk	sntd|n
|dkrnq.|j	|ddkr.|dSq.WdS)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)	ccompilerrspawnNz%the '%s' executable is not configured)
Z	distutilsrrrZnew_compilerZcustomize_compilerZexecutablesrrZfind_executable)Z	cmd_namesrrrZcompilerrurrcrcrdr]
s	


cCs@d}tr6||kr6tdkr.tjddgjdkatr6|}tj|S)Ngh㈵>Zgetpropzro.kernel.qemu1)r@_is_android_emulatorrZcheck_outputrYrnrC)ZintervalZminimum_intervalrcrcrdrC
sc
cs>tjj}tj}ztjdVWd|r8tj|ddXdS)NT)rZall_threads)rnrrBrR
is_enabledrr)r<rrcrcrddisable_faulthandler
s

rc	/Cstjjdr8ytjd}t|dStk
r6YnXd}ttdrjytjd}Wnt	k
rhYnXd}tjd	kryd
dl
}|jWntt
fk
rYn0Xi}x(|j|j|jfD]}|j|d
||<qWzpd
}xft|D]Z}ytj|}Wn4t	k
r(}z|jtjkrWYdd}~XqXtj||d7}qWWd|dk	rzx*|j|j|jfD]}|j|||q`WX|S)z/Count the number of open file descriptors.
    linuxfreebsdz
/proc/self/fdrsysconfSC_OPEN_MAXNrr)rr)rnrorprrrrrrrrrrrmrrrrGduprZEBADFr)	namesZMAXFDrrrrHr<Zfd2rrcrcrdr^
sP





c@s(eZdZdZddZddZddZdS)	SaveSignalsz
    Save an 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Csjddl}||_ttd|j|_x>dD]6}yt||}Wntk
rNw&YnX|jj|q&Wi|_dS)NrrSIGKILLSIGSTOP)rr)	signalr{rGNSIGsignalsrrrur^)rbrZsignamesignumrcrcrdrc	s
zSaveSignals.__init__cCs4x.|jD]$}|jj|}|dkr"q||j|<qWdS)N)rr	getsignalr^)rbrhandlerrcrcrdsaves
zSaveSignals.savecCs*x$|jjD]\}}|jj||qWdS)N)r^rr)rbrrrcrcrdrestore"szSaveSignals.restoreN)r_r`rarbrcrrrcrcrcrdrs
rc@s(eZdZdZddZddZddZdS)	FakePathz.Simple implementing of the path protocol.
    cCs
||_dS)N)r)rbrrcrcrdrc*szFakePath.__init__cCsd|jdS)Nz
<FakePath >)r)rbrcrcrd__repr__-szFakePath.__repr__cCs6t|jts$t|jtr,t|jtr,|jn|jSdS)N)rr
BaseExceptionrrt)rbrcrcrd
__fspath__0s
zFakePath.__fspath__N)r_r`rarbrcrrrcrcrcrdr'sr)T)F)F)Nii@i@i@ii)rrrrrrrrrrr)r!rr"r#r$)NF)F)r1F)N)Fi@ii)T)N)Nr)rJ)N(rbr_rmcollections.abccollections
contextlibZdatetimerrRr7rrrlimportlib.utilrZlogging.handlersr]rrrorqrrrrrrnrr&rr}rrZurllib.errorr[rfZ
testresultrrBrDZmultiprocessing.processrzlibrRbz2Zlzmarrrr	r
rrsrcontextmanagerrjr
r~rr9r:rr5rrrrr(rrrrrrrprrrrrrrrrrrr r!rr"r#r$rDr	rrrFrGrIr
rErrZ
SOCK_MAX_SIZEZ
skipUnlessr
__getformat__r6r8r/r0r1r?rrr@rBrurrr*ZFS_NONASCII	characterfsdecodefsencodeUnicodeErrorZTESTFN_UNICODEZunicodedata	normalizegetfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversionencodeUnicodeEncodeErrorrdecodeUnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIr.rr\r-r0rrrJrrrrZTEST_SUPPORT_DIRr5rrWrrrZrCr%rHobjectr_r|rQrRrabcMutableMappingrSrr&rrr'rr(r)r*rrrrrrrrrrrrrrrrTr[rrrZ_4GrrrXrr2r3r+rrr=r4rrr>rrAr"r#r%r*r+r4r-r/r9r,r<ZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr-r@rAZenvironment_alteredrMrNrOrLrKrPrVrUrZZskipIfZrequires_type_collectingr[r\r^r_rLrWrjrr.rrrtr7rr;r<rYrrrr]rrCrr^rrrcrcrcrd<module>s










2	
!

J			>%	


%2' 5M		


$
#
0







(




"
#
	"


:_";'

OHA YOOOO