Viewing File: /opt/alt/python35/lib64/python3.5/test/support/__pycache__/__init__.cpython-35.opt-1.pyc



Yf
Q@sdZedkredddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
ZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZyddl Z ddl!Z!Wnek
rdZ dZ!YnXyddl"Z#Wnek
rdZ#YnXyddl$Z$Wnek
rdZ$YnXyddl%Z%Wnek
rdZ%YnXyddl&Z&Wnek
r>dZ&YnXyddl'Z'Wnek
ridZ'YnXyddl(Z(Wnek
rdZ(YnXddddd	d
ddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUgQZ)GdVd
d
e*Z+GdWdde+Z,GdXddej-Z.ej/dYdZd[Z0d\d]fd^d
Z1d_d`Z2dadbZ3dcd9Z4ddd:Z5ffd\dedZ6dfd5Z7dgZ8dZ9da:da;d\Z<da=da>dhdZ?didZ@djdZAdkdlZBejjCdmrd\dndoZDdpdqZEdrdsZFdtduZGnejHZEejIZFdvduZGdwdZHdxdyZIdzdZJd{d|ZKd}dZLd~dZMdd ZNddd!ZOddZPdd"ZQdd#ZRdd$ZSdZTdZUejVejWddAZXeTddBZYddZZeZZ[ddZ\d;Z]d>Z^ej_e`jadjCddZbej_e$dZcej_e%dZdej_e&dZeej_e'dZfejjCdZgejhdkrdZindZidjjeiejkZidZlxDd?D]<ZmyejnejoemWnepk
rYqXemZlPqWeidZqejdkr<ddlrZrerjsdeqZqejtZudZvejhd@krejwjdkr
eidZvyevjxeuWneyk
rYq
XezdeveufdZvnKejdkr
ydj{euWn(e|k
r	eidj{eudZvYnXdZ}xHdAD]@Zhyehj{euWqe|k
rVejoeiehZ}PYqXqWelrreidelZ~ndZ~ejZej/dd\ddZej/d\ddZej/dd\ddZeedrej/ddDZejjejjeZejjeZejjedZdddZddZddTZddZdddddd%ZddCZGdddeZd\ddZej/ddKZej/ddLZGdddeZGddMdMejjZGdddeZGdd&d&eZeedejZeedejZeedejZej/dddfdd*Zej/ddZddZddZddZddZej/ddZddZdZdZeedr0deZdZedZddZddZdBZdCZddZddNZddUZdDZdeZdeZdeZejZddRZGdddZdYdd2Zdd3ZGdd+d+ZddZddZdd4ZdddZdadd<ZddZdd>ZddZdd	Zd
dZdd
ZddZdd,ZddZeoejdkoejdZejdk	oeZej_edZdddd-ZddZddZddGZddHZddIZddEZej/dddJZej/d dPZej/d!dOZd"d#Zejeed$d%Zd&d'ZGd(dFdFejjZGd)dQdQeZdad*dZd+d.Zdad,d-Zd.d7Zd/dZd0fd1d;ZGd2dSdSZd3d4Zd5d6Zfd7d8ZdS(Ez7Supporting definitions for the Python regression tests.ztest.supportz.support must be imported from the test packageN
PIPE_MAX_SIZEverbose
max_memuse
use_resourcesfailfastError
TestFailedResourceDenied
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_mismatchrequires_multiprocessing_queue	is_jythoncheck_impl_detailHOSTIPV6_ENABLEDfind_unused_port	bind_portopen_urlresource
temp_umask
reap_childrenTestHandlerthreading_setupthreading_cleanupreap_threads
start_threadscheck_warningscheck_no_resource_warningEnvironmentVarGuardrun_with_locale	swap_item	swap_attrMatcherset_memlimitSuppressCrashReportsortdictrun_with_tzc@seZdZdZdS)rz*Base class for regression test exceptions.N)__name__
__module____qualname____doc__rWrW:/opt/alt/python35/lib64/python3.5/test/support/__init__.pyrnsc@seZdZdZdS)rzTest failed.N)rSrTrUrVrWrWrWrXrqsc@seZdZdZdS)r	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)rSrTrUrVrWrWrWrXr	tsTccs>|r5tjtjddtdVWdQRXndVdS)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)rYrWrWrX_ignore_deprecated_imports|s
r^Frequired_oncCst|nytj|SWnUtk
ru}z5tjjt|rNtj	t
|WYdd}~XnXWdQRXdS)acImport and return the module to be tested, raising SkipTest if
    it is not available.

    If deprecated is True, any module or package deprecation messages
    will be suppressed. If a module is required on a platform but optional for
    others, set required_on to an iterable of platform prefixes which will be
    compared against sys.platform.
    N)r^	importlibr
ImportErrorsysplatform
startswithtupleunittestSkipTeststr)name
deprecatedr_msgrWrWrXr
s	
cCs{|tjkr#t|tj|=xQttjD]@}||ksX|j|dr3tj|||<tj|=q3WdS)zyHelper function to save and remove a module from sys.modules

    Raise ImportError if the module can't be imported.
    .N)rbmodules
__import__listrd)riorig_modulesmodnamerWrWrX_save_and_remove_modules

rrcCsGd}ytj|||<Wntk
r5d}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)rbrmKeyError)rirpZsavedrWrWrX_save_and_block_modules

