Warning: Cannot modify header information - headers already sent by (output started at /var/www/jonas-eriksen.dk/pic/private/index.php:1) in /var/www/jonas-eriksen.dk/pic/private/index.php on line 215
PK!Buxx)__pycache__/__init__.cpython-36.opt-1.pycnu[3 \/@sdS)Nrrr%/usr/lib64/python3.6/test/__init__.pysPK!Buxx)__pycache__/__init__.cpython-36.opt-2.pycnu[3 \/@sdS)Nrrr%/usr/lib64/python3.6/test/__init__.pysPK!Buxx#__pycache__/__init__.cpython-36.pycnu[3 \/@sdS)Nrrr%/usr/lib64/python3.6/test/__init__.pysPK!>>1support/__pycache__/__init__.cpython-36.opt-1.pycnu[3 _Vj@sl dZedkredddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZ ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl!Z"ddl#Z#ddl$m%Z%yddl&Z&ddl'Z'Wnek rBdZ&dZ'YnXy ddl(Z)Wnek rjdZ)YnXy ddl*Z*Wnek rdZ*YnXy ddl+Z+Wnek rdZ+YnXy ddl,Z,Wnek rdZ,YnXy ddl-Z-Wnek r dZ-YnXy ddl.Z.Wnek r2dZ.YnXy ddl/Z/Wnek rZdZ/YnXddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbg\Z0Gdcd d e1Z2Gddd d e2Z3Gdedde2Z4Gdfdde j5Z6ej7dhdhdiZ8difdkdldZ9dmdnZ:dodpZ;dqd=ZZ=ffdjfdsdZ>dtd9Z?dZ@dZAdaBdaCdZDdjZEdaFdudZGdvdZHdwdZIdxdyZJejjKdzr.djd{d|ZLd}d~ZMddZNddZOddZPnejQZMejRZNddZOddZPddZQddZRddZSddZTddZUddZVdd#ZWdkdd$ZXddZYdd%ZZdd&Z[dd'Z\dldd(Z]dZ^dZ_ej`ejafddJZbe^fddKZcddMZdddZeeeZfddZgdoZhdrZie jjekjldjKddZme jje*dZne jje+dZoe jje,dZpe jje-dZqejjKdZrejsdZtetdk oxetdkZuejdkreurdndZvndZvejwdkrdZxndZxdjyexejzZxdZ{xLdsD]BZ|yej}ej~e|e|kreWnek rYnXe|Z{PqWexdZejdkr:ddlZejdeZejZdZejwdkrejjdkrexdZyejeWnek rYnXedeefdZnBejdkrydjeWn&ek rexdjedǃZYnXdZxFdtD]dYZd?d@Ze jeedAdBZdCdDZdEdFZGdGdPdPejjZGdHd[d[eZdadId!ZdJd2ZdadKdLZdMd;ZdNdOZdPd"ZfdQdRd?Z dfffdSd@Z GdTd]d]Z dUdVZ dWdXZ ffdYdZZgfd[daZdad\dGZej7d]d^Zd_dbZGd`dadaZGdbdcdcZej7dddeZdfdgZdS(z7Supporting 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_module CleanImportunloadforgetrecord_original_stdoutget_original_stdoutcaptured_stdoutcaptured_stdincaptured_stderrTESTFNSAVEDCWDunlinkrmtreetemp_cwdfindfilecreate_empty_file can_symlinkfs_is_case_insensitiveis_resource_enabledrequiresrequires_freebsd_versionrequires_linux_versionrequires_mac_verrequires_hashdigestcheck_syntax_errorTransientResourcetime_outsocket_peer_resetioerror_peer_resettransient_internetBasicTestRunner run_unittest run_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_children TestHandlerthreading_setupthreading_cleanup reap_threads start_threadscheck_warningscheck_no_resource_warningEnvironmentVarGuardrun_with_locale swap_item swap_attrMatcher set_memlimitSuppressCrashReportsortdict run_with_tzPGOmissing_compiler_executablefd_countc@seZdZdZdS)r z*Base class for regression test exceptions.N)__name__ __module__ __qualname____doc__rdrd-/usr/lib64/python3.6/test/support/__init__.pyr |sc@seZdZdZdS)r z Test failed.N)r`rarbrcrdrdrdrer sc@seZdZdZdS)r zTest did not run any subtests.N)r`rarbrcrdrdrdrer 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`rarbrcrdrdrdrer sTc cs8|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)rfrdrdre_ignore_deprecated_importss  rkF) 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) rk importlibr ImportErrorsysplatform startswithtupleunittestSkipTeststr)name deprecatedrlmsgrdrdrer 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)romodules __import__listrq)rv orig_modulesmodnamerdrdre_save_and_remove_modules rc Cs>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)rorzKeyError)rvr}Zsavedrdrdre_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)Nrd)frdrdresz$anticipate_failure..)rsZexpectedFailure)Z conditionrdrdrer:scCsF|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_testsrdrdrer;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) rkrrappendrmr rnitemsrorz) rvZfreshZblockedrwr}Znames_to_removeZ fresh_nameZ blocked_nameZ fresh_moduleZ orig_namemoduleZname_to_removerdrdrers$      c Cs>yt||}Wn&tk r4tjd||fYnX|SdS)z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %rN)getattrAttributeErrorrsrt)objrvZ attributerdrdrer6s cCs|adS)N)_original_stdout)stdoutrdrdrer0scCs tptjS)N)rrorrdrdrdrer4sc Cs&y tj|=Wntk r YnXdS)N)rorzr)rvrdrdrer7s cGsny||Stk rh}zDtdkrHtd|jj|ftd|j|ftj|tj||Sd}~XnXdS)Nz%s: %sz re-run %s%r) OSErrorrprint __class__r`rchmodstatS_IRWXU)rfuncargserrrdrdre _force_run=srwincCs|||r|}ntjj|\}}|p(d}d}x<|dkrjtj|}|rJ|n||ksVdStj||d9}q0Wtjd|tdddS)NrygMbP?g?rz)tests may fail, delete still pending for ) stacklevel) rrsplitlistdirtimesleeprgwarnRuntimeWarning)rpathnamewaitallrrvtimeoutLrdrdre_waitforHs     rcCsttj|dS)N)rrr)filenamerdrdre_unlinkisrcCsttj|dS)N)rrrmdir)rrdrdre_rmdirlsrcs,fddt|ddtdd|dS)Ncsxt|tj|D]}tjj||}ytj|j}Wn<tk rn}z td||ft j dd}WYdd}~XnXt j |rt |ddt|tj|qt|tj|qWdS)Nz-support.rmtree(): os.lstat(%r) failed with %s)filerT)r)rrrrjoinlstatst_moderrro __stderr__rS_ISDIRrrr)rrvfullnamemodeexc) _rmtree_innerrdrerps   z_rmtree.._rmtree_innerT)rcSst|tj|S)N)rrr)prdrdrersz_rmtree..)r)rrd)rre_rmtreeos rc Cs^y ddl}Wntk r Yn:X|jt|d}|jjj||t|}|rZ|d|S|S)Nrr)ctypesrnZcreate_unicode_bufferlenwindllkernel32ZGetLongPathNameW)rrbufferZlengthrdrdre _longpaths    rc sFytj|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)rrvrr)rrdrers  z_rmtree.._rmtree_inner)shutilrrrr)rrd)rrers  cCs|S)Nrd)rrdrdrersc Cs*y t|Wnttfk r$YnXdS)N)rFileNotFoundErrorNotADirectoryError)rrdrdrers c Cs&y t|Wntk r YnXdS)N)rr)rrdrdrers rc Cs&y t|Wntk r YnXdS)N)rr)rrdrdrers 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) rmutilcache_from_sourcerrrabspathrrename)sourceZpyc_fileZup_oneZ legacy_pycrdrdremake_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) rrorrrrrmrr)r~rroptrdrdrers    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..USEROBJECTFLAGSZfInheritZ fReserveddwFlagsN)r`rarbwintypesZBOOLDWORD_fields_rd)rrdreUSEROBJECTFLAGSs  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..ProcessSerialNumberZ highLongOfPSNZ lowLongOfPSNN)r`rarbrrd)rrdreProcessSerialNumbersrz#cannot run without OS X gui process)Tk2z [...]zTk unavailable due to {}: {}))hasattr_is_gui_availablerrorprqrZctypes.wintypesrrZuser32ZGetProcessWindowStationZWinErrorrrZGetUserObjectInformationWZbyrefZsizeofboolrrrrZ ctypes.utilrZ LoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterrZwithdrawupdateZdestroy Exceptionrurformattyper`reason)rZ UOI_FLAGSZ WSF_VISIBLErZdllhZuofZneededresrrrrZ app_servicesrZpsnZpsn_prrooteZ err_stringrd)rrrersh         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)resourcerdrdrer $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)rrxrdrdrer!,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 j d||f||S)N-rrryz(%s version %s or higher required, not %s) rpsystemreleaserrrmapint ValueErrorrrursrt)rkw version_txtversionmin_version_txt)r min_versionsysnamerdrewrapper=s z:_requires_unix_version..decorator..wrapper) functoolswrapsr)rr)rr)rre decorator<sz)_requires_unix_version..decoratorrd)rrrrd)rrre_requires_unix_version5srcGs 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)rrdrdrer"PscGs 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)rrdrdrer#Yscsfdd}|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 j d||f||S)Nrrryz&Mac OS X %s or higher required, not %s) rorpZmac_verrrrrrrrrursrt)rrrrr)rrrdrerjs   z4requires_mac_ver..decorator..wrapper)rrr)rr)r)rrerisz#requires_mac_ver..decoratorrd)rrrd)rrer$bs csfdd}|S)aDecorator raising SkipTest if a hashing algorithm is not available The hashing algorithm could be missing or blocked by a strict crypto policy. If 'openssl' is True, then the decorator checks that OpenSSL provides the algorithm. Otherwise the check falls back to built-in implementations. ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS ValueError: unsupported hash type md4 cstjfdd}|S)Nc sXy&rtdk rtjn tjWn&tk rLtjddYnX||S)Nz hash digest 'z' is not available.)_hashlibnewhashlibrrsrt)rkwargs) digestnameropensslrdrers  z7requires_hashdigest..decorator..wrapper)rr)rr)rr)rrers z&requires_hashdigest..decoratorrd)rrrrd)rrrer%}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. )socketrHclose)familyZsocktypeZtempsockportrdrdrerGs 8 c Cs|jtjkr|jtjkrttdr>|jtjtjdkr>t dttdr~y |jtjtj dkrft dWnt k 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_INETr SOCK_STREAMrZ getsockoptZ SOL_SOCKETrr rrZ setsockoptrbindZ getsockname)sockhostrrdrdrerHs     c Cs:y|j|Wn&tk r4|jtjdYnXdS)zBBind a unix socket, raising SkipTest if PermissionError is raised.zcannot bind AF_UNIX socketsN)r PermissionErrorrrsrt)r ZaddrrdrdrerJs cCsZtjrVd}z.dec)rr)rrrd)rresystem_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) tempfilemkdtemprrrealpathmkdirrrgrrgetpidr)rquietZ dir_createdpidrdrdretemp_dirs&   r2ccsftj}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)rgetcwdchdirrrgrr)rr0Z saved_dirrdrdre change_cwd s  r5tempcwdccs: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. )rr0)r0N)r2r5)rvr0Z temp_pathZcwd_dirrdrdrer$sumaskc cs&tj|}z dVWdtj|XdS)z8Context manager that temporarily sets the process umask.N)rr7)r7ZoldmaskrdrdrerK8s  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_DIRroexists)rZsubdirrZdnfnrdrdrerIs    cCs(tj|tjtjBtjB}tj|dS)z>Create an empty file. If the file already exists, truncate it.N)ropenO_WRONLYO_CREATO_TRUNCr)rfdrdrdrer[scCs,t|j}dd|D}dj|}d|S)z%Like repr(dict), but in sorted order.cSsg|] }d|qS)z%r: %rrd).0Zpairrdrdre cszsortdict..z, z{%s})sortedrr)dictrZ reprpairsZ withcommasrdrdrer[`s  c Cs*ttd}z|jS|jttXdS)z` Create an invalid file descriptor by opening and closing a file and return its fd. wbN)r=rfilenorr)rrdrdre make_bad_fdgs  rH)linenooffsetc Csp|jt}t|ddWdQRX|j}|j|j|dk rJ|j|j||j|j|dk rl|j|j|dS)Nz exec) assertRaises SyntaxErrorcompileZ exceptionZassertIsNotNonerI assertEqualrJ)testcaseZ statementrIrJcmrrdrdrer&ss   c sVddl}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)r=seekr)r<r)rrRrrdrecheck_valid_files z*open_urlresource..check_valid_fileZurlfetchz fetching %s ...)rAccept-Encodinggzip)rzContent-Encoding)ZfileobjrFzinvalid resource %r)rVrW)Zurllib.requestZ urllib.parsepopparseZurlparserrrr TEST_DATA_DIRr;rr!rrrZrequestZ build_openerrWZ addheadersrr=ZheadersgetZGzipFilereadwriterr ) Zurlrrurllibrr<rUropeneroutsrd)rrRrrerI~s<         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_listrdrdre__init__szWarningsRecorder.__init__cCsDt|j|jkr t|jd|S|tjjkr0dStd||fdS)Nrz%r has no attribute %rrY)rrerfrrgWarningMessage_WARNING_DETAILSr)rgattrrdrdre __getattr__s  zWarningsRecorder.__getattr__cCs|j|jdS)N)rerf)rgrdrdrergszWarningsRecorder.warningscCst|j|_dS)N)rrerf)rgrdrdreresetszWarningsRecorder.resetN) r`rarbrcrhrlpropertyrgrmrdrdrdrerds  rdc 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)recordrgalwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)ro _getframe f_globalsr]clearrgrhrz simplefilterrdr|messagerematchruI issubclassrremoverr`AssertionError) filtersr0frameregistrywZreraiseZmissingrxcatseenZwarningrdrdre_filterwarningss0    rcOs.|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) r0rNT)r]Warningr)r|rr0rdrdrerRs   rc csHtjdd&}tjd||ddV|r.tWdQRX|j|gdS)aContext manager to check that no warnings are emitted. This context manager enables a given warning within its scope and checks that no warnings are emitted even with that warning enabled. If force_gc is True, a garbage collection is attempted before checking for warnings. This may help to catch warnings emitted when objects are deleted, such as ResourceWarning. Other keyword arguments are passed to warnings.filterwarnings(). T)rorp)rucategoryN)rgrhri gc_collectrO)rPrurZforce_gcwarnsrdrdrecheck_no_warningssrc csBtjdd }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)rorp)rN)rgrhriResourceWarningrrO)rPrrdrdrerSs 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)rorzcopyoriginal_modulesr`)rgZ module_namesZ module_namerrdrdrerh?s      zCleanImport.__init__cCs|S)Nrd)rgrdrdre __enter__LszCleanImport.__enter__cGstjj|jdS)N)rorzrr)rg ignore_excrdrdre__exit__OszCleanImport.__exit__N)r`rarbrcrhrrrdrdrdrer3s  c@sheZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZdS)rTz_Class to help protect the environment variable properly. Can be used as a context manager.cCstj|_i|_dS)N)renviron_environ_changed)rgrdrdrerhXszEnvironmentVarGuard.__init__cCs |j|S)N)r)rgenvvarrdrdre __getitem__\szEnvironmentVarGuard.__getitem__cCs*||jkr|jj||j|<||j|<dS)N)rrr])rgrvaluerdrdre __setitem___s zEnvironmentVarGuard.__setitem__cCs2||jkr|jj||j|<||jkr.|j|=dS)N)rrr])rgrrdrdre __delitem__es  zEnvironmentVarGuard.__delitem__cCs |jjS)N)rkeys)rgrdrdrerlszEnvironmentVarGuard.keyscCs t|jS)N)iterr)rgrdrdre__iter__oszEnvironmentVarGuard.__iter__cCs t|jS)N)rr)rgrdrdre__len__rszEnvironmentVarGuard.__len__cCs |||<dS)Nrd)rgrrrdrdresetuszEnvironmentVarGuard.setcCs ||=dS)Nrd)rgrrdrdreunsetxszEnvironmentVarGuard.unsetcCs|S)Nrd)rgrdrdrer{szEnvironmentVarGuard.__enter__cGsJx<|jjD].\}}|dkr0||jkr:|j|=q ||j|<q W|jt_dS)N)rrrrr)rgrkvrdrdrer~s   zEnvironmentVarGuard.__exit__N)r`rarbrcrhrrrrrrrrrrrdrdrdrerTSsc@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)rororiginal_valueoriginal_objectextend)rgpathsrdrdrerhszDirsOnSysPath.__init__cCs|S)Nrd)rgrdrdrerszDirsOnSysPath.__enter__cGs|jt_|jtjdd<dS)N)rrorr)rgrrdrdrerszDirsOnSysPath.__exit__N)r`rarbrcrhrrrdrdrdrers 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)rgrrrdrdrerhszTransientResource.__init__cCs|S)Nrd)rgrdrdrerszTransientResource.__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)ryrrrrrr )rgZtype_r tracebackrkZ attr_valuerdrdrers zTransientResource.__exit__)NNN)r`rarbrcrhrrrdrdrdrer's)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}~Xnt k rZ}zpx^|j }t |d krt |dt r|d}n*t |dkr8t |d t r8|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 EHOSTUNREACHq ENETUNREACHe ETIMEDOUTn EADDRNOTAVAILc EAI_AGAINr*EAI_FAILr EAI_NONAMEr EAI_NODATA WSANO_DATA*zResource %r is not availablecSsg|]\}}tt||qSrd)rr)rBrvnumrdrdrerCsz&transient_internet..cSsg|]\}}tt||qSrd)rr)rBrvrrdrdrerCscst|dd}t|tjst|tjr,|kst|tjjrTd|jkoNdknst|tjj rd|j ksd|j ksd|j ks|krt st j jjdd|dS) NriiWConnectionRefusedError TimeoutErrorEOFErrorr )r isinstancerrZgaierrorr`errorZ HTTPErrorcodeZURLErrorrrrostderrr_r)rn)captured_errnosdenied gai_errnosrdre filter_errors     z(transient_internet..filter_errorNrrr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)r rZgetdefaulttimeoutZsetdefaulttimeoutnntplibZNNTPTemporaryErrorrrorr_rrrr) Z resource_namerrZdefault_errnosZdefault_gai_errnosrZ old_timeoutrard)rrrrer+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)iorrosetattrStringIO)Z stream_namerZ orig_stdoutrdrdrecaptured_outputs  rcCstdS)zCapture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") r)rrdrdrdrerscCstdS)zCapture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") r)rrdrdrdrer%scCstdS)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)rrdrdrdrer.s 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@rrrdrdrdrer;s  rc cs.tj}tjz dVWd|r(tjXdS)N)r isenableddisableenable)Zhave_gcrdrdre disable_gcKs  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_varrrq)ZcflagsZ final_optrrdrdrepython_is_optimizedVs  rZnPZ0ngettotalrefcountZ2PZ0PrcCstjt|tS)N)structcalcsize_header_align)fmtrdrdre calcobjsizegsrcCstjt|tS)N)rr_vheaderr)rrdrdre calcvobjsizejsr cCspddl}tj|}t|tkr(|jt@sBt|tkrLt|jt@rL||j7}dt|||f}|j|||dS)Nrz&wrong size for %s: got %d, expected %d) _testcapiro getsizeofr __flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADrO)testosizerrrxrdrdre check_sizeofqs  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)rkwdsrrZ orig_localeloc)catstrrlocalesrdreinners$     z1run_with_locale..decorator..inner)r`rc)rr)rr)rrersz"run_with_locale..decoratorrd)rrrrd)rrrerUscsfdd}|S)Ncs"fdd}j|_j|_|S)Ncsy tj}Wntk r(tjdYnXdtjkr@tjd}nd}tjd<|z ||S|dkrrtjd=n |tjd<tjXdS)Nztzset requiredZTZ)rtzsetrrsrtrr)rrrZorig_tz)rtzrdrers       z-run_with_tz..decorator..inner)r`rc)rr)r)rrerszrun_with_tz..decoratorrd)rrrd)rrer\s 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_1Grvrw IGNORECASEVERBOSErrfloatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitZsizesrZmemlimitrdrdrerYs $ c@s(eZdZdZddZddZddZdS) _MemoryWatchdogz`An object which periodically watches the process' memory consumption and prints it out. cCsdjtjd|_d|_dS)Nz/proc/{pid}/statm)r1F)rrr/procfilestarted)rgrdrdrerhsz_MemoryWatchdog.__init__cCsyt|jd}Wn<tk rL}z tjdj|ttjj dSd}~XnXt d}t j tj |g|t jd|_|jd|_dS)Nrz!/proc not available for stats: {}zmemory_watchdog.py)rrT)r=r rrgrrrrorflushr subprocessPopen executableZDEVNULL mem_watchdogrr )rgrrZwatchdog_scriptrdrdrestarts   z_MemoryWatchdog.startcCs|jr|jj|jjdS)N)r rZ terminatewait)rgrdrdrestops z_MemoryWatchdog.stopN)r`rarbrcrhrrrdrdrdrer sr csfdd}|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@) rmemuserrsrtrrrr rr)rgrrmaxsizeZwatchdog)dry_runrrrdrers*    z.bigmemtest..decorator..wrapper)rr)r)rrr)rrrerszbigmemtest..decoratorrd)rrrrrd)rrrrer3s !csfdd}|S)z0Decorator for tests that fill the address space.csDttkr8td kr$td kr$tjdq@tjdtd n|SdS) Nr?rz-not enough memory: try a 32-bit build insteadz'not enough memory: %.1fG minimum neededir*llli@)rrrsrt)rg)rrdrer3sz!bigaddrspacetest..wrapperrd)rrrd)rrer41s c@seZdZddZdS)r,cCstj}|||S)N)rsZ TestResult)rgrrrdrdrerunDszBasicTestRunner.runN)r`rarbrrdrdrdrer,CscCs|S)Nrd)rrdrdre_idIsrcCs<|dkrt rtjtjSt|r(tStjdj|SdS)Nrzresource {0!r} is not enabled)rrsskiprr rr)rrdrdrerequires_resourceLs  rcCs&trt|krtjd|tfStSdS)Nz%s at Android API level %d)rA_ANDROID_API_LEVELrsrr)levelrrdrdrer>Ts  cCstdd|S)z9 Decorator for tests only applicable on CPython. T)cpython) impl_detail)rrdrdrer5[scKsVtf|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 ) rBr _parse_guardsrDrrrrsr)rxguardsZ guardnamesdefaultrdrdrer!as   r!c CsTtdkr:ddl}y|jdaWntk r8daYnXd}trF|Stj||S)z8Skip decorator for tests that use multiprocessing.Queue.NrTFz6requires a functioning shared semaphore implementation)_have_mp_queuemultiprocessingZQueuernrsr)rr&rxrdrdrer?os cCs*|sddidfSt|jd}|| fS)Nr TFr)r|values)r#Zis_truerdrdrer"~s r"cKs 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 )r"r]rpZpython_implementationr)r#r$rdrdrerBs cs,ttdsStjfdd}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.gettracec s.tj}ztjd||Stj|XdS)N)ror(settrace)rrZoriginal_trace)rrdrers   zno_tracing..wrapperN)rrorr)rrrd)rre no_tracings 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*r5)rrdrdre refcount_testsr+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_testsrrs TestSuite _filter_suiter)suiteZpredZnewtestsrrdrdrer-s    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)rrorrjunit_xml_listrrZget_xml_elementZtestsRunr Z wasSuccessfulrerrorsZfailuresr )r.Zrunnerrrrdrdre _run_suites"  r2cCstdkr dSt|jSdS)NT)_match_test_funcid)rrdrdre match_testsr5cCsd|kotjd| S)Nryz[?*\[\]])rvsearch)rrdrdre_is_full_match_testsr7csr|tkr dS|sd}f}nHttt|r4t|j}n.djttj|}t j |j fdd}|}t |a|a dS)N|cs$|r dStt|jdSdS)NTry)anyrr)Ztest_id) regex_matchrdrematch_test_regexsz)set_match_tests..match_test_regex)_match_test_patternsallrr7r __contains__rfnmatch translatervrNrwrrr3)ZpatternsrZregexr;rd)r:reset_match_testss   rAcGstjtjf}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)rsr,ZTestCaserrurorzZaddTestZ findTestCasesrZ makeSuiter-r5r2)classesZ valid_typesr.clsrdrdrer-s        cCsdS)z,Just used to check if docstrings are enabledNrdrdrdrdre_check_docstrings(srDWITH_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)r optionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)doctestrZtestmodr rr`)rr/rFrGrrrdrdrer.9scCs tjjfS)N)rorzrrdrdrdre modules_setupTsrHcCs:ddtjjD}tjjtjj|tjj|dS)NcSs"g|]\}}|jdr||fqS)z encodings.)rq)rBrrrdrdrerC[sz#modules_cleanup..)rorzrrsr)Z oldmodulesZ encodingsrdrdremodules_cleanupWs  rIcCs"trtjtjjfSdffSdS)Nr)_thread_count threading _danglingrrdrdrdrerNzscGsJtsdSd}x8t|D],}tjtjf}||kr2PtjdtqWdS)Ndg{Gz?)rJrangerKrLrMrrr)Zoriginal_valuesZ _MAX_COUNTcountr'rdrdrerOs 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. c st}z|St|XdS)N)rNrO)rkey)rrdrerszreap_threads..decorator)rJrr)rrrd)rrerPsN@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?)rJrKrZ monotonicr{rr)rZ old_countZ start_timeZdeadlinerPZdtrxrdrdrewait_threads_exits   $ rTc 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)rNrY)rrrUWNOHANGrror)Z any_processr1ZstatusrdrdrerLs 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 j t j td t|XXdS) Nz/Can't start %d threads, only %d threads startedrr<g{Gz?cSsg|]}|jr|qSrd)isAlive)rBrrdrdrerCsz!start_threads..z7Unable to join %d threads during a period of %d minutescSsg|]}|jr|qSrd)rX)rBrrdrdrerCszUnable to join %d threads)r|rrrrrrrOrmax faulthandlerZdump_tracebackrorr{)ZthreadsZunlockr rZendtimeZ starttimerrdrdrerQs>     c csnt||rtt|tt|}|r(|t|8}tdd|D}|S)a Returns the set of items in ref_api not in other_api, except for a defined list of items to be ignored in this check. By default this skips private attributes beginning with '_' but includes all magic methods, i.e. those starting and ending in '__'. css(|] }|jd s|jdr|VqdS)___N)rqendswith)rBrrdrdre sz&detect_api_mismatch..)rrx)Zref_apiZ other_apirfZ missing_itemsrdrdrer< 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) Nrra) r`rrurrxrqrrtypes ModuleTypeaddZassertCountEqual__all__)Z test_caserZname_of_moduleZextraZ blacklistZexpectedrvrrdrdrer= s)    c@s(eZdZdZdZdZddZddZdS)rZzTry 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 Wnt t 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/defaultsr^zcom.apple.CrashReporterZ DialogType)rrs developerz:this test triggers the Crash Reporter, that is intentionalrT)endr ) rorprqrrr_k32 SetErrorMode old_valuemsvcrtCrtSetReportModerrn old_modesCRT_WARN CRT_ERROR CRT_ASSERTZCRTDBG_MODE_FILECrtSetReportFileZCRTDBG_FILE_STDERRrZ getrlimit RLIMIT_CORE setrlimitrrrrPIPEZ communicaterar) rgrZSEM_NOGPFAULTERRORBOXr report_typeold_modeold_filecmdprocrrdrdrer2 sN        zSuppressCrashReport.__enter__c Gs|jdkrdStjjdrl|jj|j|jrddl}xj|jjD]$\}\}}|j |||j ||qBWn6t dk ryt j t j |jWnttfk rYnXdS)zARestore Windows ErrorMode or core file behavior to initial value.Nrr)rrorprqrrrrrrrrrrrr)rgrrrrrrdrdrers s   zSuppressCrashReport.__exit__)r`rarbrcrrrrrdrdrdrerZ) 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)rr[rd) attr_is_local attr_nameobject_to_patchrrdrecleanup szpatch..cleanup)rrjrrZ addCleanupr)Z test_instancerrZ new_valuerrd)rrrrrepatch s  rc CsFy 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) tracemallocrnZ is_tracingrsrtrrun_in_subinterp)rrrrdrdrer s  rcsHGfddd|}d||||jttt|jdS)NcseZdZfddZdS)z%check_free_after_iterating..Ac s*dy tWntk r$YnXdS)NT)next StopIteration)rg)doneitrdre__del__ s  z-check_free_after_iterating..A.__del__N)r`rarbrrd)rrrdreA srF)rLrrrZ assertTrue)rrrCrrrd)rrrecheck_free_after_iterating s   rcCs|ddlm}m}m}|j}|j|xP|jD]F}|r@||kr@q.t||}|rPn |dkrZq.|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) ccompilerrspawnN) Z distutilsrrrZ new_compilerZcustomize_compilerZ executablesrZfind_executable)Z cmd_namesrrrZcompilerrvrrdrdrer^ s     cCs@d}tr6||kr6tdkr.tjddgjdkatr6|}tj|S)Ngh㈵>Zgetpropzro.kernel.qemu1)rA_is_android_emulatorrZ check_outputrarorD)ZintervalZminimum_intervalrdrdrerD s c cs>tjj}tj}ztjdVWd|r8tj|ddXdS)NT)rZ all_threads)rorrGrZ is_enabledrr)rArrdrdredisable_faulthandler s  rc /Cstjjd r8ytjd}t|dStk r6YnXd}ttdrjytjd}Wnt k rhYnXd}tjd kryd dl }|j Wnt 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/fdrsysconf SC_OPEN_MAXNrr)rr)rorprqrrrrrrrrrrrnrrrrOduprZEBADFr) namesZMAXFDrrrrPrAZfd2rrdrdrer_ 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|rONSIGsignalsrrrzrf)rgrZsignamesignumrdrdrerhM s zSaveSignals.__init__cCs4x.|jD]$}|jj|}|dkr"q||j|<qWdS)N)rr getsignalrf)rgrhandlerrdrdresaveZ s   zSaveSignals.savecCs*x$|jjD]\}}|jj||q WdS)N)rfrr)rgrrrdrdrerestoref szSaveSignals.restoreN)r`rarbrcrhrrrdrdrdrerD s  rc@s(eZdZdZddZddZddZdS) FakePathz.Simple implementing of the path protocol. cCs ||_dS)N)r)rgrrdrdrerhn szFakePath.__init__cCsd|jdS)Nz )r)rgrdrdre__repr__q szFakePath.__repr__cCs6t|jts$t|jtr,t|jtr,|jn|jSdS)N)rr BaseExceptionrry)rgrdrdre __fspath__t s    zFakePath.__fspath__N)r`rarbrcrhrrrdrdrdrerk src cs.tj}ztj|dVWdtj|XdS)z>Temporarily change the integer string conversion length limit.N)roget_int_max_str_digitsset_int_max_str_digits)Z max_digitsZcurrentrdrdreadjust_int_max_str_digits| s   rcCsddtddDdgS)zReturns a list of C0 control characters as strings. C0 control characters defined as the byte range 0x00-0x1F, and 0x7F. cSsg|] }t|qSrd)chr)rBrrdrdrerC sz)control_characters_c0..r )rOrdrdrdrecontrol_characters_c0 sr)T)F)F)N)Nii@i@i@ii) rrrrrrrrr r!r")r&r$r'r(r))NF)F)r6F)N)Fi@ii)T)N)Nr)rR)N(rcr`rncollections.abc collections contextlibZdatetimerrZr?rrrrmimportlib.utilrZlogging.handlersrerrrprvrrrrrrorr+rrrsZ urllib.errorr`rgZ testresultrrJrLZmultiprocessing.processr&zlibrWbz2Zlzmarrrrr r r rtr contextmanagerrkr rrr:r;rr6rrrrr0rrrrrrrqrrrrrrrrrrrr r!rr"r#r$r%rErr r rGrHrJrrFrrZ SOCK_MAX_SIZEZ skipUnlessr __getformat__r7r9r0r1r2r@rrrArCrvrrr/Z FS_NONASCII characterfsdecodefsencode UnicodeErrorZTESTFN_UNICODEZ unicodedata normalizegetfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversionencodeUnicodeEncodeErrorrdecodeUnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIr3rr]r}r2r5rrrKrrrrZTEST_SUPPORT_DIRr:rr\rrr[rHr&rIobjectrdrrRrrrSrabcMutableMappingrTrr'rrr(rr)r*r+rrrrrrrrrrrrrrrrUr\rrrZ_4GrrrYr r3r4r,rrr>r5r!r%r?r"rBr*r+r-r2r3r<r5r7rAr-rDZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr.rHrIZenvironment_alteredrNrOrPrTrLrQrWrVrbZskipIfZrequires_type_collectingrcrdrfrgrMrXrrrr/rzr|r8r~rr<r=rZrrrr^rrDrr_rrrrrdrdrdres                      2   !  J    > %                 %      2 ' 5M            $ # 0           (        " #   "    :_"  ;' PK!]1support/__pycache__/__init__.cpython-36.opt-2.pycnu[3 _Vj@sf edkredddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z!ddl"Z"ddl#m$Z$yddl%Z%ddl&Z&Wnek r>dZ%dZ&YnXy ddl'Z(Wnek rfdZ(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-YnXy ddl.Z.Wnek rVdZ.YnXdddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dag\Z/Gdbd d e0Z1Gdcd d e1Z2Gddd d e1Z3Gdeddej4Z5ej6dgdgdhZ7dhfdjdkdZ8dldmZ9dndoZ:dpd<Z;dqd=ZdZ?dZ@daAdaBdZCdiZDdaEdtdZFdudZGdvdZHdwdxZIejjJdyr*didzd{ZKd|d}ZLd~dZMddZNddZOnejPZLejQZMddZNddZOddZPddZQddZRddZSddZTddZUdd"ZVdjdd#ZWddZXdd$ZYdd%ZZdd&Z[dkdd'Z\dZ]dZ^ej_ej`fddIZae]fddJZbddLZcddZdedZeddZfdnZgdqZhejiejjkdjJddZlejie)dZmejie*dZnejie+dZoejie,dZpejjJdZqejrdZsesdk otesdkZtejdkretrdndZundZuejvdkrdZwndZwdjxewejyZwdZzxLdrD]BZ{yej|ej}e{e{kre~Wne~k rYnXe{ZzPqWewdZejdkr6ddlZejdeZejZdZejvdkrejjdkrewdZyejeWnek rYnXedeefdZnBejdkrydjeWn&ek rewdjedƃZYnXdZxFdsD]d?Zejeed@dAZdBdCZdDdEZGdFdOdOejjZGdGdZdZeZdadHd ZdId1ZdadJdKZdLd:ZdMdNZdOd!ZfdPdQd>Z dfffdRd?Z GdSd\d\Z dTdUZ dVdWZ ffdXdYZgfdZd`Zdad[dFZej6d\d]Zd^daZGd_d`d`ZGdadbdbZej6dcddZdedfZdS(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_module CleanImportunloadforgetrecord_original_stdoutget_original_stdoutcaptured_stdoutcaptured_stdincaptured_stderrTESTFNSAVEDCWDunlinkrmtreetemp_cwdfindfilecreate_empty_file can_symlinkfs_is_case_insensitiveis_resource_enabledrequiresrequires_freebsd_versionrequires_linux_versionrequires_mac_verrequires_hashdigestcheck_syntax_errorTransientResourcetime_outsocket_peer_resetioerror_peer_resettransient_internetBasicTestRunner run_unittest run_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_children TestHandlerthreading_setupthreading_cleanup reap_threads start_threadscheck_warningscheck_no_resource_warningEnvironmentVarGuardrun_with_locale swap_item swap_attrMatcher set_memlimitSuppressCrashReportsortdict run_with_tzPGOmissing_compiler_executablefd_countc@s eZdZdS)r N)__name__ __module__ __qualname__rcrc-/usr/lib64/python3.6/test/support/__init__.pyr |sc@s eZdZdS)r N)r`rarbrcrcrcrdr sc@s eZdZdS)r N)r`rarbrcrcrcrdr sc@s eZdZdS)r N)r`rarbrcrcrcrdr sTc cs8|r.tjtjddtdVWdQRXndVdS)Nignorez.+ (module|package))warningscatch_warningsfilterwarningsDeprecationWarning)rercrcrd_ignore_deprecated_importss  rjF) required_oncCsft|Ty tj|Stk rV}z&tjjt|r8tj t |WYdd}~XnXWdQRXdS)N) rj importlibr ImportErrorsysplatform startswithtupleunittestSkipTeststr)name deprecatedrkmsgrcrcrdr s  cCs^|tjkrt|tj|=x>ttjD]0}||ks@|j|dr&tj|||<tj|=q&WdS)N.)rnmodules __import__listrp)ru orig_modulesmodnamercrcrd_save_and_remove_modules r~c Cs>d}ytj|||<Wntk r.d}YnXdtj|<|S)NTF)rnryKeyError)rur|Zsavedrcrcrd_save_and_block_modules  rcCs|r tjSddS)NcSs|S)Nrc)frcrcrdsz$anticipate_failure..)rrZexpectedFailure)Z conditionrcrcrdr:scCsF|dkr d}tjjtjjtjjt}|j|||d}|j||S)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)N) rjr~rappendrlr rmitemsrnry) ruZfreshZblockedrvr|Znames_to_removeZ fresh_nameZ blocked_nameZ fresh_moduleZ orig_namemoduleZname_to_removercrcrdrs$      c Cs>yt||}Wn&tk r4tjd||fYnX|SdS)Nzobject %r has no attribute %r)getattrAttributeErrorrrrs)objruZ attributercrcrdr6s cCs|adS)N)_original_stdout)stdoutrcrcrdr0scCs tptjS)N)rrnrrcrcrcrdr4sc Cs&y tj|=Wntk r YnXdS)N)rnryr)rurcrcrdr7s cGsny||Stk rh}zDtdkrHtd|jj|ftd|j|ftj|tj||Sd}~XnXdS)Nz%s: %sz re-run %s%r) OSErrorrprint __class__r`rchmodstatS_IRWXU)rfuncargserrrcrcrd _force_run=srwincCs|||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_waitforHs     rcCsttj|dS)N)rrr)filenamercrcrd_unlinkisrcCsttj|dS)N)rrrmdir)rrcrcrd_rmdirlsrcs,fddt|ddtdd|dS)Ncsxt|tj|D]}tjj||}ytj|j}Wn<tk rn}z td||ft j dd}WYdd}~XnXt j |rt |ddt|tj|qt|tj|qWdS)Nz-support.rmtree(): os.lstat(%r) failed with %s)filerT)r)rrrrjoinlstatst_moderrrn __stderr__rS_ISDIRrrr)rrufullnamemodeexc) _rmtree_innerrcrdrps   z_rmtree.._rmtree_innerT)rcSst|tj|S)N)rrr)prcrcrdrsz_rmtree..)r)rrc)rrd_rmtreeos rc Cs^y ddl}Wntk r Yn:X|jt|d}|jjj||t|}|rZ|d|S|S)Nrr)ctypesrmZcreate_unicode_bufferlenwindllkernel32ZGetLongPathNameW)rrbufferZlengthrcrcrd _longpaths    rc sFytj|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.._rmtree_inner)shutilrrrr)rrc)rrdrs  cCs|S)Nrc)rrcrcrdrsc Cs*y t|Wnttfk r$YnXdS)N)rFileNotFoundErrorNotADirectoryError)rrcrcrdrs c Cs&y t|Wntk r YnXdS)N)rr)rrcrcrdrs rc Cs&y t|Wntk r YnXdS)N)rr)rrcrcrdrs cCsBtjj|}tjjtjj|}tjj||d}tj|||S)Nc) rlutilcache_from_sourcerrrabspathrrename)sourceZpyc_fileZup_oneZ legacy_pycrcrcrdmake_legacy_pycs   rcCs\t|xNtjD]D}tjj||d}t|dx dD]}ttjj||dq8WqWdS)Nz.pyrrr) optimization)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..USEROBJECTFLAGSZfInheritZ fReserveddwFlagsN)r`rarbwintypesZBOOLDWORD_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..ProcessSerialNumberZ highLongOfPSNZ lowLongOfPSNN)r`rarbrrc)rrcrdProcessSerialNumbersrz#cannot run without OS X gui process)Tk2z [...]zTk unavailable due to {}: {}))hasattr_is_gui_availablerrnrorprZctypes.wintypesrrZuser32ZGetProcessWindowStationZWinErrorrrZGetUserObjectInformationWZbyrefZsizeofboolrrrrZ ctypes.utilrZ LoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterrZwithdrawupdateZdestroy Exceptionrtrformattyper`reason)rZ UOI_FLAGSZ WSF_VISIBLErZdllhZuofZneededresrrrrZ app_servicesrZpsnZpsn_prrooteZ err_stringrc)rrrdrsh         rcCstdkp|tkS)N)r)resourcercrcrdr $scCs>t|s |dkrd|}t||dkr:t r:ttjdS)Nz"Use of the %r resource not enabledgui)r r rr)rrwrcrcrdr!,s csfdd}|S)Ncs$tjfdd}|_|S)Nc stjkrztjjddd}yttt|jd}Wntk rLYn.X|krzdjtt }t j d||f||S)N-rrrxz(%s version %s or higher required, not %s) rosystemreleaserrqmapint ValueErrorrrtrrrs)rkw version_txtversionmin_version_txt)r min_versionsysnamercrdwrapper=s z:_requires_unix_version..decorator..wrapper) functoolswrapsr)rr)rr)rrd decorator<sz)_requires_unix_version..decoratorrc)rrrrc)rrrd_requires_unix_version5srcGs td|S)NZFreeBSD)r)rrcrcrdr"PscGs td|S)NZLinux)r)rrcrcrdr#Yscsfdd}|S)Ncs"tjfdd}|_|S)Nc sxtjdkrntjd}yttt|jd}Wntk rBYn,X|krndjtt }t j d||f||S)Nrrrxz&Mac OS X %s or higher required, not %s) rnroZmac_verrqrrrrrrtrrrs)rrrrr)rrrcrdrjs   z4requires_mac_ver..decorator..wrapper)rrr)rr)r)rrdrisz#requires_mac_ver..decoratorrc)rrrc)rrdr$bs csfdd}|S)Ncstjfdd}|S)Nc sXy&rtdk rtjn tjWn&tk rLtjddYnX||S)Nz hash digest 'z' is not available.)_hashlibnewhashlibrrrrs)rkwargs) digestnameropensslrcrdrs  z7requires_hashdigest..decorator..wrapper)rr)rr)rr)rrdrs z&requires_hashdigest..decoratorrc)rrrrc)rrrdr%}s z 127.0.0.1z::1cCs"tj||}t|}|j~|S)N)socketrHclose)familyZsocktypeZtempsockportrcrcrdrGs 8 c Cs|jtjkr|jtjkrttdr>|jtjtjdkr>t dttdr~y |jtjtj dkrft dWnt k r|YnXttdr|j tjtj d|j|df|jd}|S)N 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_INETr SOCK_STREAMrZ getsockoptZ SOL_SOCKETrr rrZ setsockoptrbindZ getsockname)sockhostrrcrcrdrHs     c Cs:y|j|Wn&tk r4|jtjdYnXdS)Nzcannot bind AF_UNIX sockets)r PermissionErrorrrrrs)r ZaddrrcrcrdrJs cCsZtjrVd}z.dec)rr)rrrc)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)NFTz+tests may fail, unable to create temp dir: )r) tempfilemkdtemprrrealpathmkdirrrfrrgetpidr)rquietZ dir_createdpidrcrcrdtemp_dirs&   r1ccsftj}ytj|Wn.tk rD|s,tjd|tddYnXztjVWdtj|XdS)Nz)tests may fail, unable to change CWD to: r))r)rgetcwdchdirrrfrr)rr/Z saved_dirrcrcrd change_cwd s  r4tempcwdccs:t||d$}t||d }|VWdQRXWdQRXdS)N)rr/)r/)r1r4)rur/Z temp_pathZcwd_dirrcrcrdr$sumaskc cs&tj|}z dVWdtj|XdS)N)rr6)r6ZoldmaskrcrcrdrK8s  datacCsbtjj|r|S|dk r&tjj||}tgtj}x*|D]"}tjj||}tjj|r8|Sq8W|S)N)rrisabsr TEST_HOME_DIRrnexists)rZsubdirrZdnfnrcrcrdrIs    cCs(tj|tjtjBtjB}tj|dS)N)ropenO_WRONLYO_CREATO_TRUNCr)rfdrcrcrdr[scCs,t|j}dd|D}dj|}d|S)NcSsg|] }d|qS)z%r: %rrc).0Zpairrcrcrd cszsortdict..z, z{%s})sortedrr)dictrZ reprpairsZ withcommasrcrcrdr[`s  c Cs*ttd}z|jS|jttXdS)Nwb)r<rfilenorr)rrcrcrd make_bad_fdgs  rG)linenooffsetc Csp|jt}t|ddWdQRX|j}|j|j|dk rJ|j|j||j|j|dk rl|j|j|dS)Nz exec) assertRaises SyntaxErrorcompileZ exceptionZassertIsNotNonerH assertEqualrI)testcaseZ statementrHrIcmrrcrcrdr&ss   c sVddl}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)r<seekr)r;r)rrQrrcrdcheck_valid_files z*open_urlresource..check_valid_fileZurlfetchz fetching %s ...)rAccept-Encodinggzip)rzContent-Encoding)ZfileobjrEzinvalid resource %r)rUrV)Zurllib.requestZ urllib.parsepopparseZurlparserrrr TEST_DATA_DIRr:rr!rrrZrequestZ build_openerrVZ addheadersrr<ZheadersgetZGzipFilereadwriterr ) Zurlrrurllibrr;rTropeneroutsrc)rrQrrdrI~s<         c@s0eZdZddZddZeddZddZd S) WarningsRecordercCs||_d|_dS)Nr) _warnings_last)selfZ warnings_listrcrcrd__init__szWarningsRecorder.__init__cCsDt|j|jkr t|jd|S|tjjkr0dStd||fdS)Nrz%r has no attribute %rrX)rrdrerrfWarningMessage_WARNING_DETAILSr)rfattrrcrcrd __getattr__s  zWarningsRecorder.__getattr__cCs|j|jdS)N)rdre)rfrcrcrdrfszWarningsRecorder.warningscCst|j|_dS)N)rrdre)rfrcrcrdresetszWarningsRecorder.resetN)r`rarbrgrkpropertyrfrlrcrcrcrdrcs rcc 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) NrZ__warningregistry__T)recordrfalwaysFzunhandled warning %srz)filter (%r, %s) did not catch any warning)rn _getframe f_globalsr\clearrfrgry simplefilterrcr{messagerematchrtI issubclassrremoverr`AssertionError) filtersr/frameregistrywZreraiseZmissingrwcatseenZwarningrcrcrd_filterwarningss0    rcOs.|jd}|s$dtff}|dkr$d}t||S)Nr/rT)r\Warningr)r{rr/rcrcrdrRs   rc csHtjdd&}tjd||ddV|r.tWdQRX|j|gdS)NT)rnro)rtcategory)rfrgrh gc_collectrN)rOrtrZforce_gcwarnsrcrcrdcheck_no_warningssrc csBtjdd }tjdtddVtWdQRX|j|gdS)NT)rnro)r)rfrgrhResourceWarningrrN)rOrrcrcrdrSs c@s$eZdZddZddZddZdS)rcGsNtjj|_x<|D]4}|tjkrtj|}|j|kr>tj|j=tj|=qWdS)N)rnrycopyoriginal_modulesr`)rfZ module_namesZ module_namerrcrcrdrg?s      zCleanImport.__init__cCs|S)Nrc)rfrcrcrd __enter__LszCleanImport.__enter__cGstjj|jdS)N)rnryrr)rf ignore_excrcrcrd__exit__OszCleanImport.__exit__N)r`rarbrgrrrcrcrcrdr3s  c@sdeZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ dS)rTcCstj|_i|_dS)N)renviron_environ_changed)rfrcrcrdrgXszEnvironmentVarGuard.__init__cCs |j|S)N)r)rfenvvarrcrcrd __getitem__\szEnvironmentVarGuard.__getitem__cCs*||jkr|jj||j|<||j|<dS)N)rrr\)rfrvaluercrcrd __setitem___s zEnvironmentVarGuard.__setitem__cCs2||jkr|jj||j|<||jkr.|j|=dS)N)rrr\)rfrrcrcrd __delitem__es  zEnvironmentVarGuard.__delitem__cCs |jjS)N)rkeys)rfrcrcrdrlszEnvironmentVarGuard.keyscCs t|jS)N)iterr)rfrcrcrd__iter__oszEnvironmentVarGuard.__iter__cCs t|jS)N)rr)rfrcrcrd__len__rszEnvironmentVarGuard.__len__cCs |||<dS)Nrc)rfrrrcrcrdsetuszEnvironmentVarGuard.setcCs ||=dS)Nrc)rfrrcrcrdunsetxszEnvironmentVarGuard.unsetcCs|S)Nrc)rfrcrcrdr{szEnvironmentVarGuard.__enter__cGsJx<|jjD].\}}|dkr0||jkr:|j|=q ||j|<q W|jt_dS)N)rrrrr)rfrkvrcrcrdr~s   zEnvironmentVarGuard.__exit__N)r`rarbrgrrrrrrrrrrrcrcrcrdrTSsc@s$eZdZddZddZddZdS) DirsOnSysPathcGs(tjdd|_tj|_tjj|dS)N)rnroriginal_valueoriginal_objectextend)rfpathsrcrcrdrgszDirsOnSysPath.__init__cCs|S)Nrc)rfrcrcrdrszDirsOnSysPath.__enter__cGs|jt_|jtjdd<dS)N)rrnrr)rfrrcrcrdrszDirsOnSysPath.__exit__N)r`rarbrgrrrcrcrcrdrs rc@s&eZdZddZddZdddZdS) r'cKs||_||_dS)N)rattrs)rfrrrcrcrdrgszTransientResource.__init__cCs|S)Nrc)rfrcrcrdrszTransientResource.__enter__NcCsT|dk rPt|j|rPx:|jjD]$\}}t||s4Pt|||kr Pq WtddS)Nz%an optional resource is not available)rxrrrrrr )rfZtype_r tracebackrjZ attr_valuercrcrdrs zTransientResource.__exit__)NNN)r`rarbrgrrrcrcrcrdr's)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}~Xnt k rZ}zpx^|j }t |dkrt |dt r|d}n*t |dkr8t |dt r8|d}nPqW||WYdd}~XnXWdtj|XdS)/N ECONNREFUSEDo ECONNRESETh EHOSTUNREACHq ENETUNREACHe ETIMEDOUTn EADDRNOTAVAILc EAI_AGAINr)EAI_FAILr EAI_NONAMEr EAI_NODATA WSANO_DATA*zResource %r is not availablecSsg|]\}}tt||qSrc)rr)rArunumrcrcrdrBsz&transient_internet..cSsg|]\}}tt||qSrc)rr)rArurrcrcrdrBscst|dd}t|tjst|tjr,|kst|tjjrTd|jkoNdknst|tjj rd|j ksd|j ksd|j ks|krt st j jjdd|dS) NriiWConnectionRefusedError TimeoutErrorEOFErrorr )r isinstancerrZgaierrorr_errorZ HTTPErrorcodeZURLErrorrrrnstderrr^r)rn)captured_errnosdenied gai_errnosrcrd filter_errors     z(transient_internet..filter_errorrrr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)r rZgetdefaulttimeoutZsetdefaulttimeoutnntplibZNNTPTemporaryErrorrrnrr^rrrr) Z resource_namerrZdefault_errnosZdefault_gai_errnosrZ old_timeoutrarc)rrrrdr+sP     c csFddl}tt|}tt||jztt|VWdtt||XdS)Nr)iorrnsetattrStringIO)Z stream_namerZ orig_stdoutrcrcrdcaptured_outputs  rcCstdS)Nr)rrcrcrcrdrscCstdS)Nr)rrcrcrcrdr%scCstdS)Nstdin)rrcrcrcrdr.s cCs*tjtrtjdtjtjdS)Ng?)gcZcollectr@rrrcrcrcrdr;s  rc cs.tj}tjz dVWd|r(tjXdS)N)r isenableddisableenable)Zhave_gcrcrcrd disable_gcKs  rcCs:tjdp d}d}x|jD]}|jdr|}qW|dkS)N PY_CFLAGSrz-O-O0-Og)rrr) sysconfigget_config_varrrp)ZcflagsZ final_optrrcrcrdpython_is_optimizedVs  rZnPZ0ngettotalrefcountZ2PZ0PrcCstjt|tS)N)structcalcsize_header_align)fmtrcrcrd calcobjsizegsrcCstjt|tS)N)rr_vheaderr)rrcrcrd calcvobjsizejsr 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_HEADrN)testosizerrrwrcrcrd check_sizeofqs  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)rkwdsrrZ orig_localeloc)catstrrlocalesrcrdinners$     z1run_with_locale..decorator..inner)r`__doc__)rr)rr)rrdrsz"run_with_locale..decoratorrc)rrrrc)rrrdrUscsfdd}|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)rtzrcrdrs       z-run_with_tz..decorator..inner)r`r)rr)r)rrdrszrun_with_tz..decoratorrc)rrrc)rrdr\s 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_1Grurv IGNORECASEVERBOSErrfloatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitZsizesrZmemlimitrcrcrdrYs $ c@s$eZdZddZddZddZdS)_MemoryWatchdogcCsdjtjd|_d|_dS)Nz/proc/{pid}/statm)r0F)rrr.procfilestarted)rfrcrcrdrgsz_MemoryWatchdog.__init__cCsyt|jd}Wn<tk rL}z tjdj|ttjj dSd}~XnXt d}t j tj |g|t jd|_|jd|_dS)Nrz!/proc not available for stats: {}zmemory_watchdog.py)rrT)r<r rrfrrrrnrflushr subprocessPopen executableZDEVNULL mem_watchdogrr )rfrrZwatchdog_scriptrcrcrdstarts   z_MemoryWatchdog.startcCs|jr|jj|jjdS)N)r rZ terminatewait)rfrcrcrdstops z_MemoryWatchdog.stopN)r`rarbrgrrrcrcrcrdr sr csfdd}|S)Ncs 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@) rmemuserrrrsrrrr rr)rfrrmaxsizeZwatchdog)dry_runrrrcrdrs*    z.bigmemtest..decorator..wrapper)rr)r)rrr)rrrdrszbigmemtest..decoratorrc)rrrrrc)rrrrdr3s !csfdd}|S)NcsDttkr8td kr$td kr$tjdq@tjdtd n|SdS) Nr?rz-not enough memory: try a 32-bit build insteadz'not enough memory: %.1fG minimum neededir)llli@)rrrrrs)rf)rrcrdr3sz!bigaddrspacetest..wrapperrc)rrrc)rrdr41s c@seZdZddZdS)r,cCstj}|||S)N)rrZ TestResult)rfrrrcrcrdrunDszBasicTestRunner.runN)r`rarbrrcrcrcrdr,CscCs|S)Nrc)rrcrcrd_idIsrcCs<|dkrt rtjtjSt|r(tStjdj|SdS)Nrzresource {0!r} is not enabled)rrrskiprr rr)rrcrcrdrequires_resourceLs  rcCs&trt|krtjd|tfStSdS)Nz%s at Android API level %d)rA_ANDROID_API_LEVELrrrr)levelrrcrcrdr>Ts  cCstdd|S)NT)cpython) impl_detail)rrcrcrdr5[scKsVtf|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 ) rBr _parse_guardsrCrrrrrr)rwguardsZ guardnamesdefaultrcrcrdr!as   r!c CsTtdkr:ddl}y|jdaWntk r8daYnXd}trF|Stj||S)NrTFz6requires a functioning shared semaphore implementation)_have_mp_queuemultiprocessingZQueuermrrr)rr&rwrcrcrdr?os cCs*|sddidfSt|jd}|| fS)Nr TFr)r{values)r#Zis_truercrcrdr"~s r"cKs t|\}}|jtjj|S)N)r"r\roZpython_implementationr)r#r$rcrcrdrBs cs,ttdsStjfdd}|SdS)Ngettracec s.tj}ztjd||Stj|XdS)N)rnr(settrace)rrZoriginal_trace)rrcrdrs   zno_tracing..wrapper)rrnrr)rrrc)rrd no_tracings r*cCs tt|S)N)r*r5)rrcrcrd refcount_testsr+cCsRg}xB|jD]8}t|tjr2t|||j|q ||r |j|q W||_dS)N)Z_testsrrr TestSuite _filter_suiter)suiteZpredZnewtestsrrcrcrdr-s    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)N) verbosityZcapture_outputrrzmultiple errors occurredz!; run in verbose mode for details)rrnrrjunit_xml_listrrZget_xml_elementZtestsRunr Z wasSuccessfulrerrorsZfailuresr )r.Zrunnerrrrcrcrd _run_suites"  r2cCstdkr dSt|jSdS)NT)_match_test_funcid)rrcrcrd match_testsr5cCsd|kotjd| S)Nrxz[?*\[\]])rusearch)rrcrcrd_is_full_match_testsr7csr|tkr dS|sd}f}nHttt|r4t|j}n.djttj|}t j |j fdd}|}t |a|a dS)N|cs$|r dStt|jdSdS)NTrx)anyrr)Ztest_id) regex_matchrcrdmatch_test_regexsz)set_match_tests..match_test_regex)_match_test_patternsallrr7r __contains__rfnmatch translaterurMrvrqr3)ZpatternsrZregexr;rc)r:rdset_match_testss   rAcGstjtjf}tj}xh|D]`}t|trT|tjkrJ|jtjtj|qzt dqt||rj|j|q|jtj |qWt |t t |dS)Nz)str arguments must be keys in sys.modules)rrr,ZTestCaserrtrnryZaddTestZ findTestCasesrZ makeSuiter-r5r2)classesZ valid_typesr.clsrcrcrdr-s        cCsdS)Nrcrcrcrcrd_check_docstrings(srDWITH_DOC_STRINGSztest requires docstringscCs`ddl}|dkrt}nd}|j|||d\}}|rBtd||ftrXtd|j|f||fS)Nr)r optionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)doctestrZtestmodr rr`)rr/rFrGrrrcrcrdr.9scCs tjjfS)N)rnryrrcrcrcrd modules_setupTsrHcCs:ddtjjD}tjjtjj|tjj|dS)NcSs"g|]\}}|jdr||fqS)z encodings.)rp)rArrrcrcrdrB[sz#modules_cleanup..)rnryrrrr)Z oldmodulesZ encodingsrcrcrdmodules_cleanupWs  rIcCs"trtjtjjfSdffSdS)Nr)_thread_count threading _danglingrrcrcrcrdrNzscGsJtsdSd}x8t|D],}tjtjf}||kr2PtjdtqWdS)Ndg{Gz?)rJrangerKrLrMrrr)Zoriginal_valuesZ _MAX_COUNTcountr'rcrcrdrOs cs"tsStjfdd}|S)Nc st}z|St|XdS)N)rNrO)rkey)rrcrdrszreap_threads..decorator)rJrr)rrrc)rrdrPsN@ccstj}z dVWdtj}||}xjtj}||kr8Ptj|kr|tj|}d||d|dd|d|d }t|tjdtq&WXdS)Nz!wait_threads() failed to cleanup z threads after z.1fz seconds (count: z , old count: )g{Gz?)rJrKrZ monotonicrzrr)rZ old_countZ start_timeZdeadlinerPZdtrwrcrcrdwait_threads_exits   $ rTc CsZttdrVd}xFy2tj|tj\}}|dkr.Ptd|tjdWqPYqXqWdS)Nwaitpidrrz2Warning -- reap_children() reaped child process %s)rrX)rrrUWNOHANGrrnr)Z any_processr0ZstatusrcrcrdrLs 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 j t j td t|XXdS) Nz/Can't start %d threads, only %d threads startedrr<g{Gz?cSsg|]}|jr|qSrc)isAlive)rArrcrcrdrBsz!start_threads..z7Unable to join %d threads during a period of %d minutescSsg|]}|jr|qSrc)rX)rArrcrcrdrBszUnable to join %d threads)r{rrrrrrrOrmax faulthandlerZdump_tracebackrnrrz)ZthreadsZunlockr rZendtimeZ starttimerrcrcrdrQs>     c csnt||rtt|tt|}|r(|t|8}tdd|D}|S)Ncss(|] }|jd s|jdr|VqdS)___N)rpendswith)rArrcrcrd sz&detect_api_mismatch..)rrx)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)Nrra) r`rrtrrxrprrtypes ModuleTypeaddZassertCountEqual__all__)Z test_caserZname_of_moduleZextraZ blacklistZexpectedrurrcrcrdr= s)    c@s$eZdZdZdZddZddZdS)rZNc Csrtjjdrddl}|jj|_d}|jj||_|jj|j|Byddl }|j Wnt t fk rlYnLXi|_ x|j|j|jgD].}|j ||j}|j||j}||f|j |<qWntdk r y*tjtj|_tjtjd|jdfWnttfk rYnXtjdkrndddd g}tj|tjtjd }||jd} WdQRX| jd krntd d dd|S)Nrrrrrz/usr/bin/defaultsr]zcom.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 getrlimit RLIMIT_CORE setrlimitrrrrPIPEZ communicaterar) rfrZSEM_NOGPFAULTERRORBOXr report_typeold_modeold_filecmdprocrrcrcrdr2 sN        zSuppressCrashReport.__enter__c Gs|jdkrdStjjdrl|jj|j|jrddl}xj|jjD]$\}\}}|j |||j ||qBWn6t dk ryt j t j |jWnttfk rYnXdS)Nrr)rrnrorprrrrrrrrrrrr)rfrrrrrrcrcrdrs s   zSuppressCrashReport.__exit__)r`rarbrrrrrcrcrcrdrZ) sAc srtdyjWn$ttfk r@tdYnXdfdd}|j|t|dS)NFTcs rtn tdS)N)rr[rc) attr_is_local attr_nameobject_to_patchrrcrdcleanup szpatch..cleanup)rrjrrZ addCleanupr)Z test_instancerrZ new_valuerrc)rrrrrdpatch s  rc CsFy ddl}Wntk r YnX|jr4tjdddl}|j|S)NrzUrun_in_subinterp() cannot be used if tracemalloc module is tracing memory allocations) tracemallocrmZ is_tracingrrrsrrun_in_subinterp)rrrrcrcrdr s  rcsHGfddd|}d||||jttt|jdS)NcseZdZfddZdS)z%check_free_after_iterating..Ac s*dy tWntk r$YnXdS)NT)next StopIteration)rf)doneitrcrd__del__ s  z-check_free_after_iterating..A.__del__N)r`rarbrrc)rrrcrdA srF)rKrrrZ assertTrue)rrrCrrrc)rrrdcheck_free_after_iterating s   rcCs|ddlm}m}m}|j}|j|xP|jD]F}|r@||kr@q.t||}|rPn |dkrZq.|j|ddkr.|dSq.WdS)Nr) ccompilerrspawn) Z distutilsrrrZ new_compilerZcustomize_compilerZ executablesrZfind_executable)Z cmd_namesrrrZcompilerrurrcrcrdr^ s     cCs@d}tr6||kr6tdkr.tjddgjdkatr6|}tj|S)Ngh㈵>Zgetpropzro.kernel.qemu1)rA_is_android_emulatorrZ check_outputrarnrD)ZintervalZminimum_intervalrcrcrdrD s c cs>tjj}tj}ztjdVWd|r8tj|ddXdS)NT)rZ all_threads)rnrrFrZ is_enabledrr)r@rrcrcrddisable_faulthandler s  rc /Cstjjd r8ytjd}t|dStk r6YnXd}ttdrjytjd}Wnt k rhYnXd}tjdkryd dl }|j Wnt 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) Nlinuxfreebsdz /proc/self/fdrsysconf SC_OPEN_MAXrr)rr)rnrorprrrrrrrrrrrmrrrrOduprZEBADFr) namesZMAXFDrrrrPr@Zfd2rrcrcrdr_ sP          c@s$eZdZddZddZddZdS) SaveSignalsc Csjddl}||_ttd|j|_x>dD]6}yt||}Wntk rNw&YnX|jj|q&Wi|_dS)NrrSIGKILLSIGSTOP)rr) signalr{rONSIGsignalsrrryrf)rfrZsignamesignumrcrcrdrgM s zSaveSignals.__init__cCs4x.|jD]$}|jj|}|dkr"q||j|<qWdS)N)rr getsignalrf)rfrhandlerrcrcrdsaveZ s   zSaveSignals.savecCs*x$|jjD]\}}|jj||q WdS)N)rfrr)rfrrrcrcrdrestoref szSaveSignals.restoreN)r`rarbrgrrrcrcrcrdrD s   rc@s$eZdZddZddZddZdS)FakePathcCs ||_dS)N)r)rfrrcrcrdrgn szFakePath.__init__cCsd|jdS)Nz )r)rfrcrcrd__repr__q szFakePath.__repr__cCs6t|jts$t|jtr,t|jtr,|jn|jSdS)N)rr BaseExceptionrrx)rfrcrcrd __fspath__t s    zFakePath.__fspath__N)r`rarbrgrrrcrcrcrdrk src cs.tj}ztj|dVWdtj|XdS)N)rnget_int_max_str_digitsset_int_max_str_digits)Z max_digitsZcurrentrcrcrdadjust_int_max_str_digits| s   rcCsddtddDdgS)NcSsg|] }t|qSrc)chr)rArrcrcrdrB sz)control_characters_c0..r )rOrcrcrcrdcontrol_characters_c0 sr)T)F)F)N)Nii@i@i@ii) rrrrrrrrrr r!)r%r#r&r'r()NF)F)r5F)N)Fi@ii)T)N)Nr)rR)N(r`rmcollections.abc collections contextlibZdatetimerrZr?rrrrlimportlib.utilrZlogging.handlersrerrrorurrrrrrnrr*rrrrZ urllib.errorr_rfZ testresultrrJrLZmultiprocessing.processr&zlibrVbz2Zlzmarrrrr r r rsr contextmanagerrjr r~rr:r;rr6rrrrr0rrrrrrrprrrrrrrrrrrr r!rr"r#r$r%rErrr rGrHrJrrFrrZ SOCK_MAX_SIZEZ skipUnlessr __getformat__r7r9r0r1r2r@rrrArCrurrr.Z FS_NONASCII characterfsdecodefsencode UnicodeErrorZTESTFN_UNICODEZ unicodedata normalizegetfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversionencodeUnicodeEncodeErrorrdecodeUnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIr2rr]r}r1r4rrrKrrrrZTEST_SUPPORT_DIRr9rr[rrr[rGr&rIobjectrcrrRrrrSrabcMutableMappingrTrr'rrr(rr)r*r+rrrrrrrrrrrrrrrrUr\rrrZ_4GrrrYr r3r4r,rrr>r5r!r%r?r"rBr*r+r-r2r3r<r5r7rAr-rDZMISSING_C_DOCSTRINGSrZHAVE_DOCSTRINGSZrequires_docstringsr.rHrIZenvironment_alteredrNrOrPrTrLrQrWrVrbZskipIfZrequires_type_collectingrcrdrfrgrMrXrrrr/rzr|r8r~rr<r=rZrrrr^rrDrr_rrrrrcrcrcrds                      2   !  J    > %                 %      2 ' 5M           $ # 0           (        " #   "    :_"  ;' PK!8\p?p?+support/__pycache__/__init__.cpython-36.pycnu[3 _Vj@sl dZedkredddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZ ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl!Z"ddl#Z#ddl$m%Z%yddl&Z&ddl'Z'Wnek rBdZ&dZ'YnXy ddl(Z)Wnek rjdZ)YnXy ddl*Z*Wnek rdZ*YnXy ddl+Z+Wnek rdZ+YnXy ddl,Z,Wnek rdZ,YnXy ddl-Z-Wnek r dZ-YnXy ddl.Z.Wnek r2dZ.YnXy ddl/Z/Wnek rZdZ/YnXddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbg\Z0Gdcd d e1Z2Gddd d e2Z3Gdedde2Z4Gdfdde j5Z6ej7dhdhdiZ8difdkdldZ9dmdnZ:dodpZ;dqd=ZZ=ffdjfdsdZ>dtd9Z?dZ@dZAdaBdaCdZDdjZEdaFdudZGdvdZHdwdZIdxdyZJejjKdzr.djd{d|ZLd}d~ZMddZNddZOddZPnejQZMejRZNddZOddZPddZQddZRddZSddZTddZUddZVdd#ZWdkdd$ZXddZYdd%ZZdd&Z[dd'Z\dldd(Z]dZ^dZ_ej`ejafddJZbe^fddKZcddMZdddZeeeZfddZgdoZhdrZie jjekjldjKddZme jje*dZne jje+dZoe jje,dZpe jje-dZqejjKdZrejsdZtetdk oxetdkZuejdkreurdndZvndZvejwdkrdZxndZxdjyexejzZxdZ{xLdsD]BZ|yej}ej~e|e|kreWnek rYnXe|Z{PqWexdZejdkr:ddlZejdeZejZdZejwdkrejjdkrexdZyejeWnek rYnXedeefdZnBejdkrydjeWn&ek rexdjedǃZYnXdZxFdtD]dYZd?d@Ze jeedAdBZdCdDZdEdFZGdGdPdPejjZGdHd[d[eZdadId!ZdJd2ZdadKdLZdMd;ZdNdOZdPd"ZfdQdRd?Z dfffdSd@Z GdTd]d]Z dUdVZ dWdXZ ffdYdZZgfd[daZdad\dGZej7d]d^Zd_dbZGd`dadaZGdbdcdcZej7dddeZdfdgZdS(z7Supporting 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_module CleanImportunloadforgetrecord_original_stdoutget_original_stdoutcaptured_stdoutcaptured_stdincaptured_stderrTESTFNSAVEDCWDunlinkrmtreetemp_cwdfindfilecreate_empty_file can_symlinkfs_is_case_insensitiveis_resource_enabledrequiresrequires_freebsd_versionrequires_linux_versionrequires_mac_verrequires_hashdigestcheck_syntax_errorTransientResourcetime_outsocket_peer_resetioerror_peer_resettransient_internetBasicTestRunner run_unittest run_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_children TestHandlerthreading_setupthreading_cleanup reap_threads start_threadscheck_warningscheck_no_resource_warningEnvironmentVarGuardrun_with_locale swap_item swap_attrMatcher set_memlimitSuppressCrashReportsortdict run_with_tzPGOmissing_compiler_executablefd_countc@seZdZdZdS)r z*Base class for regression test exceptions.N)__name__ __module__ __qualname____doc__rdrd-/usr/lib64/python3.6/test/support/__init__.pyr |sc@seZdZdZdS)r z Test failed.N)r`rarbrcrdrdrdrer sc@seZdZdZdS)r zTest did not run any subtests.N)r`rarbrcrdrdrdrer 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`rarbrcrdrdrdrer sTc cs8|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)rfrdrdre_ignore_deprecated_importss  rkF) 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) rk importlibr ImportErrorsysplatform startswithtupleunittestSkipTeststr)name deprecatedrlmsgrdrdrer 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)romodules __import__listrq)rv orig_modulesmodnamerdrdre_save_and_remove_modules rc Cs>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)rorzKeyError)rvr}Zsavedrdrdre_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)Nrd)frdrdresz$anticipate_failure..)rsZexpectedFailure)Z conditionrdrdrer:scCsF|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_testsrdrdrer;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) rkrrappendrmr rnitemsrorz) rvZfreshZblockedrwr}Znames_to_removeZ fresh_nameZ blocked_nameZ fresh_moduleZ orig_namemoduleZname_to_removerdrdrers$      c Cs>yt||}Wn&tk r4tjd||fYnX|SdS)z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %rN)getattrAttributeErrorrsrt)objrvZ attributerdrdrer6s cCs|adS)N)_original_stdout)stdoutrdrdrer0scCs tptjS)N)rrorrdrdrdrer4sc Cs&y tj|=Wntk r YnXdS)N)rorzr)rvrdrdrer7s cGsny||Stk rh}zDtdkrHtd|jj|ftd|j|ftj|tj||Sd}~XnXdS)Nz%s: %sz re-run %s%r) OSErrorrprint __class__r`rchmodstatS_IRWXU)rfuncargserrrdrdre _force_run=srwincCs|||r|}ntjj|\}}|p(d}d}x<|dkrjtj|}|rJ|n||ksVdStj||d9}q0Wtjd|tdddS)NrygMbP?g?rz)tests may fail, delete still pending for ) stacklevel) rrsplitlistdirtimesleeprgwarnRuntimeWarning)rpathnamewaitallrrvtimeoutLrdrdre_waitforHs     rcCsttj|dS)N)rrr)filenamerdrdre_unlinkisrcCsttj|dS)N)rrrmdir)rrdrdre_rmdirlsrcs,fddt|ddtdd|dS)Ncsxt|tj|D]}tjj||}ytj|j}Wn<tk rn}z td||ft j dd}WYdd}~XnXt j |rt |ddt|tj|qt|tj|qWdS)Nz-support.rmtree(): os.lstat(%r) failed with %s)filerT)r)rrrrjoinlstatst_moderrro __stderr__rS_ISDIRrrr)rrvfullnamemodeexc) _rmtree_innerrdrerps   z_rmtree.._rmtree_innerT)rcSst|tj|S)N)rrr)prdrdrersz_rmtree..)r)rrd)rre_rmtreeos rc Cs^y ddl}Wntk r Yn:X|jt|d}|jjj||t|}|rZ|d|S|S)Nrr)ctypesrnZcreate_unicode_bufferlenwindllkernel32ZGetLongPathNameW)rrbufferZlengthrdrdre _longpaths    rc sFytj|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)rrvrr)rrdrers  z_rmtree.._rmtree_inner)shutilrrrr)rrd)rrers  cCs|S)Nrd)rrdrdrersc Cs*y t|Wnttfk r$YnXdS)N)rFileNotFoundErrorNotADirectoryError)rrdrdrers c Cs&y t|Wntk r YnXdS)N)rr)rrdrdrers rc Cs&y t|Wntk r YnXdS)N)rr)rrdrdrers 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) rmutilcache_from_sourcerrrabspathrrename)sourceZpyc_fileZup_oneZ legacy_pycrdrdremake_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) rrorrrrrmrr)r~rroptrdrdrers    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..USEROBJECTFLAGSZfInheritZ fReserveddwFlagsN)r`rarbwintypesZBOOLDWORD_fields_rd)rrdreUSEROBJECTFLAGSs  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..ProcessSerialNumberZ highLongOfPSNZ lowLongOfPSNN)r`rarbrrd)rrdreProcessSerialNumbersrz#cannot run without OS X gui process)Tk2z [...]zTk unavailable due to {}: {}))hasattr_is_gui_availablerrorprqrZctypes.wintypesrrZuser32ZGetProcessWindowStationZWinErrorrrZGetUserObjectInformationWZbyrefZsizeofboolrrrrZ ctypes.utilrZ LoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterrZwithdrawupdateZdestroy Exceptionrurformattyper`reason)rZ UOI_FLAGSZ WSF_VISIBLErZdllhZuofZneededresrrrrZ app_servicesrZpsnZpsn_prrooteZ err_stringrd)rrrersh         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)resourcerdrdrer $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)rrxrdrdrer!,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 j d||f||S)N-rrryz(%s version %s or higher required, not %s) rpsystemreleaserrrmapint ValueErrorrrursrt)rkw version_txtversionmin_version_txt)r min_versionsysnamerdrewrapper=s z:_requires_unix_version..decorator..wrapper) functoolswrapsr)rr)rr)rre decorator<sz)_requires_unix_version..decoratorrd)rrrrd)rrre_requires_unix_version5srcGs 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)rrdrdrer"PscGs 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)rrdrdrer#Yscsfdd}|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 j d||f||S)Nrrryz&Mac OS X %s or higher required, not %s) rorpZmac_verrrrrrrrrursrt)rrrrr)rrrdrerjs   z4requires_mac_ver..decorator..wrapper)rrr)rr)r)rrerisz#requires_mac_ver..decoratorrd)rrrd)rrer$bs csfdd}|S)aDecorator raising SkipTest if a hashing algorithm is not available The hashing algorithm could be missing or blocked by a strict crypto policy. If 'openssl' is True, then the decorator checks that OpenSSL provides the algorithm. Otherwise the check falls back to built-in implementations. ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS ValueError: unsupported hash type md4 cstjfdd}|S)Nc sXy&rtdk rtjn tjWn&tk rLtjddYnX||S)Nz hash digest 'z' is not available.)_hashlibnewhashlibrrsrt)rkwargs) digestnameropensslrdrers  z7requires_hashdigest..decorator..wrapper)rr)rr)rr)rrers z&requires_hashdigest..decoratorrd)rrrrd)rrrer%}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. )socketrHclose)familyZsocktypeZtempsockportrdrdrerGs 8 c Cs|jtjkr|jtjkrttdr>|jtjtjdkr>t dttdr~y |jtjtj dkrft dWnt k 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_INETr SOCK_STREAMrZ getsockoptZ SOL_SOCKETrr rrZ setsockoptrbindZ getsockname)sockhostrrdrdrerHs     c CsJ|jtjksty|j|Wn&tk rD|jtjdYnXdS)zBBind a unix socket, raising SkipTest if PermissionError is raised.zcannot bind AF_UNIX socketsN) rrZAF_UNIXAssertionErrorr PermissionErrorrrsrt)r ZaddrrdrdrerJs cCsZtjrVd}z.dec)rr)rrrd)rresystem_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) tempfilemkdtemprrrealpathmkdirrrgrrgetpidr)rquietZ dir_createdpidrdrdretemp_dirs&   r3ccsftj}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)rgetcwdchdirrrgrr)rr1Z saved_dirrdrdre change_cwd s  r6tempcwdccs: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. )rr1)r1N)r3r6)rvr1Z temp_pathZcwd_dirrdrdrer$sumaskc cs&tj|}z dVWdtj|XdS)z8Context manager that temporarily sets the process umask.N)rr8)r8ZoldmaskrdrdrerK8s  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_DIRroexists)rZsubdirrZdnfnrdrdrerIs    cCs(tj|tjtjBtjB}tj|dS)z>Create an empty file. If the file already exists, truncate it.N)ropenO_WRONLYO_CREATO_TRUNCr)rfdrdrdrer[scCs,t|j}dd|D}dj|}d|S)z%Like repr(dict), but in sorted order.cSsg|] }d|qS)z%r: %rrd).0Zpairrdrdre cszsortdict..z, z{%s})sortedrr)dictrZ reprpairsZ withcommasrdrdrer[`s  c Cs*ttd}z|jS|jttXdS)z` Create an invalid file descriptor by opening and closing a file and return its fd. wbN)r>rfilenorr)rrdrdre make_bad_fdgs  rI)linenooffsetc Csp|jt}t|ddWdQRX|j}|j|j|dk rJ|j|j||j|j|dk rl|j|j|dS)Nz exec) assertRaises SyntaxErrorcompileZ exceptionZassertIsNotNonerJ assertEqualrK)testcaseZ statementrJrKcmrrdrdrer&ss   c sVddl}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)r>seekr)r=r)rrSrrdrecheck_valid_files z*open_urlresource..check_valid_fileZurlfetchz fetching %s ...)rAccept-Encodinggzip)rzContent-Encoding)ZfileobjrGzinvalid resource %r)rWrX)Zurllib.requestZ urllib.parsepopparseZurlparserrrr TEST_DATA_DIRr<rr!rrrZrequestZ build_openerrXZ addheadersrr>ZheadersgetZGzipFilereadwriterr ) Zurlrrurllibrr=rVropeneroutsrd)rrSrrerI~s<         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_listrdrdre__init__szWarningsRecorder.__init__cCsDt|j|jkr t|jd|S|tjjkr0dStd||fdS)Nrz%r has no attribute %rrZ)rrfrgrrgWarningMessage_WARNING_DETAILSr)rhattrrdrdre __getattr__s  zWarningsRecorder.__getattr__cCs|j|jdS)N)rfrg)rhrdrdrergszWarningsRecorder.warningscCst|j|_dS)N)rrfrg)rhrdrdreresetszWarningsRecorder.resetN) r`rarbrcrirmpropertyrgrnrdrdrdreres  rec 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)recordrgalwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)ro _getframe f_globalsr^clearrgrhrz simplefilterrer|messagerematchruI issubclassrremoverr`r) filtersr1frameregistrywZreraiseZmissingrxcatseenZwarningrdrdre_filterwarningss0    rcOs.|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) r1rNT)r^Warningr)r|rr1rdrdrerRs   rc csHtjdd&}tjd||ddV|r.tWdQRX|j|gdS)aContext manager to check that no warnings are emitted. This context manager enables a given warning within its scope and checks that no warnings are emitted even with that warning enabled. If force_gc is True, a garbage collection is attempted before checking for warnings. This may help to catch warnings emitted when objects are deleted, such as ResourceWarning. Other keyword arguments are passed to warnings.filterwarnings(). T)rprq)rvcategoryN)rgrhri gc_collectrP)rQrvrZforce_gcwarnsrdrdrecheck_no_warningssrc csBtjdd }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)rprq)rN)rgrhriResourceWarningrrP)rQrrdrdrerSs 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)rorzcopyoriginal_modulesr`)rhZ module_namesZ module_namerrdrdreri?s      zCleanImport.__init__cCs|S)Nrd)rhrdrdre __enter__LszCleanImport.__enter__cGstjj|jdS)N)rorzrr)rh ignore_excrdrdre__exit__OszCleanImport.__exit__N)r`rarbrcrirrrdrdrdrer3s  c@sheZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZdS)rTz_Class to help protect the environment variable properly. Can be used as a context manager.cCstj|_i|_dS)N)renviron_environ_changed)rhrdrdreriXszEnvironmentVarGuard.__init__cCs |j|S)N)r)rhenvvarrdrdre __getitem__\szEnvironmentVarGuard.__getitem__cCs*||jkr|jj||j|<||j|<dS)N)rrr^)rhrvaluerdrdre __setitem___s zEnvironmentVarGuard.__setitem__cCs2||jkr|jj||j|<||jkr.|j|=dS)N)rrr^)rhrrdrdre __delitem__es  zEnvironmentVarGuard.__delitem__cCs |jjS)N)rkeys)rhrdrdrerlszEnvironmentVarGuard.keyscCs t|jS)N)iterr)rhrdrdre__iter__oszEnvironmentVarGuard.__iter__cCs t|jS)N)rr)rhrdrdre__len__rszEnvironmentVarGuard.__len__cCs |||<dS)Nrd)rhrrrdrdresetuszEnvironmentVarGuard.setcCs ||=dS)Nrd)rhrrdrdreunsetxszEnvironmentVarGuard.unsetcCs|S)Nrd)rhrdrdrer{szEnvironmentVarGuard.__enter__cGsJx<|jjD].\}}|dkr0||jkr:|j|=q ||j|<q W|jt_dS)N)rrrrr)rhrkvrdrdrer~s   zEnvironmentVarGuard.__exit__N)r`rarbrcrirrrrrrrrrrrdrdrdrerTSsc@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)rororiginal_valueoriginal_objectextend)rhpathsrdrdreriszDirsOnSysPath.__init__cCs|S)Nrd)rhrdrdrerszDirsOnSysPath.__enter__cGs|jt_|jtjdd<dS)N)rrorr)rhrrdrdrerszDirsOnSysPath.__exit__N)r`rarbrcrirrrdrdrdrers 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)rhrrrdrdreriszTransientResource.__init__cCs|S)Nrd)rhrdrdrerszTransientResource.__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)rzrrrrrr )rhZtype_r tracebackrlZ attr_valuerdrdrers zTransientResource.__exit__)NNN)r`rarbrcrirrrdrdrdrer's)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}~Xnt k rZ}zpx^|j }t |d krt |dt r|d}n*t |dkr8t |d t r8|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 EHOSTUNREACHq ENETUNREACHe ETIMEDOUTn EADDRNOTAVAILc EAI_AGAINr+EAI_FAILr EAI_NONAMEr EAI_NODATA WSANO_DATA*zResource %r is not availablecSsg|]\}}tt||qSrd)rr)rCrvnumrdrdrerDsz&transient_internet..cSsg|]\}}tt||qSrd)rr)rCrvrrdrdrerDscst|dd}t|tjst|tjr,|kst|tjjrTd|jkoNdknst|tjj rd|j ksd|j ksd|j ks|krt st j jjdd|dS) NriiWConnectionRefusedError TimeoutErrorEOFErrorr )r isinstancerrZgaierrorraerrorZ HTTPErrorcodeZURLErrorrrrostderrr`r)rn)captured_errnosdenied gai_errnosrdre filter_errors     z(transient_internet..filter_errorNrrr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)r rZgetdefaulttimeoutZsetdefaulttimeoutnntplibZNNTPTemporaryErrorrrorr`rrrr) Z resource_namerrZdefault_errnosZdefault_gai_errnosrZ old_timeoutrard)rrrrer+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)iorrosetattrStringIO)Z stream_namerZ orig_stdoutrdrdrecaptured_outputs  rcCstdS)zCapture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") r)rrdrdrdrerscCstdS)zCapture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") r)rrdrdrdrer%scCstdS)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)rrdrdrdrer.s 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@rrrdrdrdrer;s  rc cs.tj}tjz dVWd|r(tjXdS)N)r isenableddisableenable)Zhave_gcrdrdre disable_gcKs  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_varrrq)ZcflagsZ final_optrrdrdrepython_is_optimizedVs  rZnPZ0ngettotalrefcountZ2PZ0PrcCstjt|tS)N)structcalcsize_header_align)fmtrdrdre calcobjsizegsrcCstjt|tS)N)rr_vheaderr)rrdrdre calcvobjsizejsr cCspddl}tj|}t|tkr(|jt@sBt|tkrLt|jt@rL||j7}dt|||f}|j|||dS)Nrz&wrong size for %s: got %d, expected %d) _testcapiro getsizeofr __flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADrP)testosizerrrxrdrdre check_sizeofqs  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)rkwdsrrZ orig_localeloc)catstrrlocalesrdreinners$     z1run_with_locale..decorator..inner)r`rc)rr)rr)rrersz"run_with_locale..decoratorrd)rrrrd)rrrerUscsfdd}|S)Ncs"fdd}j|_j|_|S)Ncsy tj}Wntk r(tjdYnXdtjkr@tjd}nd}tjd<|z ||S|dkrrtjd=n |tjd<tjXdS)Nztzset requiredZTZ)rtzsetrrsrtrr)rrrZorig_tz)rtzrdrers       z-run_with_tz..decorator..inner)r`rc)rr)r)rrerszrun_with_tz..decoratorrd)rrrd)rrer\s 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_1Grwrx IGNORECASEVERBOSErrfloatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitZsizesrZmemlimitrdrdrerYs $ c@s(eZdZdZddZddZddZdS) _MemoryWatchdogz`An object which periodically watches the process' memory consumption and prints it out. cCsdjtjd|_d|_dS)Nz/proc/{pid}/statm)r2F)rrr0procfilestarted)rhrdrdrerisz_MemoryWatchdog.__init__cCsyt|jd}Wn<tk rL}z tjdj|ttjj dSd}~XnXt d}t j tj |g|t jd|_|jd|_dS)Nrz!/proc not available for stats: {}zmemory_watchdog.py)rrT)r>r rrgrrrrorflushr subprocessPopen executableZDEVNULL mem_watchdogrr )rhrrZwatchdog_scriptrdrdrestarts   z_MemoryWatchdog.startcCs|jr|jj|jjdS)N)r rZ terminatewait)rhrdrdrestops z_MemoryWatchdog.stopN)r`rarbrcrirrrdrdrdrer sr csfdd}|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@) rmemuserrsrtrrrr rr)rhrrmaxsizeZwatchdog)dry_runrrrdrers*    z.bigmemtest..decorator..wrapper)rr)r)rrr)rrrerszbigmemtest..decoratorrd)rrrrrd)rrrrer3s !csfdd}|S)z0Decorator for tests that fill the address space.csDttkr8td kr$td kr$tjdq@tjdtd n|SdS) Nr?rz-not enough memory: try a 32-bit build insteadz'not enough memory: %.1fG minimum neededir+llli@)rrrsrt)rh)rrdrer3sz!bigaddrspacetest..wrapperrd)rrrd)rrer41s c@seZdZddZdS)r,cCstj}|||S)N)rsZ TestResult)rhrrrdrdrerunDszBasicTestRunner.runN)r`rarbrrdrdrdrer,CscCs|S)Nrd)rrdrdre_idIsrcCs<|dkrt rtjtjSt|r(tStjdj|SdS)Nrzresource {0!r} is not enabled)rrsskiprr rr)rrdrdrerequires_resourceLs  rcCs&trt|krtjd|tfStSdS)Nz%s at Android API level %d)rA_ANDROID_API_LEVELrsrr)levelrrdrdrer>Ts  cCstdd|S)z9 Decorator for tests only applicable on CPython. T)cpython) impl_detail)rrdrdrer5[scKsVtf|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 ) rBr _parse_guardsrErrrrsr)rxguardsZ guardnamesdefaultrdrdrer!as   r!c CsTtdkr:ddl}y|jdaWntk r8daYnXd}trF|Stj||S)z8Skip decorator for tests that use multiprocessing.Queue.NrTFz6requires a functioning shared semaphore implementation)_have_mp_queuemultiprocessingZQueuernrsr)rr&rxrdrdrer?os cCsH|sddidfSt|jd}t|j|gt|ks>t|| fS)Nr TFr)r|valuesrr)r#Zis_truerdrdrer"~s  r"cKs 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 )r"r^rpZpython_implementationr)r#r$rdrdrerBs cs,ttdsStjfdd}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.gettracec s.tj}ztjd||Stj|XdS)N)ror(settrace)rrZoriginal_trace)rrdrers   zno_tracing..wrapperN)rrorr)rrrd)rre no_tracings 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*r5)rrdrdre refcount_testsr+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_testsrrs TestSuite _filter_suiter)suiteZpredZnewtestsrrdrdrer-s    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)rrorrjunit_xml_listrrZget_xml_elementZtestsRunr Z wasSuccessfulrerrorsZfailuresr )r.Zrunnerrrrdrdre _run_suites"  r2cCstdkr dSt|jSdS)NT)_match_test_funcid)rrdrdre match_testsr5cCsd|kotjd| S)Nryz[?*\[\]])rwsearch)rrdrdre_is_full_match_testsr7csr|tkr dS|sd}f}nHttt|r4t|j}n.djttj|}t j |j fdd}|}t |a|a dS)N|cs$|r dStt|jdSdS)NTry)anyrr)Ztest_id) regex_matchrdrematch_test_regexsz)set_match_tests..match_test_regex)_match_test_patternsallrr7r __contains__rfnmatch translaterwrOrxrrr3)ZpatternsrZregexr;rd)r:reset_match_testss   rAcGstjtjf}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)rsr,ZTestCaserrurorzZaddTestZ findTestCasesrZ makeSuiter-r5r2)classesZ valid_typesr.clsrdrdrer-s        cCsdS)z,Just used to check if docstrings are enabledNrdrdrdrdre_check_docstrings(srDWITH_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)r optionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)doctestrZtestmodr rr`)rr/rFrGrrrdrdrer.9scCs tjjfS)N)rorzrrdrdrdre modules_setupTsrHcCs:ddtjjD}tjjtjj|tjj|dS)NcSs"g|]\}}|jdr||fqS)z encodings.)rq)rCrrrdrdrerD[sz#modules_cleanup..)rorzrrtr)Z oldmodulesZ encodingsrdrdremodules_cleanupWs  rIcCs"trtjtjjfSdffSdS)Nr)_thread_count threading _danglingrrdrdrdrerNzscGsJtsdSd}x8t|D],}tjtjf}||kr2PtjdtqWdS)Ndg{Gz?)rJrangerKrLrMrrr)Zoriginal_valuesZ _MAX_COUNTcountr'rdrdrerOs 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. c st}z|St|XdS)N)rNrO)rkey)rrdrerszreap_threads..decorator)rJrr)rrrd)rrerPsN@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?)rJrKrZ monotonicrrr)rZ old_countZ start_timeZdeadlinerPZdtrxrdrdrewait_threads_exits   $ rTc 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)rNrZ)rrrUWNOHANGrror)Z any_processr2ZstatusrdrdrerLs 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 j t j td t|XXdS) Nz/Can't start %d threads, only %d threads startedrr<g{Gz?cSsg|]}|jr|qSrd)isAlive)rCrrdrdrerDsz!start_threads..z7Unable to join %d threads during a period of %d minutescSsg|]}|jr|qSrd)rX)rCrrdrdrerDszUnable to join %d threads)r|rrrrrrrOrmax faulthandlerZdump_tracebackrorr)ZthreadsZunlockr rZendtimeZ starttimerrdrdrerQs>     c csnt||rrrwrHrprrwrxrrrrr)ruZtmp_dirZtmp_fpZtmp_namefpZkernel_versionrrdrdre can_xattr s,    r|cCs t}d}|r|Stj||S)zDSkip decorator for tests that require functional extended attributesz(no non-broken extended attribute support)r|rsr)rrvrxrdrdrer8 scCs$t pt}d}|r|Stj||S)z;Skip decorator for tests not run in (non-extended) PGO taskz#Not run for (non-extended) PGO task)r] PGO_EXTENDEDrsr)rrvrxrdrdreskip_if_pgo_task s r~cCs^tj|dH}|j}|j}||kr,|j}ytjj||Stk rNdSXWdQRXdS)zKDetects if the file system for the specified directory is case-insensitive.)rxFN) r,ZNamedTemporaryFilervupperrrrsamefiler)Z directorybase base_pathZ case_pathrdrdrer s)rfcCs>tt|tt|}|r(|t|8}tdd|D}|S)a Returns the set of items in ref_api not in other_api, except for a defined list of items to be ignored in this check. By default this skips private attributes beginning with '_' but includes all magic methods, i.e. those starting and ending in '__'. css(|] }|jd s|jdr|VqdS)___N)rqendswith)rCrrdrdre sz&detect_api_mismatch..)rrx)Zref_apiZ other_apirfZ missing_itemsrdrdrer< 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) Nrra) r`rrurrxrqrrtypes ModuleTypeaddZassertCountEqual__all__)Z test_caserZname_of_moduleZextraZ blacklistZexpectedrvrrdrdrer= s)    c@s(eZdZdZdZdZddZddZdS)rZzTry 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 Wnt t 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/defaultsr_zcom.apple.CrashReporterZ DialogType)rrs developerz:this test triggers the Crash Reporter, that is intentionalrT)endr ) rorprqrrr_k32 SetErrorMode old_valuemsvcrtCrtSetReportModerrn old_modesCRT_WARN CRT_ERROR CRT_ASSERTZCRTDBG_MODE_FILECrtSetReportFileZCRTDBG_FILE_STDERRrZ getrlimit RLIMIT_CORE setrlimitrrrrPIPEZ communicaterar) rhrZSEM_NOGPFAULTERRORBOXr report_typeold_modeold_filecmdprocrrdrdrer2 sN        zSuppressCrashReport.__enter__c Gs|jdkrdStjjdrl|jj|j|jrddl}xj|jjD]$\}\}}|j |||j ||qBWn6t dk ryt j t j |jWnttfk rYnXdS)zARestore Windows ErrorMode or core file behavior to initial value.Nrr)rrorprqrrrrrrrrrrrr)rhrrrrrrdrdrers s   zSuppressCrashReport.__exit__)r`rarbrcrrrrrdrdrdrerZ) 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)rr[rd) attr_is_local attr_nameobject_to_patchrrdrecleanup szpatch..cleanup)rrjrrZ addCleanupr)Z test_instancerrZ new_valuerrd)rrrrrepatch s  rc CsFy 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) tracemallocrnZ is_tracingrsrtrrun_in_subinterp)rrrrdrdrer s  rcsHGfddd|}d||||jttt|jdS)NcseZdZfddZdS)z%check_free_after_iterating..Ac s*dy tWntk r$YnXdS)NT)next StopIteration)rh)doneitrdre__del__ s  z-check_free_after_iterating..A.__del__N)r`rarbrrd)rrrdreA srF)rMrrrZ assertTrue)rrrCrrrd)rrrecheck_free_after_iterating 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_compilerZ executablesrrZfind_executable)Z cmd_namesrrrZcompilerrvrrdrdrer^ s       cCs@d}tr6||kr6tdkr.tjddgjdkatr6|}tj|S)Ngh㈵>Zgetpropzro.kernel.qemu1)rA_is_android_emulatorrZ check_outputrarorD)ZintervalZminimum_intervalrdrdrerD s c cs>tjj}tj}ztjdVWd|r8tj|ddXdS)NT)rZ all_threads)rorrHrZ is_enabledrr)rBrrdrdredisable_faulthandler s  rc /Cstjjd r8ytjd}t|dStk r6YnXd}ttdrjytjd}Wnt k rhYnXd}tjd kryd dl }|j Wnt 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/fdrsysconf SC_OPEN_MAXNrr)rr)rorprqrrrrrrrrrrrnrrrrOduprZEBADFr) namesZMAXFDrrrrPrBZfd2rrdrdrer_ 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|rONSIGsignalsrrr{rf)rhrZsignamesignumrdrdreriM s zSaveSignals.__init__cCs4x.|jD]$}|jj|}|dkr"q||j|<qWdS)N)rr getsignalrf)rhrhandlerrdrdresaveZ s   zSaveSignals.savecCs*x$|jjD]\}}|jj||q WdS)N)rfrr)rhrrrdrdrerestoref szSaveSignals.restoreN)r`rarbrcrirrrdrdrdrerD s  rc@s(eZdZdZddZddZddZdS) FakePathz.Simple implementing of the path protocol. cCs ||_dS)N)r)rhrrdrdrerin szFakePath.__init__cCsd|jdS)Nz )r)rhrdrdre__repr__q szFakePath.__repr__cCs6t|jts$t|jtr,t|jtr,|jn|jSdS)N)rr BaseExceptionrrz)rhrdrdre __fspath__t s    zFakePath.__fspath__N)r`rarbrcrirrrdrdrdrerk src cs.tj}ztj|dVWdtj|XdS)z>Temporarily change the integer string conversion length limit.N)roget_int_max_str_digitsset_int_max_str_digits)Z max_digitsZcurrentrdrdreadjust_int_max_str_digits| s   rcCsddtddDdgS)zReturns a list of C0 control characters as strings. C0 control characters defined as the byte range 0x00-0x1F, and 0x7F. cSsg|] }t|qSrd)chr)rCrrdrdrerD sz)control_characters_c0..r )rOrdrdrdrecontrol_characters_c0 sr)T)F)F)N)Nii@i@i@ii) rrrrrrrr r!r"r#)r'r%r(r)r*)NF)F)r7F)N)Fi@ii)T)N)Nr)rR)N(rcr`rncollections.abc collections contextlibZdatetimerrZr?rrrrmimportlib.utilrZlogging.handlersrerrrprwrrrrrrorr,rrrsZ urllib.errorrargZ testresultrrJrLZmultiprocessing.processr&zlibrXbz2Zlzmarrrrr r r rtr contextmanagerrkr rrr:r;rr6rrrrr0rrrrrrrqrrrrrrrrrrrr r!rr"r#r$r%rErr r rGrHrJrrFrrZ SOCK_MAX_SIZEZ skipUnlessr __getformat__r7r9r0r1r2r@rrrArCrvrrr0Z FS_NONASCII characterfsdecodefsencode UnicodeErrorZTESTFN_UNICODEZ unicodedata normalizegetfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversionencodeUnicodeEncodeErrorrdecodeUnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIr4rr]r}r3r6rrrKrrrrZTEST_SUPPORT_DIRr;rr]rrr[rIr&rIobjectrerrRrrrSrabcMutableMappingrTrr'rrr(rr)r*r+rrrrrrrrrrrrrrrrUr\rrrZ_4GrrrYr r3r4r,rrr>r5r!r%r?r"rBr*r+r-r2r3r<r5r7rAr-rDZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr.rHrIZenvironment_alteredrNrOrPrTrLrQrWrVrbZskipIfZrequires_type_collectingrcrdrfrgrMrXrrrr/rzr|r8r~rr<r=rZrrrr^rrDrr_rrrrrdrdrdres                      2   !  J    > %                 %      2 ' 5M            $ # 0           (        " #   "    :_"  ;' PK!/J6support/__pycache__/script_helper.cpython-36.opt-1.pycnu[3 _Vj)@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZmZdaddZGdddejdd#Zd d Zd dZddZddZejejdddZddZd$ddZd%ddZd&ddZd'd!d"ZdS)(N)source_from_cache)make_legacy_pycstrip_python_stderrc CsVtdkrRdtjkrdadSytjtjdddgWntjk rLdaYnXdatS)a  Returns True if our sys.executable interpreter requires environment variables in order to be able to run at all. This is designed to be used with @unittest.skipIf() to annotate tests that need to use an assert_python*() function to launch an isolated mode (-I) or no environment mode (-E) sub-interpreter process. A normal build & test does not run into this situation but it can happen when trying to run the standard library test suite from an interpreter that doesn't have an obvious home with Python's current home finding logic. Setting PYTHONHOME is one way to get most of the testsuite to run in that situation. PYTHONPATH or PYTHONUSERSITE are other common environment variables that might impact whether or not the interpreter can start. NZ PYTHONHOMETz-Ez-czimport sys; sys.exit(0)F)$__cached_interp_requires_environmentosenviron subprocessZ check_callsys executableZCalledProcessErrorr r 2/usr/lib64/python3.6/test/support/script_helper.py interpreter_requires_environments   r c@seZdZdZddZdS)_PythonRunResultz2Helper for reporting Python subprocess run resultscCsd }|j|j}}t||kr0d|| d}t||krNd|| d}|jddj}|jddj}td|j|||fdS) z4Provide helpful details about failed subcommand runsPds(... truncated stdout ...)Ns(... truncated stderr ...)asciireplacezRProcess return code is %d command line: %r stdout: --- %s --- stderr: --- %s ---i@)outerrlendecoderstripAssertionErrorrc)selfcmd_linemaxlenrrr r r fail>s   z_PythonRunResult.failN)__name__ __module__ __qualname____doc__rr r r r r;srrrrc Ost}d|kr|jd}n | o$| }tjddg}|rB|jdn| rX| rX|jd|jddri}tjdkrtjd|d<n tjj}d |krd |d <|j ||j |t j |t j t j t j |d }|*z|j\}}Wd|jt jXWdQRX|j} t|}t| |||fS) NZ __isolatedz-XZ faulthandlerz-Iz-EZ __cleanenvZwin32Z SYSTEMROOTTERM)stdinstdoutstderrenv)r popr r appendplatformrrcopyupdateextendrPopenPIPEZ communicatekill_cleanup returncoderr) argsenv_varsZ env_requiredisolatedrr'procrrrr r r run_python_until_end[s:            r7cOs4t||\}}|jr|s&|j r0| r0|j||S)N)r7rr)Zexpected_successr3r4resrr r r _assert_pythons r9cOstd||S)a| Assert that running the interpreter with `args` and optional environment variables `env_vars` succeeds (rc == 0) and return a (return code, stdout, stderr) tuple. If the __cleanenv keyword is set, env_vars is used as a fresh environment. Python is started in isolated mode (command line option -I), except if the __isolated keyword is set to False. T)T)r9)r3r4r r r assert_python_oks r:cOstd||S)z Assert that running the interpreter with `args` and optional environment variables `env_vars` fails (rc != 0) and return a (return code, stdout, stderr) tuple. See assert_python_ok() for more options. F)F)r9)r3r4r r r assert_python_failuresr;)r%r&cOsXtjg}ts|jd|j||jdttj}d|d<t j |ft j ||d|S)zRun a Python subprocess with the given arguments. kw is extra keyword args to pass to subprocess.Popen. Returns a Popen object. z-Er'Zvt100r")r$r%r&) r r r r)r- setdefaultdictrrrr.r/)r%r&r3kwrr'r r r spawn_pythons   r?cCs2|jj|jj}|jj|jtj|S)z?Run the given Popen process until completion and return stdout.)r$closer%readwaitrr1)pdatar r r kill_pythons    rEFcCsP|}|s|tjd7}tjj||}t|ddd}|j||jtj|S)Npywzutf-8)encoding) rextseppathjoinopenwriter@ importlibinvalidate_caches)Z script_dirscript_basenamesourceZ omit_suffixZscript_filename script_nameZ script_filer r r make_scripts rSc Cs|tjd}tjj||}tj|d}|dkr~|jtj}t|dkrr|ddkrrt t |}tjj |}|}n tjj |}|j |||j |tjj||fS)NziprG __pycache__)rrIrJrKzipfileZipFilesplitseprrrbasenamerMr@) zip_dir zip_basenamerRZ name_in_zip zip_filenamezip_namezip_filepartsZ legacy_pycr r r make_zip_scripts      rcr#cCstj|t|d|dS)N__init__)rmkdirrS)Zpkg_dirZ init_sourcer r r make_pkgs rfcs0g}t|dd}|j|tjj|} t|||} |j| |rjtj|dd}tj| dd} |j|| ffddtd|dD} tjj | d tjj| } |tj d} tjj || }t j |d }x&| D]}tjj || }|j ||qW|j | | |jx|D]}tj|q W|tjj || fS) Nrdr#T)doraisecsg|]}tjjg|qSr )rr[rK).0i)pkg_namer r sz make_zip_pkg..rgrTrG)rSr)rrJr\ py_compilecompiler-rangerKrIrXrYrMr@unlink)r]r^rkrPrQZdepthZcompiledrqZ init_nameZ init_basenamerRZ pkg_namesZscript_name_in_zipr_r`ranameZinit_name_in_zipr )rkr make_zip_pkgs.         rs)rrr)F)N)r#)rgF) collectionsrNr rZos.pathZtempfilerrn contextlibZshutilrXimportlib.utilrZ test.supportrrrr namedtuplerr7r9r:r;r/ZSTDOUTr?rErSrcrfrsr r r r s4 $3    PK!m6support/__pycache__/script_helper.cpython-36.opt-2.pycnu[3 _Vj)@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZmZdaddZGdddejdd#Zd d Zd dZddZddZejejdddZddZd$ddZd%ddZd&ddZd'd!d"ZdS)(N)source_from_cache)make_legacy_pycstrip_python_stderrc CsVtdkrRdtjkrdadSytjtjdddgWntjk rLdaYnXdatS)NZ PYTHONHOMETz-Ez-czimport sys; sys.exit(0)F)$__cached_interp_requires_environmentosenviron subprocessZ check_callsys executableZCalledProcessErrorr r 2/usr/lib64/python3.6/test/support/script_helper.py interpreter_requires_environments   r c@seZdZddZdS)_PythonRunResultcCsd}|j|j}}t||kr0d|| d}t||krNd|| d}|jddj}|jddj}td|j|||fdS) NPds(... truncated stdout ...)s(... truncated stderr ...)asciireplacezRProcess return code is %d command line: %r stdout: --- %s --- stderr: --- %s ---i@)outerrlendecoderstripAssertionErrorrc)selfcmd_linemaxlenrrr r r fail>s   z_PythonRunResult.failN)__name__ __module__ __qualname__rr r r r r;srrrrc Ost}d|kr|jd}n | o$| }tjddg}|rB|jdn| rX| rX|jd|jddri}tjdkrtjd|d<n tjj}d |krd |d <|j ||j |t j |t j t j t j |d }|*z|j\}}Wd|jt jXWdQRX|j} t|}t| |||fS) NZ __isolatedz-XZ faulthandlerz-Iz-EZ __cleanenvZwin32Z SYSTEMROOTTERM)stdinstdoutstderrenv)r popr r appendplatformrrcopyupdateextendrPopenPIPEZ communicatekill_cleanup returncoderr) argsenv_varsZ env_requiredisolatedrr&procrrrr r r run_python_until_end[s:            r6cOs4t||\}}|jr|s&|j r0| r0|j||S)N)r6rr)Zexpected_successr2r3resrr r r _assert_pythons r8cOstd||S)NT)T)r8)r2r3r r r assert_python_oks r9cOstd||S)NF)F)r8)r2r3r r r assert_python_failuresr:)r$r%cOsXtjg}ts|jd|j||jdttj}d|d<t j |ft j ||d|S)Nz-Er&Zvt100r!)r#r$r%) r r r r(r, setdefaultdictrrrr-r.)r$r%r2kwrr&r r r spawn_pythons   r>cCs2|jj|jj}|jj|jtj|S)N)r#closer$readwaitrr0)pdatar r r kill_pythons    rDFcCsP|}|s|tjd7}tjj||}t|ddd}|j||jtj|S)Npywzutf-8)encoding) rextseppathjoinopenwriter? importlibinvalidate_caches)Z script_dirscript_basenamesourceZ omit_suffixZscript_filename script_nameZ script_filer r r make_scripts rRc Cs|tjd}tjj||}tj|d}|dkr~|jtj}t|dkrr|ddkrrt t |}tjj |}|}n tjj |}|j |||j |tjj||fS)NziprF __pycache__)rrHrIrJzipfileZipFilesplitseprrrbasenamerLr?) zip_dir zip_basenamerQZ name_in_zip zip_filenamezip_namezip_filepartsZ legacy_pycr r r make_zip_scripts      rbr"cCstj|t|d|dS)N__init__)rmkdirrR)Zpkg_dirZ init_sourcer r r make_pkgs recs0g}t|dd}|j|tjj|} t|||} |j| |rjtj|dd}tj| dd} |j|| ffddtd|dD} tjj | d tjj| } |tj d} tjj || }t j |d }x&| D]}tjj || }|j ||qW|j | | |jx|D]}tj|q W|tjj || fS) Nrcr"T)doraisecsg|]}tjjg|qSr )rrZrJ).0i)pkg_namer r sz make_zip_pkg..rfrSrF)rRr(rrIr[ py_compilecompiler,rangerJrHrWrXrLr?unlink)r\r]rjrOrPZdepthZcompiledrpZ init_nameZ init_basenamerQZ pkg_namesZscript_name_in_zipr^r_r`nameZinit_name_in_zipr )rjr make_zip_pkgs.         rr)rrr)F)N)r")rfF) collectionsrMr rZos.pathZtempfilerrm contextlibZshutilrWimportlib.utilrZ test.supportrrrr namedtuplerr6r8r9r:r.ZSTDOUTr>rDrRrbrerrr r r r s4 $3    PK!/J0support/__pycache__/script_helper.cpython-36.pycnu[3 _Vj)@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZmZdaddZGdddejdd#Zd d Zd dZddZddZejejdddZddZd$ddZd%ddZd&ddZd'd!d"ZdS)(N)source_from_cache)make_legacy_pycstrip_python_stderrc CsVtdkrRdtjkrdadSytjtjdddgWntjk rLdaYnXdatS)a  Returns True if our sys.executable interpreter requires environment variables in order to be able to run at all. This is designed to be used with @unittest.skipIf() to annotate tests that need to use an assert_python*() function to launch an isolated mode (-I) or no environment mode (-E) sub-interpreter process. A normal build & test does not run into this situation but it can happen when trying to run the standard library test suite from an interpreter that doesn't have an obvious home with Python's current home finding logic. Setting PYTHONHOME is one way to get most of the testsuite to run in that situation. PYTHONPATH or PYTHONUSERSITE are other common environment variables that might impact whether or not the interpreter can start. NZ PYTHONHOMETz-Ez-czimport sys; sys.exit(0)F)$__cached_interp_requires_environmentosenviron subprocessZ check_callsys executableZCalledProcessErrorr r 2/usr/lib64/python3.6/test/support/script_helper.py interpreter_requires_environments   r c@seZdZdZddZdS)_PythonRunResultz2Helper for reporting Python subprocess run resultscCsd }|j|j}}t||kr0d|| d}t||krNd|| d}|jddj}|jddj}td|j|||fdS) z4Provide helpful details about failed subcommand runsPds(... truncated stdout ...)Ns(... truncated stderr ...)asciireplacezRProcess return code is %d command line: %r stdout: --- %s --- stderr: --- %s ---i@)outerrlendecoderstripAssertionErrorrc)selfcmd_linemaxlenrrr r r fail>s   z_PythonRunResult.failN)__name__ __module__ __qualname____doc__rr r r r r;srrrrc Ost}d|kr|jd}n | o$| }tjddg}|rB|jdn| rX| rX|jd|jddri}tjdkrtjd|d<n tjj}d |krd |d <|j ||j |t j |t j t j t j |d }|*z|j\}}Wd|jt jXWdQRX|j} t|}t| |||fS) NZ __isolatedz-XZ faulthandlerz-Iz-EZ __cleanenvZwin32Z SYSTEMROOTTERM)stdinstdoutstderrenv)r popr r appendplatformrrcopyupdateextendrPopenPIPEZ communicatekill_cleanup returncoderr) argsenv_varsZ env_requiredisolatedrr'procrrrr r r run_python_until_end[s:            r7cOs4t||\}}|jr|s&|j r0| r0|j||S)N)r7rr)Zexpected_successr3r4resrr r r _assert_pythons r9cOstd||S)a| Assert that running the interpreter with `args` and optional environment variables `env_vars` succeeds (rc == 0) and return a (return code, stdout, stderr) tuple. If the __cleanenv keyword is set, env_vars is used as a fresh environment. Python is started in isolated mode (command line option -I), except if the __isolated keyword is set to False. T)T)r9)r3r4r r r assert_python_oks r:cOstd||S)z Assert that running the interpreter with `args` and optional environment variables `env_vars` fails (rc != 0) and return a (return code, stdout, stderr) tuple. See assert_python_ok() for more options. F)F)r9)r3r4r r r assert_python_failuresr;)r%r&cOsXtjg}ts|jd|j||jdttj}d|d<t j |ft j ||d|S)zRun a Python subprocess with the given arguments. kw is extra keyword args to pass to subprocess.Popen. Returns a Popen object. z-Er'Zvt100r")r$r%r&) r r r r)r- setdefaultdictrrrr.r/)r%r&r3kwrr'r r r spawn_pythons   r?cCs2|jj|jj}|jj|jtj|S)z?Run the given Popen process until completion and return stdout.)r$closer%readwaitrr1)pdatar r r kill_pythons    rEFcCsP|}|s|tjd7}tjj||}t|ddd}|j||jtj|S)Npywzutf-8)encoding) rextseppathjoinopenwriter@ importlibinvalidate_caches)Z script_dirscript_basenamesourceZ omit_suffixZscript_filename script_nameZ script_filer r r make_scripts rSc Cs|tjd}tjj||}tj|d}|dkr~|jtj}t|dkrr|ddkrrt t |}tjj |}|}n tjj |}|j |||j |tjj||fS)NziprG __pycache__)rrIrJrKzipfileZipFilesplitseprrrbasenamerMr@) zip_dir zip_basenamerRZ name_in_zip zip_filenamezip_namezip_filepartsZ legacy_pycr r r make_zip_scripts      rcr#cCstj|t|d|dS)N__init__)rmkdirrS)Zpkg_dirZ init_sourcer r r make_pkgs rfcs0g}t|dd}|j|tjj|} t|||} |j| |rjtj|dd}tj| dd} |j|| ffddtd|dD} tjj | d tjj| } |tj d} tjj || }t j |d }x&| D]}tjj || }|j ||qW|j | | |jx|D]}tj|q W|tjj || fS) Nrdr#T)doraisecsg|]}tjjg|qSr )rr[rK).0i)pkg_namer r sz make_zip_pkg..rgrTrG)rSr)rrJr\ py_compilecompiler-rangerKrIrXrYrMr@unlink)r]r^rkrPrQZdepthZcompiledrqZ init_nameZ init_basenamerRZ pkg_namesZscript_name_in_zipr_r`ranameZinit_name_in_zipr )rkr make_zip_pkgs.         rs)rrr)F)N)r#)rgF) collectionsrNr rZos.pathZtempfilerrn contextlibZshutilrXimportlib.utilrZ test.supportrrrr namedtuplerr7r9r:r;r/ZSTDOUTr?rErSrcrfrsr r r r s4 $3    PK!r&XX3support/__pycache__/testresult.cpython-36.opt-1.pycnu[3 \ @s6dZddlZddlZddlZddlZddlZddlZddljj Z ddl m Z Gdddej Z GdddZdd d Zdd d Zed kr2GdddejZejZejejeejZeeddejDZeejZejeZ e!dej"e!dddx(e j#e j$D]Z%e!e%j&ddqWe!dS)z=Test runner and result class for the regression test suite. N)datetimecseZdZdddZdddZfddZeddZfd d Zd$d d Z ddZ eddZ fddZ fddZ fddZfddZfddZfddZddZd d!Zd"d#ZZS)%RegressionTestResult=F -cs\tj||ddd|_tjd|_|jjdtjj dd|_ d|_ g|_ t ||_dS)Nr)stream descriptions verbosityTZ testsuitestart )super__init__bufferETZElement_RegressionTestResult__suitesetrZutcnowZ isoformat_RegressionTestResult__e!_RegressionTestResult__start_timeZ_RegressionTestResult__resultsbool_RegressionTestResult__verbose)selfrr r ) __class__//usr/lib64/python3.6/test/support/testresult.pyrs zRegressionTestResult.__init__cCsLy |j}Wntk r"t|SXy|Stk rBt|SXt|S)N)idAttributeErrorstr TypeErrorrepr)clstestZtest_idrrrZ__getIds   zRegressionTestResult.__getIdcsVtj|tj|jd|_}tj|_|j rR|j j |j |d|j j dS)NZtestcasez ... )r startTestr SubElementrrtime perf_counterrrrwritegetDescriptionflush)rr!e)rrrr"+s   zRegressionTestResult.startTestFc KsP|j}d|_|dkrdS|jd|jd|j||jd|jdd|jd|jdd|jrz|jdtj|jd|r|jdk r|jjj }|t j |d_ |j dk r|j jj }|t j |d _ x|jD]t\}}| s| rqt j ||} t|d r>xD|jD],\} } | r,| j| t| n t| | _ q Wqt|| _ qWdS) NnameZstatusrunresultZ completedr$z0.6fz system-outz system-erritems)rrpop_RegressionTestResult__getIdrr$r%Z_stdout_buffergetvaluerstriprr#textZ_stderr_bufferr-hasattrr) rr!Zcaptureargsr)stdoutstderrkvZe2Zk2Zv2rrr _add_result3s4     z RegressionTestResult._add_resultcCs|jr|jj|ddS)Nr)rrr&)rcZwordrrrZ__writeSszRegressionTestResult.__writecCslt|tr0|jdkr|j}q8|jd|j}nt|}tj||d}tj|||}|dj|dj|dS)Nbuiltins.)typemessager=) isinstancer> __module____name__r tracebackformat_exceptionjoin)r Zerr_typeZ err_valueZerr_tbtypenamemsgtbrrrZ__makeErrorDictWs  z$RegressionTestResult.__makeErrorDictcs4|j|d|j|dtj|||jdddS)NT)errorEERROR)r9$_RegressionTestResult__makeErrorDictr addError_RegressionTestResult__write)rr!err)rrrrMjszRegressionTestResult.addErrorcs4|j|d|j|dtj|||jdddS)NT)outputxzexpected failure)r9rLr addExpectedFailurerN)rr!rO)rrrrRosz'RegressionTestResult.addExpectedFailurecs4|j|d|j|dtj|||jdddS)NT)ZfailureFFAIL)r9rLr addFailurerN)rr!rO)rrrrUtszRegressionTestResult.addFailurecs2|j||dtj|||jdd|dS)N)ZskippedSzskipped )r9r addSkiprN)rr!reason)rrrrWyszRegressionTestResult.addSkipcs&|j|tj||jdddS)Nr<ok)r9r addSuccessrN)rr!)rrrrZ~s  zRegressionTestResult.addSuccesscs*|j|ddtj||jdddS)NZUNEXPECTED_SUCCESS)Zoutcomeuzunexpected success)r9r addUnexpectedSuccessrN)rr!)rrrr\s z)RegressionTestResult.addUnexpectedSuccesscCs2|jr|jjd|jd|j|jd|jdS)NrrKrT)rrr&printErrorListerrorsfailures)rrrr printErrorss z RegressionTestResult.printErrorscCs`xZ|D]R\}}|jj|j|jj|d|j|d|jj|j|jjd|qWdS)Nz: rz%s )rr& separator1r' separator2)rZflavorr^r!rOrrrr]s z#RegressionTestResult.printErrorListcCsH|j}|jdt|j|jdtt|j|jdtt|j|S)NZtestsr^r_)rrrZtestsRunlenr^r_)rr)rrrget_xml_elements z$RegressionTestResult.get_xml_element)F)rBrA __qualname__rarbr classmethodr/r"r9rNrLrMrRrUrWrZr\r`r]rd __classcell__rr)rrrs"           rc@seZdZdddZddZdS)QuietRegressionTestRunnerFcCst|dd|_||j_dS)Nr)rr,r)rrrrrrrsz"QuietRegressionTestRunner.__init__cCs||j|jS)N)r,)rr!rrrr+s zQuietRegressionTestRunner.runN)F)rBrArerr+rrrrrhs rhFcCs&|rtjtjt||dStjt|dS)N)Z resultclassrr )r) functoolspartialunittestZTextTestRunnerrrh)r rrrrget_test_runner_classs rlcCst|||S)N)rl)rr Zcapture_outputrrrget_test_runnersrm__main__c@s,eZdZddZddZddZddZd S) TestTestscCsdS)Nr)rrrr test_passszTestTests.test_passcCstjddS)Ng?)r$Zsleep)rrrrtest_pass_slowszTestTests.test_pass_slowcCs*tdtjdtdtjd|jddS)Nr5)filer6zfailure message)printsysr5r6Zfail)rrrr test_failszTestTests.test_failcCs(tdtjdtdtjdtddS)Nr5)rrr6z error message)rsrtr5r6 RuntimeError)rrrr test_errorszTestTests.test_errorN)rBrArerprqrurwrrrrrosroccs|]}|dkVqdS)z-vNr).0arrr srzzOutput:zXML: r=)end)F)F)'__doc__riiortr$rCrkZxml.etree.ElementTreeZetreeZ ElementTreerrZTextTestResultrrhrlrmrBZTestCaseroZ TestSuiteZsuiteZaddTestZ makeSuiteStringIOrsumargvZ runner_clsr5Zrunnerr+r,rsr0Z tostringlistrdsdecoderrrrs4         PK! P  3support/__pycache__/testresult.cpython-36.opt-2.pycnu[3 \ @s2ddlZddlZddlZddlZddlZddlZddljjZ ddl m Z Gdddej Z GdddZ ddd Zdd d Zed kr.Gd ddejZejZejejeejZeeddejDZeejZejeZe dej!e dddx(e j"ej#D]Z$e e$j%ddqWe dS)N)datetimecseZdZdddZdddZfddZeddZfd d Zd$d d Z ddZ eddZ fddZ fddZ fddZfddZfddZfddZddZd d!Zd"d#ZZS)%RegressionTestResult=F -cs\tj||ddd|_tjd|_|jjdtjj dd|_ d|_ g|_ t ||_dS)Nr)stream descriptions verbosityTZ testsuitestart )super__init__bufferETZElement_RegressionTestResult__suitesetrZutcnowZ isoformat_RegressionTestResult__e!_RegressionTestResult__start_timeZ_RegressionTestResult__resultsbool_RegressionTestResult__verbose)selfrr r ) __class__//usr/lib64/python3.6/test/support/testresult.pyrs zRegressionTestResult.__init__cCsLy |j}Wntk r"t|SXy|Stk rBt|SXt|S)N)idAttributeErrorstr TypeErrorrepr)clstestZtest_idrrrZ__getIds   zRegressionTestResult.__getIdcsVtj|tj|jd|_}tj|_|j rR|j j |j |d|j j dS)NZtestcasez ... )r startTestr SubElementrrtime perf_counterrrrwritegetDescriptionflush)rr!e)rrrr"+s   zRegressionTestResult.startTestFc KsP|j}d|_|dkrdS|jd|jd|j||jd|jdd|jd|jdd|jrz|jdtj|jd|r|jdk r|jjj }|t j |d_ |j dk r|j jj }|t j |d _ x|jD]t\}}| s| rqt j ||} t|d r>xD|jD],\} } | r,| j| t| n t| | _ q Wqt|| _ qWdS) NnameZstatusrunresultZ completedr$z0.6fz system-outz system-erritems)rrpop_RegressionTestResult__getIdrr$r%Z_stdout_buffergetvaluerstriprr#textZ_stderr_bufferr-hasattrr) rr!Zcaptureargsr)stdoutstderrkvZe2Zk2Zv2rrr _add_result3s4     z RegressionTestResult._add_resultcCs|jr|jj|ddS)Nr)rrr&)rcZwordrrrZ__writeSszRegressionTestResult.__writecCslt|tr0|jdkr|j}q8|jd|j}nt|}tj||d}tj|||}|dj|dj|dS)Nbuiltins.)typemessager=) isinstancer> __module____name__r tracebackformat_exceptionjoin)r Zerr_typeZ err_valueZerr_tbtypenamemsgtbrrrZ__makeErrorDictWs  z$RegressionTestResult.__makeErrorDictcs4|j|d|j|dtj|||jdddS)NT)errorEERROR)r9$_RegressionTestResult__makeErrorDictr addError_RegressionTestResult__write)rr!err)rrrrMjszRegressionTestResult.addErrorcs4|j|d|j|dtj|||jdddS)NT)outputxzexpected failure)r9rLr addExpectedFailurerN)rr!rO)rrrrRosz'RegressionTestResult.addExpectedFailurecs4|j|d|j|dtj|||jdddS)NT)ZfailureFFAIL)r9rLr addFailurerN)rr!rO)rrrrUtszRegressionTestResult.addFailurecs2|j||dtj|||jdd|dS)N)ZskippedSzskipped )r9r addSkiprN)rr!reason)rrrrWyszRegressionTestResult.addSkipcs&|j|tj||jdddS)Nr<ok)r9r addSuccessrN)rr!)rrrrZ~s  zRegressionTestResult.addSuccesscs*|j|ddtj||jdddS)NZUNEXPECTED_SUCCESS)Zoutcomeuzunexpected success)r9r addUnexpectedSuccessrN)rr!)rrrr\s z)RegressionTestResult.addUnexpectedSuccesscCs2|jr|jjd|jd|j|jd|jdS)NrrKrT)rrr&printErrorListerrorsfailures)rrrr printErrorss z RegressionTestResult.printErrorscCs`xZ|D]R\}}|jj|j|jj|d|j|d|jj|j|jjd|qWdS)Nz: rz%s )rr& separator1r' separator2)rZflavorr^r!rOrrrr]s z#RegressionTestResult.printErrorListcCsH|j}|jdt|j|jdtt|j|jdtt|j|S)NZtestsr^r_)rrrZtestsRunlenr^r_)rr)rrrget_xml_elements z$RegressionTestResult.get_xml_element)F)rBrA __qualname__rarbr classmethodr/r"r9rNrLrMrRrUrWrZr\r`r]rd __classcell__rr)rrrs"           rc@seZdZdddZddZdS)QuietRegressionTestRunnerFcCst|dd|_||j_dS)Nr)rr,r)rrrrrrrsz"QuietRegressionTestRunner.__init__cCs||j|jS)N)r,)rr!rrrr+s zQuietRegressionTestRunner.runN)F)rBrArerr+rrrrrhs rhFcCs&|rtjtjt||dStjt|dS)N)Z resultclassrr )r) functoolspartialunittestZTextTestRunnerrrh)r rrrrget_test_runner_classs rlcCst|||S)N)rl)rr Zcapture_outputrrrget_test_runnersrm__main__c@s,eZdZddZddZddZddZd S) TestTestscCsdS)Nr)rrrr test_passszTestTests.test_passcCstjddS)Ng?)r$Zsleep)rrrrtest_pass_slowszTestTests.test_pass_slowcCs*tdtjdtdtjd|jddS)Nr5)filer6zfailure message)printsysr5r6Zfail)rrrr test_failszTestTests.test_failcCs(tdtjdtdtjdtddS)Nr5)rrr6z error message)rsrtr5r6 RuntimeError)rrrr test_errorszTestTests.test_errorN)rBrArerprqrurwrrrrrosroccs|]}|dkVqdS)z-vNr).0arrr srzzOutput:zXML: r=)end)F)F)&riiortr$rCrkZxml.etree.ElementTreeZetreeZ ElementTreerrZTextTestResultrrhrlrmrBZTestCaseroZ TestSuiteZsuiteZaddTestZ makeSuiteStringIOrsumargvZ runner_clsr5Zrunnerr+r,rsr0Z tostringlistrdsdecoderrrrs2         PK!r&XX-support/__pycache__/testresult.cpython-36.pycnu[3 \ @s6dZddlZddlZddlZddlZddlZddlZddljj Z ddl m Z Gdddej Z GdddZdd d Zdd d Zed kr2GdddejZejZejejeejZeeddejDZeejZejeZ e!dej"e!dddx(e j#e j$D]Z%e!e%j&ddqWe!dS)z=Test runner and result class for the regression test suite. N)datetimecseZdZdddZdddZfddZeddZfd d Zd$d d Z ddZ eddZ fddZ fddZ fddZfddZfddZfddZddZd d!Zd"d#ZZS)%RegressionTestResult=F -cs\tj||ddd|_tjd|_|jjdtjj dd|_ d|_ g|_ t ||_dS)Nr)stream descriptions verbosityTZ testsuitestart )super__init__bufferETZElement_RegressionTestResult__suitesetrZutcnowZ isoformat_RegressionTestResult__e!_RegressionTestResult__start_timeZ_RegressionTestResult__resultsbool_RegressionTestResult__verbose)selfrr r ) __class__//usr/lib64/python3.6/test/support/testresult.pyrs zRegressionTestResult.__init__cCsLy |j}Wntk r"t|SXy|Stk rBt|SXt|S)N)idAttributeErrorstr TypeErrorrepr)clstestZtest_idrrrZ__getIds   zRegressionTestResult.__getIdcsVtj|tj|jd|_}tj|_|j rR|j j |j |d|j j dS)NZtestcasez ... )r startTestr SubElementrrtime perf_counterrrrwritegetDescriptionflush)rr!e)rrrr"+s   zRegressionTestResult.startTestFc KsP|j}d|_|dkrdS|jd|jd|j||jd|jdd|jd|jdd|jrz|jdtj|jd|r|jdk r|jjj }|t j |d_ |j dk r|j jj }|t j |d _ x|jD]t\}}| s| rqt j ||} t|d r>xD|jD],\} } | r,| j| t| n t| | _ q Wqt|| _ qWdS) NnameZstatusrunresultZ completedr$z0.6fz system-outz system-erritems)rrpop_RegressionTestResult__getIdrr$r%Z_stdout_buffergetvaluerstriprr#textZ_stderr_bufferr-hasattrr) rr!Zcaptureargsr)stdoutstderrkvZe2Zk2Zv2rrr _add_result3s4     z RegressionTestResult._add_resultcCs|jr|jj|ddS)Nr)rrr&)rcZwordrrrZ__writeSszRegressionTestResult.__writecCslt|tr0|jdkr|j}q8|jd|j}nt|}tj||d}tj|||}|dj|dj|dS)Nbuiltins.)typemessager=) isinstancer> __module____name__r tracebackformat_exceptionjoin)r Zerr_typeZ err_valueZerr_tbtypenamemsgtbrrrZ__makeErrorDictWs  z$RegressionTestResult.__makeErrorDictcs4|j|d|j|dtj|||jdddS)NT)errorEERROR)r9$_RegressionTestResult__makeErrorDictr addError_RegressionTestResult__write)rr!err)rrrrMjszRegressionTestResult.addErrorcs4|j|d|j|dtj|||jdddS)NT)outputxzexpected failure)r9rLr addExpectedFailurerN)rr!rO)rrrrRosz'RegressionTestResult.addExpectedFailurecs4|j|d|j|dtj|||jdddS)NT)ZfailureFFAIL)r9rLr addFailurerN)rr!rO)rrrrUtszRegressionTestResult.addFailurecs2|j||dtj|||jdd|dS)N)ZskippedSzskipped )r9r addSkiprN)rr!reason)rrrrWyszRegressionTestResult.addSkipcs&|j|tj||jdddS)Nr<ok)r9r addSuccessrN)rr!)rrrrZ~s  zRegressionTestResult.addSuccesscs*|j|ddtj||jdddS)NZUNEXPECTED_SUCCESS)Zoutcomeuzunexpected success)r9r addUnexpectedSuccessrN)rr!)rrrr\s z)RegressionTestResult.addUnexpectedSuccesscCs2|jr|jjd|jd|j|jd|jdS)NrrKrT)rrr&printErrorListerrorsfailures)rrrr printErrorss z RegressionTestResult.printErrorscCs`xZ|D]R\}}|jj|j|jj|d|j|d|jj|j|jjd|qWdS)Nz: rz%s )rr& separator1r' separator2)rZflavorr^r!rOrrrr]s z#RegressionTestResult.printErrorListcCsH|j}|jdt|j|jdtt|j|jdtt|j|S)NZtestsr^r_)rrrZtestsRunlenr^r_)rr)rrrget_xml_elements z$RegressionTestResult.get_xml_element)F)rBrA __qualname__rarbr classmethodr/r"r9rNrLrMrRrUrWrZr\r`r]rd __classcell__rr)rrrs"           rc@seZdZdddZddZdS)QuietRegressionTestRunnerFcCst|dd|_||j_dS)Nr)rr,r)rrrrrrrsz"QuietRegressionTestRunner.__init__cCs||j|jS)N)r,)rr!rrrr+s zQuietRegressionTestRunner.runN)F)rBrArerr+rrrrrhs rhFcCs&|rtjtjt||dStjt|dS)N)Z resultclassrr )r) functoolspartialunittestZTextTestRunnerrrh)r rrrrget_test_runner_classs rlcCst|||S)N)rl)rr Zcapture_outputrrrget_test_runnersrm__main__c@s,eZdZddZddZddZddZd S) TestTestscCsdS)Nr)rrrr test_passszTestTests.test_passcCstjddS)Ng?)r$Zsleep)rrrrtest_pass_slowszTestTests.test_pass_slowcCs*tdtjdtdtjd|jddS)Nr5)filer6zfailure message)printsysr5r6Zfail)rrrr test_failszTestTests.test_failcCs(tdtjdtdtjdtddS)Nr5)rrr6z error message)rsrtr5r6 RuntimeError)rrrr test_errorszTestTests.test_errorN)rBrArerprqrurwrrrrrosroccs|]}|dkVqdS)z-vNr).0arrr srzzOutput:zXML: r=)end)F)F)'__doc__riiortr$rCrkZxml.etree.ElementTreeZetreeZ ElementTreerrZTextTestResultrrhrlrmrBZTestCaseroZ TestSuiteZsuiteZaddTestZ makeSuiteStringIOrsumargvZ runner_clsr5Zrunnerr+r,rsr0Z tostringlistrdsdecoderrrrs4         PK!C敏..support/__init__.pynu["""Supporting definitions for the Python regression tests.""" if __name__ != 'test.support': raise ImportError('test.support must be imported from the test package') import contextlib import errno import fnmatch import functools import gc import socket import stat import sys import os import platform import shutil import warnings import unittest import importlib import UserDict import re import time import struct import sysconfig import types try: import thread except ImportError: thread = None __all__ = ["Error", "TestFailed", "TestDidNotRun", "ResourceDenied", "import_module", "verbose", "use_resources", "max_memuse", "record_original_stdout", "get_original_stdout", "unload", "unlink", "rmtree", "forget", "is_resource_enabled", "requires", "requires_mac_ver", "find_unused_port", "bind_port", "fcmp", "have_unicode", "is_jython", "TESTFN", "HOST", "FUZZ", "SAVEDCWD", "temp_cwd", "findfile", "sortdict", "check_syntax_error", "open_urlresource", "check_warnings", "check_py3k_warnings", "CleanImport", "EnvironmentVarGuard", "captured_output", "captured_stdout", "TransientResource", "transient_internet", "run_with_locale", "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup", "threading_cleanup", "reap_threads", "start_threads", "cpython_only", "check_impl_detail", "get_attribute", "py3k_bytes", "import_fresh_module", "threading_cleanup", "reap_children", "strip_python_stderr", "IPV6_ENABLED", "run_with_tz", "SuppressCrashReport"] SHORT_TIMEOUT = 30.0 # Added to make backporting from 3.x easier class Error(Exception): """Base class for regression test exceptions.""" class TestFailed(Error): """Test failed.""" class TestDidNotRun(Error): """Test did not run any subtests.""" class ResourceDenied(unittest.SkipTest): """Test skipped because it requested a disallowed resource. This is raised when a test calls requires() for a resource that has not been enabled. It is used to distinguish between expected and unexpected skips. """ @contextlib.contextmanager def _ignore_deprecated_imports(ignore=True): """Context manager to suppress package and module deprecation warnings when importing them. If ignore is False, this context manager has no effect.""" if ignore: with warnings.catch_warnings(): warnings.filterwarnings("ignore", ".+ (module|package)", DeprecationWarning) yield else: yield def import_module(name, deprecated=False): """Import and return the module to be tested, raising SkipTest if it is not available. If deprecated is True, any module or package deprecation messages will be suppressed.""" with _ignore_deprecated_imports(deprecated): try: return importlib.import_module(name) except ImportError, msg: raise unittest.SkipTest(str(msg)) def _save_and_remove_module(name, orig_modules): """Helper function to save and remove a module from sys.modules Raise ImportError if the module can't be imported.""" # try to import the module and raise an error if it can't be imported if name not in sys.modules: __import__(name) del sys.modules[name] for modname in list(sys.modules): if modname == name or modname.startswith(name + '.'): orig_modules[modname] = sys.modules[modname] del sys.modules[modname] def _save_and_block_module(name, orig_modules): """Helper function to save and block a module in sys.modules Return True if the module was in sys.modules, False otherwise.""" saved = True try: orig_modules[name] = sys.modules[name] except KeyError: saved = False sys.modules[name] = None return saved def import_fresh_module(name, fresh=(), blocked=(), deprecated=False): """Imports and returns a module, deliberately bypassing the sys.modules cache and importing a fresh copy of the module. Once the import is complete, the sys.modules cache is restored to its original state. Modules named in fresh are also imported anew if needed by the import. If one of these modules can't be imported, None is returned. Importing of modules named in blocked is prevented while the fresh import takes place. If deprecated is True, any module or package deprecation messages will be suppressed.""" # NOTE: test_heapq, test_json, and test_warnings include extra sanity # checks to make sure that this utility function is working as expected with _ignore_deprecated_imports(deprecated): # Keep track of modules saved for later restoration as well # as those which just need a blocking entry removed orig_modules = {} names_to_remove = [] _save_and_remove_module(name, orig_modules) try: for fresh_name in fresh: _save_and_remove_module(fresh_name, orig_modules) for blocked_name in blocked: if not _save_and_block_module(blocked_name, orig_modules): names_to_remove.append(blocked_name) fresh_module = importlib.import_module(name) except ImportError: fresh_module = None finally: for orig_name, module in orig_modules.items(): sys.modules[orig_name] = module for name_to_remove in names_to_remove: del sys.modules[name_to_remove] return fresh_module def get_attribute(obj, name): """Get an attribute, raising SkipTest if AttributeError is raised.""" try: attribute = getattr(obj, name) except AttributeError: if isinstance(obj, types.ModuleType): msg = "module %r has no attribute %r" % (obj.__name__, name) elif isinstance(obj, types.ClassType): msg = "class %s has no attribute %r" % (obj.__name__, name) elif isinstance(obj, types.InstanceType): msg = "%s instance has no attribute %r" % (obj.__class__.__name__, name) elif isinstance(obj, type): msg = "type object %r has no attribute %r" % (obj.__name__, name) else: msg = "%r object has no attribute %r" % (type(obj).__name__, name) raise unittest.SkipTest(msg) else: return attribute verbose = 1 # Flag set to 0 by regrtest.py use_resources = None # Flag set to [] by regrtest.py max_memuse = 0 # Disable bigmem tests (they will still be run with # small sizes, to make sure they work.) real_max_memuse = 0 failfast = False # _original_stdout is meant to hold stdout at the time regrtest began. # This may be "the real" stdout, or IDLE's emulation of stdout, or whatever. # The point is to have some flavor of stdout the user can actually see. _original_stdout = None def record_original_stdout(stdout): global _original_stdout _original_stdout = stdout def get_original_stdout(): return _original_stdout or sys.stdout def unload(name): try: del sys.modules[name] except KeyError: pass def _force_run(path, func, *args): try: return func(*args) except EnvironmentError as err: if verbose >= 2: print('%s: %s' % (err.__class__.__name__, err)) print('re-run %s%r' % (func.__name__, args)) os.chmod(path, stat.S_IRWXU) return func(*args) if sys.platform.startswith("win"): def _waitfor(func, pathname, waitall=False): # Perform the operation func(pathname) # Now setup the wait loop if waitall: dirname = pathname else: dirname, name = os.path.split(pathname) dirname = dirname or '.' # Check for `pathname` to be removed from the filesystem. # The exponential backoff of the timeout amounts to a total # of ~1 second after which the deletion is probably an error # anyway. # Testing on an i7@4.3GHz shows that usually only 1 iteration is # required when contention occurs. timeout = 0.001 while timeout < 1.0: # Note we are only testing for the existence of the file(s) in # the contents of the directory regardless of any security or # access rights. If we have made it this far, we have sufficient # permissions to do that much using Python's equivalent of the # Windows API FindFirstFile. # Other Windows APIs can fail or give incorrect results when # dealing with files that are pending deletion. L = os.listdir(dirname) if not (L if waitall else name in L): return # Increase the timeout and try again time.sleep(timeout) timeout *= 2 warnings.warn('tests may fail, delete still pending for ' + pathname, RuntimeWarning, stacklevel=4) def _unlink(filename): _waitfor(os.unlink, filename) def _rmdir(dirname): _waitfor(os.rmdir, dirname) def _rmtree(path): def _rmtree_inner(path): for name in _force_run(path, os.listdir, path): fullname = os.path.join(path, name) if os.path.isdir(fullname): _waitfor(_rmtree_inner, fullname, waitall=True) _force_run(fullname, os.rmdir, fullname) else: _force_run(fullname, os.unlink, fullname) _waitfor(_rmtree_inner, path, waitall=True) _waitfor(lambda p: _force_run(p, os.rmdir, p), path) else: _unlink = os.unlink _rmdir = os.rmdir def _rmtree(path): try: shutil.rmtree(path) return except EnvironmentError: pass def _rmtree_inner(path): for name in _force_run(path, os.listdir, path): fullname = os.path.join(path, name) try: mode = os.lstat(fullname).st_mode except EnvironmentError: mode = 0 if stat.S_ISDIR(mode): _rmtree_inner(fullname) _force_run(path, os.rmdir, fullname) else: _force_run(path, os.unlink, fullname) _rmtree_inner(path) os.rmdir(path) def unlink(filename): try: _unlink(filename) except OSError as exc: if exc.errno not in (errno.ENOENT, errno.ENOTDIR): raise def rmdir(dirname): try: _rmdir(dirname) except OSError as error: # The directory need not exist. if error.errno != errno.ENOENT: raise def rmtree(path): try: _rmtree(path) except OSError, e: # Unix returns ENOENT, Windows returns ESRCH. if e.errno not in (errno.ENOENT, errno.ESRCH): raise def forget(modname): '''"Forget" a module was ever imported by removing it from sys.modules and deleting any .pyc and .pyo files.''' unload(modname) for dirname in sys.path: unlink(os.path.join(dirname, modname + os.extsep + 'pyc')) # Deleting the .pyo file cannot be within the 'try' for the .pyc since # the chance exists that there is no .pyc (and thus the 'try' statement # is exited) but there is a .pyo file. unlink(os.path.join(dirname, modname + os.extsep + 'pyo')) # Check whether a gui is actually available def _is_gui_available(): if hasattr(_is_gui_available, 'result'): return _is_gui_available.result reason = None if sys.platform.startswith('win'): # if Python is running as a service (such as the buildbot service), # gui interaction may be disallowed import ctypes import ctypes.wintypes UOI_FLAGS = 1 WSF_VISIBLE = 0x0001 class USEROBJECTFLAGS(ctypes.Structure): _fields_ = [("fInherit", ctypes.wintypes.BOOL), ("fReserved", ctypes.wintypes.BOOL), ("dwFlags", ctypes.wintypes.DWORD)] dll = ctypes.windll.user32 h = dll.GetProcessWindowStation() if not h: raise ctypes.WinError() uof = USEROBJECTFLAGS() needed = ctypes.wintypes.DWORD() res = dll.GetUserObjectInformationW(h, UOI_FLAGS, ctypes.byref(uof), ctypes.sizeof(uof), ctypes.byref(needed)) if not res: raise ctypes.WinError() if not bool(uof.dwFlags & WSF_VISIBLE): reason = "gui not available (WSF_VISIBLE flag not set)" elif sys.platform == 'darwin': # The Aqua Tk implementations on OS X can abort the process if # being called in an environment where a window server connection # cannot be made, for instance when invoked by a buildbot or ssh # process not running under the same user id as the current console # user. To avoid that, raise an exception if the window manager # connection is not available. from ctypes import cdll, c_int, pointer, Structure from ctypes.util import find_library app_services = cdll.LoadLibrary(find_library("ApplicationServices")) if app_services.CGMainDisplayID() == 0: reason = "gui tests cannot run without OS X window manager" else: class ProcessSerialNumber(Structure): _fields_ = [("highLongOfPSN", c_int), ("lowLongOfPSN", c_int)] psn = ProcessSerialNumber() psn_p = pointer(psn) if ( (app_services.GetCurrentProcess(psn_p) < 0) or (app_services.SetFrontProcess(psn_p) < 0) ): reason = "cannot run without OS X gui process" # check on every platform whether tkinter can actually do anything if not reason: try: from Tkinter import Tk root = Tk() root.withdraw() root.update() root.destroy() except Exception as e: err_string = str(e) if len(err_string) > 50: err_string = err_string[:50] + ' [...]' reason = 'Tk unavailable due to {}: {}'.format(type(e).__name__, err_string) _is_gui_available.reason = reason _is_gui_available.result = not reason return _is_gui_available.result def is_resource_enabled(resource): """Test 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. """ return use_resources is None or resource in use_resources def requires(resource, msg=None): """Raise ResourceDenied if the specified resource is not available.""" if not is_resource_enabled(resource): if msg is None: msg = "Use of the `%s' resource not enabled" % resource raise ResourceDenied(msg) if resource == 'gui' and not _is_gui_available(): raise ResourceDenied(_is_gui_available.reason) def requires_mac_ver(*min_version): """Decorator 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. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): if sys.platform == 'darwin': version_txt = platform.mac_ver()[0] try: version = tuple(map(int, version_txt.split('.'))) except ValueError: pass else: if version < min_version: min_version_txt = '.'.join(map(str, min_version)) raise unittest.SkipTest( "Mac OS X %s or higher required, not %s" % (min_version_txt, version_txt)) return func(*args, **kw) wrapper.min_version = min_version return wrapper return decorator # Don't use "localhost", since resolving it uses the DNS under recent # Windows versions (see issue #18792). HOST = "127.0.0.1" HOSTv6 = "::1" def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM): """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 socket.error 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.""" tempsock = socket.socket(family, socktype) port = bind_port(tempsock) tempsock.close() del tempsock return port def bind_port(sock, host=HOST): """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. """ if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM: if hasattr(socket, 'SO_REUSEADDR'): if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1: raise TestFailed("tests should never set the SO_REUSEADDR " \ "socket option on TCP/IP sockets!") if hasattr(socket, 'SO_REUSEPORT'): try: if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: raise TestFailed("tests should never set the SO_REUSEPORT " \ "socket option on TCP/IP sockets!") except EnvironmentError: # Python's socket module was compiled using modern headers # thus defining SO_REUSEPORT but this process is running # under an older kernel that does not support SO_REUSEPORT. pass if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'): sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) sock.bind((host, 0)) port = sock.getsockname()[1] return port def _is_ipv6_enabled(): """Check whether IPv6 is enabled on this host.""" if socket.has_ipv6: sock = None try: sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.bind((HOSTv6, 0)) return True except socket.error: pass finally: if sock: sock.close() return False IPV6_ENABLED = _is_ipv6_enabled() def system_must_validate_cert(f): """Skip the test on TLS certificate validation failures.""" @functools.wraps(f) def dec(*args, **kwargs): try: f(*args, **kwargs) except IOError as e: if "CERTIFICATE_VERIFY_FAILED" in str(e): raise unittest.SkipTest("system does not contain " "necessary certificates") raise return dec FUZZ = 1e-6 def fcmp(x, y): # fuzzy comparison function if isinstance(x, float) or isinstance(y, float): try: fuzz = (abs(x) + abs(y)) * FUZZ if abs(x-y) <= fuzz: return 0 except: pass elif type(x) == type(y) and isinstance(x, (tuple, list)): for i in range(min(len(x), len(y))): outcome = fcmp(x[i], y[i]) if outcome != 0: return outcome return (len(x) > len(y)) - (len(x) < len(y)) return (x > y) - (x < y) # A constant likely larger than the underlying OS pipe buffer size, to # make writes blocking. # Windows limit seems to be around 512 B, and many Unix kernels have a # 64 KiB pipe buffer size or 16 * PAGE_SIZE: take a few megs to be sure. # (see issue #17835 for a discussion of this number). PIPE_MAX_SIZE = 4 * 1024 * 1024 + 1 # A constant likely larger than the underlying OS socket buffer size, to make # writes blocking. # The socket buffer sizes can usually be tuned system-wide (e.g. through sysctl # on Linux), or on a per-socket basis (SO_SNDBUF/SO_RCVBUF). See issue #18643 # for a discussion of this number). SOCK_MAX_SIZE = 16 * 1024 * 1024 + 1 is_jython = sys.platform.startswith('java') try: unicode have_unicode = True except NameError: have_unicode = False requires_unicode = unittest.skipUnless(have_unicode, 'no unicode support') def u(s): return unicode(s, 'unicode-escape') # FS_NONASCII: non-ASCII Unicode character encodable by # sys.getfilesystemencoding(), or None if there is no such character. FS_NONASCII = None if have_unicode: for character in ( # First try printable and common characters to have a readable filename. # For each character, the encoding list are just example of encodings able # to encode the character (the list is not exhaustive). # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1 unichr(0x00E6), # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3 unichr(0x0130), # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257 unichr(0x0141), # U+03C6 (Greek Small Letter Phi): cp1253 unichr(0x03C6), # U+041A (Cyrillic Capital Letter Ka): cp1251 unichr(0x041A), # U+05D0 (Hebrew Letter Alef): Encodable to cp424 unichr(0x05D0), # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic unichr(0x060C), # U+062A (Arabic Letter Teh): cp720 unichr(0x062A), # U+0E01 (Thai Character Ko Kai): cp874 unichr(0x0E01), # Then try more "special" characters. "special" because they may be # interpreted or displayed differently depending on the exact locale # encoding and the font. # U+00A0 (No-Break Space) unichr(0x00A0), # U+20AC (Euro Sign) unichr(0x20AC), ): try: # In Windows, 'mbcs' is used, and encode() returns '?' # for characters missing in the ANSI codepage if character.encode(sys.getfilesystemencoding())\ .decode(sys.getfilesystemencoding())\ != character: raise UnicodeError except UnicodeError: pass else: FS_NONASCII = character break # Filename used for testing if os.name == 'java': # Jython disallows @ in module names TESTFN = '$test' elif os.name == 'riscos': TESTFN = 'testfile' else: TESTFN = '@test' # Unicode name only used if TEST_FN_ENCODING exists for the platform. if have_unicode: # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding() # TESTFN_UNICODE is a filename that can be encoded using the # file system encoding, but *not* with the default (ascii) encoding if isinstance('', unicode): # python -U # XXX perhaps unicode() should accept Unicode strings? TESTFN_UNICODE = "@test-\xe0\xf2" else: # 2 latin characters. TESTFN_UNICODE = unicode("@test-\xe0\xf2", "latin-1") TESTFN_ENCODING = sys.getfilesystemencoding() # TESTFN_UNENCODABLE is a filename that should *not* be # able to be encoded by *either* the default or filesystem encoding. # This test really only makes sense on Windows NT platforms # which have special Unicode support in posixmodule. if (not hasattr(sys, "getwindowsversion") or sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME TESTFN_UNENCODABLE = None else: # Japanese characters (I think - from bug 846133) TESTFN_UNENCODABLE = eval('u"@test-\u5171\u6709\u3055\u308c\u308b"') try: # XXX - Note - should be using TESTFN_ENCODING here - but for # Windows, "mbcs" currently always operates as if in # errors=ignore' mode - hence we get '?' characters rather than # the exception. 'Latin1' operates as we expect - ie, fails. # See [ 850997 ] mbcs encoding ignores errors TESTFN_UNENCODABLE.encode("Latin1") except UnicodeEncodeError: pass else: print \ 'WARNING: The filename %r CAN be encoded by the filesystem. ' \ 'Unicode filename tests may not be effective' \ % TESTFN_UNENCODABLE # Disambiguate TESTFN for parallel testing, while letting it remain a valid # module name. TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid()) # Define the URL of a dedicated HTTP server for the network tests. # The URL must use clear-text HTTP: no redirection to encrypted HTTPS. TEST_HTTP_URL = "http://www.pythontest.net" # Save the initial cwd SAVEDCWD = os.getcwd() @contextlib.contextmanager def temp_dir(path=None, quiet=False): """Return a context manager that creates a temporary directory. Arguments: path: the directory to create temporarily. If omitted or None, defaults to creating a temporary directory using tempfile.mkdtemp. quiet: if False (the default), the context manager raises an exception on error. Otherwise, if the path is specified and cannot be created, only a warning is issued. """ dir_created = False if path is None: import tempfile path = tempfile.mkdtemp() dir_created = True path = os.path.realpath(path) else: if (have_unicode and isinstance(path, unicode) and not os.path.supports_unicode_filenames): try: path = path.encode(sys.getfilesystemencoding() or 'ascii') except UnicodeEncodeError: if not quiet: raise unittest.SkipTest('unable to encode the cwd name with ' 'the filesystem encoding.') try: os.mkdir(path) dir_created = True except OSError: if not quiet: raise warnings.warn('tests may fail, unable to create temp dir: ' + path, RuntimeWarning, stacklevel=3) if dir_created: pid = os.getpid() try: yield path finally: # In case the process forks, let only the parent remove the # directory. The child has a diffent process id. (bpo-30028) if dir_created and pid == os.getpid(): rmtree(path) @contextlib.contextmanager def change_cwd(path, quiet=False): """Return a context manager that changes the current working directory. Arguments: path: the directory to use as the temporary current working directory. quiet: if False (the default), the context manager raises an exception on error. Otherwise, it issues only a warning and keeps the current working directory the same. """ saved_dir = os.getcwd() try: os.chdir(path) except OSError: if not quiet: raise warnings.warn('tests may fail, unable to change CWD to: ' + path, RuntimeWarning, stacklevel=3) try: yield os.getcwd() finally: os.chdir(saved_dir) @contextlib.contextmanager def temp_cwd(name='tempcwd', quiet=False): """ 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. """ with temp_dir(path=name, quiet=quiet) as temp_path: with change_cwd(temp_path, quiet=quiet) as cwd_dir: yield cwd_dir # TEST_HOME_DIR refers to the top level directory of the "test" package # that contains Python's regression test suite TEST_SUPPORT_DIR = os.path.dirname(os.path.abspath(__file__)) TEST_HOME_DIR = os.path.dirname(TEST_SUPPORT_DIR) # TEST_DATA_DIR is used as a target download location for remote resources TEST_DATA_DIR = os.path.join(TEST_HOME_DIR, "data") def findfile(file, subdir=None): """Try to find a file on sys.path and the working 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).""" if os.path.isabs(file): return file if subdir is not None: file = os.path.join(subdir, file) path = [TEST_HOME_DIR] + sys.path for dn in path: fn = os.path.join(dn, file) if os.path.exists(fn): return fn return file def sortdict(dict): "Like repr(dict), but in sorted order." items = dict.items() items.sort() reprpairs = ["%r: %r" % pair for pair in items] withcommas = ", ".join(reprpairs) return "{%s}" % withcommas def make_bad_fd(): """ Create an invalid file descriptor by opening and closing a file and return its fd. """ file = open(TESTFN, "wb") try: return file.fileno() finally: file.close() unlink(TESTFN) def check_syntax_error(testcase, statement, errtext='', lineno=None, offset=None): with testcase.assertRaisesRegexp(SyntaxError, errtext) as cm: compile(statement, '', 'exec') err = cm.exception if lineno is not None: testcase.assertEqual(err.lineno, lineno) if offset is not None: testcase.assertEqual(err.offset, offset) def open_urlresource(url, check=None): import urlparse, urllib2 filename = urlparse.urlparse(url)[2].split('/')[-1] # '/': it's URL! fn = os.path.join(TEST_DATA_DIR, filename) def check_valid_file(fn): f = open(fn) if check is None: return f elif check(f): f.seek(0) return f f.close() if os.path.exists(fn): f = check_valid_file(fn) if f is not None: return f unlink(fn) # Verify the requirement before downloading the file requires('urlfetch') print >> get_original_stdout(), '\tfetching %s ...' % url f = urllib2.urlopen(url, timeout=15) try: with open(fn, "wb") as out: s = f.read() while s: out.write(s) s = f.read() finally: f.close() f = check_valid_file(fn) if f is not None: return f raise TestFailed('invalid resource "%s"' % fn) class WarningsRecorder(object): """Convenience wrapper for the warnings list returned on entry to the warnings.catch_warnings() context manager. """ def __init__(self, warnings_list): self._warnings = warnings_list self._last = 0 def __getattr__(self, attr): if len(self._warnings) > self._last: return getattr(self._warnings[-1], attr) elif attr in warnings.WarningMessage._WARNING_DETAILS: return None raise AttributeError("%r has no attribute %r" % (self, attr)) @property def warnings(self): return self._warnings[self._last:] def reset(self): self._last = len(self._warnings) def _filterwarnings(filters, quiet=False): """Catch 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. """ # Clear the warning registry of the calling module # in order to re-raise the warnings. frame = sys._getframe(2) registry = frame.f_globals.get('__warningregistry__') if registry: registry.clear() with warnings.catch_warnings(record=True) as w: # Set filter "always" to record all warnings. Because # test_warnings swap the module, we need to look up in # the sys.modules dictionary. sys.modules['warnings'].simplefilter("always") yield WarningsRecorder(w) # Filter the recorded warnings reraise = [warning.message for warning in w] missing = [] for msg, cat in filters: seen = False for exc in reraise[:]: message = str(exc) # Filter out the matching messages if (re.match(msg, message, re.I) and issubclass(exc.__class__, cat)): seen = True reraise.remove(exc) if not seen and not quiet: # This filter caught nothing missing.append((msg, cat.__name__)) if reraise: raise AssertionError("unhandled warning %r" % reraise[0]) if missing: raise AssertionError("filter (%r, %s) did not catch any warning" % missing[0]) @contextlib.contextmanager def check_warnings(*filters, **kwargs): """Context manager to silence warnings. Accept 2-tuples as positional arguments: ("message regexp", WarningCategory) Optional argument: - if 'quiet' is True, it does not fail if a filter catches nothing (default True without argument, default False if some filters are defined) Without argument, it defaults to: check_warnings(("", Warning), quiet=True) """ quiet = kwargs.get('quiet') if not filters: filters = (("", Warning),) # Preserve backward compatibility if quiet is None: quiet = True return _filterwarnings(filters, quiet) @contextlib.contextmanager def check_py3k_warnings(*filters, **kwargs): """Context manager to silence py3k 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 False) Without argument, it defaults to: check_py3k_warnings(("", DeprecationWarning), quiet=False) """ if sys.py3kwarning: if not filters: filters = (("", DeprecationWarning),) else: # It should not raise any py3k warning filters = () return _filterwarnings(filters, kwargs.get('quiet')) class CleanImport(object): """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 """ def __init__(self, *module_names): self.original_modules = sys.modules.copy() for module_name in module_names: if module_name in sys.modules: module = sys.modules[module_name] # It is possible that module_name is just an alias for # another module (e.g. stub for modules renamed in 3.x). # In that case, we also need delete the real module to clear # the import cache. if module.__name__ != module_name: del sys.modules[module.__name__] del sys.modules[module_name] def __enter__(self): return self def __exit__(self, *ignore_exc): sys.modules.update(self.original_modules) class EnvironmentVarGuard(UserDict.DictMixin): """Class to help protect the environment variable properly. Can be used as a context manager.""" def __init__(self): self._environ = os.environ self._changed = {} def __getitem__(self, envvar): return self._environ[envvar] def __setitem__(self, envvar, value): # Remember the initial value on the first access if envvar not in self._changed: self._changed[envvar] = self._environ.get(envvar) self._environ[envvar] = value def __delitem__(self, envvar): # Remember the initial value on the first access if envvar not in self._changed: self._changed[envvar] = self._environ.get(envvar) if envvar in self._environ: del self._environ[envvar] def keys(self): return self._environ.keys() def set(self, envvar, value): self[envvar] = value def unset(self, envvar): del self[envvar] def __enter__(self): return self def __exit__(self, *ignore_exc): for (k, v) in self._changed.items(): if v is None: if k in self._environ: del self._environ[k] else: self._environ[k] = v os.environ = self._environ class DirsOnSysPath(object): """Context manager to temporarily add directories to sys.path. This makes a copy of sys.path, appends any directories given as positional arguments, then reverts sys.path to the copied settings when the context ends. Note that *all* sys.path modifications in the body of the context manager, including replacement of the object, will be reverted at the end of the block. """ def __init__(self, *paths): self.original_value = sys.path[:] self.original_object = sys.path sys.path.extend(paths) def __enter__(self): return self def __exit__(self, *ignore_exc): sys.path = self.original_object sys.path[:] = self.original_value class TransientResource(object): """Raise ResourceDenied if an exception is raised while the context manager is in effect that matches the specified exception and attributes.""" def __init__(self, exc, **kwargs): self.exc = exc self.attrs = kwargs def __enter__(self): return self def __exit__(self, type_=None, value=None, traceback=None): """If type_ is a subclass of self.exc and value has attributes matching self.attrs, raise ResourceDenied. Otherwise let the exception propagate (if any).""" if type_ is not None and issubclass(self.exc, type_): for attr, attr_value in self.attrs.iteritems(): if not hasattr(value, attr): break if getattr(value, attr) != attr_value: break else: raise ResourceDenied("an optional resource is not available") @contextlib.contextmanager def transient_internet(resource_name, timeout=30.0, errnos=()): """Return a context manager that raises ResourceDenied when various issues with the Internet connection manifest themselves as exceptions.""" default_errnos = [ ('ECONNREFUSED', 111), ('ECONNRESET', 104), ('EHOSTUNREACH', 113), ('ENETUNREACH', 101), ('ETIMEDOUT', 110), # socket.create_connection() fails randomly with # EADDRNOTAVAIL on Travis CI. ('EADDRNOTAVAIL', 99), ] default_gai_errnos = [ ('EAI_AGAIN', -3), ('EAI_FAIL', -4), ('EAI_NONAME', -2), ('EAI_NODATA', -5), # Windows defines EAI_NODATA as 11001 but idiotic getaddrinfo() # implementation actually returns WSANO_DATA i.e. 11004. ('WSANO_DATA', 11004), ] denied = ResourceDenied("Resource '%s' is not available" % resource_name) captured_errnos = errnos gai_errnos = [] if not captured_errnos: captured_errnos = [getattr(errno, name, num) for (name, num) in default_errnos] gai_errnos = [getattr(socket, name, num) for (name, num) in default_gai_errnos] def filter_error(err): n = getattr(err, 'errno', None) if (isinstance(err, socket.timeout) or (isinstance(err, socket.gaierror) and n in gai_errnos) or n in captured_errnos): if not verbose: sys.stderr.write(denied.args[0] + "\n") raise denied old_timeout = socket.getdefaulttimeout() try: if timeout is not None: socket.setdefaulttimeout(timeout) yield except IOError as err: # urllib can wrap original socket errors multiple times (!), we must # unwrap to get at the original error. while True: a = err.args if len(a) >= 1 and isinstance(a[0], IOError): err = a[0] # The error can also be wrapped as args[1]: # except socket.error as msg: # raise IOError('socket error', msg).with_traceback(sys.exc_info()[2]) elif len(a) >= 2 and isinstance(a[1], IOError): err = a[1] else: break filter_error(err) raise # XXX should we catch generic exceptions and look for their # __cause__ or __context__? finally: socket.setdefaulttimeout(old_timeout) @contextlib.contextmanager def captured_output(stream_name): """Return a context manager used by captured_stdout and captured_stdin that temporarily replaces the sys stream *stream_name* with a StringIO.""" import StringIO orig_stdout = getattr(sys, stream_name) setattr(sys, stream_name, StringIO.StringIO()) try: yield getattr(sys, stream_name) finally: setattr(sys, stream_name, orig_stdout) def captured_stdout(): """Capture the output of sys.stdout: with captured_stdout() as s: print "hello" self.assertEqual(s.getvalue(), "hello") """ return captured_output("stdout") def captured_stderr(): return captured_output("stderr") def captured_stdin(): return captured_output("stdin") def gc_collect(): """Force as many objects as possible to be collected. In non-CPython implementations of Python, this is needed because timely deallocation is not guaranteed by the garbage collector. (Even in CPython this can be the case in case of reference cycles.) This means that __del__ methods may be called later than expected and weakrefs may remain alive for longer than expected. This function tries its best to force all garbage objects to disappear. """ gc.collect() if is_jython: time.sleep(0.1) gc.collect() gc.collect() _header = '2P' if hasattr(sys, "gettotalrefcount"): _header = '2P' + _header _vheader = _header + 'P' def calcobjsize(fmt): return struct.calcsize(_header + fmt + '0P') def calcvobjsize(fmt): return struct.calcsize(_vheader + fmt + '0P') _TPFLAGS_HAVE_GC = 1<<14 _TPFLAGS_HEAPTYPE = 1<<9 def check_sizeof(test, o, size): import _testcapi result = sys.getsizeof(o) # add GC header size if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\ ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))): size += _testcapi.SIZEOF_PYGC_HEAD msg = 'wrong size for %s: got %d, expected %d' \ % (type(o), result, size) test.assertEqual(result, size, msg) #======================================================================= # Decorator for running a function in a different locale, correctly resetting # it afterwards. def run_with_locale(catstr, *locales): def decorator(func): def inner(*args, **kwds): try: import locale category = getattr(locale, catstr) orig_locale = locale.setlocale(category) except AttributeError: # if the test author gives us an invalid category string raise except: # cannot retrieve original locale, so do nothing locale = orig_locale = None else: for loc in locales: try: locale.setlocale(category, loc) break except: pass # now run the function, resetting the locale on exceptions try: return func(*args, **kwds) finally: if locale and orig_locale: locale.setlocale(category, orig_locale) inner.func_name = func.func_name inner.__doc__ = func.__doc__ return inner return decorator #======================================================================= # Decorator for running a function in a specific timezone, correctly # resetting it afterwards. def run_with_tz(tz): def decorator(func): def inner(*args, **kwds): try: tzset = time.tzset except AttributeError: raise unittest.SkipTest("tzset required") if 'TZ' in os.environ: orig_tz = os.environ['TZ'] else: orig_tz = None os.environ['TZ'] = tz tzset() # now run the function, resetting the tz on exceptions try: return func(*args, **kwds) finally: if orig_tz is None: del os.environ['TZ'] else: os.environ['TZ'] = orig_tz time.tzset() inner.__name__ = func.__name__ inner.__doc__ = func.__doc__ return inner return decorator #======================================================================= # Big-memory-test support. Separate from 'resources' because memory use should be configurable. # Some handy shorthands. Note that these are used for byte-limits as well # as size-limits, in the various bigmem tests _1M = 1024*1024 _1G = 1024 * _1M _2G = 2 * _1G _4G = 4 * _1G MAX_Py_ssize_t = sys.maxsize def set_memlimit(limit): global max_memuse global real_max_memuse sizes = { 'k': 1024, 'm': _1M, 'g': _1G, 't': 1024*_1G, } m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit, re.IGNORECASE | re.VERBOSE) if m is None: raise ValueError('Invalid memory limit %r' % (limit,)) memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()]) real_max_memuse = memlimit if memlimit > MAX_Py_ssize_t: memlimit = MAX_Py_ssize_t if memlimit < _2G - 1: raise ValueError('Memory limit %r too low to be useful' % (limit,)) max_memuse = memlimit def bigmemtest(minsize, memuse, overhead=5*_1M): """Decorator for bigmem tests. 'minsize' is the minimum useful size for the test (in arbitrary, test-interpreted units.) 'memuse' is the number of 'bytes per size' for the test, or a good estimate of it. 'overhead' specifies fixed overhead, independent of the testsize, and defaults to 5Mb. The decorator tries to guess a good value for 'size' and passes it to the decorated test function. If minsize * memuse is more than the allowed memory use (as defined by max_memuse), the test is skipped. Otherwise, minsize is adjusted upward to use up to max_memuse. """ def decorator(f): def wrapper(self): if not max_memuse: # If max_memuse is 0 (the default), # we still want to run the tests with size set to a few kb, # to make sure they work. We still want to avoid using # too much memory, though, but we do that noisily. maxsize = 5147 self.assertFalse(maxsize * memuse + overhead > 20 * _1M) else: maxsize = int((max_memuse - overhead) / memuse) if maxsize < minsize: # Really ought to print 'test skipped' or something if verbose: sys.stderr.write("Skipping %s because of memory " "constraint\n" % (f.__name__,)) return # Try to keep some breathing room in memory use maxsize = max(maxsize - 50 * _1M, minsize) return f(self, maxsize) wrapper.minsize = minsize wrapper.memuse = memuse wrapper.overhead = overhead return wrapper return decorator def precisionbigmemtest(size, memuse, overhead=5*_1M, dry_run=True): def decorator(f): def wrapper(self): if not real_max_memuse: maxsize = 5147 else: maxsize = size if ((real_max_memuse or not dry_run) and real_max_memuse < maxsize * memuse): if verbose: sys.stderr.write("Skipping %s because of memory " "constraint\n" % (f.__name__,)) return return f(self, maxsize) wrapper.size = size wrapper.memuse = memuse wrapper.overhead = overhead return wrapper return decorator def bigaddrspacetest(f): """Decorator for tests that fill the address space.""" def wrapper(self): if max_memuse < MAX_Py_ssize_t: if verbose: sys.stderr.write("Skipping %s because of memory " "constraint\n" % (f.__name__,)) else: return f(self) return wrapper #======================================================================= # unittest integration. class BasicTestRunner: def run(self, test): result = unittest.TestResult() test(result) return result def _id(obj): return obj def requires_resource(resource): if resource == 'gui' and not _is_gui_available(): return unittest.skip(_is_gui_available.reason) if is_resource_enabled(resource): return _id else: return unittest.skip("resource {0!r} is not enabled".format(resource)) def cpython_only(test): """ Decorator for tests only applicable on CPython. """ return impl_detail(cpython=True)(test) def impl_detail(msg=None, **guards): if check_impl_detail(**guards): return _id if msg is None: guardnames, default = _parse_guards(guards) if default: msg = "implementation detail not available on {0}" else: msg = "implementation detail specific to {0}" guardnames = sorted(guardnames.keys()) msg = msg.format(' or '.join(guardnames)) return unittest.skip(msg) def _parse_guards(guards): # Returns a tuple ({platform_name: run_me}, default_value) if not guards: return ({'cpython': True}, False) is_true = guards.values()[0] assert guards.values() == [is_true] * len(guards) # all True or all False return (guards, not is_true) # Use the following check to guard CPython's implementation-specific tests -- # or to run them only on the implementation(s) guarded by the arguments. def check_impl_detail(**guards): """This function returns True or False depending on the host platform. Examples: if check_impl_detail(): # only on CPython (default) if check_impl_detail(jython=True): # only on Jython if check_impl_detail(cpython=False): # everywhere except on CPython """ guards, default = _parse_guards(guards) return guards.get(platform.python_implementation().lower(), default) def _filter_suite(suite, pred): """Recursively filter test cases in a suite based on a predicate.""" newtests = [] for test in suite._tests: if isinstance(test, unittest.TestSuite): _filter_suite(test, pred) newtests.append(test) else: if pred(test): newtests.append(test) suite._tests = newtests def _run_suite(suite): """Run tests from a unittest.TestSuite-derived class.""" if verbose: runner = unittest.TextTestRunner(sys.stdout, verbosity=2, failfast=failfast) else: runner = BasicTestRunner() result = runner.run(suite) if not result.testsRun and not result.skipped: raise TestDidNotRun if not result.wasSuccessful(): if len(result.errors) == 1 and not result.failures: err = result.errors[0][1] elif len(result.failures) == 1 and not result.errors: err = result.failures[0][1] else: err = "multiple errors occurred" if not verbose: err += "; run in verbose mode for details" raise TestFailed(err) # By default, don't filter tests _match_test_func = None _match_test_patterns = None def match_test(test): # Function used by support.run_unittest() and regrtest --list-cases if _match_test_func is None: return True else: return _match_test_func(test.id()) def _is_full_match_test(pattern): # If a pattern contains at least one dot, it's considered # as a full test identifier. # Example: 'test.test_os.FileTests.test_access'. # # Reject patterns which contain fnmatch patterns: '*', '?', '[...]' # or '[!...]'. For example, reject 'test_access*'. return ('.' in pattern) and (not re.search(r'[?*\[\]]', pattern)) def set_match_tests(patterns): global _match_test_func, _match_test_patterns if patterns == _match_test_patterns: # No change: no need to recompile patterns. return if not patterns: func = None # set_match_tests(None) behaves as set_match_tests(()) patterns = () elif all(map(_is_full_match_test, patterns)): # Simple case: all patterns are full test identifier. # The test.bisect utility only uses such full test identifiers. func = set(patterns).__contains__ else: regex = '|'.join(map(fnmatch.translate, patterns)) # The search *is* case sensitive on purpose: # don't use flags=re.IGNORECASE regex_match = re.compile(regex).match def match_test_regex(test_id): if regex_match(test_id): # The regex matchs the whole identifier like # 'test.test_os.FileTests.test_access' return True else: # Try to match parts of the test identifier. # For example, split 'test.test_os.FileTests.test_access' # into: 'test', 'test_os', 'FileTests' and 'test_access'. return any(map(regex_match, test_id.split("."))) func = match_test_regex # Create a copy since patterns can be mutable and so modified later _match_test_patterns = tuple(patterns) _match_test_func = func def run_unittest(*classes): """Run tests from unittest.TestCase-derived classes.""" valid_types = (unittest.TestSuite, unittest.TestCase) suite = unittest.TestSuite() for cls in classes: if isinstance(cls, str): if cls in sys.modules: suite.addTest(unittest.findTestCases(sys.modules[cls])) else: raise ValueError("str arguments must be keys in sys.modules") elif isinstance(cls, valid_types): suite.addTest(cls) else: suite.addTest(unittest.makeSuite(cls)) _filter_suite(suite, match_test) _run_suite(suite) #======================================================================= # Check for the presence of docstrings. HAVE_DOCSTRINGS = (check_impl_detail(cpython=False) or sys.platform == 'win32' or sysconfig.get_config_var('WITH_DOC_STRINGS')) requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS, "test requires docstrings") #======================================================================= # doctest driver. def run_doctest(module, verbosity=None): """Run doctest on the given module. Return (#failures, #tests). If optional argument verbosity is not specified (or is None), pass test.support's belief about verbosity on to doctest. Else doctest's usual behavior is used (it searches sys.argv for -v). """ import doctest if verbosity is None: verbosity = verbose else: verbosity = None # Direct doctest output (normally just errors) to real stdout; doctest # output shouldn't be compared by regrtest. save_stdout = sys.stdout sys.stdout = get_original_stdout() try: f, t = doctest.testmod(module, verbose=verbosity) if f: raise TestFailed("%d of %d doctests failed" % (f, t)) finally: sys.stdout = save_stdout if verbose: print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t) return f, t #======================================================================= # Threading support to prevent reporting refleaks when running regrtest.py -R # Flag used by saved_test_environment of test.libregrtest.save_env, # to check if a test modified the environment. The flag should be set to False # before running a new test. # # For example, threading_cleanup() sets the flag is the function fails # to cleanup threads. environment_altered = False # NOTE: we use thread._count() rather than threading.enumerate() (or the # moral equivalent thereof) because a threading.Thread object is still alive # until its __bootstrap() method has returned, even after it has been # unregistered from the threading module. # thread._count(), on the other hand, only gets decremented *after* the # __bootstrap() method has returned, which gives us reliable reference counts # at the end of a test run. def threading_setup(): if thread: return thread._count(), else: return 1, def threading_cleanup(nb_threads): if not thread: return _MAX_COUNT = 10 for count in range(_MAX_COUNT): n = thread._count() if n == nb_threads: break time.sleep(0.1) # XXX print a warning in case of failure? def reap_threads(func): """Use 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. """ if not thread: return func @functools.wraps(func) def decorator(*args): key = threading_setup() try: return func(*args) finally: threading_cleanup(*key) return decorator @contextlib.contextmanager def wait_threads_exit(timeout=60.0): """ 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. """ old_count = thread._count() try: yield finally: start_time = time.time() deadline = start_time + timeout while True: count = thread._count() if count <= old_count: break if time.time() > deadline: dt = time.time() - start_time msg = ("wait_threads() failed to cleanup %s " "threads after %.1f seconds " "(count: %s, old count: %s)" % (count - old_count, dt, count, old_count)) raise AssertionError(msg) time.sleep(0.010) gc_collect() def reap_children(): """Use 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. """ # Reap all our dead child processes so we don't leave zombies around. # These hog resources and might be causing some of the buildbots to die. if hasattr(os, 'waitpid'): any_process = -1 while True: try: # This will raise an exception on Windows. That's ok. pid, status = os.waitpid(any_process, os.WNOHANG) if pid == 0: break except: break @contextlib.contextmanager def start_threads(threads, unlock=None): threads = list(threads) started = [] try: try: for t in threads: t.start() started.append(t) except: if verbose: print("Can't start %d threads, only %d threads started" % (len(threads), len(started))) raise yield finally: if unlock: unlock() endtime = starttime = time.time() for timeout in range(1, 16): endtime += 60 for t in started: t.join(max(endtime - time.time(), 0.01)) started = [t for t in started if t.isAlive()] if not started: break if verbose: print('Unable to join %d threads during a period of ' '%d minutes' % (len(started), timeout)) started = [t for t in started if t.isAlive()] if started: raise AssertionError('Unable to join %d threads' % len(started)) @contextlib.contextmanager def swap_attr(obj, attr, new_val): """Temporary swap out an attribute with a new object. Usage: with swap_attr(obj, "attr", 5): ... This will set obj.attr to 5 for the duration of the with: block, restoring the old value at the end of the block. If `attr` doesn't exist on `obj`, it will be created and then deleted at the end of the block. The old value (or None if it doesn't exist) will be assigned to the target of the "as" clause, if there is one. """ if hasattr(obj, attr): real_val = getattr(obj, attr) setattr(obj, attr, new_val) try: yield real_val finally: setattr(obj, attr, real_val) else: setattr(obj, attr, new_val) try: yield finally: if hasattr(obj, attr): delattr(obj, attr) @contextlib.contextmanager def swap_item(obj, item, new_val): """Temporary swap out an item with a new object. Usage: with swap_item(obj, "item", 5): ... This will set obj["item"] to 5 for the duration of the with: block, restoring the old value at the end of the block. If `item` doesn't exist on `obj`, it will be created and then deleted at the end of the block. The old value (or None if it doesn't exist) will be assigned to the target of the "as" clause, if there is one. """ if item in obj: real_val = obj[item] obj[item] = new_val try: yield real_val finally: obj[item] = real_val else: obj[item] = new_val try: yield finally: if item in obj: del obj[item] def py3k_bytes(b): """Emulate the py3k bytes() constructor. NOTE: This is only a best effort function. """ try: # memoryview? return b.tobytes() except AttributeError: try: # iterable of ints? return b"".join(chr(x) for x in b) except TypeError: return bytes(b) requires_type_collecting = unittest.skipIf(hasattr(sys, 'getcounts'), 'types are immortal if COUNT_ALLOCS is defined') def args_from_interpreter_flags(): """Return a list of command-line arguments reproducing the current settings in sys.flags.""" import subprocess return subprocess._args_from_interpreter_flags() def strip_python_stderr(stderr): """Strip 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. """ stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip() return stderr def check_free_after_iterating(test, iter, cls, args=()): class A(cls): def __del__(self): done[0] = True try: next(it) except StopIteration: pass done = [False] it = iter(A(*args)) # Issue 26494: Shouldn't crash test.assertRaises(StopIteration, next, it) # The sequence should be deallocated just after the end of iterating gc_collect() test.assertTrue(done[0]) @contextlib.contextmanager def disable_gc(): have_gc = gc.isenabled() gc.disable() try: yield finally: if have_gc: gc.enable() def python_is_optimized(): """Find if Python was built with optimizations.""" cflags = sysconfig.get_config_var('PY_CFLAGS') or '' final_opt = "" for opt in cflags.split(): if opt.startswith('-O'): final_opt = opt return final_opt not in ('', '-O0', '-Og') class SuppressCrashReport: """Try 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. """ old_value = None old_modes = None def __enter__(self): """On 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. """ if sys.platform.startswith('win'): # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx # GetErrorMode is not available on Windows XP and Windows Server 2003, # but SetErrorMode returns the previous value, so we can use that import ctypes self._k32 = ctypes.windll.kernel32 SEM_NOGPFAULTERRORBOX = 0x02 self.old_value = self._k32.SetErrorMode(SEM_NOGPFAULTERRORBOX) self._k32.SetErrorMode(self.old_value | SEM_NOGPFAULTERRORBOX) # Suppress assert dialogs in debug builds # (see http://bugs.python.org/issue23314) try: import _testcapi _testcapi.CrtSetReportMode except (AttributeError, ImportError): # no _testcapi or a release build pass else: self.old_modes = {} for report_type in [_testcapi.CRT_WARN, _testcapi.CRT_ERROR, _testcapi.CRT_ASSERT]: old_mode = _testcapi.CrtSetReportMode(report_type, _testcapi.CRTDBG_MODE_FILE) old_file = _testcapi.CrtSetReportFile(report_type, _testcapi.CRTDBG_FILE_STDERR) self.old_modes[report_type] = old_mode, old_file else: try: import resource except ImportError: resource = None if resource is not None: try: self.old_value = resource.getrlimit(resource.RLIMIT_CORE) resource.setrlimit(resource.RLIMIT_CORE, (0, self.old_value[1])) except (ValueError, OSError): pass if sys.platform == 'darwin': # Check if the 'Crash Reporter' on OSX was configured # in 'Developer' mode and warn that it will get triggered # when it is. # # This assumes that this context manager is used in tests # that might trigger the next manager. import subprocess cmd = ['/usr/bin/defaults', 'read', 'com.apple.CrashReporter', 'DialogType'] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = proc.communicate()[0] if stdout.strip() == b'developer': sys.stdout.write("this test triggers the Crash Reporter, " "that is intentional") sys.stdout.flush() return self def __exit__(self, *ignore_exc): """Restore Windows ErrorMode or core file behavior to initial value.""" if self.old_value is None: return if sys.platform.startswith('win'): self._k32.SetErrorMode(self.old_value) if self.old_modes: import _testcapi for report_type, (old_mode, old_file) in self.old_modes.items(): _testcapi.CrtSetReportMode(report_type, old_mode) _testcapi.CrtSetReportFile(report_type, old_file) else: import resource try: resource.setrlimit(resource.RLIMIT_CORE, self.old_value) except (ValueError, OSError): pass def _crash_python(): """Deliberate crash of Python. Python can be killed by a segmentation fault (SIGSEGV), a bus error (SIGBUS), or a different error depending on the platform. Use SuppressCrashReport() to prevent a crash report from popping up. """ import _testcapi with SuppressCrashReport(): _testcapi._read_null() def fd_count(): """Count the number of open file descriptors. """ if sys.platform.startswith(('linux', 'freebsd')): try: names = os.listdir("/proc/self/fd") # Substract one because listdir() opens internally a file # descriptor to list the content of the /proc/self/fd/ directory. return len(names) - 1 except OSError as exc: if exc.errno != errno.ENOENT: raise MAXFD = 256 if hasattr(os, 'sysconf'): try: MAXFD = os.sysconf("SC_OPEN_MAX") except OSError: pass old_modes = None if sys.platform == 'win32': # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process # on invalid file descriptor if Python is compiled in debug mode try: import msvcrt msvcrt.CrtSetReportMode except (AttributeError, ImportError): # no msvcrt or a release build pass else: old_modes = {} for report_type in (msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT): old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, 0) try: count = 0 for fd in range(MAXFD): try: # Prefer dup() over fstat(). fstat() can require input/output # whereas dup() doesn't. fd2 = os.dup(fd) except OSError as e: if e.errno != errno.EBADF: raise else: os.close(fd2) count += 1 finally: if old_modes is not None: for report_type in (msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT): msvcrt.CrtSetReportMode(report_type, old_modes[report_type]) return count class SaveSignals: """ 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. """ def __init__(self): import signal self.signal = signal self.signals = list(range(1, signal.NSIG)) # SIGKILL and SIGSTOP signals cannot be ignored nor catched for signame in ('SIGKILL', 'SIGSTOP'): try: signum = getattr(signal, signame) except AttributeError: continue self.signals.remove(signum) self.handlers = {} def save(self): for signum in self.signals: handler = self.signal.getsignal(signum) if handler is None: # getsignal() returns None if a signal handler was not # registered by the Python signal module, # and the handler is not SIG_DFL nor SIG_IGN. # # Ignore the signal: we cannot restore the handler. continue self.handlers[signum] = handler def restore(self): for signum, handler in self.handlers.items(): self.signal.signal(signum, handler) PK! ~support/script_helper.pynu[# Common utility functions used by various script execution tests # e.g. test_cmd_line, test_cmd_line_script and test_runpy import sys import os import re import os.path import tempfile import subprocess import py_compile import contextlib import shutil try: import zipfile except ImportError: # If Python is build without Unicode support, importing _io will # fail, which, in turn, means that zipfile cannot be imported # Most of this module can then still be used. pass from test.support import strip_python_stderr # Executing the interpreter in a subprocess def _assert_python(expected_success, *args, **env_vars): cmd_line = [sys.executable] if not env_vars: cmd_line.append('-E') cmd_line.extend(args) # Need to preserve the original environment, for in-place testing of # shared library builds. env = os.environ.copy() env.update(env_vars) p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) try: out, err = p.communicate() finally: subprocess._cleanup() p.stdout.close() p.stderr.close() rc = p.returncode err = strip_python_stderr(err) if (rc and expected_success) or (not rc and not expected_success): raise AssertionError( "Process return code is %d, " "stderr follows:\n%s" % (rc, err.decode('ascii', 'ignore'))) return rc, out, err def assert_python_ok(*args, **env_vars): """ Assert that running the interpreter with `args` and optional environment variables `env_vars` is ok and return a (return code, stdout, stderr) tuple. """ return _assert_python(True, *args, **env_vars) def assert_python_failure(*args, **env_vars): """ Assert that running the interpreter with `args` and optional environment variables `env_vars` fails and return a (return code, stdout, stderr) tuple. """ return _assert_python(False, *args, **env_vars) def python_exit_code(*args): cmd_line = [sys.executable, '-E'] cmd_line.extend(args) with open(os.devnull, 'w') as devnull: return subprocess.call(cmd_line, stdout=devnull, stderr=subprocess.STDOUT) def spawn_python(*args, **kwargs): cmd_line = [sys.executable, '-E'] cmd_line.extend(args) return subprocess.Popen(cmd_line, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kwargs) def kill_python(p): p.stdin.close() data = p.stdout.read() p.stdout.close() # try to cleanup the child so we don't appear to leak when running # with regrtest -R. p.wait() subprocess._cleanup() return data def run_python(*args, **kwargs): if __debug__: p = spawn_python(*args, **kwargs) else: p = spawn_python('-O', *args, **kwargs) stdout_data = kill_python(p) return p.wait(), stdout_data # Script creation utilities @contextlib.contextmanager def temp_dir(): dirname = tempfile.mkdtemp() dirname = os.path.realpath(dirname) try: yield dirname finally: shutil.rmtree(dirname) def make_script(script_dir, script_basename, source): script_filename = script_basename+os.extsep+'py' script_name = os.path.join(script_dir, script_filename) script_file = open(script_name, 'w') script_file.write(source) script_file.close() return script_name def compile_script(script_name): py_compile.compile(script_name, doraise=True) if __debug__: compiled_name = script_name + 'c' else: compiled_name = script_name + 'o' return compiled_name def make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None): zip_filename = zip_basename+os.extsep+'zip' zip_name = os.path.join(zip_dir, zip_filename) zip_file = zipfile.ZipFile(zip_name, 'w') if name_in_zip is None: name_in_zip = os.path.basename(script_name) zip_file.write(script_name, name_in_zip) zip_file.close() #if test.test_support.verbose: # zip_file = zipfile.ZipFile(zip_name, 'r') # print 'Contents of %r:' % zip_name # zip_file.printdir() # zip_file.close() return zip_name, os.path.join(zip_name, name_in_zip) def make_pkg(pkg_dir, init_source=''): os.mkdir(pkg_dir) make_script(pkg_dir, '__init__', init_source) def make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, source, depth=1, compiled=False): unlink = [] init_name = make_script(zip_dir, '__init__', '') unlink.append(init_name) init_basename = os.path.basename(init_name) script_name = make_script(zip_dir, script_basename, source) unlink.append(script_name) if compiled: init_name = compile_script(init_name) script_name = compile_script(script_name) unlink.extend((init_name, script_name)) pkg_names = [os.sep.join([pkg_name]*i) for i in range(1, depth+1)] script_name_in_zip = os.path.join(pkg_names[-1], os.path.basename(script_name)) zip_filename = zip_basename+os.extsep+'zip' zip_name = os.path.join(zip_dir, zip_filename) zip_file = zipfile.ZipFile(zip_name, 'w') for name in pkg_names: init_name_in_zip = os.path.join(name, init_basename) zip_file.write(init_name, init_name_in_zip) zip_file.write(script_name, script_name_in_zip) zip_file.close() for name in unlink: os.unlink(name) #if test.test_support.verbose: # zip_file = zipfile.ZipFile(zip_name, 'r') # print 'Contents of %r:' % zip_name # zip_file.printdir() # zip_file.close() return zip_name, os.path.join(zip_name, script_name_in_zip) PK!  support/testresult.pynu['''Test runner and result class for the regression test suite. ''' import functools import io import sys import time import traceback import unittest import xml.etree.ElementTree as ET from datetime import datetime class RegressionTestResult(unittest.TextTestResult): separator1 = '=' * 70 + '\n' separator2 = '-' * 70 + '\n' def __init__(self, stream, descriptions, verbosity): super().__init__(stream=stream, descriptions=descriptions, verbosity=0) self.buffer = True self.__suite = ET.Element('testsuite') self.__suite.set('start', datetime.utcnow().isoformat(' ')) self.__e = None self.__start_time = None self.__results = [] self.__verbose = bool(verbosity) @classmethod def __getId(cls, test): try: test_id = test.id except AttributeError: return str(test) try: return test_id() except TypeError: return str(test_id) return repr(test) def startTest(self, test): super().startTest(test) self.__e = e = ET.SubElement(self.__suite, 'testcase') self.__start_time = time.perf_counter() if self.__verbose: self.stream.write(f'{self.getDescription(test)} ... ') self.stream.flush() def _add_result(self, test, capture=False, **args): e = self.__e self.__e = None if e is None: return e.set('name', args.pop('name', self.__getId(test))) e.set('status', args.pop('status', 'run')) e.set('result', args.pop('result', 'completed')) if self.__start_time: e.set('time', f'{time.perf_counter() - self.__start_time:0.6f}') if capture: if self._stdout_buffer is not None: stdout = self._stdout_buffer.getvalue().rstrip() ET.SubElement(e, 'system-out').text = stdout if self._stderr_buffer is not None: stderr = self._stderr_buffer.getvalue().rstrip() ET.SubElement(e, 'system-err').text = stderr for k, v in args.items(): if not k or not v: continue e2 = ET.SubElement(e, k) if hasattr(v, 'items'): for k2, v2 in v.items(): if k2: e2.set(k2, str(v2)) else: e2.text = str(v2) else: e2.text = str(v) def __write(self, c, word): if self.__verbose: self.stream.write(f'{word}\n') @classmethod def __makeErrorDict(cls, err_type, err_value, err_tb): if isinstance(err_type, type): if err_type.__module__ == 'builtins': typename = err_type.__name__ else: typename = f'{err_type.__module__}.{err_type.__name__}' else: typename = repr(err_type) msg = traceback.format_exception(err_type, err_value, None) tb = traceback.format_exception(err_type, err_value, err_tb) return { 'type': typename, 'message': ''.join(msg), '': ''.join(tb), } def addError(self, test, err): self._add_result(test, True, error=self.__makeErrorDict(*err)) super().addError(test, err) self.__write('E', 'ERROR') def addExpectedFailure(self, test, err): self._add_result(test, True, output=self.__makeErrorDict(*err)) super().addExpectedFailure(test, err) self.__write('x', 'expected failure') def addFailure(self, test, err): self._add_result(test, True, failure=self.__makeErrorDict(*err)) super().addFailure(test, err) self.__write('F', 'FAIL') def addSkip(self, test, reason): self._add_result(test, skipped=reason) super().addSkip(test, reason) self.__write('S', f'skipped {reason!r}') def addSuccess(self, test): self._add_result(test) super().addSuccess(test) self.__write('.', 'ok') def addUnexpectedSuccess(self, test): self._add_result(test, outcome='UNEXPECTED_SUCCESS') super().addUnexpectedSuccess(test) self.__write('u', 'unexpected success') def printErrors(self): if self.__verbose: self.stream.write('\n') self.printErrorList('ERROR', self.errors) self.printErrorList('FAIL', self.failures) def printErrorList(self, flavor, errors): for test, err in errors: self.stream.write(self.separator1) self.stream.write(f'{flavor}: {self.getDescription(test)}\n') self.stream.write(self.separator2) self.stream.write('%s\n' % err) def get_xml_element(self): e = self.__suite e.set('tests', str(self.testsRun)) e.set('errors', str(len(self.errors))) e.set('failures', str(len(self.failures))) return e class QuietRegressionTestRunner: def __init__(self, stream, buffer=False): self.result = RegressionTestResult(stream, None, 0) self.result.buffer = buffer def run(self, test): test(self.result) return self.result def get_test_runner_class(verbosity, buffer=False): if verbosity: return functools.partial(unittest.TextTestRunner, resultclass=RegressionTestResult, buffer=buffer, verbosity=verbosity) return functools.partial(QuietRegressionTestRunner, buffer=buffer) def get_test_runner(stream, verbosity, capture_output=False): return get_test_runner_class(verbosity, capture_output)(stream) if __name__ == '__main__': class TestTests(unittest.TestCase): def test_pass(self): pass def test_pass_slow(self): time.sleep(1.0) def test_fail(self): print('stdout', file=sys.stdout) print('stderr', file=sys.stderr) self.fail('failure message') def test_error(self): print('stdout', file=sys.stdout) print('stderr', file=sys.stderr) raise RuntimeError('error message') suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestTests)) stream = io.StringIO() runner_cls = get_test_runner_class(sum(a == '-v' for a in sys.argv)) runner = runner_cls(sys.stdout) result = runner.run(suite) print('Output:', stream.getvalue()) print('XML: ', end='') for s in ET.tostringlist(result.get_xml_element()): print(s.decode(), end='') print() PK!E[// __init__.pynu[# Dummy file to make this directory a package. PK!&=support/__init__.pycnu[ {fc=@s dZedkr!ednddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZddlZyddlZWnek r:dZnXddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d4d<d=d>d?d@g=ZdAZdefdBYZdefdCYZdefdDYZdejfdEYZ ej!e"dFZ#e$dGZ%dHZ&dIZ'dde$dJZ(dKZ)dLZ*dZ+dMa,dMa-e$Z.da/dNZ0dOZ1dPZ2dQZ3e j j4dRr+e$dSZ5dTZ6dUZ7dVZ8ne j9Z6e j:Z7dWZ8dXZ9dYZ:dZZ;d[Z<d\Z=d]Z>dd^Z?d_Z@d`ZAdaZBejCejDdbZEeAdcZFddZGeGZHdeZIdfZJdgZKdZLdZMe j j4dkZNyeOe"ZPWneQk r-e$ZPnXejRePdlZSdmZTdZUePrxeVdneVdoeVdpeVdqeVdreVdseVdteVdueVdveVdweVdxf D]XZWy7eWjXe jYjZe jYeWkre[nWne[k rqXeWZUPqWne j\dkkr6dyZ]ne j\dzkrNd{Z]nd|Z]ePre^d}eOrrd~Z_neOd~dZ_e jYZ`eae d se jbddkrdZcqeddZcyecjXdWneek rqXdecGHndjfe]e jgZ]dZhe jiZjej!de$dZkej!e$dZlej!de$dZme jnjoe jnjpeqZre jnjoerZse jnjtesdZuddZvdZwdZxd}dddZyddZzde{fdYZ|e$dZ}ej!dZ~ej!dZd&e{fdYZd'ejfdYZde{fdYZd*e{fdYZej!dAddZej!dZdZdZdZdZdZeae drdeZnedZdZdZdZdZdZdZdZdZdieZdeZdheZe jZdZdedZdee"dZdZd0ddYZdZdZdZddZdZdZdZdZdadadZdZdZdZede$pW e j dkpW ejdZejRedZddZe$ZdZdZdZej!ddZdZej!ddZej!dZej!dZdZejeae ddZdZdZddZej!dZdZd@ddYZdZdZdddYZdS(s7Supporting definitions for the Python regression tests.s test.supports3test.support must be imported from the test packageiNtErrort TestFailedt TestDidNotRuntResourceDeniedt import_moduletverboset use_resourcest max_memusetrecord_original_stdouttget_original_stdouttunloadtunlinktrmtreetforgettis_resource_enabledtrequirestrequires_mac_vertfind_unused_portt bind_porttfcmpt have_unicodet is_jythontTESTFNtHOSTtFUZZtSAVEDCWDttemp_cwdtfindfiletsortdicttcheck_syntax_errortopen_urlresourcetcheck_warningstcheck_py3k_warningst CleanImporttEnvironmentVarGuardtcaptured_outputtcaptured_stdouttTransientResourcettransient_internettrun_with_localet set_memlimitt bigmemtesttbigaddrspacetesttBasicTestRunnert run_unittestt run_doctesttthreading_setuptthreading_cleanupt reap_threadst start_threadst cpython_onlytcheck_impl_detailt get_attributet py3k_bytestimport_fresh_modulet reap_childrentstrip_python_stderrt IPV6_ENABLEDt run_with_tztSuppressCrashReportg>@cBseZdZRS(s*Base class for regression test exceptions.(t__name__t __module__t__doc__(((s-/usr/lib64/python2.7/test/support/__init__.pyR4scBseZdZRS(s Test failed.(R<R=R>(((s-/usr/lib64/python2.7/test/support/__init__.pyR7scBseZdZRS(sTest did not run any subtests.(R<R=R>(((s-/usr/lib64/python2.7/test/support/__init__.pyR:scBseZdZRS(sTest skipped because it requested a disallowed resource. This is raised when a test calls requires() for a resource that has not been enabled. It is used to distinguish between expected and unexpected skips. (R<R=R>(((s-/usr/lib64/python2.7/test/support/__init__.pyR=sccs=|r4tjtjddtdVWdQXndVdS(sContext manager to suppress package and module deprecation warnings when importing them. If ignore is False, this context manager has no effect.tignores.+ (module|package)N(twarningstcatch_warningstfilterwarningstDeprecationWarning(R?((s-/usr/lib64/python2.7/test/support/__init__.pyt_ignore_deprecated_importsEs   c CsSt|Aytj|SWn(tk rH}tjt|nXWdQXdS(sImport 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.N(RDt importlibRt ImportErrortunittesttSkipTesttstr(tnamet deprecatedtmsg((s-/usr/lib64/python2.7/test/support/__init__.pyRTs  cCs|tjkr&t|tj|=nxTttjD]C}||ks[|j|dr6tj|||t|t rd|j|f}ndt |j|f}t j |nX|SdS(s?Get an attribute, raising SkipTest if AttributeError is raised.smodule %r has no attribute %rsclass %s has no attribute %rs%s instance has no attribute %rs"type object %r has no attribute %rs%r object has no attribute %rN( tgetattrtAttributeErrort isinstancettypest ModuleTypeR<t ClassTypet InstanceTypet __class__ttypeRGRH(tobjRJt attributeRL((s-/usr/lib64/python2.7/test/support/__init__.pyR4s iicCs |adS(N(t_original_stdout(tstdout((s-/usr/lib64/python2.7/test/support/__init__.pyRscCs tp tjS(N(RrRNRs(((s-/usr/lib64/python2.7/test/support/__init__.pyR scCs&ytj|=Wntk r!nXdS(N(RNRORW(RJ((s-/usr/lib64/python2.7/test/support/__init__.pyR s cGsxy||SWnctk rs}tdkrVd|jj|fGHd|j|fGHntj|tj||SXdS(Nis%s: %ss re-run %s%r(tEnvironmentErrorRRnR<tostchmodtstattS_IRWXU(tpathtfunctargsterr((s-/usr/lib64/python2.7/test/support/__init__.pyt _force_runs twincCs|||r|}n$tjj|\}}|p:d}d}xR|dkrtj|}|rm|n ||ks}dStj||d9}qFWtjd|tdddS(NRMgMbP?g?is)tests may fail, delete still pending for t stackleveli( RuRytsplittlistdirttimetsleepR@twarntRuntimeWarning(RztpathnametwaitalltdirnameRJttimeouttL((s-/usr/lib64/python2.7/test/support/__init__.pyt_waitfors     cCsttj|dS(N(RRuR (tfilename((s-/usr/lib64/python2.7/test/support/__init__.pyt_unlinkscCsttj|dS(N(RRutrmdir(R((s-/usr/lib64/python2.7/test/support/__init__.pyt_rmdirscs6fdt|dttd|dS(Ncsxt|tj|D]i}tjj||}tjj|rlt|dtt|tj|qt|tj |qWdS(NR( R}RuRRytjointisdirRRVRR (RyRJtfullname(t _rmtree_inner(s-/usr/lib64/python2.7/test/support/__init__.pyRs RcSst|tj|S(N(R}RuR(tp((s-/usr/lib64/python2.7/test/support/__init__.pyt t(RRV(Ry((Rs-/usr/lib64/python2.7/test/support/__init__.pyt_rmtreescsSytj|dSWntk r(nXfd|tj|dS(Ncsxt|tj|D]}tjj||}ytj|j}Wntk r`d}nXtj |r|t|tj |qt|tj |qWdS(Ni( R}RuRRyRtlstattst_modeRtRwtS_ISDIRRR (RyRJRtmode(R(s-/usr/lib64/python2.7/test/support/__init__.pyRs   (tshutilR RtRuR(Ry((Rs-/usr/lib64/python2.7/test/support/__init__.pyRs   cCsIyt|Wn4tk rD}|jtjtjfkrEqEnXdS(N(RtOSErrorterrnotENOENTtENOTDIR(Rtexc((s-/usr/lib64/python2.7/test/support/__init__.pyR $s cCs@yt|Wn+tk r;}|jtjkr<q<nXdS(N(RRRR(Rterror((s-/usr/lib64/python2.7/test/support/__init__.pyR+s cCsIyt|Wn4tk rD}|jtjtjfkrEqEnXdS(N(RRRRtESRCH(Ryte((s-/usr/lib64/python2.7/test/support/__init__.pyR 3s cCsjt|xYtjD]N}ttjj||tjdttjj||tjdqWdS(sm"Forget" a module was ever imported by removing it from sys.modules and deleting any .pyc and .pyo files.tpyctpyoN(R RNRyR RuRtextsep(RTR((s-/usr/lib64/python2.7/test/support/__init__.pyR ;s $csttdrtjSd}tjjdr ddlddld}d}dj ffdY}j j }|j }|sj n|}jj}|j||j|j|j|}|sj nt|j|@sd}qntjdkrdd lm} mm} m } dd lm} | j| d } | jd krd }qd| ffdY}|}| |}| j|d ks| j|d krd}qn|sy;ddlm}|}|j |j!|j"Wqt#k r}t$|}t%|dkrz|d d}ndj&t'|j(|}qXn|t_)| t_tjS(NtresultR~iitUSEROBJECTFLAGScs;eZdjjfdjjfdjjfgZRS(tfInheritt fReservedtdwFlags(R<R=twintypestBOOLtDWORDt_fields_((tctypes(s-/usr/lib64/python2.7/test/support/__init__.pyRRss,gui not available (WSF_VISIBLE flag not set)tdarwin(tcdlltc_inttpointert Structure(t find_librarytApplicationServicesis0gui tests cannot run without OS X window managertProcessSerialNumbercs eZdfdfgZRS(t highLongOfPSNt lowLongOfPSN(R<R=R((R(s-/usr/lib64/python2.7/test/support/__init__.pyRts s#cannot run without OS X gui process(tTki2s [...]sTk unavailable due to {}: {}(*thasattrt_is_gui_availableRRYRNtplatformRRRtctypes.wintypesRtwindlltuser32tGetProcessWindowStationtWinErrorRRtGetUserObjectInformationWtbyreftsizeoftboolRRRRt ctypes.utilRt LoadLibrarytCGMainDisplayIDtGetCurrentProcesstSetFrontProcesstTkinterRtwithdrawtupdatetdestroyt ExceptionRItlentformatRoR<treason(Rt UOI_FLAGSt WSF_VISIBLERtdllthtuoftneededtresRRRRt app_servicesRtpsntpsn_pRtrootRt err_string((RRs-/usr/lib64/python2.7/test/support/__init__.pyRGsh         "          cCstdkp|tkS(sTest 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(RRY(tresource((s-/usr/lib64/python2.7/test/support/__init__.pyRscCs`t|s4|dkr%d|}nt|n|dkr\t r\ttjndS(s@Raise ResourceDenied if the specified resource is not available.s$Use of the `%s' resource not enabledtguiN(RRYRRR(RRL((s-/usr/lib64/python2.7/test/support/__init__.pyRs    csfd}|S(sDecorator 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.tjfd}|_|S(Ncstjdkrtjd}y"ttt|jd}Wntk rTqX|krdjtt }t j d||fqn||S(NRiRMs&Mac OS X %s or higher required, not %s( RNRtmac_verttupletmaptintRt ValueErrorRRIRGRH(R{tkwt version_txttversiontmin_version_txt(Rzt min_version(s-/usr/lib64/python2.7/test/support/__init__.pytwrappers"  (t functoolstwrapsR(RzR(R(Rzs-/usr/lib64/python2.7/test/support/__init__.pyt decorators! ((RR((Rs-/usr/lib64/python2.7/test/support/__init__.pyRss 127.0.0.1s::1cCs/tj||}t|}|j~|S(s 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 socket.error 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.(tsocketRtclose(tfamilytsocktypettempsocktport((s-/usr/lib64/python2.7/test/support/__init__.pyRs 6  cCs|jtjkr|jtjkrttdrc|jtjtjdkrct dqcnttdry1|jtjtj dkrt dnWqt k rqXnttdr|j tjtj dqn|j|df|jd}|S(s%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. t SO_REUSEADDRisHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets!t SO_REUSEPORTsHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!tSO_EXCLUSIVEADDRUSEi(RRtAF_INETRot SOCK_STREAMRt getsockoptt SOL_SOCKETRRRRtt setsockoptRtbindt getsockname(tsockthostR((s-/usr/lib64/python2.7/test/support/__init__.pyRs$ cCs{tjrwd}zNy3tjtjtj}|jtdftSWntjk r[nXWd|rs|j nXnt S(s+Check whether IPv6 is enabled on this host.iN( Rthas_ipv6RYtAF_INET6RRtHOSTv6RVRRRX(R((s-/usr/lib64/python2.7/test/support/__init__.pyt_is_ipv6_enabled$s cs"tjfd}|S(s5Skip the test on TLS certificate validation failures.csRy||Wn:tk rM}dt|krGtjdnnXdS(NtCERTIFICATE_VERIFY_FAILEDs.system does not contain necessary certificates(tIOErrorRIRGRH(R{tkwargsR(tf(s-/usr/lib64/python2.7/test/support/__init__.pytdec7s (RR(R R ((R s-/usr/lib64/python2.7/test/support/__init__.pytsystem_must_validate_cert5s gư>cCs#t|tst|trcy8t|t|t}t|||krUdSWqqXnt|t|krt|ttfrxPttt |t |D]-}t ||||}|dkr|SqWt |t |kt |t |kS||k||kS(Ni( RitfloattabsRRoRRQtrangetminRR(txtytfuzztitoutcome((s-/usr/lib64/python2.7/test/support/__init__.pyRDs-( ,iiitjavasno unicode supportcCs t|dS(Nsunicode-escape(tunicode(ts((s-/usr/lib64/python2.7/test/support/__init__.pytumsii0iAiiii i*iii s$testtriscosttestfiles@testRs@test-slatin-1tgetwindowsversioniis'u"@test-\u5171\u6709\u3055\u308c\u308b"tLatin1sgWARNING: The filename %r CAN be encoded by the filesystem. Unicode filename tests may not be effectives {}_{}_tmpshttp://www.pythontest.netccsQt}|dkrEddl}|j}t}tjj|}ntrt |t rtjj ry|j t jpd}Wqtk r|stjdqqXnytj|t}Wn7tk r|sntjd|tddnX|rtj}nz |VWd|rL|tjkrLt|nXdS(sReturn 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. iNtasciis;unable to encode the cwd name with the filesystem encoding.s+tests may fail, unable to create temp dir: Ri(RXRYttempfiletmkdtempRVRuRytrealpathRRiRtsupports_unicode_filenamestencodeRNtgetfilesystemencodingtUnicodeEncodeErrorRGRHtmkdirRR@RRtgetpidR (Rytquiett dir_createdR tpid((s-/usr/lib64/python2.7/test/support/__init__.pyttemp_dirs6          ccs{tj}ytj|Wn7tk rV|s9ntjd|tddnXztjVWdtj|XdS(sgReturn 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. s)tests may fail, unable to change CWD to: RiN(RutgetcwdtchdirRR@RR(RyR)t saved_dir((s-/usr/lib64/python2.7/test/support/__init__.pyt change_cwd s   ttempcwdc csBtd|d|'}t|d| }|VWdQXWdQXdS(s 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. RyR)N(R,R0(RJR)t temp_pathtcwd_dir((s-/usr/lib64/python2.7/test/support/__init__.pyR&stdatacCstjj|r|S|dk r:tjj||}ntgtj}x9|D]1}tjj||}tjj|rQ|SqQW|S(sTry to find a file on sys.path and the working 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).N(RuRytisabsRYRt TEST_HOME_DIRRNtexists(tfiletsubdirRytdntfn((s-/usr/lib64/python2.7/test/support/__init__.pyRAs  cCsJ|j}|jg|D]}d|^q}dj|}d|S(s%Like repr(dict), but in sorted order.s%r: %rs, s{%s}(R]tsortR(tdictR]tpairt reprpairst withcommas((s-/usr/lib64/python2.7/test/support/__init__.pyROs   cCs9ttd}z|jSWd|jttXdS(s` Create an invalid file descriptor by opening and closing a file and return its fd. twbN(topenRtfilenoRR (R8((s-/usr/lib64/python2.7/test/support/__init__.pyt make_bad_fdWs  cCs||jt|}t|ddWdQX|j}|dk rV|j|j|n|dk rx|j|j|ndS(Ns texec(tassertRaisesRegexpt SyntaxErrortcompilet exceptionRYt assertEqualtlinenotoffset(ttestcaset statementterrtextRKRLtcmR|((s-/usr/lib64/python2.7/test/support/__init__.pyRcs   c sSddl}ddl}|j|djdd}tjjt|}fd}tjj|r||}|dk r|St |nt dt d|IJ|j |dd}zNt |d 9}|j} x#| r |j| |j} qWWdQXWd|jX||}|dk r?|Std |dS( Niit/csGt|}dkr|S|r9|jd|S|jdS(Ni(RBRYtseekR(R;R (tcheck(s-/usr/lib64/python2.7/test/support/__init__.pytcheck_valid_filess    turlfetchs fetching %s ...RiRAsinvalid resource "%s"(turlparseturllib2RRuRyRt TEST_DATA_DIRR7RYR RR turlopenRBtreadtwriteRR( turlRSRVRWRR;RTR toutR((RSs-/usr/lib64/python2.7/test/support/__init__.pyRls.            tWarningsRecordercBs8eZdZdZdZedZdZRS(syConvenience wrapper for the warnings list returned on entry to the warnings.catch_warnings() context manager. cCs||_d|_dS(Ni(t _warningst_last(tselft warnings_list((s-/usr/lib64/python2.7/test/support/__init__.pyt__init__s cCs\t|j|jkr,t|jd|S|tjjkrBdStd||fdS(Nis%r has no attribute %r( RR_R`RgR@tWarningMessaget_WARNING_DETAILSRYRh(Ratattr((s-/usr/lib64/python2.7/test/support/__init__.pyt __getattr__s cCs|j|jS(N(R_R`(Ra((s-/usr/lib64/python2.7/test/support/__init__.pyR@scCst|j|_dS(N(RR_R`(Ra((s-/usr/lib64/python2.7/test/support/__init__.pytresets(R<R=R>RcRgtpropertyR@Rh(((s-/usr/lib64/python2.7/test/support/__init__.pyR^s   c csptjd}|jjd}|r4|jntjdt&}tjdj dt |VWdQXg|D]}|j ^qu}g}x|D]\}} t } x[|D]R} t | } tj|| tjrt| j| rt} |j| qqW| r| r|j|| jfqqW|rOtd|dn|rltd |dndS( sCatch 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. it__warningregistry__trecordR@talwaysNsunhandled warning %ris)filter (%r, %s) did not catch any warning(RNt _getframet f_globalstgettclearR@RARVROt simplefilterR^tmessageRXRItretmatchtIt issubclassRntremoveR\R<tAssertionError( tfiltersR)tframetregistrytwtwarningtreraisetmissingRLtcattseenRRr((s-/usr/lib64/python2.7/test/support/__init__.pyt_filterwarningss0  cOsI|jd}|s<dtff}|dkr<t}q<nt||S(sContext 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)RN(RotWarningRYRVR(RyR R)((s-/usr/lib64/python2.7/test/support/__init__.pyRs   cOs@tjr$|s*dtff}q*nd}t||jdS(sjContext manager to silence py3k 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 False) Without argument, it defaults to: check_py3k_warnings(("", DeprecationWarning), quiet=False) RR)((RNt py3kwarningRCRRo(RyR ((s-/usr/lib64/python2.7/test/support/__init__.pyR s  cBs)eZdZdZdZdZRS(s,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 cGsotjj|_xV|D]N}|tjkrtj|}|j|krZtj|j=ntj|=qqWdS(N(RNROtcopytoriginal_modulesR<(Rat module_namest module_nameRe((s-/usr/lib64/python2.7/test/support/__init__.pyRcs  cCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyt __enter__scGstjj|jdS(N(RNRORR(Rat ignore_exc((s-/usr/lib64/python2.7/test/support/__init__.pyt__exit__s(R<R=R>RcRR(((s-/usr/lib64/python2.7/test/support/__init__.pyR!s  cBs_eZdZdZdZdZdZdZdZdZ dZ d Z RS( s_Class to help protect the environment variable properly. Can be used as a context manager.cCstj|_i|_dS(N(Rutenviront_environt_changed(Ra((s-/usr/lib64/python2.7/test/support/__init__.pyRc(s cCs |j|S(N(R(Ratenvvar((s-/usr/lib64/python2.7/test/support/__init__.pyt __getitem__,scCs<||jkr+|jj||j|RcRRRRRRRR(((s-/usr/lib64/python2.7/test/support/__init__.pyR"#s        t DirsOnSysPathcBs)eZdZdZdZdZRS(sContext 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-tj|_tj|_tjj|dS(N(RNRytoriginal_valuetoriginal_objecttextend(Ratpaths((s-/usr/lib64/python2.7/test/support/__init__.pyRc^s  cCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyRcscGs|jt_|jtj(dS(N(RRNRyR(RaR((s-/usr/lib64/python2.7/test/support/__init__.pyRfs (R<R=R>RcRR(((s-/usr/lib64/python2.7/test/support/__init__.pyRRs   cBs2eZdZdZdZddddZRS(sRaise ResourceDenied if an exception is raised while the context manager is in effect that matches the specified exception and attributes.cKs||_||_dS(N(Rtattrs(RaRR ((s-/usr/lib64/python2.7/test/support/__init__.pyRcps cCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyRtscCs}|dk ryt|j|ryxX|jjD]8\}}t||sMPnt|||kr.Pq.q.WtdndS(sIf type_ is a subclass of self.exc and value has attributes matching self.attrs, raise ResourceDenied. Otherwise let the exception propagate (if any).s%an optional resource is not availableN(RYRvRRt iteritemsRRgR(Rattype_Rt tracebackRft attr_value((s-/usr/lib64/python2.7/test/support/__init__.pyRwsN(R<R=R>RcRRYR(((s-/usr/lib64/python2.7/test/support/__init__.pyR%ks  c #sdddd d!d"g}d#d$d%d&d'g}td||gsg|D]\}}tt||^qVg|D]\}}tt||^qnfd}tj}zy%|dk rtj|ndVWntk r} xxtr}| j } t | dkrGt | dtrG| d} qt | dkryt | dtry| d} qPqW|| nXWdtj|XdS((sReturn a context manager that raises ResourceDenied when various issues with the Internet connection manifest themselves as exceptions.t ECONNREFUSEDiot ECONNRESETiht EHOSTUNREACHiqt ENETUNREACHiet ETIMEDOUTint EADDRNOTAVAILict EAI_AGAINitEAI_FAILit EAI_NONAMEit EAI_NODATAit WSANO_DATAi*sResource '%s' is not availablecst|dd}t|tjsNt|tjrB|ksN|kr{tsrtjj j ddnndS(NRis ( RgRYRiRRtgaierrorRRNtstderrR[R{(R|tn(tcaptured_errnostdeniedt gai_errnos(s-/usr/lib64/python2.7/test/support/__init__.pyt filter_errors Niii(Rio(Rih(Riq(Rie(Rin(Ric(Ri(Ri(Ri(Ri(Ri*( RRgRRtgetdefaulttimeoutRYtsetdefaulttimeoutR RVR{RRi( t resource_nameRterrnostdefault_errnostdefault_gai_errnosRJtnumRt old_timeoutR|ta((RRRs-/usr/lib64/python2.7/test/support/__init__.pyR&sJ  (+     % %   ccs[ddl}tt|}tt||jztt|VWdtt||XdS(sReturn a context manager used by captured_stdout and captured_stdin that temporarily replaces the sys stream *stream_name* with a StringIO.iN(tStringIORgRNtsetattr(t stream_nameRt orig_stdout((s-/usr/lib64/python2.7/test/support/__init__.pyR#s  cCs tdS(sCapture the output of sys.stdout: with captured_stdout() as s: print "hello" self.assertEqual(s.getvalue(), "hello") Rs(R#(((s-/usr/lib64/python2.7/test/support/__init__.pyR$scCs tdS(NR(R#(((s-/usr/lib64/python2.7/test/support/__init__.pytcaptured_stderrscCs tdS(Ntstdin(R#(((s-/usr/lib64/python2.7/test/support/__init__.pytcaptured_stdinscCs8tjtr tjdntjtjdS(sForce 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(tgctcollectRRR(((s-/usr/lib64/python2.7/test/support/__init__.pyt gc_collects  t2PtgettotalrefcounttPcCstjt|dS(Nt0P(tstructtcalcsizet_header(tfmt((s-/usr/lib64/python2.7/test/support/__init__.pyt calcobjsizescCstjt|dS(NR(RRt_vheader(R((s-/usr/lib64/python2.7/test/support/__init__.pyt calcvobjsizesii cCsddl}tj|}t|tkr:|jt@s_t|tkrot|jt@ro||j7}ndt|||f}|j|||dS(Nis&wrong size for %s: got %d, expected %d( t _testcapiRNt getsizeofRot __flags__t_TPFLAGS_HEAPTYPEt_TPFLAGS_HAVE_GCtSIZEOF_PYGC_HEADRJ(ttesttotsizeRRRL((s-/usr/lib64/python2.7/test/support/__init__.pyt check_sizeofs %csfd}|S(Ncs1fd}j|_j|_|S(Ncsy.ddl}t|}|j|}Wn$tk rDnAd}}n1Xx-D]%}y|j||PWq\q\Xq\Wz||SWd|r|r|j||nXdS(Ni(tlocaleRgt setlocaleRhRY(R{tkwdsRtcategoryt orig_localetloc(tcatstrRztlocales(s-/usr/lib64/python2.7/test/support/__init__.pytinners$    (t func_nameR>(RzR(RR(Rzs-/usr/lib64/python2.7/test/support/__init__.pyRs  ((RRR((RRs-/usr/lib64/python2.7/test/support/__init__.pyR'scsfd}|S(Ncs.fd}j|_j|_|S(Ncsy tj}Wn tk r/tjdnXdtjkrOtjd}nd}tjd<|z||SWd|dkrtjd=n |tjd(RzR(R(Rzs-/usr/lib64/python2.7/test/support/__init__.pyR:s  ((RR((Rs-/usr/lib64/python2.7/test/support/__init__.pyR:9scCsidd6td6td6dtd6}tjd|tjtjB}|dkrgtd|fntt |j d||j d j }|a |t krt }n|tdkrtd |fn|adS( NiRtmtgtts(\d+(\.\d+)?) (K|M|G|T)b?$sInvalid memory limit %riis$Memory limit %r too low to be useful(t_1Mt_1GRsRtt IGNORECASEtVERBOSERYRRRtgrouptlowertreal_max_memusetMAX_Py_ssize_tt_2GR(tlimittsizesRtmemlimit((s-/usr/lib64/python2.7/test/support/__init__.pyR(bs   2  icsfd}|S(sQDecorator for bigmem tests. 'minsize' is the minimum useful size for the test (in arbitrary, test-interpreted units.) 'memuse' is the number of 'bytes per size' for the test, or a good estimate of it. 'overhead' specifies fixed overhead, independent of the testsize, and defaults to 5Mb. The decorator tries to guess a good value for 'size' and passes it to the decorated test function. If minsize * memuse is more than the allowed memory use (as defined by max_memuse), the test is skipped. Otherwise, minsize is adjusted upward to use up to max_memuse. cs7fd}|_|_|_|S(Ncsts.d}|j|dtkn^tt}|krutrqtjjdjfndSt |dt}||S(Niis)Skipping %s because of memory constraint i2( Rt assertFalseRRRRNRR[R<tmax(Ratmaxsize(R tmemusetminsizetoverhead(s-/usr/lib64/python2.7/test/support/__init__.pyRs"  (RRR(R R(RRR(R s-/usr/lib64/python2.7/test/support/__init__.pyRs    ((RRRR((RRRs-/usr/lib64/python2.7/test/support/__init__.pyR)ws csfd}|S(Ncs7fd}|_|_|_|S(Ncsftsd}n}ts" rYt|krYtrUtjjdjfndS||S(Nis)Skipping %s because of memory constraint (RRRNRR[R<(RaR(tdry_runR RR(s-/usr/lib64/python2.7/test/support/__init__.pyRs   (RRR(R R(RRRR(R s-/usr/lib64/python2.7/test/support/__init__.pyRs    ((RRRRR((RRRRs-/usr/lib64/python2.7/test/support/__init__.pytprecisionbigmemtestscsfd}|S(s0Decorator for tests that fill the address space.cs@ttkr2tr<tjjdjfq<n |SdS(Ns)Skipping %s because of memory constraint (RRRRNRR[R<(Ra(R (s-/usr/lib64/python2.7/test/support/__init__.pyRs   ((R R((R s-/usr/lib64/python2.7/test/support/__init__.pyR*scBseZdZRS(cCstj}|||S(N(RGt TestResult(RaRR((s-/usr/lib64/python2.7/test/support/__init__.pytruns  (R<R=R(((s-/usr/lib64/python2.7/test/support/__init__.pyR+scCs|S(N((Rp((s-/usr/lib64/python2.7/test/support/__init__.pyt_idscCsP|dkr&t r&tjtjSt|r6tStjdj|SdS(NRsresource {0!r} is not enabled(RRGtskipRRRR(R((s-/usr/lib64/python2.7/test/support/__init__.pytrequires_resources  cCstdt|S(s9 Decorator for tests only applicable on CPython. tcpython(t impl_detailRV(R((s-/usr/lib64/python2.7/test/support/__init__.pyR2scKs}t|rtS|dkrpt|\}}|r=d}nd}t|j}|jdj|}ntj |S(Ns*implementation detail not available on {0}s%implementation detail specific to {0}s or ( R3RRYt _parse_guardstsortedRRRRGR(RLtguardst guardnamestdefault((s-/usr/lib64/python2.7/test/support/__init__.pyRs   cCsW|sitd6tfS|jd}|j|gt|ksLt|| fS(NRi(RVRXtvaluesRRx(R tis_true((s-/usr/lib64/python2.7/test/support/__init__.pyR s %cKs.t|\}}|jtjj|S(s5This function returns True or False depending on the host platform. Examples: if check_impl_detail(): # only on CPython (default) if check_impl_detail(jython=True): # only on Jython if check_impl_detail(cpython=False): # everywhere except on CPython (R RoRtpython_implementationR(R R ((s-/usr/lib64/python2.7/test/support/__init__.pyR3scCsrg}x\|jD]Q}t|tjrEt|||j|q||r|j|qqW||_dS(s>Recursively filter test cases in a suite based on a predicate.N(t_testsRiRGt TestSuitet _filter_suiteR\(tsuitetpredtnewtestsR((s-/usr/lib64/python2.7/test/support/__init__.pyRs  cCstr'tjtjdddt}n t}|j|}|j r\|j r\t n|j st |j dkr|j r|j dd}nLt |jdkr|j r|jdd}nd}ts|d7}nt|ndS( s2Run tests from a unittest.TestSuite-derived class.t verbosityitfailfastiismultiple errors occurreds!; run in verbose mode for detailsN(RRGtTextTestRunnerRNRsRR+RttestsRuntskippedRt wasSuccessfulRterrorstfailuresR(RtrunnerRR|((s-/usr/lib64/python2.7/test/support/__init__.pyt _run_suites      cCs$tdkrtSt|jSdS(N(t_match_test_funcRYRVtid(R((s-/usr/lib64/python2.7/test/support/__init__.pyt match_test#s cCsd|kotjd| S(NRMs[?*\[\]](Rstsearch(tpattern((s-/usr/lib64/python2.7/test/support/__init__.pyt_is_full_match_test+scs|tkrdS|s%d}d}nittt|rLt|j}nBdjttj |}t j |j fd}|}t |a|adS(Nt|cs0|rtStt|jdSdS(NRM(RVtanyRR(ttest_id(t regex_match(s-/usr/lib64/python2.7/test/support/__init__.pytmatch_test_regexJs ((t_match_test_patternsRYtallRR&Rt __contains__Rtfnmatcht translateRsRHRtRR!(tpatternsRztregexR+((R*s-/usr/lib64/python2.7/test/support/__init__.pytset_match_tests5s    cGstjtjf}tj}x|D]}t|trx|tjkri|jtjtj|qt dq%t||r|j|q%|jtj |q%Wt |t t |dS(s1Run tests from unittest.TestCase-derived classes.s)str arguments must be keys in sys.modulesN(RGRtTestCaseRiRIRNROtaddTestt findTestCasesRt makeSuiteRR#R (tclassest valid_typesRtcls((s-/usr/lib64/python2.7/test/support/__init__.pyR,]s    Rtwin32tWITH_DOC_STRINGSstest requires docstringscCsddl}|dkr!t}nd}tj}tt_z>|j|d|\}}|rytd||fnWd|t_Xtrd|j|fGHn||fS(s Run doctest on the given module. Return (#failures, #tests). If optional argument verbosity is not specified (or is None), pass test.support's belief about verbosity on to doctest. Else doctest's usual behavior is used (it searches sys.argv for -v). iNRs%d of %d doctests faileds,doctest (%s) ... %d tests with zero failures( tdoctestRYRRNRsR ttestmodRR<(ReRR=t save_stdoutR R((s-/usr/lib64/python2.7/test/support/__init__.pyR-|s      cCstrtjfSdSdS(Ni(i(tthreadt_count(((s-/usr/lib64/python2.7/test/support/__init__.pyR.s cCsTts dSd}x=t|D]/}tj}||kr?PntjdqWdS(Ni g?(R@RRARR(t nb_threadst _MAX_COUNTtcountR((s-/usr/lib64/python2.7/test/support/__init__.pyR/s  cs,ts Stjfd}|S(sUse 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(R.R/(R{tkey(Rz(s-/usr/lib64/python2.7/test/support/__init__.pyRs (R@RR(RzR((Rzs-/usr/lib64/python2.7/test/support/__init__.pyR0sgN@ccstj}z dVWdtj}||}xtrtj}||krSPntj|krtj|}d|||||f}t|ntjdtq1WXdS(sE 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. NsYwait_threads() failed to cleanup %s threads after %.1f seconds (count: %s, old count: %s)g{Gz?(R@RARRVRxRR(Rt old_countt start_timetdeadlineRDtdtRL((s-/usr/lib64/python2.7/test/support/__init__.pytwait_threads_exits         cCscttdr_d}xGtr[y/tj|tj\}}|dkrLPnWqPqXqWndS(sUse 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. twaitpidiiN(RRuRVRKtWNOHANG(t any_processR+tstatus((s-/usr/lib64/python2.7/test/support/__init__.pyR7s   c cst|}g}zfy,x%|D]}|j|j|qWWn.trkdt|t|fGHnnXdVWd|r|ntj}}xtddD]}|d7}x.|D]&}|jt|tjdqWg|D]}|j r|^q}|sPntrdt||fGHqqWXg|D]}|j rE|^qE}|rt dt|ndS(Ns/Can't start %d threads, only %d threads startediii<g{Gz?s7Unable to join %d threads during a period of %d minutessUnable to join %d threads( RQtstartR\RRRRRRtisAliveRx(tthreadstunlocktstartedRtendtimet starttimeR((s-/usr/lib64/python2.7/test/support/__init__.pyR1s:       $%%ccst||rNt||}t|||z |VWdt|||Xn<t|||z dVWdt||rt||nXdS(sTemporary 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(RRgRtdelattr(RpRftnew_valtreal_val((s-/usr/lib64/python2.7/test/support/__init__.pyt swap_attr)s  ccsk||kr:||}|||rsN(ttobytesRhRt TypeErrortbytes(tb((s-/usr/lib64/python2.7/test/support/__init__.pyR5gs  t getcountss-types are immortal if COUNT_ALLOCS is definedcCsddl}|jS(sZReturn a list of command-line arguments reproducing the current settings in sys.flags.iN(t subprocesst_args_from_interpreter_flags(Rc((s-/usr/lib64/python2.7/test/support/__init__.pytargs_from_interpreter_flagsys cCstjdd|j}|S(sStrip 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\]\r?\n?$R(Rstsubtstrip(R((s-/usr/lib64/python2.7/test/support/__init__.pyR8scsid|ffdY}tg||||jttt|jddS(NtAcseZfdZRS(cs0tdRYRRRR(((s-/usr/lib64/python2.7/test/support/__init__.pyR;s  GcCs*ddl}t|jWdQXdS(sDeliberate crash of Python. Python can be killed by a segmentation fault (SIGSEGV), a bus error (SIGBUS), or a different error depending on the platform. Use SuppressCrashReport() to prevent a crash report from popping up. iN(RR;t _read_null(R((s-/usr/lib64/python2.7/test/support/__init__.pyt _crash_pythons  c Cstjjd rdy!tjd}t|dSWqdtk r`}|jtjkraqaqdXnd}t tdrytj d}Wqtk rqXnd }tjdkr+yd d l }|j Wnttfk rq+Xi}x9|j|j|jfD]}|j |d ||RcRR(((s-/usr/lib64/python2.7/test/support/__init__.pyR_s ((ii@i@i@ii(i@ii(((((R>R<RFt contextlibRR/RRRRwRNRuRRR@RGREtUserDictRsRRRxRjR@RYt__all__t SHORT_TIMEOUTRRRRRHRtcontextmanagerRVRDRXRRUR[R6R4RRRRRRrRR R R}RRRRRRR RR R RRRRRRRRRRRR9R RRt PIPE_MAX_SIZEt SOCK_MAX_SIZERRRt NameErrort skipUnlesstrequires_unicodeRt FS_NONASCIItunichrt characterR$R%tdecodet UnicodeErrorRJRRitTESTFN_UNICODEtTESTFN_ENCODINGRRtTESTFN_UNENCODABLEtevalR&RR(t TEST_HTTP_URLR-RR,R0RRyRtabspatht__file__tTEST_SUPPORT_DIRR6RRXRRRDRRtobjectR^RRR R!t DictMixinR"RR%R&R#R$RRRRRRRRRRR'R:RRRt_4GRRR(R)RR*R+RRR2RR R3RR R!R,R#R&R3R,RytHAVE_DOCSTRINGStrequires_docstringsR-tenvironment_alteredR.R/R0RJR7R1RYR[R5tskipIftrequires_type_collectingReR8RqRvR}R;RRR(((s-/usr/lib64/python2.7/test/support/__init__.pyts                                    &      !         J  < $                               .    * ' /D         $ "     '       (    &  #       e  d?d@g=ZdAZdefdBYZdefdCYZdefdDYZdejfdEYZ ej!e"dFZ#e$dGZ%dHZ&dIZ'dde$dJZ(dKZ)dLZ*dZ+dMa,dMa-e$Z.da/dNZ0dOZ1dPZ2dQZ3e j j4dRr+e$dSZ5dTZ6dUZ7dVZ8ne j9Z6e j:Z7dWZ8dXZ9dYZ:dZZ;d[Z<d\Z=d]Z>dd^Z?d_Z@d`ZAdaZBejCejDdbZEeAdcZFddZGeGZHdeZIdfZJdgZKdZLdZMe j j4dkZNyeOe"ZPWneQk r-e$ZPnXejRePdlZSdmZTdZUePrxeVdneVdoeVdpeVdqeVdreVdseVdteVdueVdveVdweVdxf D]XZWy7eWjXe jYjZe jYeWkre[nWne[k rqXeWZUPqWne j\dkkr6dyZ]ne j\dzkrNd{Z]nd|Z]ePre^d}eOrrd~Z_neOd~dZ_e jYZ`eae d se jbddkrdZcqeddZcyecjXdWneek rqXdecGHndjfe]e jgZ]dZhe jiZjej!de$dZkej!e$dZlej!de$dZme jnjoe jnjpeqZre jnjoerZse jnjtesdZuddZvdZwdZxd}dddZyddZzde{fdYZ|e$dZ}ej!dZ~ej!dZd&e{fdYZd'ejfdYZde{fdYZd*e{fdYZej!dAddZej!dZdZdZdZdZdZeae drdeZnedZdZdZdZdZdZdZdZdZdieZdeZdheZe jZdZdedZdee"dZdZd0ddYZdZdZdZddZdZdZdZdZdadadZdZdZdZede$pW e j dkpW ejdZejRedZddZe$ZdZdZdZej!ddZdZej!ddZej!dZej!dZdZejeae ddZdZdZddZej!dZdZd@ddYZdZdZdddYZdS(s7Supporting definitions for the Python regression tests.s test.supports3test.support must be imported from the test packageiNtErrort TestFailedt TestDidNotRuntResourceDeniedt import_moduletverboset use_resourcest max_memusetrecord_original_stdouttget_original_stdouttunloadtunlinktrmtreetforgettis_resource_enabledtrequirestrequires_mac_vertfind_unused_portt bind_porttfcmpt have_unicodet is_jythontTESTFNtHOSTtFUZZtSAVEDCWDttemp_cwdtfindfiletsortdicttcheck_syntax_errortopen_urlresourcetcheck_warningstcheck_py3k_warningst CleanImporttEnvironmentVarGuardtcaptured_outputtcaptured_stdouttTransientResourcettransient_internettrun_with_localet set_memlimitt bigmemtesttbigaddrspacetesttBasicTestRunnert run_unittestt run_doctesttthreading_setuptthreading_cleanupt reap_threadst start_threadst cpython_onlytcheck_impl_detailt get_attributet py3k_bytestimport_fresh_modulet reap_childrentstrip_python_stderrt IPV6_ENABLEDt run_with_tztSuppressCrashReportg>@cBseZdZRS(s*Base class for regression test exceptions.(t__name__t __module__t__doc__(((s-/usr/lib64/python2.7/test/support/__init__.pyR4scBseZdZRS(s Test failed.(R<R=R>(((s-/usr/lib64/python2.7/test/support/__init__.pyR7scBseZdZRS(sTest did not run any subtests.(R<R=R>(((s-/usr/lib64/python2.7/test/support/__init__.pyR:scBseZdZRS(sTest skipped because it requested a disallowed resource. This is raised when a test calls requires() for a resource that has not been enabled. It is used to distinguish between expected and unexpected skips. (R<R=R>(((s-/usr/lib64/python2.7/test/support/__init__.pyR=sccs=|r4tjtjddtdVWdQXndVdS(sContext manager to suppress package and module deprecation warnings when importing them. If ignore is False, this context manager has no effect.tignores.+ (module|package)N(twarningstcatch_warningstfilterwarningstDeprecationWarning(R?((s-/usr/lib64/python2.7/test/support/__init__.pyt_ignore_deprecated_importsEs   c CsSt|Aytj|SWn(tk rH}tjt|nXWdQXdS(sImport 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.N(RDt importlibRt ImportErrortunittesttSkipTesttstr(tnamet deprecatedtmsg((s-/usr/lib64/python2.7/test/support/__init__.pyRTs  cCs|tjkr&t|tj|=nxTttjD]C}||ks[|j|dr6tj|||t|t rd|j|f}ndt |j|f}t j |nX|SdS(s?Get an attribute, raising SkipTest if AttributeError is raised.smodule %r has no attribute %rsclass %s has no attribute %rs%s instance has no attribute %rs"type object %r has no attribute %rs%r object has no attribute %rN( tgetattrtAttributeErrort isinstancettypest ModuleTypeR<t ClassTypet InstanceTypet __class__ttypeRGRH(tobjRJt attributeRL((s-/usr/lib64/python2.7/test/support/__init__.pyR4s iicCs |adS(N(t_original_stdout(tstdout((s-/usr/lib64/python2.7/test/support/__init__.pyRscCs tp tjS(N(RrRNRs(((s-/usr/lib64/python2.7/test/support/__init__.pyR scCs&ytj|=Wntk r!nXdS(N(RNRORW(RJ((s-/usr/lib64/python2.7/test/support/__init__.pyR s cGsxy||SWnctk rs}tdkrVd|jj|fGHd|j|fGHntj|tj||SXdS(Nis%s: %ss re-run %s%r(tEnvironmentErrorRRnR<tostchmodtstattS_IRWXU(tpathtfunctargsterr((s-/usr/lib64/python2.7/test/support/__init__.pyt _force_runs twincCs|||r|}n$tjj|\}}|p:d}d}xR|dkrtj|}|rm|n ||ks}dStj||d9}qFWtjd|tdddS(NRMgMbP?g?is)tests may fail, delete still pending for t stackleveli( RuRytsplittlistdirttimetsleepR@twarntRuntimeWarning(RztpathnametwaitalltdirnameRJttimeouttL((s-/usr/lib64/python2.7/test/support/__init__.pyt_waitfors     cCsttj|dS(N(RRuR (tfilename((s-/usr/lib64/python2.7/test/support/__init__.pyt_unlinkscCsttj|dS(N(RRutrmdir(R((s-/usr/lib64/python2.7/test/support/__init__.pyt_rmdirscs6fdt|dttd|dS(Ncsxt|tj|D]i}tjj||}tjj|rlt|dtt|tj|qt|tj |qWdS(NR( R}RuRRytjointisdirRRVRR (RyRJtfullname(t _rmtree_inner(s-/usr/lib64/python2.7/test/support/__init__.pyRs RcSst|tj|S(N(R}RuR(tp((s-/usr/lib64/python2.7/test/support/__init__.pyt t(RRV(Ry((Rs-/usr/lib64/python2.7/test/support/__init__.pyt_rmtreescsSytj|dSWntk r(nXfd|tj|dS(Ncsxt|tj|D]}tjj||}ytj|j}Wntk r`d}nXtj |r|t|tj |qt|tj |qWdS(Ni( R}RuRRyRtlstattst_modeRtRwtS_ISDIRRR (RyRJRtmode(R(s-/usr/lib64/python2.7/test/support/__init__.pyRs   (tshutilR RtRuR(Ry((Rs-/usr/lib64/python2.7/test/support/__init__.pyRs   cCsIyt|Wn4tk rD}|jtjtjfkrEqEnXdS(N(RtOSErrorterrnotENOENTtENOTDIR(Rtexc((s-/usr/lib64/python2.7/test/support/__init__.pyR $s cCs@yt|Wn+tk r;}|jtjkr<q<nXdS(N(RRRR(Rterror((s-/usr/lib64/python2.7/test/support/__init__.pyR+s cCsIyt|Wn4tk rD}|jtjtjfkrEqEnXdS(N(RRRRtESRCH(Ryte((s-/usr/lib64/python2.7/test/support/__init__.pyR 3s cCsjt|xYtjD]N}ttjj||tjdttjj||tjdqWdS(sm"Forget" a module was ever imported by removing it from sys.modules and deleting any .pyc and .pyo files.tpyctpyoN(R RNRyR RuRtextsep(RTR((s-/usr/lib64/python2.7/test/support/__init__.pyR ;s $csttdrtjSd}tjjdr ddlddld}d}dj ffdY}j j }|j }|sj n|}jj}|j||j|j|j|}|sj nt|j|@sd}qntjdkrdd lm} mm} m } dd lm} | j| d } | jd krd }qd| ffdY}|}| |}| j|d ks| j|d krd}qn|sy;ddlm}|}|j |j!|j"Wqt#k r}t$|}t%|dkrz|d d}ndj&t'|j(|}qXn|t_)| t_tjS(NtresultR~iitUSEROBJECTFLAGScs;eZdjjfdjjfdjjfgZRS(tfInheritt fReservedtdwFlags(R<R=twintypestBOOLtDWORDt_fields_((tctypes(s-/usr/lib64/python2.7/test/support/__init__.pyRRss,gui not available (WSF_VISIBLE flag not set)tdarwin(tcdlltc_inttpointert Structure(t find_librarytApplicationServicesis0gui tests cannot run without OS X window managertProcessSerialNumbercs eZdfdfgZRS(t highLongOfPSNt lowLongOfPSN(R<R=R((R(s-/usr/lib64/python2.7/test/support/__init__.pyRts s#cannot run without OS X gui process(tTki2s [...]sTk unavailable due to {}: {}(*thasattrt_is_gui_availableRRYRNtplatformRRRtctypes.wintypesRtwindlltuser32tGetProcessWindowStationtWinErrorRRtGetUserObjectInformationWtbyreftsizeoftboolRRRRt ctypes.utilRt LoadLibrarytCGMainDisplayIDtGetCurrentProcesstSetFrontProcesstTkinterRtwithdrawtupdatetdestroyt ExceptionRItlentformatRoR<treason(Rt UOI_FLAGSt WSF_VISIBLERtdllthtuoftneededtresRRRRt app_servicesRtpsntpsn_pRtrootRt err_string((RRs-/usr/lib64/python2.7/test/support/__init__.pyRGsh         "          cCstdkp|tkS(sTest 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(RRY(tresource((s-/usr/lib64/python2.7/test/support/__init__.pyRscCs`t|s4|dkr%d|}nt|n|dkr\t r\ttjndS(s@Raise ResourceDenied if the specified resource is not available.s$Use of the `%s' resource not enabledtguiN(RRYRRR(RRL((s-/usr/lib64/python2.7/test/support/__init__.pyRs    csfd}|S(sDecorator 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.tjfd}|_|S(Ncstjdkrtjd}y"ttt|jd}Wntk rTqX|krdjtt }t j d||fqn||S(NRiRMs&Mac OS X %s or higher required, not %s( RNRtmac_verttupletmaptintRt ValueErrorRRIRGRH(R{tkwt version_txttversiontmin_version_txt(Rzt min_version(s-/usr/lib64/python2.7/test/support/__init__.pytwrappers"  (t functoolstwrapsR(RzR(R(Rzs-/usr/lib64/python2.7/test/support/__init__.pyt decorators! ((RR((Rs-/usr/lib64/python2.7/test/support/__init__.pyRss 127.0.0.1s::1cCs/tj||}t|}|j~|S(s 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 socket.error 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.(tsocketRtclose(tfamilytsocktypettempsocktport((s-/usr/lib64/python2.7/test/support/__init__.pyRs 6  cCs|jtjkr|jtjkrttdrc|jtjtjdkrct dqcnttdry1|jtjtj dkrt dnWqt k rqXnttdr|j tjtj dqn|j|df|jd}|S(s%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. t SO_REUSEADDRisHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets!t SO_REUSEPORTsHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!tSO_EXCLUSIVEADDRUSEi(RRtAF_INETRot SOCK_STREAMRt getsockoptt SOL_SOCKETRRRRtt setsockoptRtbindt getsockname(tsockthostR((s-/usr/lib64/python2.7/test/support/__init__.pyRs$ cCs{tjrwd}zNy3tjtjtj}|jtdftSWntjk r[nXWd|rs|j nXnt S(s+Check whether IPv6 is enabled on this host.iN( Rthas_ipv6RYtAF_INET6RRtHOSTv6RVRRRX(R((s-/usr/lib64/python2.7/test/support/__init__.pyt_is_ipv6_enabled$s cs"tjfd}|S(s5Skip the test on TLS certificate validation failures.csRy||Wn:tk rM}dt|krGtjdnnXdS(NtCERTIFICATE_VERIFY_FAILEDs.system does not contain necessary certificates(tIOErrorRIRGRH(R{tkwargsR(tf(s-/usr/lib64/python2.7/test/support/__init__.pytdec7s (RR(R R ((R s-/usr/lib64/python2.7/test/support/__init__.pytsystem_must_validate_cert5s gư>cCs#t|tst|trcy8t|t|t}t|||krUdSWqqXnt|t|krt|ttfrxPttt |t |D]-}t ||||}|dkr|SqWt |t |kt |t |kS||k||kS(Ni( RitfloattabsRRoRRQtrangetminRR(txtytfuzztitoutcome((s-/usr/lib64/python2.7/test/support/__init__.pyRDs-( ,iiitjavasno unicode supportcCs t|dS(Nsunicode-escape(tunicode(ts((s-/usr/lib64/python2.7/test/support/__init__.pytumsii0iAiiii i*iii s$testtriscosttestfiles@testRs@test-slatin-1tgetwindowsversioniis'u"@test-\u5171\u6709\u3055\u308c\u308b"tLatin1sgWARNING: The filename %r CAN be encoded by the filesystem. Unicode filename tests may not be effectives {}_{}_tmpshttp://www.pythontest.netccsQt}|dkrEddl}|j}t}tjj|}ntrt |t rtjj ry|j t jpd}Wqtk r|stjdqqXnytj|t}Wn7tk r|sntjd|tddnX|rtj}nz |VWd|rL|tjkrLt|nXdS(sReturn 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. iNtasciis;unable to encode the cwd name with the filesystem encoding.s+tests may fail, unable to create temp dir: Ri(RXRYttempfiletmkdtempRVRuRytrealpathRRiRtsupports_unicode_filenamestencodeRNtgetfilesystemencodingtUnicodeEncodeErrorRGRHtmkdirRR@RRtgetpidR (Rytquiett dir_createdR tpid((s-/usr/lib64/python2.7/test/support/__init__.pyttemp_dirs6          ccs{tj}ytj|Wn7tk rV|s9ntjd|tddnXztjVWdtj|XdS(sgReturn 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. s)tests may fail, unable to change CWD to: RiN(RutgetcwdtchdirRR@RR(RyR)t saved_dir((s-/usr/lib64/python2.7/test/support/__init__.pyt change_cwd s   ttempcwdc csBtd|d|'}t|d| }|VWdQXWdQXdS(s 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. RyR)N(R,R0(RJR)t temp_pathtcwd_dir((s-/usr/lib64/python2.7/test/support/__init__.pyR&stdatacCstjj|r|S|dk r:tjj||}ntgtj}x9|D]1}tjj||}tjj|rQ|SqQW|S(sTry to find a file on sys.path and the working 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).N(RuRytisabsRYRt TEST_HOME_DIRRNtexists(tfiletsubdirRytdntfn((s-/usr/lib64/python2.7/test/support/__init__.pyRAs  cCsJ|j}|jg|D]}d|^q}dj|}d|S(s%Like repr(dict), but in sorted order.s%r: %rs, s{%s}(R]tsortR(tdictR]tpairt reprpairst withcommas((s-/usr/lib64/python2.7/test/support/__init__.pyROs   cCs9ttd}z|jSWd|jttXdS(s` Create an invalid file descriptor by opening and closing a file and return its fd. twbN(topenRtfilenoRR (R8((s-/usr/lib64/python2.7/test/support/__init__.pyt make_bad_fdWs  cCs||jt|}t|ddWdQX|j}|dk rV|j|j|n|dk rx|j|j|ndS(Ns texec(tassertRaisesRegexpt SyntaxErrortcompilet exceptionRYt assertEqualtlinenotoffset(ttestcaset statementterrtextRKRLtcmR|((s-/usr/lib64/python2.7/test/support/__init__.pyRcs   c sSddl}ddl}|j|djdd}tjjt|}fd}tjj|r||}|dk r|St |nt dt d|IJ|j |dd}zNt |d 9}|j} x#| r |j| |j} qWWdQXWd|jX||}|dk r?|Std |dS( Niit/csGt|}dkr|S|r9|jd|S|jdS(Ni(RBRYtseekR(R;R (tcheck(s-/usr/lib64/python2.7/test/support/__init__.pytcheck_valid_filess    turlfetchs fetching %s ...RiRAsinvalid resource "%s"(turlparseturllib2RRuRyRt TEST_DATA_DIRR7RYR RR turlopenRBtreadtwriteRR( turlRSRVRWRR;RTR toutR((RSs-/usr/lib64/python2.7/test/support/__init__.pyRls.            tWarningsRecordercBs8eZdZdZdZedZdZRS(syConvenience wrapper for the warnings list returned on entry to the warnings.catch_warnings() context manager. cCs||_d|_dS(Ni(t _warningst_last(tselft warnings_list((s-/usr/lib64/python2.7/test/support/__init__.pyt__init__s cCs\t|j|jkr,t|jd|S|tjjkrBdStd||fdS(Nis%r has no attribute %r( RR_R`RgR@tWarningMessaget_WARNING_DETAILSRYRh(Ratattr((s-/usr/lib64/python2.7/test/support/__init__.pyt __getattr__s cCs|j|jS(N(R_R`(Ra((s-/usr/lib64/python2.7/test/support/__init__.pyR@scCst|j|_dS(N(RR_R`(Ra((s-/usr/lib64/python2.7/test/support/__init__.pytresets(R<R=R>RcRgtpropertyR@Rh(((s-/usr/lib64/python2.7/test/support/__init__.pyR^s   c csptjd}|jjd}|r4|jntjdt&}tjdj dt |VWdQXg|D]}|j ^qu}g}x|D]\}} t } x[|D]R} t | } tj|| tjrt| j| rt} |j| qqW| r| r|j|| jfqqW|rOtd|dn|rltd |dndS( sCatch 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. it__warningregistry__trecordR@talwaysNsunhandled warning %ris)filter (%r, %s) did not catch any warning(RNt _getframet f_globalstgettclearR@RARVROt simplefilterR^tmessageRXRItretmatchtIt issubclassRntremoveR\R<tAssertionError( tfiltersR)tframetregistrytwtwarningtreraisetmissingRLtcattseenRRr((s-/usr/lib64/python2.7/test/support/__init__.pyt_filterwarningss0  cOsI|jd}|s<dtff}|dkr<t}q<nt||S(sContext 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)RN(RotWarningRYRVR(RyR R)((s-/usr/lib64/python2.7/test/support/__init__.pyRs   cOs@tjr$|s*dtff}q*nd}t||jdS(sjContext manager to silence py3k 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 False) Without argument, it defaults to: check_py3k_warnings(("", DeprecationWarning), quiet=False) RR)((RNt py3kwarningRCRRo(RyR ((s-/usr/lib64/python2.7/test/support/__init__.pyR s  cBs)eZdZdZdZdZRS(s,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 cGsotjj|_xV|D]N}|tjkrtj|}|j|krZtj|j=ntj|=qqWdS(N(RNROtcopytoriginal_modulesR<(Rat module_namest module_nameRe((s-/usr/lib64/python2.7/test/support/__init__.pyRcs  cCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyt __enter__scGstjj|jdS(N(RNRORR(Rat ignore_exc((s-/usr/lib64/python2.7/test/support/__init__.pyt__exit__s(R<R=R>RcRR(((s-/usr/lib64/python2.7/test/support/__init__.pyR!s  cBs_eZdZdZdZdZdZdZdZdZ dZ d Z RS( s_Class to help protect the environment variable properly. Can be used as a context manager.cCstj|_i|_dS(N(Rutenviront_environt_changed(Ra((s-/usr/lib64/python2.7/test/support/__init__.pyRc(s cCs |j|S(N(R(Ratenvvar((s-/usr/lib64/python2.7/test/support/__init__.pyt __getitem__,scCs<||jkr+|jj||j|RcRRRRRRRR(((s-/usr/lib64/python2.7/test/support/__init__.pyR"#s        t DirsOnSysPathcBs)eZdZdZdZdZRS(sContext 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-tj|_tj|_tjj|dS(N(RNRytoriginal_valuetoriginal_objecttextend(Ratpaths((s-/usr/lib64/python2.7/test/support/__init__.pyRc^s  cCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyRcscGs|jt_|jtj(dS(N(RRNRyR(RaR((s-/usr/lib64/python2.7/test/support/__init__.pyRfs (R<R=R>RcRR(((s-/usr/lib64/python2.7/test/support/__init__.pyRRs   cBs2eZdZdZdZddddZRS(sRaise ResourceDenied if an exception is raised while the context manager is in effect that matches the specified exception and attributes.cKs||_||_dS(N(Rtattrs(RaRR ((s-/usr/lib64/python2.7/test/support/__init__.pyRcps cCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyRtscCs}|dk ryt|j|ryxX|jjD]8\}}t||sMPnt|||kr.Pq.q.WtdndS(sIf type_ is a subclass of self.exc and value has attributes matching self.attrs, raise ResourceDenied. Otherwise let the exception propagate (if any).s%an optional resource is not availableN(RYRvRRt iteritemsRRgR(Rattype_Rt tracebackRft attr_value((s-/usr/lib64/python2.7/test/support/__init__.pyRwsN(R<R=R>RcRRYR(((s-/usr/lib64/python2.7/test/support/__init__.pyR%ks  c #sdddd d!d"g}d#d$d%d&d'g}td||gsg|D]\}}tt||^qVg|D]\}}tt||^qnfd}tj}zy%|dk rtj|ndVWntk r} xxtr}| j } t | dkrGt | dtrG| d} qt | dkryt | dtry| d} qPqW|| nXWdtj|XdS((sReturn a context manager that raises ResourceDenied when various issues with the Internet connection manifest themselves as exceptions.t ECONNREFUSEDiot ECONNRESETiht EHOSTUNREACHiqt ENETUNREACHiet ETIMEDOUTint EADDRNOTAVAILict EAI_AGAINitEAI_FAILit EAI_NONAMEit EAI_NODATAit WSANO_DATAi*sResource '%s' is not availablecst|dd}t|tjsNt|tjrB|ksN|kr{tsrtjj j ddnndS(NRis ( RgRYRiRRtgaierrorRRNtstderrR[R{(R|tn(tcaptured_errnostdeniedt gai_errnos(s-/usr/lib64/python2.7/test/support/__init__.pyt filter_errors Niii(Rio(Rih(Riq(Rie(Rin(Ric(Ri(Ri(Ri(Ri(Ri*( RRgRRtgetdefaulttimeoutRYtsetdefaulttimeoutR RVR{RRi( t resource_nameRterrnostdefault_errnostdefault_gai_errnosRJtnumRt old_timeoutR|ta((RRRs-/usr/lib64/python2.7/test/support/__init__.pyR&sJ  (+     % %   ccs[ddl}tt|}tt||jztt|VWdtt||XdS(sReturn a context manager used by captured_stdout and captured_stdin that temporarily replaces the sys stream *stream_name* with a StringIO.iN(tStringIORgRNtsetattr(t stream_nameRt orig_stdout((s-/usr/lib64/python2.7/test/support/__init__.pyR#s  cCs tdS(sCapture the output of sys.stdout: with captured_stdout() as s: print "hello" self.assertEqual(s.getvalue(), "hello") Rs(R#(((s-/usr/lib64/python2.7/test/support/__init__.pyR$scCs tdS(NR(R#(((s-/usr/lib64/python2.7/test/support/__init__.pytcaptured_stderrscCs tdS(Ntstdin(R#(((s-/usr/lib64/python2.7/test/support/__init__.pytcaptured_stdinscCs8tjtr tjdntjtjdS(sForce 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(tgctcollectRRR(((s-/usr/lib64/python2.7/test/support/__init__.pyt gc_collects  t2PtgettotalrefcounttPcCstjt|dS(Nt0P(tstructtcalcsizet_header(tfmt((s-/usr/lib64/python2.7/test/support/__init__.pyt calcobjsizescCstjt|dS(NR(RRt_vheader(R((s-/usr/lib64/python2.7/test/support/__init__.pyt calcvobjsizesii cCsddl}tj|}t|tkr:|jt@s_t|tkrot|jt@ro||j7}ndt|||f}|j|||dS(Nis&wrong size for %s: got %d, expected %d( t _testcapiRNt getsizeofRot __flags__t_TPFLAGS_HEAPTYPEt_TPFLAGS_HAVE_GCtSIZEOF_PYGC_HEADRJ(ttesttotsizeRRRL((s-/usr/lib64/python2.7/test/support/__init__.pyt check_sizeofs %csfd}|S(Ncs1fd}j|_j|_|S(Ncsy.ddl}t|}|j|}Wn$tk rDnAd}}n1Xx-D]%}y|j||PWq\q\Xq\Wz||SWd|r|r|j||nXdS(Ni(tlocaleRgt setlocaleRhRY(R{tkwdsRtcategoryt orig_localetloc(tcatstrRztlocales(s-/usr/lib64/python2.7/test/support/__init__.pytinners$    (t func_nameR>(RzR(RR(Rzs-/usr/lib64/python2.7/test/support/__init__.pyRs  ((RRR((RRs-/usr/lib64/python2.7/test/support/__init__.pyR'scsfd}|S(Ncs.fd}j|_j|_|S(Ncsy tj}Wn tk r/tjdnXdtjkrOtjd}nd}tjd<|z||SWd|dkrtjd=n |tjd(RzR(R(Rzs-/usr/lib64/python2.7/test/support/__init__.pyR:s  ((RR((Rs-/usr/lib64/python2.7/test/support/__init__.pyR:9scCsidd6td6td6dtd6}tjd|tjtjB}|dkrgtd|fntt |j d||j d j }|a |t krt }n|tdkrtd |fn|adS( NiRtmtgtts(\d+(\.\d+)?) (K|M|G|T)b?$sInvalid memory limit %riis$Memory limit %r too low to be useful(t_1Mt_1GRsRtt IGNORECASEtVERBOSERYRRRtgrouptlowertreal_max_memusetMAX_Py_ssize_tt_2GR(tlimittsizesRtmemlimit((s-/usr/lib64/python2.7/test/support/__init__.pyR(bs   2  icsfd}|S(sQDecorator for bigmem tests. 'minsize' is the minimum useful size for the test (in arbitrary, test-interpreted units.) 'memuse' is the number of 'bytes per size' for the test, or a good estimate of it. 'overhead' specifies fixed overhead, independent of the testsize, and defaults to 5Mb. The decorator tries to guess a good value for 'size' and passes it to the decorated test function. If minsize * memuse is more than the allowed memory use (as defined by max_memuse), the test is skipped. Otherwise, minsize is adjusted upward to use up to max_memuse. cs7fd}|_|_|_|S(Ncsts.d}|j|dtkn^tt}|krutrqtjjdjfndSt |dt}||S(Niis)Skipping %s because of memory constraint i2( Rt assertFalseRRRRNRR[R<tmax(Ratmaxsize(R tmemusetminsizetoverhead(s-/usr/lib64/python2.7/test/support/__init__.pyRs"  (RRR(R R(RRR(R s-/usr/lib64/python2.7/test/support/__init__.pyRs    ((RRRR((RRRs-/usr/lib64/python2.7/test/support/__init__.pyR)ws csfd}|S(Ncs7fd}|_|_|_|S(Ncsftsd}n}ts" rYt|krYtrUtjjdjfndS||S(Nis)Skipping %s because of memory constraint (RRRNRR[R<(RaR(tdry_runR RR(s-/usr/lib64/python2.7/test/support/__init__.pyRs   (RRR(R R(RRRR(R s-/usr/lib64/python2.7/test/support/__init__.pyRs    ((RRRRR((RRRRs-/usr/lib64/python2.7/test/support/__init__.pytprecisionbigmemtestscsfd}|S(s0Decorator for tests that fill the address space.cs@ttkr2tr<tjjdjfq<n |SdS(Ns)Skipping %s because of memory constraint (RRRRNRR[R<(Ra(R (s-/usr/lib64/python2.7/test/support/__init__.pyRs   ((R R((R s-/usr/lib64/python2.7/test/support/__init__.pyR*scBseZdZRS(cCstj}|||S(N(RGt TestResult(RaRR((s-/usr/lib64/python2.7/test/support/__init__.pytruns  (R<R=R(((s-/usr/lib64/python2.7/test/support/__init__.pyR+scCs|S(N((Rp((s-/usr/lib64/python2.7/test/support/__init__.pyt_idscCsP|dkr&t r&tjtjSt|r6tStjdj|SdS(NRsresource {0!r} is not enabled(RRGtskipRRRR(R((s-/usr/lib64/python2.7/test/support/__init__.pytrequires_resources  cCstdt|S(s9 Decorator for tests only applicable on CPython. tcpython(t impl_detailRV(R((s-/usr/lib64/python2.7/test/support/__init__.pyR2scKs}t|rtS|dkrpt|\}}|r=d}nd}t|j}|jdj|}ntj |S(Ns*implementation detail not available on {0}s%implementation detail specific to {0}s or ( R3RRYt _parse_guardstsortedRRRRGR(RLtguardst guardnamestdefault((s-/usr/lib64/python2.7/test/support/__init__.pyRs   cCs2|sitd6tfS|jd}|| fS(NRi(RVRXtvalues(R tis_true((s-/usr/lib64/python2.7/test/support/__init__.pyR scKs.t|\}}|jtjj|S(s5This function returns True or False depending on the host platform. Examples: if check_impl_detail(): # only on CPython (default) if check_impl_detail(jython=True): # only on Jython if check_impl_detail(cpython=False): # everywhere except on CPython (R RoRtpython_implementationR(R R ((s-/usr/lib64/python2.7/test/support/__init__.pyR3scCsrg}x\|jD]Q}t|tjrEt|||j|q||r|j|qqW||_dS(s>Recursively filter test cases in a suite based on a predicate.N(t_testsRiRGt TestSuitet _filter_suiteR\(tsuitetpredtnewtestsR((s-/usr/lib64/python2.7/test/support/__init__.pyRs  cCstr'tjtjdddt}n t}|j|}|j r\|j r\t n|j st |j dkr|j r|j dd}nLt |jdkr|j r|jdd}nd}ts|d7}nt|ndS( s2Run tests from a unittest.TestSuite-derived class.t verbosityitfailfastiismultiple errors occurreds!; run in verbose mode for detailsN(RRGtTextTestRunnerRNRsRR+RttestsRuntskippedRt wasSuccessfulRterrorstfailuresR(RtrunnerRR|((s-/usr/lib64/python2.7/test/support/__init__.pyt _run_suites      cCs$tdkrtSt|jSdS(N(t_match_test_funcRYRVtid(R((s-/usr/lib64/python2.7/test/support/__init__.pyt match_test#s cCsd|kotjd| S(NRMs[?*\[\]](Rstsearch(tpattern((s-/usr/lib64/python2.7/test/support/__init__.pyt_is_full_match_test+scs|tkrdS|s%d}d}nittt|rLt|j}nBdjttj |}t j |j fd}|}t |a|adS(Nt|cs0|rtStt|jdSdS(NRM(RVtanyRR(ttest_id(t regex_match(s-/usr/lib64/python2.7/test/support/__init__.pytmatch_test_regexJs ((t_match_test_patternsRYtallRR&Rt __contains__Rtfnmatcht translateRsRHRtRR!(tpatternsRztregexR+((R*s-/usr/lib64/python2.7/test/support/__init__.pytset_match_tests5s    cGstjtjf}tj}x|D]}t|trx|tjkri|jtjtj|qt dq%t||r|j|q%|jtj |q%Wt |t t |dS(s1Run tests from unittest.TestCase-derived classes.s)str arguments must be keys in sys.modulesN(RGRtTestCaseRiRIRNROtaddTestt findTestCasesRt makeSuiteRR#R (tclassest valid_typesRtcls((s-/usr/lib64/python2.7/test/support/__init__.pyR,]s    Rtwin32tWITH_DOC_STRINGSstest requires docstringscCsddl}|dkr!t}nd}tj}tt_z>|j|d|\}}|rytd||fnWd|t_Xtrd|j|fGHn||fS(s Run doctest on the given module. Return (#failures, #tests). If optional argument verbosity is not specified (or is None), pass test.support's belief about verbosity on to doctest. Else doctest's usual behavior is used (it searches sys.argv for -v). iNRs%d of %d doctests faileds,doctest (%s) ... %d tests with zero failures( tdoctestRYRRNRsR ttestmodRR<(ReRR=t save_stdoutR R((s-/usr/lib64/python2.7/test/support/__init__.pyR-|s      cCstrtjfSdSdS(Ni(i(tthreadt_count(((s-/usr/lib64/python2.7/test/support/__init__.pyR.s cCsTts dSd}x=t|D]/}tj}||kr?PntjdqWdS(Ni g?(R@RRARR(t nb_threadst _MAX_COUNTtcountR((s-/usr/lib64/python2.7/test/support/__init__.pyR/s  cs,ts Stjfd}|S(sUse 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(R.R/(R{tkey(Rz(s-/usr/lib64/python2.7/test/support/__init__.pyRs (R@RR(RzR((Rzs-/usr/lib64/python2.7/test/support/__init__.pyR0sgN@ccstj}z dVWdtj}||}xtrtj}||krSPntj|krtj|}d|||||f}t|ntjdtq1WXdS(sE 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. NsYwait_threads() failed to cleanup %s threads after %.1f seconds (count: %s, old count: %s)g{Gz?(R@RARRVRxRR(Rt old_countt start_timetdeadlineRDtdtRL((s-/usr/lib64/python2.7/test/support/__init__.pytwait_threads_exits         cCscttdr_d}xGtr[y/tj|tj\}}|dkrLPnWqPqXqWndS(sUse 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. twaitpidiiN(RRuRVRKtWNOHANG(t any_processR+tstatus((s-/usr/lib64/python2.7/test/support/__init__.pyR7s   c cst|}g}zfy,x%|D]}|j|j|qWWn.trkdt|t|fGHnnXdVWd|r|ntj}}xtddD]}|d7}x.|D]&}|jt|tjdqWg|D]}|j r|^q}|sPntrdt||fGHqqWXg|D]}|j rE|^qE}|rt dt|ndS(Ns/Can't start %d threads, only %d threads startediii<g{Gz?s7Unable to join %d threads during a period of %d minutessUnable to join %d threads( RQtstartR\RRRRRRtisAliveRx(tthreadstunlocktstartedRtendtimet starttimeR((s-/usr/lib64/python2.7/test/support/__init__.pyR1s:       $%%ccst||rNt||}t|||z |VWdt|||Xn<t|||z dVWdt||rt||nXdS(sTemporary 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(RRgRtdelattr(RpRftnew_valtreal_val((s-/usr/lib64/python2.7/test/support/__init__.pyt swap_attr)s  ccsk||kr:||}|||rsN(ttobytesRhRt TypeErrortbytes(tb((s-/usr/lib64/python2.7/test/support/__init__.pyR5gs  t getcountss-types are immortal if COUNT_ALLOCS is definedcCsddl}|jS(sZReturn a list of command-line arguments reproducing the current settings in sys.flags.iN(t subprocesst_args_from_interpreter_flags(Rc((s-/usr/lib64/python2.7/test/support/__init__.pytargs_from_interpreter_flagsys cCstjdd|j}|S(sStrip 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\]\r?\n?$R(Rstsubtstrip(R((s-/usr/lib64/python2.7/test/support/__init__.pyR8scsid|ffdY}tg||||jttt|jddS(NtAcseZfdZRS(cs0tdRYRRRR(((s-/usr/lib64/python2.7/test/support/__init__.pyR;s  GcCs*ddl}t|jWdQXdS(sDeliberate crash of Python. Python can be killed by a segmentation fault (SIGSEGV), a bus error (SIGBUS), or a different error depending on the platform. Use SuppressCrashReport() to prevent a crash report from popping up. iN(RR;t _read_null(R((s-/usr/lib64/python2.7/test/support/__init__.pyt _crash_pythons  c Cstjjd rdy!tjd}t|dSWqdtk r`}|jtjkraqaqdXnd}t tdrytj d}Wqtk rqXnd }tjdkr+yd d l }|j Wnttfk rq+Xi}x9|j|j|jfD]}|j |d ||RcRR(((s-/usr/lib64/python2.7/test/support/__init__.pyR_s ((ii@i@i@ii(i@ii(((((R>R<RFt contextlibRR/RRRRwRNRuRRR@RGREtUserDictRsRRRxRjR@RYt__all__t SHORT_TIMEOUTRRRRRHRtcontextmanagerRVRDRXRRUR[R6R4RRRRRRrRR R R}RRRRRRR RR R RRRRRRRRRRRR9R RRt PIPE_MAX_SIZEt SOCK_MAX_SIZERRRt NameErrort skipUnlesstrequires_unicodeRt FS_NONASCIItunichrt characterR$R%tdecodet UnicodeErrorRJRRitTESTFN_UNICODEtTESTFN_ENCODINGRRtTESTFN_UNENCODABLEtevalR&RR(t TEST_HTTP_URLR-RR,R0RRyRtabspatht__file__tTEST_SUPPORT_DIRR6RRXRRRDRRtobjectR^RRR R!t DictMixinR"RR%R&R#R$RRRRRRRRRRR'R:RRRt_4GRRR(R)RR*R+RRR2RR R3RR R!R,R#R&R3R,RytHAVE_DOCSTRINGStrequires_docstringsR-tenvironment_alteredR.R/R0RJR7R1RYR[R5tskipIftrequires_type_collectingReR8RqRvR}R;RRR(((s-/usr/lib64/python2.7/test/support/__init__.pyts                                    &      !         J  < $                               .    * ' /D         $ "     '       (    &  #       e  R(tzip_dirt zip_basenameRCt name_in_zipt zip_filenametzip_nametzip_file((s2/usr/lib64/python2.7/test/support/script_helper.pytmake_zip_scriptzs  tcCs!tj|t|d|dS(Nt__init__(R tmkdirRE(tpkg_dirt init_source((s2/usr/lib64/python2.7/test/support/script_helper.pytmake_pkgs icCsg}t|dd}|j|tjj|} t|||} |j| |rt|}t| } |j|| fngtd|dD]} tjj |g| ^q} tjj | dtjj| } |tj d}tjj ||}t j |d}x3| D]+}tjj || }|j ||q'W|j | | |jx|D]}tj|qwW|tjj || fS(NRYRXiiRLR%(RER R R5RPRKR trangetsepR=R<RMRNR>Rtunlink(RQRRtpkg_nameR@RAtdepthtcompiledR`t init_namet init_basenameRCtit pkg_namestscript_name_in_zipRTRURVtnametinit_name_in_zip((s2/usr/lib64/python2.7/test/support/script_helper.pyt make_zip_pkgs.    9%   (RR tretos.pathR3RRHt contextlibR7RMt ImportErrort test.supportRR R"R$R*R,R0R2tcontextmanagerR:RERKRORWR]R#Rk(((s2/usr/lib64/python2.7/test/support/script_helper.pyts4                    PK!;rq##support/script_helper.pyonu[ {fc@s.ddlZddlZddlZddlZddlZddlZddlZddlZddlZyddl Z Wne k rnXddl m Z dZ dZdZdZdZdZd Zejd Zd Zd Zdd ZddZdedZdS(iN(tstrip_python_stderrc Ostjg}|s"|jdn|j|tjj}|j|tj |dtj dtj dtj d|}z|j \}}Wdtj |j j|jjX|j}t|}|r|s| r | r td||jddfn|||fS( Ns-Etstdintstdouttstderrtenvs-Process return code is %d, stderr follows: %stasciitignore(tsyst executabletappendtextendtostenvirontcopytupdatet subprocesstPopentPIPEt communicatet_cleanupRtcloseRt returncodeRtAssertionErrortdecode( texpected_successtargstenv_varstcmd_lineRtptoutterrtrc((s2/usr/lib64/python2.7/test/support/script_helper.pyt_assert_pythons*        cOstt||S(s Assert that running the interpreter with `args` and optional environment variables `env_vars` is ok and return a (return code, stdout, stderr) tuple. (R tTrue(RR((s2/usr/lib64/python2.7/test/support/script_helper.pytassert_python_ok2scOstt||S(s Assert that running the interpreter with `args` and optional environment variables `env_vars` fails and return a (return code, stdout, stderr) tuple. (R tFalse(RR((s2/usr/lib64/python2.7/test/support/script_helper.pytassert_python_failure9sc GsWtjdg}|j|ttjd#}tj|d|dtjSWdQXdS(Ns-EtwRR( RRR topenR tdevnullRtcalltSTDOUT(RRR'((s2/usr/lib64/python2.7/test/support/script_helper.pytpython_exit_code@s  c OsGtjdg}|j|tj|dtjdtjdtj|S(Ns-ERRR(RRR RRRR)(RtkwargsR((s2/usr/lib64/python2.7/test/support/script_helper.pyt spawn_pythonGs  cCsA|jj|jj}|jj|jtj|S(N(RRRtreadtwaitRR(Rtdata((s2/usr/lib64/python2.7/test/support/script_helper.pyt kill_pythonNs     cOs.td||}t|}|j|fS(Ns-O(R,R0R.(RR+Rt stdout_data((s2/usr/lib64/python2.7/test/support/script_helper.pyt run_pythonXs ccs<tj}tjj|}z |VWdtj|XdS(N(ttempfiletmkdtempR tpathtrealpathtshutiltrmtree(tdirname((s2/usr/lib64/python2.7/test/support/script_helper.pyttemp_diras   cCsP|tjd}tjj||}t|d}|j||j|S(NtpyR%(R textsepR5tjoinR&twriteR(t script_dirtscript_basenametsourcetscript_filenamet script_namet script_file((s2/usr/lib64/python2.7/test/support/script_helper.pyt make_scriptjs   cCs!tj|dt|d}|S(Ntdoraiseto(t py_compiletcompileR!(RCt compiled_name((s2/usr/lib64/python2.7/test/support/script_helper.pytcompile_scriptrs cCs|tjd}tjj||}tj|d}|dkrYtjj|}n|j|||j |tjj||fS(NtzipR%( R R<R5R=tzipfiletZipFiletNonetbasenameR>R(tzip_dirt zip_basenameRCt name_in_zipt zip_filenametzip_nametzip_file((s2/usr/lib64/python2.7/test/support/script_helper.pytmake_zip_scriptzs  tcCs!tj|t|d|dS(Nt__init__(R tmkdirRE(tpkg_dirt init_source((s2/usr/lib64/python2.7/test/support/script_helper.pytmake_pkgs icCsg}t|dd}|j|tjj|} t|||} |j| |rt|}t| } |j|| fngtd|dD]} tjj |g| ^q} tjj | dtjj| } |tj d}tjj ||}t j |d}x3| D]+}tjj || }|j ||q'W|j | | |jx|D]}tj|qwW|tjj || fS(NRYRXiiRLR%(RER R R5RPRKR trangetsepR=R<RMRNR>Rtunlink(RQRRtpkg_nameR@RAtdepthtcompiledR`t init_namet init_basenameRCtit pkg_namestscript_name_in_zipRTRURVtnametinit_name_in_zip((s2/usr/lib64/python2.7/test/support/script_helper.pyt make_zip_pkgs.    9%   (RR tretos.pathR3RRHt contextlibR7RMt ImportErrort test.supportRR R"R$R*R,R0R2tcontextmanagerR:RERKRORWR]R#Rk(((s2/usr/lib64/python2.7/test/support/script_helper.pyts4                    PK!A?|| __init__.pycnu[ zfc@sdS(N((((s%/usr/lib64/python2.7/test/__init__.pyttPK!A?|| __init__.pyonu[ zfc@sdS(N((((s%/usr/lib64/python2.7/test/__init__.pyttPK!g 2))script_helper.pynu[from test.support.script_helper import * PK!GKFscript_helper.pycnu[ zfc@sddlTdS(i(t*N(ttest.support.script_helper(((s*/usr/lib64/python2.7/test/script_helper.pyttPK!GKFscript_helper.pyonu[ zfc@sddlTdS(i(t*N(ttest.support.script_helper(((s*/usr/lib64/python2.7/test/script_helper.pyttPK!ӨqOOtest_support.pynu[import sys import test.support sys.modules['test.test_support'] = test.support PK!J[test_support.pycnu[ zfc@s,ddlZddlZejejds  PK!J[test_support.pyonu[ zfc@s,ddlZddlZejejds  PK!Buxx)__pycache__/__init__.cpython-36.opt-1.pycnu[PK!Buxx)__pycache__/__init__.cpython-36.opt-2.pycnu[PK!Buxx#__pycache__/__init__.cpython-36.pycnu[PK!>>1msupport/__pycache__/__init__.cpython-36.opt-1.pycnu[PK!]1Asupport/__pycache__/__init__.cpython-36.opt-2.pycnu[PK!8\p?p?+#support/__pycache__/__init__.cpython-36.pycnu[PK!/J6Ucsupport/__pycache__/script_helper.cpython-36.opt-1.pycnu[PK!m6}support/__pycache__/script_helper.cpython-36.opt-2.pycnu[PK!/J0ٔsupport/__pycache__/script_helper.cpython-36.pycnu[PK!r&XX3support/__pycache__/testresult.cpython-36.opt-1.pycnu[PK! P  3support/__pycache__/testresult.cpython-36.opt-2.pycnu[PK!r&XX-#support/__pycache__/testresult.cpython-36.pycnu[PK!C敏.. support/__init__.pynu[PK! ~;support/script_helper.pynu[PK!  Rsupport/testresult.pynu[PK!E[// l__init__.pynu[PK!&=amsupport/__init__.pycnu[PK!Oaa7support/__init__.pyonu[PK! ܔsupport/script_helper.pycnu[PK!;rq##>support/script_helper.pyonu[PK!A?|| __init__.pycnu[PK!A?|| b__init__.pyonu[PK!g 2))script_helper.pynu[PK!GKFscript_helper.pycnu[PK!GKF~script_helper.pyonu[PK!ӨqOOytest_support.pynu[PK!J[test_support.pycnu[PK!J[Htest_support.pyonu[PKO