3  f@s dZedkredddlZddlZddlZddlZddlZddl 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 rbdZ(YnXy ddl)Z)Wnek rdZ)YnXy ddl*Z*Wnek rdZ*YnXy ddl+Z+Wnek rdZ+YnXy ddl,Z,Wnek rdZ,YnXy ddl-Z-Wnek r*dZ-YnXddd d 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 e/Z0Gdcd d e0Z1Gdddde0Z2Gdeddej3Z4ej5d]dgdhZ6d^fdjdkdZ7dldmZ8dndoZ9dpd<Z:dqd=Z;ffdifdrdZdZ?da@daAdZBdiZCdaDdtdZEdudZFdvdZGdwdxZHejjIdyrd_dzd{ZJd|d}ZKd~dZLddZMddZNnejOZKejPZLddZMddZNddZOddZPddZQddZRddZSddZTdd#ZUd`dd$ZVddZWdd%ZXdd&ZYdd'ZZdZ[dZ\ej]ej^fddIZ_e[fddJZ`ddLZaddZbebZcddZddcZedfZfejgehjidjIddZjejge)dZkejge*dZlejge+dZmejge,dZnejjIdZoejpdZqeqdk o:eqdkZrejdkrXerrRdndZsndZsejtdkrndZundZudjveuejwZudZxxLdgD]BZyyejzej{eyeykre|Wne|k rYnXeyZxPqWeudZ}ejdkrddl~Z~e~jde}Z}ejZdZejtdkrhejjdkreudZyejeWnek rPYnXedeefdZnBejdkrydjeWn&ek reudjedŃZYnXdZxFdhD]d?Zd@dAZGdBdOdOejjZGdCdZdZeZdadDd!ZdEd1ZdadFdGZdHd:ZdId"ZfdJdKd>ZdfffdLd?ZGdMd\d\ZdNdOZdPdQZffdRdSZgfdTd`Zda dUdFZ ej5dVdWZ dXdaZ GdYdZdZZ Gd[d\d\ZdS(vz7Supporting definitions for the Python regression tests.z test.supportz.support must be imported from the test packageN)get_test_runner PIPE_MAX_SIZEverbose max_memuse use_resourcesfailfastError TestFailed TestDidNotRunResourceDenied import_moduleimport_fresh_module CleanImportunloadforgetrecord_original_stdoutget_original_stdoutcaptured_stdoutcaptured_stdincaptured_stderrTESTFNSAVEDCWDunlinkrmtreetemp_cwdfindfilecreate_empty_file can_symlinkfs_is_case_insensitiveis_resource_enabledrequiresrequires_freebsd_versionrequires_linux_versionrequires_mac_vercheck_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__rcrc:/opt/alt/python36/lib64/python3.6/test/support/__init__.pyr usc@seZdZdZdS)r z Test failed.N)r_r`rarbrcrcrcrdr xsc@seZdZdZdS)r zTest did not run any subtests.N)r_r`rarbrcrcrcrdr {sc@seZdZdZdS)r zTest skipped because it requested a disallowed resource. This is raised when a test calls requires() for a resource that has not be enabled. It is used to distinguish between expected and unexpected skips. N)r_r`rarbrcrcrcrdr ~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)rercrcrd_ignore_deprecated_importss  rjF) required_oncCsft|Ty tj|Stk rV}z&tjjt|r8tj t |WYdd}~XnXWdQRXdS)acImport and return the module to be tested, raising SkipTest if it is not available. If deprecated is True, any module or package deprecation messages will be suppressed. If a module is required on a platform but optional for others, set required_on to an iterable of platform prefixes which will be compared against sys.platform. N) rj importlibr ImportErrorsysplatform startswithtupleunittestSkipTeststr)name deprecatedrkmsgrcrcrdr s  cCs^|tjkrt|tj|=x>ttjD]0}||ks@|j|dr&tj|||<tj|=q&WdS)zyHelper function to save and remove a module from sys.modules Raise ImportError if the module can't be imported. .N)rnmodules __import__listrp)ru orig_modulesmodnamercrcrd_save_and_remove_modules r~c 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)rnryKeyError)rur|Zsavedrcrcrd_save_and_block_modules  rcCs|r tjSddS)zDecorator to mark a test that is known to be broken in some cases Any use of this decorator should have a comment identifying the associated tracker issue. cSs|S)Nrc)frcrcrdsz$anticipate_failure..)rrZexpectedFailure)Z conditionrcrcrdr9scCsF|dkr d}tjjtjjtjjt}|j|||d}|j||S)zGeneric load_tests implementation for simple test packages. Most packages can implement load_tests using this function as follows: def load_tests(*args): return load_package_tests(os.path.dirname(__file__), *args) Nztest*)Z start_dirZ top_level_dirpattern)ospathdirname__file__ZdiscoverZaddTests)Zpkg_dirloaderZstandard_testsrZtop_dirZ package_testsrcrcrdr:s c Cst|i}g}t||zfyHx|D]}t||q&Wx |D]}t||s>|j|q>Wtj|}Wntk r~d}YnXWdx|jD]\} } | tj | <qWx|D] } tj | =qWX|SQRXdS)aImport and return a module, deliberately bypassing sys.modules. This function imports and returns a fresh copy of the named Python module by removing the named module from sys.modules before doing the import. Note that unlike reload, the original module is not affected by this operation. *fresh* is an iterable of additional module names that are also removed from the sys.modules cache before doing the import. *blocked* is an iterable of module names that are replaced with None in the module cache during the import to ensure that attempts to import them raise ImportError. The named module and any modules named in the *fresh* and *blocked* parameters are saved before starting the import and then reinserted into sys.modules when the fresh import is complete. Module and package deprecation messages are suppressed during this import if *deprecated* is True. This function will raise ImportError if the named module cannot be imported. N) rjr~rappendrlr rmitemsrnry) ruZfreshZblockedrvr|Znames_to_removeZ fresh_nameZ blocked_nameZ fresh_moduleZ orig_namemoduleZname_to_removercrcrdrs$      c Cs>yt||}Wn&tk r4tjd||fYnX|SdS)z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %rN)getattrAttributeErrorrrrs)objruZ attributercrcrdr5s cCs|adS)N)_original_stdout)stdoutrcrcrdr)scCs tptjS)N)rrnrrcrcrcrdr-sc Cs&y tj|=Wntk r YnXdS)N)rnryr)rurcrcrdr0s 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_run6srwincCs|||r|}ntjj|\}}|p(d}d}x<|dkrjtj|}|rJ|n||ksVdStj||d9}q0Wtjd|tdddS)NrxgMbP?g?rz)tests may fail, delete still pending for ) stacklevel) rrsplitlistdirtimesleeprfwarnRuntimeWarning)rpathnamewaitallrrutimeoutLrcrcrd_waitforAs     rcCsttj|dS)N)rrr)filenamercrcrd_unlinkbsrcCsttj|dS)N)rrrmdir)rrcrcrd_rmdiresrcs,fddt|ddtdd|dS)Ncsxt|tj|D]}tjj||}ytj|j}Wn<tk rn}z td||ft j dd}WYdd}~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_innerrcrdris   z_rmtree.._rmtree_innerT)rcSst|tj|S)N)rrr)prcrcrdrxsz_rmtree..)r)rrc)rrd_rmtreehs rc Cs^y ddl}Wntk r Yn:X|jt|d}|jjj||t|}|rZ|d|S|S)Nrr)ctypesrmZcreate_unicode_bufferlenwindllkernel32ZGetLongPathNameW)rrbufferZlengthrcrcrd _longpathzs    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)aMove a PEP 3147/488 pyc file to its legacy pyc location. :param source: The file system path to the source file. The source file does not need to exist, however the PEP 3147/488 pyc file must exist. :return: The file system path to the legacy pyc file. c) rlutilcache_from_sourcerrrabspathrrename)sourceZpyc_fileZup_oneZ legacy_pycrcrcrdmake_legacy_pycs   rcCs\t|xNtjD]D}tjj||d}t|dx dD]}ttjj||dq8WqWdS) z'Forget' a module was ever imported. This removes the module from sys.modules and deletes any PEP 3147/488 or legacy .pyc files. z.pyrrr) optimizationN)rrr) rrnrrrrrlrr)r}rroptrcrcrdrs    csttdrtjSd}tjjdrddlddld}d}Gfdddj}j j }|j }|sjj |}j j}|j||j|j|j|}|sj t|j|@sd}ntjdkrVdd lm} mm} m} dd lm} | j| d } | jdkrd }nFGfd dd| }|}| |}| j|dksR| j|dkrVd}|sy.ddlm}|}|j|j |j!Wn\t"k r}z>t#|}t$|dkr|ddd}dj%t&|j'|}WYdd}~XnX|t_(| t_tjS)Nresultrrrcs.eZdZdjjfdjjfdjjfgZdS)z*_is_gui_available..USEROBJECTFLAGSZfInheritZ fReserveddwFlagsN)r_r`rawintypesZBOOLDWORD_fields_rc)rrcrdUSEROBJECTFLAGSs  rz,gui not available (WSF_VISIBLE flag not set)darwin)cdllc_intpointer Structure) find_libraryZApplicationServicesz0gui tests cannot run without OS X window managercseZdZdfdfgZdS)z._is_gui_available..ProcessSerialNumberZ highLongOfPSNZ lowLongOfPSNN)r_r`rarrc)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)zTest whether a resource is enabled. Known resources are set by regrtest.py. If not running under regrtest.py, all resources are assumed enabled unless use_resources has been set. N)r)resourcercrcrdr scCs>t|s |dkrd|}t||dkr:t r:ttjdS)z@Raise ResourceDenied if the specified resource is not available.Nz"Use of the %r resource not enabledgui)r r rr)rrwrcrcrdr!%s csfdd}|S)zDecorator raising SkipTest if the OS is `sysname` and the version is less than `min_version`. For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if the FreeBSD version is less than 7.2. cs$tjfdd}|_|S)Nc stjkrztjjddd}yttt|jd}Wntk rLYn.X|krzdjtt }t j d||f||S)N-rrrxz(%s version %s or higher required, not %s) rosystemreleaserrqmapint ValueErrorrrtrrrs)rkw version_txtversionmin_version_txt)r min_versionsysnamercrdwrapper6s z:_requires_unix_version..decorator..wrapper) functoolswrapsr)rr)rr)rrd decorator5sz)_requires_unix_version..decoratorrc)rrrrc)rrrd_requires_unix_version.srcGs td|S)zDecorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is less than `min_version`. For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD version is less than 7.2. ZFreeBSD)r)rrcrcrdr"IscGs td|S)zDecorator raising SkipTest if the OS is Linux and the Linux version is less than `min_version`. For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux version is less than 2.6.32. ZLinux)r)rrcrcrdr#Rscsfdd}|S)zDecorator raising SkipTest if the OS is Mac OS X and the OS X version if less than min_version. For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version is lesser than 10.5. cs"tjfdd}|_|S)Nc sxtjdkrntjd}yttt|jd}Wntk rBYn,X|krndjtt }t j d||f||S)Nrrrxz&Mac OS X %s or higher required, not %s) rnroZmac_verrqrrrrrrtrrrs)rrrrr)rrrcrdrcs   z4requires_mac_ver..decorator..wrapper)rrr)rr)r)rrdrbsz#requires_mac_ver..decoratorrc)rrrc)rrdr$[s z 127.0.0.1z::1cCs"tj||}t|}|j~|S)a Returns an unused port that should be suitable for binding. This is achieved by creating a temporary socket with the same family and type as the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to the specified host address (defaults to 0.0.0.0) with the port set to 0, eliciting an unused ephemeral port from the OS. The temporary socket is then closed and deleted, and the ephemeral port is returned. Either this method or bind_port() should be used for any tests where a server socket needs to be bound to a particular port for the duration of the test. Which one to use depends on whether the calling code is creating a python socket, or if an unused port needs to be provided in a constructor or passed to an external program (i.e. the -accept argument to openssl's s_server mode). Always prefer bind_port() over find_unused_port() where possible. Hard coded ports should *NEVER* be used. As soon as a server socket is bound to a hard coded port, the ability to run multiple instances of the test simultaneously on the same host is compromised, which makes the test a ticking time bomb in a buildbot environment. On Unix buildbots, this may simply manifest as a failed test, which can be recovered from without intervention in most cases, but on Windows, the entire python process can completely and utterly wedge, requiring someone to log in to the buildbot and manually kill the affected process. (This is easy to reproduce on Windows, unfortunately, and can be traced to the SO_REUSEADDR socket option having different semantics on Windows versus Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind, listen and then accept connections on identical host/ports. An EADDRINUSE OSError will be raised at some point (depending on the platform and the order bind and listen were called on each socket). However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE will ever be raised when attempting to bind two identical host/ports. When accept() is called on each socket, the second caller's process will steal the port from the first caller, leaving them both in an awkwardly wedged state where they'll no longer respond to any signals or graceful kills, and must be forcibly killed via OpenProcess()/TerminateProcess(). The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option instead of SO_REUSEADDR, which effectively affords the same semantics as SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open Source world compared to Windows ones, this is a common mistake. A quick look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when openssl.exe is called with the 's_server' option, for example. See http://bugs.python.org/issue2550 for more info. The following site also has a very thorough description about the implications of both REUSEADDR and EXCLUSIVEADDRUSE on Windows: http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx) XXX: although this approach is a vast improvement on previous attempts to elicit unused ports, it rests heavily on the assumption that the ephemeral port returned to us by the OS won't immediately be dished back out to some other process when we close and delete our temporary socket but before our calling code has a chance to bind the returned port. We can deal with this issue if/when we come across it. )socketrGclose)familyZsocktypeZtempsockportrcrcrdrF}s 8 c Cs|jtjkr|jtjkrttdr>|jtjtjdkr>t dttdrdt j kry |jtjtj dkrpt dWnt k rYnXttdr|jtjtjd|j|df|jd}|S) a%Bind the socket to a free port and return the port number. Relies on ephemeral ports in order to ensure we are using an unbound port. This is important as many tests may be running simultaneously, especially in a buildbot environment. This method raises an exception if the sock.family is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR or SO_REUSEPORT set on it. Tests should *never* set these socket options for TCP/IP sockets. The only case for setting these options is testing multicasting via multiple UDP sockets. Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. on Windows), it will be set on the socket. This will prevent anyone else from bind()'ing to our host/port for the duration of the test. SO_REUSEADDRrzHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets! SO_REUSEPORTZWITHIN_PYTHON_RPM_BUILDzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!SO_EXCLUSIVEADDRUSEr)rrAF_INETr SOCK_STREAMrZ getsockoptZ SOL_SOCKETrr renvironrrZ setsockoptrbindZ getsockname)sockhostrrcrcrdrGs       c CsJ|jtjksty|j|Wn&tk rD|jtjdYnXdS)zBBind a unix socket, raising SkipTest if PermissionError is raised.zcannot bind AF_UNIX socketsN) rrZAF_UNIXAssertionErrorrPermissionErrorrrrrs)rZaddrrcrcrdrIs cCsZtjrVd}z.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)aReturn a context manager that creates a temporary directory. Arguments: path: the directory to create temporarily. If omitted or None, defaults to creating a temporary directory using tempfile.mkdtemp. quiet: if False (the default), the context manager raises an exception on error. Otherwise, if the path is specified and cannot be created, only a warning is issued. FNTz+tests may fail, unable to create temp dir: )r) tempfilemkdtemprrrealpathmkdirrrfrrgetpidr)rquietZ dir_createdpidrcrcrdtemp_dirs&   r.ccsftj}ytj|Wn.tk rD|s,tjd|tddYnXztjVWdtj|XdS)agReturn a context manager that changes the current working directory. Arguments: path: the directory to use as the temporary current working directory. quiet: if False (the default), the context manager raises an exception on error. Otherwise, it issues only a warning and keeps the current working directory the same. z)tests may fail, unable to change CWD to: r&)rN)rgetcwdchdirrrfrr)rr,Z saved_dirrcrcrd change_cwds  r1tempcwdccs:t||d$}t||d }|VWdQRXWdQRXdS)a Context manager that temporarily creates and changes the CWD. The function temporarily changes the current working directory after creating a temporary directory in the current directory with name *name*. If *name* is None, the temporary directory is created using tempfile.mkdtemp. If *quiet* is False (default) and it is not possible to create or change the CWD, an error is raised. If *quiet* is True, only a warning is raised and the original CWD is used. )rr,)r,N)r.r1)rur,Z temp_pathZcwd_dirrcrcrdrsumaskc cs&tj|}z dVWdtj|XdS)z8Context manager that temporarily sets the process umask.N)rr3)r3ZoldmaskrcrcrdrJs  datacCsbtjj|r|S|dk r&tjj||}tgtj}x*|D]"}tjj||}tjj|r8|Sq8W|S)a[Try to find a file on sys.path or in the test directory. If it is not found the argument passed to the function is returned (this does not necessarily signal failure; could still be the legitimate path). Setting *subdir* indicates a relative path to use to find the file rather than looking directly in the path directories. N)rrisabsr TEST_HOME_DIRrnexists)rZsubdirrZdnfnrcrcrdr#s    cCs(tj|tjtjBtjB}tj|dS)z>Create an empty file. If the file already exists, truncate it.N)ropenO_WRONLYO_CREATO_TRUNCr)rfdrcrcrdr5scCs,t|j}dd|D}dj|}d|S)z%Like repr(dict), but in sorted order.cSsg|] }d|qS)z%r: %rrc).0Zpairrcrcrd =szsortdict..z, z{%s})sortedrr)dictrZ reprpairsZ withcommasrcrcrdrZ:s  c Cs*ttd}z|jS|jttXdS)z` Create an invalid file descriptor by opening and closing a file and return its fd. wbN)r9rfilenorr)rrcrcrd make_bad_fdAs  rD)linenooffsetc Csp|jt}t|ddWdQRX|j}|j|j|dk rJ|j|j||j|j|dk rl|j|j|dS)Nz exec) assertRaises SyntaxErrorcompileZ exceptionZassertIsNotNonerE assertEqualrF)testcaseZ statementrErFcmrrcrcrdr%Ms   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)r9seekr)r8r)rrNrrcrdcheck_valid_fileas z*open_urlresource..check_valid_fileZurlfetchz fetching %s ...)rAccept-Encodinggzip)rzContent-Encoding)ZfileobjrBzinvalid resource %r)rRrS)Zurllib.requestZ urllib.parsepopparseZurlparserrrr TEST_DATA_DIRr7rr!rrrZrequestZ build_openerrSZ addheadersrr9ZheadersgetZGzipFilereadwriterr ) Zurlrrurllibrr8rQropeneroutsrc)rrNrrdrHXs<         c@s4eZdZdZddZddZeddZdd Zd S) WarningsRecorderzyConvenience wrapper for the warnings list returned on entry to the warnings.catch_warnings() context manager. cCs||_d|_dS)Nr) _warnings_last)selfZ warnings_listrcrcrd__init__szWarningsRecorder.__init__cCsDt|j|jkr t|jd|S|tjjkr0dStd||fdS)Nrz%r has no attribute %rrU)rrarbrrfWarningMessage_WARNING_DETAILSr)rcattrrcrcrd __getattr__s  zWarningsRecorder.__getattr__cCs|j|jdS)N)rarb)rcrcrcrdrfszWarningsRecorder.warningscCst|j|_dS)N)rrarb)rcrcrcrdresetszWarningsRecorder.resetN) r_r`rarbrdrhpropertyrfrircrcrcrdr`s  r`c cs tjd}|jjd}|r"|jtjdd }tjdjdt |VWdQRXt |}g}xz|D]r\}}d} xH|ddD]8}|j } t j |t| t jrt| j|rd} |j|qW| rf| rf|j||jfqfW|rtd |d |rtd |d dS) zCatch the warnings, then check if all the expected warnings have been raised and re-raise unexpected warnings. If 'quiet' is True, only re-raise the unexpected warnings. rZ__warningregistry__T)recordrfalwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)rn _getframe f_globalsrYclearrfrgry simplefilterr`r{messagerematchrtI issubclassrremoverr_r) filtersr,frameregistrywZreraiseZmissingrwcatseenZwarningrcrcrd_filterwarningss0    r}cOs.|jd}|s$dtff}|dkr$d}t||S)aContext manager to silence warnings. Accept 2-tuples as positional arguments: ("message regexp", WarningCategory) Optional argument: - if 'quiet' is True, it does not fail if a filter catches nothing (default True without argument, default False if some filters are defined) Without argument, it defaults to: check_warnings(("", Warning), quiet=True) r,rNT)rYWarningr})rwr r,rcrcrdrQs   c 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)rkrl)categoryN)rfrgrhResourceWarning gc_collectrK)rLZwarnsrcrcrdrRs c@s(eZdZdZddZddZddZdS) ra,Context manager to force import to return a new module reference. This is useful for testing module-level behaviours, such as the emission of a DeprecationWarning on import. Use like this: with CleanImport("foo"): importlib.import_module("foo") # new reference cGsNtjj|_x<|D]4}|tjkrtj|}|j|kr>tj|j=tj|=qWdS)N)rnrycopyoriginal_modulesr_)rcZ module_namesZ module_namerrcrcrdrds      zCleanImport.__init__cCs|S)Nrc)rcrcrcrd __enter__szCleanImport.__enter__cGstjj|jdS)N)rnryrr)rc ignore_excrcrcrd__exit__szCleanImport.__exit__N)r_r`rarbrdrrrcrcrcrdrs  c@sheZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZdS)rSz_Class to help protect the environment variable properly. Can be used as a context manager.cCstj|_i|_dS)N)rr_environ_changed)rcrcrcrdrdszEnvironmentVarGuard.__init__cCs |j|S)N)r)rcenvvarrcrcrd __getitem__szEnvironmentVarGuard.__getitem__cCs*||jkr|jj||j|<||j|<dS)N)rrrY)rcrvaluercrcrd __setitem__!s zEnvironmentVarGuard.__setitem__cCs2||jkr|jj||j|<||jkr.|j|=dS)N)rrrY)rcrrcrcrd __delitem__'s  zEnvironmentVarGuard.__delitem__cCs |jjS)N)rkeys)rcrcrcrdr.szEnvironmentVarGuard.keyscCs t|jS)N)iterr)rcrcrcrd__iter__1szEnvironmentVarGuard.__iter__cCs t|jS)N)rr)rcrcrcrd__len__4szEnvironmentVarGuard.__len__cCs |||<dS)Nrc)rcrrrcrcrdset7szEnvironmentVarGuard.setcCs ||=dS)Nrc)rcrrcrcrdunset:szEnvironmentVarGuard.unsetcCs|S)Nrc)rcrcrcrdr=szEnvironmentVarGuard.__enter__cGsJx<|jjD].\}}|dkr0||jkr:|j|=q ||j|<q W|jt_dS)N)rrrrr)rcrkvrcrcrdr@s   zEnvironmentVarGuard.__exit__N)r_r`rarbrdrrrrrrrrrrrcrcrcrdrSsc@s(eZdZdZddZddZddZdS) DirsOnSysPathaContext manager to temporarily add directories to sys.path. This makes a copy of sys.path, appends any directories given as positional arguments, then reverts sys.path to the copied settings when the context ends. Note that *all* sys.path modifications in the body of the context manager, including replacement of the object, will be reverted at the end of the block. cGs(tjdd|_tj|_tjj|dS)N)rnroriginal_valueoriginal_objectextend)rcpathsrcrcrdrdVszDirsOnSysPath.__init__cCs|S)Nrc)rcrcrcrdr[szDirsOnSysPath.__enter__cGs|jt_|jtjdd<dS)N)rrnrr)rcrrcrcrdr^szDirsOnSysPath.__exit__N)r_r`rarbrdrrrcrcrcrdrJs 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)rcrr rcrcrdrdhszTransientResource.__init__cCs|S)Nrc)rcrcrcrdrlszTransientResource.__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)rurrrrrr )rcZtype_r tracebackrgZ attr_valuercrcrdros zTransientResource.__exit__)NNN)r_r`rarbrdrrrcrcrcrdr&cs)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||qSrc)rr)r>runumrcrcrdr?sz&transient_internet..cSsg|]\}}tt||qSrc)rr)r>rurrcrcrdr?scst|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_errorNrrr)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)zReturn a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO.rN)iorrnsetattrStringIO)Z stream_namerZ orig_stdoutrcrcrdcaptured_outputs  rcCstdS)zCapture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") r)rrcrcrcrdrscCstdS)zCapture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") r)rrcrcrcrdrscCstdS)a Capture the input to sys.stdin: with captured_stdin() as stdin: stdin.write('hello\n') stdin.seek(0) # call test code that consumes from sys.stdin captured = input() self.assertEqual(captured, "hello") stdin)rrcrcrcrdrs cCs*tjtrtjdtjtjdS)aForce as many objects as possible to be collected. In non-CPython implementations of Python, this is needed because timely deallocation is not guaranteed by the garbage collector. (Even in CPython this can be the case in case of reference cycles.) This means that __del__ methods may be called later than expected and weakrefs may remain alive for longer than expected. This function tries its best to force all garbage objects to disappear. g?N)gcZcollectr?rrrcrcrcrdrs  rc cs.tj}tjz dVWd|r(tjXdS)N)r isenableddisableenable)Zhave_gcrcrcrd disable_gc s  rcCs:tjdp d}d}x|jD]}|jdr|}qW|dkS)z,Find if Python was built with optimizations. PY_CFLAGSrz-O-O0-Og)rrr) sysconfigget_config_varrrp)ZcflagsZ final_optrrcrcrdpython_is_optimizeds  rZnPZ0ngettotalrefcountZ2PZ0PrcCstjt|tS)N)structcalcsize_header_align)fmtrcrcrd calcobjsize)srcCstjt|tS)N)rr_vheaderr)rrcrcrd calcvobjsize,sr cCspddl}tj|}t|tkr(|jt@sBt|tkrLt|jt@rL||j7}dt|||f}|j|||dS)Nrz&wrong size for %s: got %d, expected %d) _testcapirn getsizeofr __flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADrK)testosizerrrwrcrcrd check_sizeof3s  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)catstrrlocalesrcrdinnerDs$     z1run_with_locale..decorator..inner)r_rb)rr)rr)rrdrCsz"run_with_locale..decoratorrc)rrrrc)rrrdrTBscsfdd}|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)rtzrcrdrhs       z-run_with_tz..decorator..inner)r_rb)rr)r)rrdrgszrun_with_tz..decoratorrc)rrrc)rrdr[fs 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_1Grrrs IGNORECASEVERBOSErrfloatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitZsizesrZmemlimitrcrcrdrXs $ c@s(eZdZdZddZddZddZdS) _MemoryWatchdogz`An object which periodically watches the process' memory consumption and prints it out. cCsdjtjd|_d|_dS)Nz/proc/{pid}/statm)r-F)rrr+procfilestarted)rcrcrcrdrdsz_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)r9rrrfrrrrnrflushr subprocessPopen executableZDEVNULL mem_watchdogrr)rcrrZwatchdog_scriptrcrcrdstarts   z_MemoryWatchdog.startcCs|jr|jj|jjdS)N)rr Z terminatewait)rcrcrcrdstops z_MemoryWatchdog.stopN)r_r`rarbrdr r rcrcrcrdrsrcsfdd}|S)atDecorator for bigmem tests. 'size' is a requested size for the test (in arbitrary, test-interpreted units.) 'memuse' is the number of bytes per unit for the test, or a good estimate of it. For example, a test that needs two byte buffers, of 4 GiB each, could be decorated with @bigmemtest(size=_4G, memuse=2). The 'size' argument is normally passed to the decorated test method as an extra argument. If 'dry_run' is true, the value passed to the test method may be less than the requested value. If 'dry_run' is false, it means the test doesn't support dummy runs when -M is not specified. cs fdd__S)Nc sj}j}tsd}n|}ts$ rFt||krFtjd||dtr|tr|ttdj||ddt}|j nd}z ||S|r|j XdS) Niz'not enough memory: %.1fG minimum neededir&z* ... expected peak memory use: {peak:.1f}G)Zpeaki@i@) rmemuserrrrsrrrrr r )rcrr maxsizeZwatchdog)dry_runrrrcrdrs*    z.bigmemtest..decorator..wrapper)rr )r)rr r)rrrdrszbigmemtest..decoratorrc)rr rrrc)rr rrdr2s !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@)rrrrrs)rc)rrcrdrsz!bigaddrspacetest..wrapperrc)rrrc)rrdr3s c@seZdZddZdS)r+cCstj}|||S)N)rrZ TestResult)rcrrrcrcrdrunszBasicTestRunner.runN)r_r`rarrcrcrcrdr+scCs|S)Nrc)rrcrcrd_id srcCs<|dkrt rtjtjSt|r(tStjdj|SdS)Nrzresource {0!r} is not enabled)rrrskiprr rr)rrcrcrdrequires_resources  rcCs&trt|krtjd|tfStSdS)Nz%s at Android API level %d)r@_ANDROID_API_LEVELrrrr)levelrrcrcrdr=s  cCstdd|S)z9 Decorator for tests only applicable on CPython. T)cpython) impl_detail)rrcrcrdr4scKsVtf|rtS|dkrLt|\}}|r,d}nd}t|j}|jdj|}tj|S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or ) rAr _parse_guardsr@rrrrrr)rwguardsZ guardnamesdefaultrcrcrdr#s   rc CsTtdkr:ddl}y|jdaWntk r8daYnXd}trF|Stj||S)z8Skip decorator for tests that use multiprocessing.Queue.NrTFz6requires a functioning shared semaphore implementation)_have_mp_queuemultiprocessingZQueuermrrr)rrrwrcrcrdr>1s cCsH|sddidfSt|jd}t|j|gt|ks>t|| fS)NrTFr)r{valuesrr)rZis_truercrcrdr@s  rcKs t|\}}|jtjj|S)a5This function returns True or False depending on the host platform. Examples: if check_impl_detail(): # only on CPython (default) if check_impl_detail(jython=True): # only on Jython if check_impl_detail(cpython=False): # everywhere except on CPython )rrYroZpython_implementationr)rrrcrcrdrAJs cs,ttdsStjfdd}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.gettracec s.tj}ztjd||Stj|XdS)N)rnr settrace)rr Zoriginal_trace)rrcrdrZs   zno_tracing..wrapperN)rrnrr)rrrc)rrd no_tracingUs r"cCs tt|S)aDecorator for tests which involve reference counting. To start, the decorator does not run the test if is not run by CPython. After that, any trace function is unset during the test to prevent unexpected refcounts caused by the trace function. )r"r4)rrcrcrd refcount_testesr#cCsRg}xB|jD]8}t|tjr2t|||j|q ||r |j|q W||_dS)z>Recursively filter test cases in a suite based on a predicate.N)Z_testsrrr TestSuite _filter_suiter)suiteZpredZnewtestsrrcrcrdr%ps    r%cCsttjttdk d}|j|}tdk r4tj|j|js>t |j st |j dkrl|j rl|j dd}n6t |j dkr|j r|j dd}nd}ts|d7}t|dS)z2Run tests from a unittest.TestSuite-derived class.N) verbosityZcapture_outputrrzmultiple errors occurredz!; run in verbose mode for details)rrnrrjunit_xml_listrrZget_xml_elementZtestsRunr Z wasSuccessfulrerrorsZfailuresr )r&Zrunnerrrrcrcrd _run_suite|s"  r*cCstdkr dSt|jSdS)NT)_match_test_funcid)rrcrcrd match_testsr-cCsd|kotjd| S)Nrxz[?*\[\]])rrsearch)rrcrcrd_is_full_match_testsr/csr|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_patternsallrr/r __contains__rfnmatch translaterrrJrsrqr+)ZpatternsrZregexr3rc)r2rdset_match_testss   r9cGstjtjf}tj}xh|D]`}t|trT|tjkrJ|jtjtj|qzt dqt||rj|j|q|jtj |qWt |t t |dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesN)rrr$ZTestCaserrtrnryZaddTestZ findTestCasesrZ makeSuiter%r-r*)classesZ valid_typesr&clsrcrcrdr,s        cCsdS)z,Just used to check if docstrings are enabledNrcrcrcrcrd_check_docstringssr<WITH_DOC_STRINGSztest requires docstringscCs`ddl}|dkrt}nd}|j|||d\}}|rBtd||ftrXtd|j|f||fS)aRun doctest on the given module. Return (#failures, #tests). If optional argument verbosity is not specified (or is None), pass support's belief about verbosity on to doctest. Else doctest's usual behavior is used (it searches sys.argv for -v). rN)r optionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)doctestrZtestmodr rr_)rr'r>r?rrrcrcrdr-scCs tjjfS)N)rnryrrcrcrcrd modules_setupsr@cCs:ddtjjD}tjjtjj|tjj|dS)NcSs"g|]\}}|jdr||fqS)z encodings.)rp)r>rrrcrcrdr?sz#modules_cleanup..)rnryrror)Z oldmodulesZ encodingsrcrcrdmodules_cleanups  rAcCs"trtjtjjfSdffSdS)Nr)_thread_count threading _danglingrrcrcrcrdrM<scGsJtsdSd}x8t|D],}tjtjf}||kr2PtjdtqWdS)Ndg{Gz?)rBrangerCrDrErrr)Zoriginal_valuesZ _MAX_COUNTcountrrcrcrdrNBs 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)rMrN)rkey)rrcrdrVszreap_threads..decorator)rBrr)rrrc)rrdrONsN@ccstj}z dVWdtj}||}xjtj}||kr8Ptj|kr|tj|}d||d|dd|d|d }t|tjdtq&WXdS) aH bpo-31234: Context manager to wait until all threads created in the with statement exit. Use _thread.count() to check if threads exited. Indirectly, wait until threads exit the internal t_bootstrap() C function of the _thread module. threading_setup() and threading_cleanup() are designed to emit a warning if a test leaves running threads in the background. This context manager is designed to cleanup threads started by the _thread.start_new_thread() which doesn't allow to wait for thread exit, whereas thread.Thread has a join() method. Nz!wait_threads() failed to cleanup z threads after z.1fz seconds (count: z , old count: )g{Gz?)rBrCrZ monotonicrrr)rZ old_countZ start_timeZdeadlinerHZdtrwrcrcrdwait_threads_exit`s   $ rLc CsZttdrVd}xFy2tj|tj\}}|dkr.Ptd|tjdWqPYqXqWdS)zUse this function at the end of test_main() whenever sub-processes are started. This will help ensure that no extra children (zombies) stick around to hog resources and create problems when looking for refleaks. waitpidrrz2Warning -- reap_children() reaped child process %s)rNrU)rrrMWNOHANGrrnr)Z any_processr-ZstatusrcrcrdrKs ccs*t|}g}zZy$x|D]}|j|j|qWWn*trVtdt|t|fYnXdVWdz|rt|tj}}xltddD]^}|d7}x$|D]}|jt |tjdqWdd|D}|sPtrtdt||fqWWdd d|D}|r"t j t j td t|XXdS) Nz/Can't start %d threads, only %d threads startedrr<g{Gz?cSsg|]}|jr|qSrc)isAlive)r>rrcrcrdr?sz!start_threads..z7Unable to join %d threads during a period of %d minutescSsg|]}|jr|qSrc)rP)r>rrcrcrdr?szUnable to join %d threads)r{r rrrrrrGrmax faulthandlerZdump_tracebackrnrr)ZthreadsZunlockrrZendtimeZ starttimerrcrcrdrPs>     c csnt||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)rpendswith)r>rrcrcrd sz&detect_api_mismatch..)rrp)Zref_apiZ other_apireZ missing_itemsrcrcrdr; s  cCs|dkr|jf}nt|tr"|f}t|}xbt|D]V}|jds4||krLq4t||}t|dd|kst|d r4t|tj  r4|j |q4W|j |j |dS)aAssert that the __all__ variable of 'module' contains all public names. The module's public names (its API) are detected automatically based on whether they match the public name convention and were defined in 'module'. The 'name_of_module' argument can specify (as a string or tuple thereof) what module(s) an API could be defined in in order to be detected as a public API. One case for this is when 'module' imports part of its public API from other modules, possibly a C backend (like 'csv' and its '_csv'). The 'extra' argument can be a set of names that wouldn't otherwise be automatically detected as "public", like objects without a proper '__module__' attribute. If provided, it will be added to the automatically detected ones. The 'blacklist' argument can be a set of names that must not be treated as part of the public API even though their names indicate otherwise. Usage: import bar import foo import unittest from test import support class MiscTestCase(unittest.TestCase): def test__all__(self): support.check__all__(self, foo) class OtherTestCase(unittest.TestCase): def test__all__(self): extra = {'BAR_CONST', 'FOO_CONST'} blacklist = {'baz'} # Undocumented name. # bar imports part of its API from _bar. support.check__all__(self, bar, ('bar', '_bar'), extra=extra, blacklist=blacklist) Nryr`) r_rrtrrprprrtypes ModuleTypeaddZassertCountEqual__all__)Z test_caserZname_of_moduleZextraZ blacklistZexpectedrurrcrcrdr< s)    c@s(eZdZdZdZdZddZddZdS)rYzTry to prevent a crash report from popping up. On Windows, don't display the Windows Error Reporting dialog. On UNIX, disable the creation of coredump file. Nc Csrtjjdrddl}|jj|_d}|jj||_|jj|j|Byddl }|j 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/defaultsrZzcom.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 communicaterYr) rcrZSEM_NOGPFAULTERRORBOXr report_typeold_modeold_filecmdprocrrcrcrdr 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)rrnrorprrrrrrrrrrrr)rcrrrrrrcrcrdr0 s   zSuppressCrashReport.__exit__)r_r`rarbrrrrrcrcrcrdrY s Ac srtdyjWn$ttfk r@tdYnXdfdd}|j|t|dS)zOverride 'object_to_patch'.'attr_name' with 'new_value'. Also, add a cleanup procedure to 'test_instance' to restore 'object_to_patch' value for 'attr_name'. The 'attr_name' should be a valid attribute for 'object_to_patch'. FNTcs rtn tdS)N)rrSrc) attr_is_local attr_nameobject_to_patchrrcrdcleanup[ szpatch..cleanup)rrbrrZ addCleanupr)Z test_instancerrZ new_valuerrc)rrrrrdpatchE 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) tracemallocrmZ is_tracingrrrsrrun_in_subinterp)rrrrcrcrdrg s  rcsHGfddd|}d||||jttt|jdS)NcseZdZfddZdS)z%check_free_after_iterating..Ac s*dy tWntk r$YnXdS)NT)next StopIteration)rc)doneitrcrd__del__} s  z-check_free_after_iterating..A.__del__N)r_r`rarrc)rrrcrdA| srF)rHrrrZ assertTrue)rrr;rrrc)rrrdcheck_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_namesrrrZcompilerrurrcrcrdr] s       cCs@d}tr6||kr6tdkr.tjddgjdkatr6|}tj|S)Ngh㈵>Zgetpropzro.kernel.qemu1)r@_is_android_emulatorrZ check_outputrYrnrC)ZintervalZminimum_intervalrcrcrdrC s c cs>tjj}tj}ztjdVWd|r8tj|ddXdS)NT)rZ all_threads)rnrrCrR is_enabledrr)r=rrcrcrddisable_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)rnrorprrrrrrrrrrrmrrrrGduprZEBADFr) namesZMAXFDrrrrHr=Zfd2rrcrcrdr^ sP          c@s(eZdZdZddZddZddZdS) SaveSignalsz Save an restore signal handlers. This class is only able to save/restore signal handlers registered by the Python signal module: see bpo-13285 for "external" signal handlers. c Csjddl}||_ttd|j|_x>dD]6}yt||}Wntk rNw&YnX|jj|q&Wi|_dS)NrrSIGKILLSIGSTOP)rr) signalr{rGNSIGsignalsrrrvr^)rcrZsignamesignumrcrcrdrd s zSaveSignals.__init__cCs4x.|jD]$}|jj|}|dkr"q||j|<qWdS)N)rr getsignalr^)rcrhandlerrcrcrdsave s   zSaveSignals.savecCs*x$|jjD]\}}|jj||q WdS)N)r^rr)rcrrrcrcrdrestore# szSaveSignals.restoreN)r_r`rarbrdrrrcrcrcrdr s  rc@s(eZdZdZddZddZddZdS) FakePathz.Simple implementing of the path protocol. cCs ||_dS)N)r)rcrrcrcrdrd+ szFakePath.__init__cCsd|jdS)Nz )r)rcrcrcrd__repr__. szFakePath.__repr__cCs6t|jts$t|jtr,t|jtr,|jn|jSdS)N)rr BaseExceptionrru)rcrcrcrd __fspath__1 s    zFakePath.__fspath__N)r_r`rarbrdrrrcrcrcrdr( sr)T)F)F)Nii@i@i@ii) rrrrrrrrrrr)r"r r#r$r%)NF)F)r2F)N)Fi@ii)T)N)Nr)rJ)N(rbr_rmcollections.abc collections contextlibZdatetimerrRr7rrrlimportlib.utilrZlogging.handlersr]rrrorrrrrrrrnrr'rr}rrZ urllib.errorr\rfZ testresultrrBrDZmultiprocessing.processrzlibrSbz2Zlzmarrrr r r rsr contextmanagerrjr r~rr9r:rr5rrrrr(rrrrrrrprrrrrrrrrrrr r!rr"r#r$rDr rrrFrGrIr rErrZ SOCK_MAX_SIZEZ skipUnlessr __getformat__r6r8r/r0r1r?rrr@rBrurrr+Z FS_NONASCII characterfsdecodefsencode UnicodeErrorZTESTFN_UNICODEZ unicodedata normalizegetfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversionencodeUnicodeEncodeErrorrdecodeUnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIr/rr\r.r1rrrJrrrrZTEST_SUPPORT_DIRr6rrXrrrZrDr%rHobjectr`r}rQrRrabcMutableMappingrSrr&rrr'rr(r)r*rrrrrrrrrrrrrrrrTr[rrrZ_4GrrrXrr2r3r+rrr=r4rrr>rrAr"r#r%r*r+r4r-r/r9r,r<ZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr-r@rAZenvironment_alteredrMrNrOrLrKrPrVrUrZZskipIfZrequires_type_collectingr[r\r^r_rLrWrjrr.rrrtr7rr;r<rYrrrr]rrCrr^rrrcrcrcrds                    2   !  J   > &                 %      2 ' 5M         $ # 0           (        " #   "     :_"  ;'