rtcCs|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)NrW)frWrWrX<lambda>sz$anticipate_failure.<locals>.<lambda>)rfZexpectedFailure)Z	conditionrWrWrXr6scCsk|dkrd}tjjtjjtjjt}|jd|d|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_testsrwZtop_dirZ
package_testsrWrWrXr7s			
cCst|i}g}t||z}y^x|D]}t||q3Wx*|D]"}t||sQ|j|qQWtj|}Wntk
rd}YnXWdx'|jD]\}	}
|
tj	|	<qWx|D]}tj	|=qWX|SWdQRXdS)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)
r^rrrtappendr`r
raitemsrbrm)riZfreshZblockedrjrpZnames_to_removeZ
fresh_nameZblocked_nameZfresh_moduleZ	orig_namemoduleZname_to_removerWrWrXrs$





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

cCs
|adS)N)_original_stdout)stdoutrWrWrXrscCs
tptjS)N)rrbrrWrWrWrXr#scCs'ytj|=Wntk
r"YnXdS)N)rbrmrs)rirWrWrXr
&s
cGsy||SWntk
r}z_tdkr`td|jj|ftd|j|ftj|tj||SWYdd}~XnXdS)Nz%s: %szre-run %s%r)	OSErrorrprint	__class__rSrxchmodstatS_IRWXU)ryfuncargserrrWrWrX
_force_run,srwincCs|||r|}n$tjj|\}}|p:d}d}xR|dkrtj|}|rm|n	||ks}dStj||d9}qFWtjd|tdddS)NrlgMbP?g?rz)tests may fail, delete still pending for 
stacklevel)	rxrysplitlistdirtimesleeprZwarnRuntimeWarning)rpathnamewaitallrzritimeoutLrWrWrX_waitfor7s
	

rcCsttj|dS)N)rrxr)filenamerWrWrX_unlinkXsrcCsttj|dS)N)rrxrmdir)rzrWrWrX_rmdir[srcs<fddt|ddtdd|dS)Ncsxt|tj|D]}tjj||}ytj|j}WnHtk
r}z(td||fdt	j
d}WYdd}~XnXtj|rt
|ddt|tj|qt|tj|qWdS)Nz-support.rmtree(): os.lstat(%r) failed with %sfilerrT)rrxrryjoinlstatst_moderrrb
__stderr__rS_ISDIRrrr)ryrifullnamemodeexc)
_rmtree_innerrWrXr_s
z_rmtree.<locals>._rmtree_innerrTcSst|tj|S)N)rrxr)prWrWrXrvnsz_rmtree.<locals>.<lambda>)r)ryrW)rrX_rmtree^srcsWytj|dSWntk
r)YnXfdd|tj|dS)Nc
sxt|tj|D]}tjj||}ytj|j}Wntk
rad}YnXtj	|r|t|tj
|qt|tj|qWdS)Nr)rrxrryrrrrrrrr)ryrirr)rrWrXrzs

z_rmtree.<locals>._rmtree_inner)shutilrrrxr)ryrW)rrXrss


cCs-yt|Wnttfk
r(YnXdS)N)rFileNotFoundErrorNotADirectoryError)rrWrWrXrscCs'yt|Wntk
r"YnXdS)N)rr)rzrWrWrXrs
rcCs'yt|Wntk
r"YnXdS)N)rr)ryrWrWrXrs
cCs]tjj|}tjjtjj|}tjj||d}tj|||S)aMove a PEP 3147/488 pyc file to its legacy pyc location.

    :param source: The file system path to the source file.  The source file
        does not need to exist, however the PEP 3147/488 pyc file must exist.
    :return: The file system path to the legacy pyc file.
    c)	r`utilcache_from_sourcerxryrzabspathrrename)sourceZpyc_fileZup_oneZ
legacy_pycrWrWrXmake_legacy_pycs
rcCsvt|xetjD]Z}tjj||d}t|dx*dD]"}ttjj|d|qHWqWdS)	z'Forget' a module was ever imported.

    This removes the module from sys.modules and deletes any PEP 3147/488 or
    legacy .pyc files.
    z.pyrrroptimizationN)rrr)	r
rbryrxrrr`rr)rqrzroptrWrWrXrs

csttdrtjSd}tjjdrddlddld}d}Gfdddj}j	j
}|j}|sj|}j
j}|j||j|j|j|}|sjt|j|@sd}ntjdkrdd	lm}	mm}
m}dd
lm}|	j|d}
|
jdkrd}naGfd
dd|}|}|
|}|
j|dks|
j|dkrd}|sy;ddlm}|}|j|j |j!Wnrt"k
r}zRt#|}t$|dkrq|ddd}dj%t&|j'|}WYdd}~XnX|t_(|t_tjS)NresultrrrcsCeZdZdjjfdjjfdjjfgZdS)z*_is_gui_available.<locals>.USEROBJECTFLAGSZfInheritZ	fReserveddwFlagsN)rSrTrUwintypesZBOOLDWORD_fields_rW)ctypesrWrXUSEROBJECTFLAGSsrz,gui not available (WSF_VISIBLE flag not set)darwin)cdllc_intpointer	Structure)find_libraryZApplicationServicesz0gui tests cannot run without OS X window managercs(eZdZdfdfgZdS)z._is_gui_available.<locals>.ProcessSerialNumberZ
highLongOfPSNZlowLongOfPSNN)rSrTrUrrW)rrWrXProcessSerialNumbers	rz#cannot run without OS X gui process)Tk2z [...]zTk unavailable due to {}: {}))hasattr_is_gui_availablerrbrcrdrZctypes.wintypesrwindllZuser32ZGetProcessWindowStationZWinErrorrrZGetUserObjectInformationWZbyrefZsizeofboolrrrrZctypes.utilrZLoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterrZwithdrawupdateZdestroy	ExceptionrhlenformattyperSreason)rZ	UOI_FLAGSZWSF_VISIBLErZdllhZuofZneededresrrrrZapp_servicesrZpsnZpsn_prrooteZ
err_stringrW)rrrXrsh			"			

	
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)resourcerWrWrXrscCsWt|s.|dkr"d|}t||dkrStrSttjdS)z@Raise ResourceDenied if the specified resource is not available.Nz"Use of the %r resource not enabledgui)rr	rr)rrkrWrWrXr
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.
    cs4tjfdd}|_|S)Nc
stjkrtjjddd}y"ttt|jd}Wntk
rdYnAX|krdjtt	}t
jd||f||S)N-rrrlz(%s version %s or higher required, not %s)rcsystemreleaserremapint
ValueErrorrrhrfrg)rkwversion_txtversionmin_version_txt)rmin_versionsysnamerWrXwrappers"
z:_requires_unix_version.<locals>.decorator.<locals>.wrapper)	functoolswrapsr)rr)rr)rrX	decorators'	z)_requires_unix_version.<locals>.decoratorrW)rrrrW)rrrX_requires_unix_versionsrcGs
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)rrWrWrXr.scGs
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)rrWrWrXr 7scsfdd}|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.
    cs1tjfdd}|_|S)Ncstjdkrtjd}y"ttt|jd}Wntk
rUYn>X|krdjtt	}t
jd||f||S)Nrrrlz&Mac OS X %s or higher required, not %s)rbrcZmac_verrerrrrrrhrfrg)rrrrr)rrrWrXrHs"
z4requires_mac_ver.<locals>.decorator.<locals>.wrapper)rrr)rr)r)rrXrGs$	z#requires_mac_ver.<locals>.decoratorrW)rrrW)rrXr!@sz	127.0.0.1z::1cCs/tj||}t|}|j~|S)a
Returns an unused port that should be suitable for binding.  This is
    achieved by creating a temporary socket with the same family and type as
    the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
    the specified host address (defaults to 0.0.0.0) with the port set to 0,
    eliciting an unused ephemeral port from the OS.  The temporary socket is
    then closed and deleted, and the ephemeral port is returned.

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

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

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

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

    XXX: although this approach is a vast improvement on previous attempts to
    elicit unused ports, it rests heavily on the assumption that the ephemeral
    port returned to us by the OS won't immediately be dished back out to some
    other process when we close and delete our temporary socket but before our
    calling code has a chance to bind the returned port.  We can deal with this
    issue if/when we come across it.
    )socketr?close)familyZsocktypeZtempsockportrWrWrXr>bs
8
cCs
|jtjkr|jtjkrttdr]|jtjtjdkr]t	dttdrdt
jkry.|jtjtjdkrt	dWnt
k
rYnXttdr|jtjtjd|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_REUSEPORTZWITHIN_PYTHON_RPM_BUILDzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!SO_EXCLUSIVEADDRUSEr)rrAF_INETrSOCK_STREAMrZ
getsockoptZ
SOL_SOCKETrrrxenvironrrZ
setsockoptrbindZgetsockname)sockhostrrWrWrXr?s $
cCsstjrod}zLy3tjtjtj}|jtdfdSWntk
rYYnXWd|rn|jXdS)z+Check whether IPv6 is enabled on this host.NrTF)rZhas_ipv6ZAF_INET6rrHOSTv6rr)rrWrWrX_is_ipv6_enableds	
	rcs%tjfdd}|S)z5Skip the test on TLS certificate validation failures.csay||WnItk
r\}z)dt|krGtjdWYdd}~XnXdS)NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)IOErrorrhrfrg)rkwargsr)rurWrXdecsz&system_must_validate_cert.<locals>.dec)rr)rurrW)rurXsystem_must_validate_certs!	rriZdoubleZIEEEztest requires IEEE 754 doublesz
requires zlibz
requires gzipzrequires bz2z
requires lzmajavaz$testz@testz	{}_{}_tmpæİŁφКא،تก €u-àòɘŁğrZNFDntceru-共Ł♡ͣztWARNING: The filename %r CAN be encoded by the filesystem encoding (%s). Unicode filename tests may not be effectives-surrogateescapewrccsd}|dkr9tj}d}tjj|}nOytj|d}Wn5tk
r|sitjd|t	ddYnXz	|VWd|rt
|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)tempfileZmkdtemprxryrealpathmkdirrrZrrr)ryquietZdir_createdrWrWrXtemp_dirs"



	rccsytj}ytj|Wn5tk
rT|s6tjd|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: rrN)rxgetcwdchdirrrZrr)ryrZ	saved_dirrWrWrX
change_cwds


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

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

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

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

    Setting *subdir* indicates a relative path to use to find the file
    rather than looking directly in the path directories.
    N)rxryisabsr
TEST_HOME_DIRrbexists)rZsubdirryZdnfnrWrWrXrs
cCs4tj|tjtjBtjB}tj|dS)z>Create an empty file. If the file already exists, truncate it.N)rxopenO_WRONLYO_CREATO_TRUNCr)rfdrWrWrXrs#cCs<t|j}dd|D}dj|}d|S)z%Like repr(dict), but in sorted order.cSsg|]}d|qS)z%r: %rrW).0ZpairrWrWrX
<listcomp>s	zsortdict.<locals>.<listcomp>z, z{%s})sortedr~r)dictr~Z	reprpairsZ
withcommasrWrWrXrQscCs9ttd}z|jSWd|jttXdS)z`
    Create an invalid file descriptor by opening and closing a file and return
    its fd.
    wbN)r$rfilenorr)rrWrWrXmake_bad_fd	s

r/linenooffsetcCs|jt}t|ddWdQRX|j}|j|j|dk	ra|j|j||j|j|dk	r|j|j|dS)Nz
<test string>exec)assertRaisesSyntaxErrorcompileZ	exceptionZassertIsNotNoner0assertEqualr1)testcaseZ	statementr0r1cmrrWrWrXr"s	csddl}ddl}jdd|jj|djdd}tjjt	|}fdd}tjj
|r||}|dk	r|St|tdt
rtd	|d
t|jj}tr|jjd|j|d
d}trC|jjddkrCtjd|}zOt|d9}	|j}
x#|
r|	j|
|j}
qgWWdQRXWd|jX||}|dk	r|Std|dS)Nrcheckr/rcsMt|}dkr"|S|r?|jd|S|jdS)Nr)r$seekr)r#ru)rr9rrWrXcheck_valid_file)s
z*open_urlresource.<locals>.check_valid_fileZurlfetchz	fetching %s ...rAccept-EncodinggziprzContent-EncodingZfileobjr-zinvalid resource %r)r=r>)Zurllib.requestZurllib.parsepopparseZurlparserrxryr
TEST_DATA_DIRr"rrrrrZrequestZbuild_openerr>Z
addheadersr}r$ZheadersgetZGzipFilereadwriterr)Zurlrrurllibrr#r<ruZopeneroutsrW)rr9rrXr@ s<#	

	
c@sLeZdZdZddZddZeddZdd	Zd
S)WarningsRecorderzyConvenience wrapper for the warnings list returned on
       entry to the warnings.catch_warnings() context manager.
    cCs||_d|_dS)Nr)	_warnings_last)selfZ
warnings_listrWrWrX__init__Vs	zWarningsRecorder.__init__cCs\t|j|jkr,t|jd|S|tjjkrBdStd||fdS)Nrz%r has no attribute %rr@)rrKrLrrZWarningMessage_WARNING_DETAILSr)rMattrrWrWrX__getattr__Zs
zWarningsRecorder.__getattr__cCs|j|jdS)N)rKrL)rMrWrWrXrZaszWarningsRecorder.warningscCst|j|_dS)N)rrKrL)rMrWrWrXreseteszWarningsRecorder.resetN)	rSrTrUrVrNrRpropertyrZrSrWrWrWrXrJRs
rJc
cs^tjd}|jjd}|r1|jtjdd&}tjdjdt	|VWdQRXt
|}g}x|D]\}}d}	xd|ddD]R}|j}
tj
|t|
tjrt|
j|rd}	|j|qW|	r|r|j||jfqW|r@td	|d
|rZtd|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__recordTrZalwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)rb	_getframe	f_globalsrDclearrZr[rmsimplefilterrJromessagerematchrhI
issubclassrremover}rSAssertionError)filtersrframeregistrywZreraiseZmissingrkcatseenZwarningrWrWrX_filterwarningsis0
	rhcOsC|jd}|s6dtff}|dkr6d}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)
    rrNT)rDWarningrh)rbrrrWrWrXrHsccsOtjdd&}tjddtdVtWdQRX|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.
    rUTrVcategoryN)rZr[r\ResourceWarning
gc_collectr6)r7ZwarnsrWrWrXrIs
c@s:eZdZdZddZddZddZdS)	ra,Context manager to force import to return a new module reference.

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

    Use like this:

        with CleanImport("foo"):
            importlib.import_module("foo") # new reference
    cGsitjj|_xP|D]H}|tjkrtj|}|j|krWtj|j=tj|=qWdS)N)rbrmcopyoriginal_modulesrS)rMZmodule_namesZmodule_namerrWrWrXrNs


zCleanImport.__init__cCs|S)NrW)rMrWrWrX	__enter__szCleanImport.__enter__cGstjj|jdS)N)rbrmrrn)rM
ignore_excrWrWrX__exit__szCleanImport.__exit__N)rSrTrUrVrNrorqrWrWrWrXrs

c@seZdZdZddZddZddZdd	Zd
dZdd
Z	ddZ
ddZddZddZ
ddZdS)rJz_Class to help protect the environment variable properly.  Can be used as
    a context manager.cCstj|_i|_dS)N)rxr_environ_changed)rMrWrWrXrNszEnvironmentVarGuard.__init__cCs|j|S)N)rr)rMenvvarrWrWrX__getitem__szEnvironmentVarGuard.__getitem__cCs9||jkr(|jj||j|<||j|<dS)N)rsrrrD)rMrtvaluerWrWrX__setitem__szEnvironmentVarGuard.__setitem__cCsE||jkr(|jj||j|<||jkrA|j|=dS)N)rsrrrD)rMrtrWrWrX__delitem__szEnvironmentVarGuard.__delitem__cCs
|jjS)N)rrkeys)rMrWrWrXryszEnvironmentVarGuard.keyscCs
t|jS)N)iterrr)rMrWrWrX__iter__szEnvironmentVarGuard.__iter__cCs
t|jS)N)rrr)rMrWrWrX__len__szEnvironmentVarGuard.__len__cCs|||<dS)NrW)rMrtrvrWrWrXsetszEnvironmentVarGuard.setcCs||=dS)NrW)rMrtrWrWrXunsetszEnvironmentVarGuard.unsetcCs|S)NrW)rMrWrWrXroszEnvironmentVarGuard.__enter__cGsexR|jjD]A\}}|dkrD||jkrQ|j|=q||j|<qW|jt_dS)N)rsr~rrrxr)rMrpkvrWrWrXrqs
zEnvironmentVarGuard.__exit__N)rSrTrUrVrNrurwrxryr{r|r}r~rorqrWrWrWrXrJsc@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.
    cGs6tjdd|_tj|_tjj|dS)N)rbryoriginal_valueoriginal_objectextend)rMpathsrWrWrXrNszDirsOnSysPath.__init__cCs|S)NrW)rMrWrWrXro#szDirsOnSysPath.__enter__cGs&|jt_|jtjdd<dS)N)rrbryr)rMrprWrWrXrq&szDirsOnSysPath.__exit__N)rSrTrUrVrNrorqrWrWrWrXrs
rc@sCeZdZdZddZddZdddddZdS)	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)rMrrrWrWrXrN0s	zTransientResource.__init__cCs|S)NrW)rMrWrWrXro4szTransientResource.__enter__NcCst|dk	rpt|j|rpxO|jjD]2\}}t||sJPt|||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)r_rrr~rrr	)rMZtype_rv	tracebackrQZ
attr_valuerWrWrXrq7szTransientResource.__exit__)rSrTrUrVrNrorqrWrWrWrXr#+serrnorg>@errnosc	#sdd d!d"d#g}d%d'd)d+d,g}td||gsrdd|Ddd|Dfdd}tj}z!y"|dk	rtj|dVWntjk
r}z/trtjj	j
dd|WYdd}~Xntk
r}zxr|j
}t|dkr_t
|dtr_|d}q$t|dkrt
|dtr|d}q$Pq$W||WYdd}~XnXWdtj|XdS)-zReturn a context manager that raises ResourceDenied when various issues
    with the Internet connection manifest themselves as exceptions.ECONNREFUSEDo
ECONNRESEThEHOSTUNREACHqENETUNREACHe	ETIMEDOUTn	EAI_AGAINrEAI_FAILr
EAI_NONAMEr
EAI_NODATA
WSANO_DATA*zResource %r is not availablecSs(g|]\}}tt||qSrW)rr)r)rinumrWrWrXr*ds	z&transient_internet.<locals>.<listcomp>cSs(g|]\}}tt||qSrW)rr)r)rirrWrWrXr*fs	cst|dd}t|tjst|tjrB|kst|tjjrvd|jkoqdknst|tjj	rd|j
ksd|j
ksd|j
ks|krtstj
jjdd|dS)	NriiWConnectionRefusedErrorTimeoutErrorEOFErrorr
)r
isinstancerrZgaierrorrGerrorZ	HTTPErrorcodeZURLErrorrrrbstderrrFr)rn)captured_errnosdenied
gai_errnosrWrXfilter_errorisz(transient_internet.<locals>.filter_errorNrrr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)r	rZgetdefaulttimeoutZsetdefaulttimeoutnntplibZNNTPTemporaryErrorrrbrrFrrrr)	Z
resource_namerrZdefault_errnosZdefault_gai_errnosrZold_timeoutrarW)rrrrXr'LsN			
	

		%
%

c
cs[ddl}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)iorrbsetattrStringIO)Zstream_namerZorig_stdoutrWrWrXcaptured_outputsrcCs
tdS)zCapture the output of sys.stdout:

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

       with captured_stderr() as stderr:
           print("hello", file=sys.stderr)
       self.assertEqual(stderr.getvalue(), "hello\n")
    r)rrWrWrWrXrscCs
tdS)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)rrWrWrWrXrs
cCs5tjtrtjdtjtjdS)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:rrrWrWrWrXrls




rlc
cs7tj}tjz	dVWd|r2tjXdS)N)r	isenableddisableenable)Zhave_gcrWrWrX
disable_gcs
	rcCsQtjdpd}d}x)|jD]}|jdr(|}q(W|dkS)z,Find if Python was built with optimizations.	PY_CFLAGSrz-O-O0-Og)rrr)	sysconfigget_config_varrrd)ZcflagsZ	final_optrrWrWrXpython_is_optimizeds
rZnPZ0ngettotalrefcountZ2PZ0PrcCstjt|tS)N)structcalcsize_header_align)fmtrWrWrXcalcobjsizesrcCstjt|tS)N)rr_vheaderr)rrWrWrXcalcvobjsizesr	cCsddl}tj|}t|tkr:|jt@s_t|tkrlt|jt@rl||j7}dt|||f}|j|||dS)Nrz&wrong size for %s: got %d, expected %d)		_testcapirb	getsizeofr	__flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADr6)testosizerrrkrWrWrXcheck_sizeofs%
rcsfdd}|S)Ncs4fdd}j|_j|_|S)Ncsy.ddl}t|}|j|}Wn&tk
rEYnCd}}Yn2Xx.D]&}y|j||PWq^Yq^Xq^Wz||SWd|r|r|j||XdS)Nr)localer	setlocaler)rkwdsrrjZorig_localeloc)catstrrlocalesrWrXinner	s$

	z1run_with_locale.<locals>.decorator.<locals>.inner)rSrV)rr)rr)rrXrsz"run_with_locale.<locals>.decoratorrW)rrrrW)rrrXrKscsfdd}|S)Ncs1fdd}j|_j|_|S)Ncsy
tj}Wn!tk
r0tjdYnXdtjkrPtjd}nd}tjd<|z||SWd|dkrtjd=n
|tjd<tjXdS)Nztzset requiredZTZ)rtzsetrrfrgrxr)rrrZorig_tz)rtzrWrXr-s




z-run_with_tz.<locals>.decorator.<locals>.inner)rSrV)rr)r)rrXr,szrun_with_tz.<locals>.decoratorrW)rrrW)rrXrR+sc	Csdddtdtddti}tjd|tjtjB}|dkr`td|ftt|j	d||j	d	j
}|a|tkrt}|t
dkrtd
|f|adS)Nrimgtz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rrrz$Memory limit %r too low to be useful)_1M_1Gr\r]
IGNORECASEVERBOSErrfloatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitZsizesrZmemlimitrWrWrXrOUs2c@s:eZdZdZddZddZddZdS)	_MemoryWatchdogz`An object which periodically watches the process' memory consumption
    and prints it out.
    cCs(djdtj|_d|_dS)Nz/proc/{pid}/statmpidF)rrxgetpidprocfilestarted)rMrWrWrXrNosz_MemoryWatchdog.__init__cCsyt|jd}WnOtk
rg}z/tjdj|ttjj	dSWYdd}~XnXt
d}tjtj
|gd|dtj|_|jd|_dS)Nrz!/proc not available for stats: {}zmemory_watchdog.pyrrT)r$rrrZrrrrbrflushr
subprocessPopen
executableZDEVNULLmem_watchdogrr)rMrurZwatchdog_scriptrWrWrXstartss

z_MemoryWatchdog.startcCs'|jr#|jj|jjdS)N)rrZ	terminatewait)rMrWrWrXstops	
z_MemoryWatchdog.stopN)rSrTrUrVrNrrrWrWrWrXrjsrcsfdd}|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}ts!d}n|}ts4r_t||kr_tjd||dtrtrttdjd||dt}|j	nd}z||SWd|r|j
XdS)	Niz'not enough memory: %.1fG minimum neededirz* ... expected peak memory use: {peak:.1f}GZpeaki@i@)rmemuserrfrgrrrrrr)rMrrmaxsizeZwatchdog)dry_runrurrWrXrs*			
	
z.bigmemtest.<locals>.decorator.<locals>.wrapper)rr)ru)rrr)rurrXrs		zbigmemtest.<locals>.decoratorrW)rrrrrW)rrrrXr/s
!csfdd}|S)z0Decorator for tests that fill the address space.cs^ttkrPtd
kr6tdkr6tjdqZtjdtdn
|SdS)
Nr?rz-not enough memory: try a 32-bit build insteadz'not enough memory: %.1fG minimum neededirllli@)rrrfrg)rM)rurWrXrsz!bigaddrspacetest.<locals>.wrapperrW)rurrW)rurXr0sc@seZdZddZdS)r(cCstj}|||S)N)rfZ
TestResult)rMrrrWrWrXruns
zBasicTestRunner.runN)rSrTrUrrWrWrWrXr(scCs|S)NrW)rrWrWrX_idsrcCsP|dkr&tr&tjtjSt|r6tStjdj|SdS)Nrzresource {0!r} is not enabled)rrfskiprrrr)rrWrWrXrequires_resources
rcCstdd|S)z9
    Decorator for tests only applicable on CPython.
    cpythonT)impl_detail)rrWrWrXr1scKszt|rtS|dkrmt|\}}|r=d}nd}t|j}|jdj|}tj|S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or )	r;r
_parse_guardsr+ryrrrfr)rkguardsZ
guardnamesdefaultrWrWrXrs	rcCsjtdkrGddl}y|jdaWntk
rFdaYnXd}trW|Stj||S)z8Skip decorator for tests that use multiprocessing.Queue.NrTFz6requires a functioning shared semaphore implementation)_have_mp_queuemultiprocessingZQueuerarfr)rrrkrWrWrXr9s


cCs7|sddidfSt|jd}||fS)NrTFr)rovalues)rZis_truerWrWrXrsrcKs.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
    )rrDrcZpython_implementationr)rrrWrWrXr;scs<ttdsStjfdd}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.gettracecs?tj}ztjd||SWdtj|XdS)N)rbr	settrace)rrZoriginal_trace)rrWrXrs

zno_tracing.<locals>.wrapperN)rrbrr)rrrW)rrX
no_tracings!rcCstt|S)aDecorator for tests which involve reference counting.

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

    )rr1)rrWrWrX
refcount_test#srcCsog}xY|jD]N}t|tjrEt|||j|q||r|j|qW||_dS)z>Recursively filter test cases in a suite based on a predicate.N)Z_testsrrf	TestSuite
_filter_suiter})suiteZpredZnewtestsrrWrWrXr.s
rcCstr'tjtjdddt}n	t}|j|}|jst	|j
dkr~|jr~|j
dd}nIt	|jdkr|j
r|jdd}nd}ts|d7}t|dS)	z2Run tests from a unittest.TestSuite-derived class.	verbosityrrrrzmultiple errors occurredz!; run in verbose mode for detailsN)
rrfZTextTestRunnerrbrrr(rZ
wasSuccessfulrerrorsZfailuresr)rZrunnerrrrWrWrX
_run_suite:s	
rcCswtdkrdS|j}xTtD]L}tj||r?dSx-|jdD]}tj||rOdSqOWq#WdS)NTrlF)match_testsidfnmatchZfnmatchcaser)rZtest_idZ
match_testrirWrWrX_match_testNs
rcGstjtjf}tj}x|D]}t|trx|tjkri|jtjtj|qt	dq%t||r|j|q%|jtj
|q%Wt|tt
|dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesN)rfr
ZTestCaserrhrbrmZaddTestZ
findTestCasesrZ	makeSuiterrr)classesZvalid_typesrclsrWrWrXr)_s
 
cCsdS)z,Just used to check if docstrings are enabledNrWrWrWrWrX_check_docstringsvsrwin32WITH_DOC_STRINGSztest requires docstringscCsddl}|dkr!t}nd}|j|d|d|\}}|rdtd||ftrtd|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).
    rNroptionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)doctestrZtestmodrrrS)rrrrrurrWrWrXr*s	!cCstjjfS)N)rbrmrmrWrWrWrX
modules_setupsrcCsMddtjjD}tjjtjj|tjj|dS)NcSs1g|]'\}}|jdr||fqS)z
encodings.)rd)r)rrrWrWrXr*s		z#modules_cleanup.<locals>.<listcomp>)rbrmr~rYr)Z
oldmodules	encodingsrWrWrXmodules_cleanups
r cCs-trtjtjjfSdffSdS)Nr)_thread_count	threading	_danglingrmrWrWrWrXrDscGsats
dSd}xJt|D]<}tjtjf}||krEPtjdtqWdS)Ndg{Gz?)r!ranger"r#r$rrrl)Zoriginal_valuesZ
_MAX_COUNTcountrrWrWrXrEs
cs/ts
Stjfdd}|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.
    cs)t}z|SWdt|XdS)N)rDrE)rkey)rrWrXrs	zreap_threads.<locals>.decorator)r!rr)rrrW)rrXrFs!c	CsXttdrTd}x<y,tj|tj\}}|dkrCPWqPYqXqWdS)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.
    waitpidrrNr@)rrxr)WNOHANG)Zany_processrZstatusrWrWrXrBs	ccsvt|}g}ziy,x%|D]}|j|j|qWWn1trmtdt|t|fYnXdVWdz|r|tj}}xtddD]{}|d7}x.|D]&}|jt	|tjdqWdd|D}|s	Ptrtdt||fqWWdd	d|D}|rpt
jtj
td
t|XXdS)Nz/Can't start %d threads, only %d threads startedrr<g{Gz?cSs"g|]}|jr|qSrW)isAlive)r)rrWrWrXr*s	z!start_threads.<locals>.<listcomp>z7Unable to join %d threads during a period of %d minutescSs"g|]}|jr|qSrW)r,)r)rrWrWrXr*s	zUnable to join %d threads)rorr}rrrrr&rmaxfaulthandlerZdump_tracebackrbrra)ZthreadsZunlockrrZendtimeZ	starttimerrWrWrXrGs>

	

$c
cst||rNt||}t|||z	|VWdt|||Xn9t|||z	dVWdt||rt||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)rrQnew_valreal_valrWrWrXrMs		ccsh||kr:||}|||<z	|VWd|||<Xn*|||<z	dVWd||krc||=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.
    NrW)ritemr0r1rWrWrXrL:s

	
	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?)r\substrip)rrWrWrXstrip_python_stderrYsr6Z	getcountsz-types are immortal if COUNT_ALLOCS is definedcCs
tjS)znReturn a list of command-line arguments reproducing the current
    settings in sys.flags and sys.warnoptions.)rZ_args_from_interpreter_flagsrWrWrWrXargs_from_interpreter_flagsfsr7c@s@eZdZddZddZddZddZd	S)
rCcCs#tjjj|d||_dS)Nr)logginghandlersBufferingHandlerrNmatcher)rMr;rWrWrXrNpszTestHandler.__init__cCsdS)NFrW)rMrWrWrXshouldFlushyszTestHandler.shouldFlushcCs$|j||jj|jdS)N)rbufferr}__dict__)rMrUrWrWrXemit|s
zTestHandler.emitcKs:d}x-|jD]"}|jj||rd}PqW|S)zW
        Look for a saved dict whose keys/values match the supplied arguments.
        FT)r=r;matches)rMrrdrWrWrXr@szTestHandler.matchesN)rSrTrUrNr<r?r@rWrWrWrXrCos	c@s.eZdZdZddZddZdS)	rNrkr[cKsPd}xC|D];}||}|j|}|j|||s
d}Pq
W|S)a.
        Try to match a single dict with the supplied arguments.

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

zMatcher.matchescCsjt|t|kr!d}nEt|tk	sB||jkrQ||k}n|j|dk}|S)zT
        Try to match a single stored value (dv) with a supplied value (v).
        Fr)rrh_partial_matchesfind)rMrrCrrrWrWrXrBs	!zMatcher.match_valueN)rkr[)rSrTrUrDr@rBrWrWrWrXrNsc
Csotdk	rtStd}ytjt|d}Wn!tttfk
rWd}YnXtj||a|S)NrTF)_can_symlinkrrxsymlinkrNotImplementedErrorrr`)Zsymlink_pathcanrWrWrXrs


cCs,t}d}|r|Stj||S)z8Skip decorator for tests that require functional symlinkz*Requires functional symlink implementation)rrfr)rokrkrWrWrXr+s	cCs	tdk	rtSttds(d}ntj\}}zttd}yutj|ddtj|jddt	j
}tjd|}|dkpt
|jddk}Wntk
rd}YnXWdQRXWdttt|X|a|S)	NsetxattrFr-s	user.testr3z
2.6.(\d{1,2})r')
_can_xattrrrxrZmkstempr$rrKr.rcrr\r]rrrr)rIZtmp_fpZtmp_namefpZkernel_versionrrWrWrX	can_xattrs&	+

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

    By default this skips private attributes beginning with '_' but
    includes all magic methods, i.e. those starting and ending in '__'.
    css4|]*}|jds(|jdr|VqdS)___N)rdendswith)r)rrWrWrX	<genexpr>sz&detect_api_mismatch.<locals>.<genexpr>)r}rP)Zref_apiZ	other_apirYZ
missing_itemsrWrWrXr8s
"c@s:eZdZdZdZdZddZddZdS)rPzTry 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
Cstjjdrddl}|jj|_d}|jj||_|jj|j|Byddl	}|j
Wnttfk
rYqXi|_
xH|j|j|jgD]C}|j
||j}|j||j}||f|j
|<qWntdk	r]y9tjtj|_tjtjd|jdfWnttfk
r\YnXtjdkrddd	d
g}tj|dtjdtj}||jd}	WdQRX|	jd
krtddddd|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/defaultsrEzcom.apple.CrashReporterZ
DialogTyperrs	developerz:this test triggers the Crash Reporter, that is intentionalendrrT) rbrcrdrrZkernel32_k32SetErrorMode	old_valuemsvcrtCrtSetReportModerra	old_modesZCRT_WARNZ	CRT_ERRORZ
CRT_ASSERTZCRTDBG_MODE_FILECrtSetReportFileZCRTDBG_FILE_STDERRrZ	getrlimitRLIMIT_CORE	setrlimitrrrrPIPEZcommunicater5r)
rMrZSEM_NOGPFAULTERRORBOXr]report_typeold_modeold_filecmdprocrrWrWrXro	sN						
zSuppressCrashReport.__enter__cGs|jdkrdStjjdr|jj|j|jrddl}x|jjD]2\}\}}|j	|||j
||q]WnAtdk	rytjtj
|jWnttfk
rYnXdS)zARestore Windows ErrorMode or core file behavior to initial value.Nrr)r\rbrcrdrZr[r_r]r~r^r`rrbrarr)rMrpr]rdrerfrWrWrXrqL	s	"zSuppressCrashReport.__exit__)rSrTrUrVr\r_rorqrWrWrWrXrP	s
AcstdyjWn*ttfk
rPtdYnXdfdd}|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)rr/rW)
attr_is_local	attr_nameobject_to_patchr\rWrXcleanupw	szpatch.<locals>.cleanup)rr>rrsZ
addCleanupr)Z
test_instancerkrjZ	new_valuerlrW)rirjrkr\rXpatcha	s


rmcCsYyddl}Wntk
r$YnX|jr@tjdddl}|j|S)zi
    Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
    module is enabled.
    rNzUrun_in_subinterp() cannot be used if tracemalloc module is tracing memory allocations)tracemallocraZ
is_tracingrfrgrrun_in_subinterp)rrnrrWrWrXro	s
rocsbGfddd|}d||||jttt|jdS)Ncs%eZdZfddZdS)z%check_free_after_iterating.<locals>.Acs-dytWntk
r(YnXdS)NT)next
StopIteration)rM)doneitrWrX__del__	s

z-check_free_after_iterating.<locals>.A.__del__N)rSrTrUrtrW)rrrsrWrXA	sruF)r3rqrprlZ
assertTrue)rrzrrrurW)rrrsrXcheck_free_after_iterating	s	rvii@i@i@ii)rrrrrrrr	r
rr)r
r)rrrrri@ii)rVrSracollections.abccollections
contextlibrr.rrrr`importlib.utilZlogging.handlersr8rrxrcr\rrrrrrbrrrrfZurllib.errorrGrZr!r#Zmultiprocessing.processrzlibr>bz2Zlzmar__all__rrrrgr	contextmanagerr^r
rrrtr6r7rr2rrrrrrrrrr
rrdrrrrrrrrrrrrrrr r!r<rrrr>r?rr=rrZ
SOCK_MAX_SIZEZ
skipUnlessr
__getformat__r3r5r,r-r.r:rirrrZFS_NONASCII	characterfsdecodefsencodeUnicodeErrorZTESTFN_UNICODEZunicodedata	normalizegetfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversionencodeUnicodeEncodeErrorrdecodeUnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIrrrrrrrAryrzrr{ZTEST_SUPPORT_DIRr!rrCrrrQr/r"r@objectrJrhrHrIrabcMutableMappingrJrr#rrr$rr%r&r'rrrrrlrrrrrrrrrrrKrRrrrZ_4GrrrOrr/r0r(rrr1rrr9rr;rrrrrr)rrZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr*rr rDrErFrBrGrMrLr6ZskipIfZrequires_type_collectingr7r9r:rCrNrFrr+rMrOr4rr8rPrmrorvrWrWrWrX<module>sv






										
2	
!		
J			>&			




	



!2' 5	J		



$#


	0

			#
		"
_"
Back to Directory File Manager