a :j @s dZedkredddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZgdZdZej d kre d krd Zd Zd Z dZ!Gddde"Z#Gddde#Z$Gddde#Z%Gdddej&Z'ej(doddZ)ddZ*dpdddd Z+d!d"Z,d#d$Z-d%d&Z.d'd(Z/dqd)d*Z0d+d,Z1dZ2dZ3da4da5dZ6dZ7da8d-d.Z9d/d0Z:d1d2Z;d3d4Zd8d9Z?d:d;Z@dd?ZBne jCZ?e jDZ@d@d=ZAdAd?ZBdBdCZCdDdEZDdFdGZEdHdIZFdJdKZGdLdMZHdNdOZIdsdPdQZJdRdSZKdTdUZLdVdWZMdXdYZNdZd[ZOd\ZPd]ZQeReSTd^=d_d`ZUdtdbdcZVdudedfZWdvdhdiZXdwdkdlZYej =dmZZe[ednZ\ej d kr&e\r dondpZ]ndZ]e j^dmkrZdad?d@Zej(dAdBZdCdDZGdEdFdFZdGdHZGdIdJdJZGdKdLdLZeZGdMdNdNZeZejGdOdPdPZeZejGdQdRdRZeZdSdTZej j Z e dUv sDJdVdWZ GdXdYdYZ GdZd[d[Zdd\d]d^Zd_d`ZdadbZej(dcddZdedfZej(dgdhZeedidjdkZej(ddmdnZdS(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_vercheck_syntax_errorcheck_syntax_warningTransientResourcetime_outsocket_peer_resetioerror_peer_resetBasicTestRunner 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__skip_if_buggy_ucrt_strfptimeignore_warnings is_jython is_androidcheck_impl_detail unix_shellsetswitchintervalopen_urlresource temp_umask reap_childrenthreading_setupthreading_cleanup reap_threads start_threadscheck_warningscheck_no_resource_warningcheck_no_warningsEnvironmentVarGuardrun_with_locale swap_item swap_attrMatcher set_memlimitSuppressCrashReportsortdict run_with_tzPGOmissing_compiler_executablefd_count ALWAYS_EQNEVER_EQLARGESTSMALLESTLOOPBACK_TIMEOUTINTERNET_TIMEOUT SHORT_TIMEOUT LONG_TIMEOUTg@win32ZARM gN@g>@gr@c@seZdZdZdS)r z*Base class for regression test exceptions.N__name__ __module__ __qualname____doc__riri+/usr/lib/python3.9/test/support/__init__.pyr vsr c@seZdZdZdS)r z Test failed.Nrdriririrjr ysr c@seZdZdZdS)r zTest did not run any subtests.Nrdriririrjr |sr c@seZdZdZdS)r zTest skipped because it requested a disallowed resource. This is raised when a test calls requires() for a resource that has not be enabled. It is used to distinguish between expected and unexpected skips. Nrdriririrjr sr TccsL|rBt$tddtdVWdqH1s60YndVdS)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_warningsfilterwarningsDeprecationWarningrkririrj_ignore_deprecated_importss &rqcsfdd}|S)zDecorator to suppress deprecation warnings. Use of context managers to hide warnings make diffs more noisy and tools like 'git blame' less useful. cstfdd}|S)NcsPt4tjdd|g|Ri|WdS1sB0YdS)Nrkcategory)rlrm simplefilter)selfargskwargs)rstestrirjwrappers z3ignore_warnings..decorator..wrapper functoolswraps)rxryrrrxrj decoratorsz"ignore_warnings..decoratorri)rsr~rirrrjr>s r>Fri) required_onc Cst|pzt|WWdStyh}z,tjt|rFt t |WYd}~n d}~00Wdn1s~0YdS)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) rq importlibr ImportErrorsysplatform startswithtupleunittestSkipTeststr)name deprecatedrmsgririrjr s r cCsZ|tjvrt|tj|=ttjD]0}||ks>||dr$tj|||<tj|=q$dS)zyHelper function to save and remove a module from sys.modules Raise ImportError if the module can't be imported. .N)rmodules __import__listr)r orig_modulesmodnameririrj_save_and_remove_modules rcCs<d}ztj|||<Wnty,d}Yn0dtj|<|S)zHelper function to save and block a module in sys.modules Return True if the module was in sys.modules, False otherwise. TFNrrKeyError)rrZsavedririrj_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|SNrifririrjz$anticipate_failure..)rZexpectedFailure)Z conditionririrjr9sr9cCsF|dur d}tjtjtjt}|j|||d}|||S)zGeneric load_tests implementation for simple test packages. Most packages can implement load_tests using this function as follows: def load_tests(*args): return load_package_tests(os.path.dirname(__file__), *args) Nztest*)Z start_dirZ top_level_dirpattern)ospathdirname__file__ZdiscoverZaddTests)Zpkg_dirloaderZstandard_testsrZtop_dirZ package_testsririrjr:s  r:c Cst|i}g}t||zz@|D]}t||q$|D]}t||s8||q8t|}Wntytd}Yn0W|D]\} } | tj | <q|D] } tj | =qn0|D]\} } | tj | <q|D] } tj | =q0|WdS1s0YdS)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) rqrrappendrr ritemsrr) rZfreshZblockedrrZnames_to_removeZ fresh_nameZ blocked_nameZ fresh_moduleZ orig_namemoduleZname_to_removeririrjrs,           rcCs<zt||}Wn$ty2td||fYn0|SdS)z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %rN)getattrAttributeErrorrr)objrZ attributeririrjr5%s  r5cCs|adSr)_original_stdout)stdoutririrjr:srcCs tptjSr)rrrriririrjr>srcCs$z tj|=WntyYn0dSrr)rririrjrAs  rc Gsxz ||WStyr}zPtdkrHtd|jj|ftd|j|ft|tj||WYd}~Sd}~00dS)Nz%s: %sz re-run %s%r) OSErrorrprint __class__rerchmodstatS_IRWXU)rfuncrverrririrj _force_runGs rwincCs|||r|}ntj|\}}|p(d}d}|dkrjt|}|rJ|sVn||vsVdSt||d9}q.tjd|tdddS)NrMbP?g?rz)tests may fail, delete still pending for  stacklevel) rrsplitlistdirtimesleeprlwarnRuntimeWarning)rpathnamewaitallrrtimeoutLririrj_waitforRs    rcCsttj|dSr)rrrfilenameririrj_unlinkssrcCsttj|dSr)rrrmdirrririrj_rmdirvsrcs,fddt|ddtdd|dS)Nc st|tj|D]}tj||}zt|j}Wn>tyn}z&td||ft j dd}WYd}~n d}~00t |rt |ddt|tj|qt|tj|qdS)Nz-support.rmtree(): os.lstat(%r) failed with %sfilerTr)rrrrjoinlstatst_moderrr __stderr__rS_ISDIRrrr)rrfullnamemodeexc _rmtree_innerrirjrzs  _rmtree.._rmtree_innerTrcSst|tj|Sr)rrr)pririrjrrz_rmtree..)rrrirrj_rmtreeys rcCs\z ddl}WntyYn:0|t|d}|jj||t|}|rX|d|S|S)Nrr)ctypesrZcreate_unicode_bufferlenwindllZkernel32ZGetLongPathNameW)rrbufferZlengthririrj _longpaths    rcsNddl}z||WdSty*Yn0fdd|t|dS)Nrc s~t|tj|D]j}tj||}zt|j}WntyFd}Yn0t |rj|t|tj |qt|tj |qdSNr) rrrrrrrrrrrr)rrrrrrirjrs   r)shutilrrrr)rrrirrjrs   cCs|Srrirririrjrsc Cs(z t|Wnttfy"Yn0dSr)rFileNotFoundErrorNotADirectoryErrorrririrjrs rcCs$z t|WntyYn0dSr)rrrririrjrs  rcCs$z t|WntyYn0dSr)rrrririrjrs  rcCsBtj|}tjtj|}tj||d}t|||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) rutilcache_from_sourcerrrabspathrrename)sourceZpyc_fileZup_oneZ legacy_pycririrjmake_legacy_pycs   rcCsTt|tjD]@}tj||d}t|ddD]}ttjj||dq4qdS)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.pyr)rr) optimizationN) rrrrrrrrr)rrroptririrjrs   rc sttdrtjSd}tjdr0tr0d}nBtjdrddlddld}d}Gfdddj }j j }| }|s |}j}||||||}|sƈ t|j|@sd}ntjd krrdd lm} mm} m } dd lm} | | d } | dkr,d }nFGfddd| }|}| |}| |dksn| |dkrrd}|sz.ddlm}|}| |!|"Wn^t#y}zDt$|}t%|dkr|ddd}d&t'|j(|}WYd}~n d}~00|t_)| t_tjS)Nresultrz(gui is not available on Windows IoT Corerrcs.eZdZdjjfdjjfdjjfgZdS)z*_is_gui_available..USEROBJECTFLAGSZfInheritZ fReserveddwFlagsN)rerfrgwintypesZBOOLDWORD_fields_ri)rrirjUSEROBJECTFLAGSs   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)rerfrgrri)rrirjProcessSerialNumbersrz#cannot run without OS X gui process)Tk2z [...]zTk unavailable due to {}: {})*hasattr_is_gui_availablerrrrZ win32_is_iotrZctypes.wintypesrrZuser32ZGetProcessWindowStationZWinErrorrrZGetUserObjectInformationWZbyrefZsizeofboolrrrrZ ctypes.utilrZ LoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterrZwithdrawupdateZdestroy Exceptionrrformattyperereason)rZ UOI_FLAGSZ WSF_VISIBLErdllhZuofZneededresrrrrZ app_servicesrZpsnZpsn_prrooteZ err_stringri)rrrjrsr         rcCstdup|tvS)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)rresourceririrjr 1sr cCs<t|s |durd|}t||dkr8ts8ttjdS)z@Raise ResourceDenied if the specified resource is not available.Nz"Use of the %r resource not enabledgui)r r rr)r rririrjr!9s r!cCsddl}dtt|}|ddd}||krrzttt|d}Wnt yfd}Yqv0||k}nd}t ||d|d|S) zDecorator raising SkipTest if the OS is `sysname` and the version is less than `min_version`. For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if the FreeBSD version is less than 7.2. rNr-rFz version z or higher required, not ) rrmaprreleasersystemrint ValueErrorrskipIf)sysname min_versionrmin_version_txt version_txtversionskipririrj_requires_unix_versionBs      rcGs 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. ZFreeBSDrrririrjr"]sr"cGs 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. ZLinuxrrririrjr#fsr#csfdd}|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"tfdd}|_|S)Ncsztjdkrltd}zttt|d}Wnty@Yn,0|krldtt }t d||f|i|S)Nrrrz&Mac OS X %s or higher required, not %s) rrZmac_verrr rrrrrrr)rvkwrrr)rrrirjryws   z4requires_mac_ver..decorator..wrapper)r{r|rrryrrrjr~vsz#requires_mac_ver..decoratorri)rr~rirrjr$os r$cstfdd}|S)z5Skip the test on TLS certificate validation failures.c sTz|i|Wn<tyN}z$dt|vr8tdWYd}~n d}~00dS)NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)rrrr)rvrwrrrirjdecs   z&system_must_validate_cert..decrz)rrrirrjsystem_must_validate_certsr i@iZdoubleZIEEEztest requires IEEE 754 doubles requires zlibcCs0z ddl}Wnty"d}Yn0t||Sr)zlibrr skipUnless)rr"ririrjr8s    r8 requires gzipcCs0z ddl}Wnty"d}Yn0t||Sr)gziprrr#)rr%ririrjr/s    r/ requires bz2cCs0z ddl}Wnty"d}Yn0t||Sr)bz2rrr#)rr'ririrjr0s    r0 requires lzmacCs0z ddl}Wnty"d}Yn0t||Sr)lzmarrr#)rr)ririrjr1s    r1ZjavaZgetandroidapilevelz/system/bin/shz/bin/shz$testz@testz {}_{}_tmpzhttp://www.pythontest.netr) æuİuŁuφuКuאu،uتuก u€u -àòɘŁğrZNFDntru-共Ł♡ͣztWARNING: The filename %r CAN be encoded by the filesystem encoding (%s). Unicode filename tests may not be effectives-surrogateescape)swr-sssc csddl}d}|dur.|}d}tj|}nZzt|d}WnFty}z.|sVtjd|d|t ddWYd}~n d}~00|rt }z"|VW|r|t krt |n|r|t krt |0dS) 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. rNFTz5tests may fail, unable to create temporary directory : r) tempfilemkdtemprrrealpathmkdirrrlrrgetpidr)rquietr1Z dir_createdrpidririrjtemp_diris6  r8c cst}zttj|WnFtyd}z.|s4tjd|d|tddWYd}~n d}~00ztVWt|n t|0dS)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. zBtests may fail, unable to change the current working directory to r/r0rN) rgetcwdchdirrr3rrlrr)rr6Z saved_dirrririrj change_cwds  r;tempcwdc csbt||dB}t||d}|VWdn1s60YWdn1sT0YdS)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. )rr6)r6N)r8r;)rr6Z temp_pathZcwd_dirririrjrsrumaskc cs0t|}zdVWt|n t|0dS)z8Context manager that temporarily sets the process umask.N)rr=)r=ZoldmaskririrjrEs rEdatacCsbtj|r|S|dur&tj||}tgtj}|D]&}tj||}tj|r6|Sq6|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_DIRrexists)rZsubdirrdnfnririrjrs  rcCs(t|tjtjBtjB}t|dS)z>Create an empty file. If the file already exists, truncate it.N)ropenO_WRONLYO_CREATO_TRUNCclose)rfdririrjrsrcCs,t|}dd|D}d|}d|S)z%Like repr(dict), but in sorted order.cSsg|] }d|qS)z%r: %rri).0Zpairririrj rzsortdict..z, z{%s})sortedrr)dictrZ reprpairsZ withcommasririrjrUs  rUcCs<ttd}z|W|ttS|tt0dS)z` Create an invalid file descriptor by opening and closing a file and return its fd. wbN)rDrfilenorHrrririrj make_bad_fds rPlinenooffsetcCs|t|}t|ddWdn1s.0Y|j}||j|dur`||j|||j|dur||j|dS)Nz exec)ZassertRaisesRegex SyntaxErrorcompileZ exceptionassertIsNotNonerR assertEqualrS)testcase statementerrtextrRrScmrririrjr%s*  r%cCstjdd(}tdtt|ddWdn1s:0Y|t|d||\}|t|j t|j |r| t |j |||j d||j|dur||j|tjdd.}tdtt|||||dWdn1s0Y||gdS) NTrecordalwaysz rTrerrorrQ)rlrmrt SyntaxWarningrVrXr assertTrue issubclassrsZ assertRegexrmessagerrWrRr%)rYrZr[rRrSwarnsrririrjr&s$ *  $r&c sddl}ddl}z ddl}Wnty2d}Yn0dd|j|ddd}tj t |}fdd}tj |r||}|dur|St |tdtrtd |td |j} |r| jd | j|td }|r |jd dkr |j|d}z\t|d4} |} | r<| | |} q Wdn1sR0YW|n |0||}|dur|Std|dS)Nrcheckr/csDt|gRi}dur"|S|r8|d|S|dSr)rDseekrH)rCrrvrfrrirjcheck_valid_file0s z*open_urlresource..check_valid_fileZurlfetchz fetching %s ...r)zAccept-Encodingr%rzContent-Encodingr%)ZfileobjrNzinvalid resource %r)Zurllib.requestZ urllib.parser%rpopparseZurlparserrrr TEST_DATA_DIRrArr!rrrZrequestZ build_openerZ addheadersrrDr_ZheadersgetZGzipFilereadwriterHr ) ZurlrvrZurllibr%rrCrkrZopeneroutsrirjrjrD#sD          . rDc@s4eZdZdZddZddZeddZdd Zd S) WarningsRecorderzyConvenience wrapper for the warnings list returned on entry to the warnings.catch_warnings() context manager. cCs||_d|_dSr _warnings_last)ruZ warnings_listririrj__init__]szWarningsRecorder.__init__cCsDt|j|jkr t|jd|S|tjjvr0dStd||fdS)Nrhz%r has no attribute %r)rrwrxrrlWarningMessage_WARNING_DETAILSr)ruattrririrj __getattr__as  zWarningsRecorder.__getattr__cCs|j|jdSrrvruririrjrlhszWarningsRecorder.warningscCst|j|_dSr)rrwrxr~ririrjresetlszWarningsRecorder.resetN) rerfrgrhryr}propertyrlrriririrjruYs  ruc cstd}|jd}|r"|tjdd*}tjddt |VWdn1s^0Yt |}g}|D]j\}}d} |ddD]8}|j } t |t| t jrt| j|rd} ||q| sx|sx|||jfqx|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__Tr]rlr_NFzunhandled warning %srz)filter (%r, %s) did not catch any warning)r _getframe f_globalsrpclearrlrmrrtrurrdrematchrIrcrremoverreAssertionError) filtersr6frameregistrywZreraiseZmissingrcatseenZwarningririrj_filterwarningsps4  (   rcOs.|d}|s$dtff}|dur$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) r6rNT)rpWarningr)rrwr6ririrjrKs   rKccs\tjdd0}tjd||ddV|r.tWdn1sB0Y||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(). Tr]r_)rdrsN)rlrmrn gc_collectrX)rYrdrsforce_gcreririrjrMs$rMccs8t|tdddVWdn1s*0YdS)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)rsrN)rMResourceWarning)rYririrjrLsrLc@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 cGsJtj|_|D]4}|tjvrtj|}|j|kr|n|r<|0dSr)rZ isenableddisableenable)rZhave_gcririrj disable_gcs rcCs6tdp d}d}|D]}|dr|}q|dvS)z,Find if Python was built with optimizations.Z PY_CFLAGSrz-O)rz-O0z-Og) sysconfigget_config_varrr)ZcflagsZ final_optrririrjpython_is_optimizeds   rZnPZ0nZ getobjectsZ2PZ0PncCstt|tSr)structcalcsize_header_alignZfmtririrj calcobjsizesrcCstt|tSr)rr_vheaderrrririrj calcvobjsizesri@icCspddl}t|}t|tkr(|jt@sBt|tkrLt|jt@rL||j7}dt|||f}||||dS)Nrz&wrong size for %s: got %d, expected %d) _testinternalcapir getsizeofr __flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADrX)rxosizerrrririrj check_sizeofs     rcsfdd}|S)Ncs$fdd}j|_j|_|S)Nc sz ddl}t|}||}Wn&ty4YnBd}}Yn00D](}z|||WqvWqLYqL0qLz&|i|W|r|r|||Sn|r|r|||0dSr)localer setlocaler)rvkwdsrrsZ orig_localeZloc)catstrrlocalesrirjinners.     z1run_with_locale..decorator..innerrerhrrrrrrjr~sz"run_with_locale..decoratorri)rrr~rirrjrOsrOcsfdd}|S)Ncs"fdd}j|_j|_|S)Nc sz tj}Wnty&tdYn0dtjvr>tjd}nd}tjd<|zH|i|W|durttjd=n |tjd<tS|tjd<tn&|durtjd=n |tjd<t0dS)Nztzset requiredZTZ)rtzsetrrrrr)rvrrZorig_tz)rtzrirjrs0           z-run_with_tz..decorator..innerrrrrrjr~szrun_with_tz..decoratorri)rr~rirrjrVs rVircCsdttdtd}td|tjtjB}|dur>td|ftt| d|| d }|a |t krrt }|t dkrtd|f|adS)Nr)rmgtz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rrr0z$Memory limit %r too low to be useful)_1M_1Grr IGNORECASEVERBOSErrfloatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitZsizesrZmemlimitririrjrS(s" $ rSc@s(eZdZdZddZddZddZdS) _MemoryWatchdogz`An object which periodically watches the process' memory consumption and prints it out. cCsdjtd|_d|_dS)Nz/proc/{pid}/statm)r7F)rrr5procfilestartedr~ririrjryBsz_MemoryWatchdog.__init__c Cszt|jd}WnBtyR}z*td|ttj WYd}~dSd}~00|2t d}t j tj |g|t jd|_Wdn1s0Yd|_dS)Nrz!/proc not available for stats: {}zmemory_watchdog.py)rrT)rDrrrlrrrrrflushr subprocessPopen executableZDEVNULL mem_watchdogr)rurrZwatchdog_scriptririrjstartFs   &z_MemoryWatchdog.startcCs|jr|j|jdSr)rrZ terminatewaitr~ririrjstopVs z_MemoryWatchdog.stopN)rerfrgrhryrrriririrjr=srcsfdd}|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)Ncsj}j}tsd}n|}ts"sDt||krDtd||dtrztrzttdj||ddt}| nd}z||W|r| Sn|r| 0dS)Ni'not enough memory: %.1fG minimum needed@z* ... expected peak memory use: {peak:.1f}G)Zpeak) rmemuserrrrrrrrr)rurrmaxsizeZwatchdog)dry_runrryrirjryjs<     z.bigmemtest..decorator..wrapper)rrrrrrrryrjr~iszbigmemtest..decoratorri)rrrr~rirrjr2\s !r2csfdd}|S)z0Decorator for tests that fill the address space.csDttkr8tdkr$tdkr$tdq@tdtdn|SdS)Nllz-not enough memory: try a 32-bit build insteadrr)rrrrr~rrirjrysz!bigaddrspacetest..wrapperrirrirrjr3s r3c@seZdZddZdS)r+cCst}|||Sr)rZ TestResult)rurxrririrjrunszBasicTestRunner.runN)rerfrgrriririrjr+sr+cCs|Srri)rririrj_idsrcCs:|dkrtsttjSt|r&tStd|SdS)Nr zresource {0!r} is not enabled)rrrrr rrr ririrjrequires_resources  rcCstdd|S)z9 Decorator for tests only applicable on CPython. T)cpython) impl_detailr}ririrjr4sr4cKsZtfi|rtS|durPt|\}}|r0d}nd}t|}|d|}t|S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or ) rAr _parse_guardsrLrrrrr)rguardsZ guardnamesdefaultririrjr s  r cCsH|sddidfSt|d}t||gt|ks>J|| fS)NrTFr)rvaluesr)r Zis_trueririrjr s  r cKs t|\}}|t|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 rprZpython_implementationr)r r ririrjrAs rAcs,ttdsStfdd}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.gettracec s>t}z$td|i|Wt|St|0dSr)rrsettrace)rvrwZoriginal_tracerrirjrys  zno_tracing..wrapperN)rrr{r|rrirrj no_tracings  rcCs 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. )rr4r}ririrj refcount_testsrcCsNg}|jD]8}t|tjr0t||||q ||r ||q ||_dS)z>Recursively filter test cases in a suite based on a predicate.N)Z_tests isinstancer TestSuite _filter_suiter)suiteZpredZnewtestsrxririrjrs     rcCsttjttdud}||}tdur4t||jsD|j sDt | st |j dkrp|jsp|j dd}n4t |jdkr|j s|jdd}nd}ts|d7}t|dS)z2Run tests from a unittest.TestSuite-derived class.N) verbosityZcapture_outputrrzmultiple errors occurredz!; run in verbose mode for details)rrrrjunit_xml_listrrZget_xml_elementZtestsRunZskippedr Z wasSuccessfulrerrorsZfailuresr )rZrunnerrrririrj _run_suites"   rcCstdur dSt|SdSNT)_match_test_funcidr}ririrj match_testsrcCsd|votd| S)Nrz[?*\[\]])rsearch)rririrj_is_full_match_test%srcs~|dur d}|durd}d|tkr4t|\}|tkrHt|\}t|at|adushdurzfdd}|adS)Nrics*d}d}r|}r |}|o(| S)NTFri)test_idZacceptrkZ accept_funcZ ignore_funcrirjmatch_functionDsz'set_match_tests..match_function)_accept_test_patterns_compile_match_function_ignore_test_patternsrr)Zaccept_patternsZignore_patternsr"rir!rjset_match_tests/s   r&cs^|sd}d}nHttt|r(t|j}n.dttj|}t |j fdd}|}||fS)Nri|cs$|r dStt|dSdS)NTr)anyr r)r Z regex_matchrirjmatch_test_regex_sz1_compile_match_function..match_test_regex) allr rr __contains__rfnmatch translaterrVr)ZpatternsrZregexr*rir)rjr$Ps   r$cGstjtjf}t}|D]`}t|trR|tjvrH|ttj|qxt dqt||rh||q|t |qt |t t |dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesN)rrZTestCaserrrrZaddTestZ findTestCasesrZ makeSuiterrr)classesZ valid_typesrclsririrjr,os       r,cCsdS)z,Just used to check if docstrings are enabledNririririrj_check_docstringssr1ZWITH_DOC_STRINGSztest requires docstringscCs`ddl}|durt}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 rre)rrr2r3rrririrjr-sr-cCs(|D]}td|tjddqdS)Nz Warning -- T)rr) splitlinesrrr)rlineririrj print_warnings r6cCs tjfSr)rrrriririrj modules_setupsr7cCs:ddtjD}tjtj|tj|dS)NcSs"g|]\}}|dr||fqS)z encodings.)r)rJrrririrjrKs  z#modules_cleanup..)rrrrr)Z oldmodulesZ encodingsririrjmodules_cleanups  r8cCsttjfSr)_thread_count threading _danglingrriririrjrGsrGc Gsd}t|D]}ttjf}||kr*q|sda|d}td|d|dd|ddt|d|D]}td |qnd}d}t d t q dS) NdTrz&threading_cleanup() failed to cleanup rz threads (count: z , dangling: )zDangling thread: {Gz?) ranger9r:r;r<environment_alteredr6rrrr)Zoriginal_valuesZ _MAX_COUNTcountr Zdangling_threadsthreadririrjrHs*   rHcstfdd}|S)zUse this function when threads are being used. This will ensure that the threads are cleaned up even when the test fails. cs(t}z|Wt|St|0dSr)rGrH)rvkeyrrirjr~s zreap_threads..decoratorrz)rr~rirrjrIsrIccs|dur t}t}zdVWt}||}t}||kr@qt|krt|}d||d|dd|d|d }t|tdtq.n~t}||}t}||krqt|krt|}d||d|dd|d|d }t|tdtq0dS) 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 .1fz seconds (count: z , old count: r>r?)r`r9r:r monotonicrrr)rZ old_countZ start_timeZdeadlinerBdtrririrjwait_threads_exit sN        rHcCs8|dur t}|||r4d|dd}t|dS)zcJoin a thread. Raise an AssertionError if the thread is still alive after timeout seconds. Nzfailed to join the thread in rE seconds)r`ris_aliver)rCrrririrj join_thread1s  rKcCshttdrttdsdSztdtj\}}WntyDYqdYn0|dkrPqdtd|daqdS)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. waitpidWNOHANGNrhrz%reap_children() reaped child process T)rrrLrMrr6rA)r7statusririrjrF=s   rFccsLddl}t|}g}z.z7Unable to join %d threads during a period of %d minutescSsg|]}|r|qSrirQrRririrjrKyrzUnable to join %d threads) faulthandlerrrrrrrrrFr@rmaxZdump_tracebackrrr)ZthreadsZunlockrSrrZendtimeZ starttimerririrjrJYsz        rJc cst||rHt||}t|||z|VWt|||qt|||0nBt|||zdVWt||rt||nt||rt||0dS)aTemporary swap out an attribute with a new object. Usage: with swap_attr(obj, "attr", 5): ... This will set obj.attr to 5 for the duration of the with: block, restoring the old value at the end of the block. If `attr` doesn't exist on `obj`, it will be created and then deleted at the end of the block. The old value (or None if it doesn't exist) will be assigned to the target of the "as" clause, if there is one. N)rrrdelattr)rr|new_valreal_valririrjrQ~s      rQc csn||vr8||}|||<z|VW|||<qj|||<0n2|||<zdVW||vrj||=n||vrh||=0dS)aTemporary swap out an item with a new object. Usage: with swap_item(obj, "item", 5): ... This will set obj["item"] to 5 for the duration of the with: block, restoring the old value at the end of the block. If `item` doesn't exist on `obj`, it will be created and then deleted at the end of the block. The old value (or None if it doesn't exist) will be assigned to the target of the "as" clause, if there is one. Nri)ritemrVrWririrjrPsrPcCstS)znReturn a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.)rZ_args_from_interpreter_flagsriririrjargs_from_interpreter_flagssrYcCstS)zgReturn a list of command-line arguments reproducing the current optimization settings in sys.flags.)rZ"_optim_args_from_interpreter_flagsriririrj!optim_args_from_interpreter_flagssrZc@s eZdZdZddZddZdS)rR)rrdcKs:d}|D],}||}||}||||sd}q6q|S)a. Try to match a single dict with the supplied arguments. Keys whose values are strings and which are in self._partial_matches will be checked for partial (i.e. substring) matches. You can extend this scheme to (for example) do regular expression matching, etc. TF)rp match_value)rudrwrrrdvririrjmatchess zMatcher.matchescCsHt|t|krd}n.t|tus,||jvr6||k}n||dk}|S)zT Try to match a single stored value (dv) with a supplied value (v). Fr)rr_partial_matchesfind)rurr]rrririrjr[s  zMatcher.match_valueN)rerfrgr_r^r[riririrjrRsrRc CsXtdur tStd}ztt|d}WntttfyDd}Yn 0t||a|S)NrTF) _can_symlinkrrsymlinkrNotImplementedErrorrr)Z symlink_pathcanririrjrs   rcCs t}d}|r|St||S)z8Skip decorator for tests that require functional symlinkz*Requires functional symlink implementation)rrrrxokrririrjr.sr.cCsXddl}tdurBtjdkr>|ddkr>tjdkr>dandatrTt d |S|S) a- Skip decorator for tests that use buggy strptime/strftime If the UCRT bugs are present time.localtime().tm_zone will be an empty string, otherwise we assume the UCRT bugs are fixed See bpo-37552 [Windows] strptime/strftime return invalid results with UCRT version 17763.615 rNrbrcp65001rTFz!buggy MSVC UCRT strptime/strftime) r _buggy_ucrtrrZgetdefaultlocaler localtimetm_zonerr)rxrririrjr= s   r=c@sheZdZdZdddZddZejdkr0ddZd d Zd d Z d dZ ddddZ ddddZ dS) PythonSymlinkz3Creates a symlink for the current Python executableNcCs@|ptjt|_g|_tjtj|_ g|_ d|_ | dSr) rrrrlink_linkedr3rrreal _also_link_env_platform_specific)rurlririrjry s zPythonSymlink.__init__cCsdSrrir~ririrjrq! sz PythonSymlink._platform_specificrbc Csddl}tj|jr0tj|js0|d|_|tj}tj |}tj |j }|j |tj |tj|fttj t|dD]&}|j |tj |tj|fqddtjD|_tj |j|jd<tdrtj tj|jd<dS)Nrzvcruntime*.dllcSsi|]}|t|qSri)upperrgetenv)rJrririrj : rz4PythonSymlink._platform_specific..Z PYTHONHOMETZ PYTHONPATH)_winapirrlexistsrnrAZGetModuleFileNamerZ dllhandlerrlrorrbasenameglobescaperrprZis_python_buildr)rururZsrc_dirZdest_dirZruntimeririrjrq% s&    cCsJt|j|j|j|j|jD] \}}t|||j|q$|Sr)rrbrnrlrmrro)rurnrlririrjr? s  zPythonSymlink.__enter__c CsX|jD]L}zt|WqtyP}z trtt|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&|]}|dr|dr|VqdS)___N)rendswith)rJrririrj sz&detect_api_mismatch..)rr)Zref_apiZ other_apirkZ missing_itemsririrjr; s  r;cCs|dur|jf}nt|tr"|f}t|}t|D]R}|ds2||vrJq2t||}t|dd|vszt|ds2t|tj s2| |q2| |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) Nrrf) rerrrrrrrtypes ModuleTypeaddZassertCountEqual__all__)Z test_caserZname_of_moduleZextraZ blacklistZexpectedrrririrjr< s )      r<cCsz ddl}Wnty YdS0||j|jB|jB|jBt|dr|j|j |j fD]2}|r| ||j | ||jqZ| |dqZdS)NrCrtSetReportMode)msvcrtr SetErrorModeZSEM_FAILCRITICALERRORSZSEM_NOALIGNMENTFAULTEXCEPTSEM_NOGPFAULTERRORBOXZSEM_NOOPENFILEERRORBOXrCRT_WARN CRT_ERROR CRT_ASSERTrCRTDBG_MODE_FILECrtSetReportFileCRTDBG_FILE_STDERR)rrrririrjsuppress_msvcrt_asserts s"   rc@s(eZdZdZdZdZddZddZdS)rTzTry 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 Cstjdrz ddl}Wnty,YdS0||j|_||j|jBt|dri|_ |j |j |j fD].}| ||j}|||j}||f|j |<qnnzddl}||_Wntyd|_Yn0|jdur$z2|j|jj|_|j|jjd|jdfWnttfy"Yn0tjdkrgd}tj|tjtjd}||d}Wdn1st0Y|d krtd d d d |S)zOn Windows, disable Windows Error Reporting dialogs using SetErrorMode() and CrtSetReportMode(). On UNIX, try to save the previous core file size limit, then set soft limit to 0. rrNrrr)z/usr/bin/defaultsrqzcom.apple.CrashReporterZ DialogType)rrs developerz:this test triggers the Crash Reporter, that is intentionalrT)endr)rrrrrrr old_valuer old_modesrrrrrrrr Z getrlimit RLIMIT_CORE setrlimitrrrrr~rstripr) rur report_typeold_modeold_filer rprocrririrjr s\           ,zSuppressCrashReport.__enter__c Gs|jdurdStjdrfddl}||j|jr|jD]$\}\}}|||| ||q>n:|j durz|j |j j |jWnt tfyYn0dS)zARestore Windows ErrorMode or core file behavior to initial value.Nrr)rrrrrrrrrrr rrrr)rurrrrrririrjrI s     zSuppressCrashReport.__exit__)rerfrgrhrrrrriririrjrT s CrTc sptdzjWn"ttfy>tdYn0dfdd}||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 tdSr)rrUriZ attr_is_local attr_nameobject_to_patchrrirjcleanupt szpatch..cleanup)r__dict__rrZ addCleanupr)Z test_instancerrZ new_valuerrirrjpatch^ s  rcCsDz ddl}WntyYn0|r2tdddl}||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) tracemallocr is_tracingrr _testcapirun_in_subinterp)coderrririrjr s   rcsHGfddd|}d||||ttt|dS)NcseZdZfddZdS)z%check_free_after_iterating..Acs(dz tWnty"Yn0dSr)next StopIterationr~Zdoneitrirj__del__ s   z-check_free_after_iterating..A.__del__N)rerfrgrrirrirjA srF)Z assertRaisesrrrrb)rxrr0rvrrirrjcheck_free_after_iterating s   rcCsddlm}m}m}m}|}|||jdkrXz |Wn|j yVYdS0|j D]Z}|rp||vrpq^t ||}|r|dusJd|n|sq^| |ddur^|dSq^dS)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) ccompilerrspawnrZmsvcNz%the '%s' executable is not configured) Z distutilsrrrrZ new_compilerZcustomize_compilerZ compiler_typeZ initializeZDistutilsPlatformErrorZ executablesrZfind_executable)Z cmd_namesrrrrZcompilerrrririrjrX s(        rXcCs@d}tr6||kr6tdur.tddgdkatr6|}t|S)Ngh㈵>Zgetpropzro.kernel.qemu1)r@_is_android_emulatorrZ check_outputrrrC)ZintervalZminimum_intervalririrjrC s rCc csXddl}tj}|}z$|dVW|rT|j|ddn|rR|j|dd0dS)NrT)rZ all_threads)rSrrrO is_enabledrr)rSrIrririrjdisable_faulthandler s rc Cstjdr8ztd}t|dWSty6Yn0d}ttdrhztd}Wnt yfYn0d}tjdkrzd dl }|j Wnt t fyYn,0i}|j|j|jfD]}| |d ||<qzd }t|D]\}zt|}Wn6t y }z|jtjkr WYd}~qd}~00t||d7}qW|dur|j|j|jfD]}| |||qRn4|dur|j|j|jfD]}| |||q0|S) z/Count the number of open file descriptors. )linuxZfreebsdz /proc/self/fdrsysconf SC_OPEN_MAXNrbr)rrrrrrrrrrrrrrrrrr@duprZEBADFrH) namesZMAXFDrrrrBrIZfd2rririrjrY s`            rYc@s(eZdZdZddZddZddZdS) SaveSignalsz Save and restore signal handlers. This class is only able to save/restore signal handlers registered by the Python signal module: see bpo-13285 for "external" signal handlers. c Cs^ddl}||_||_dD]6}zt||}WntyDYqYn0|j|qi|_dS)Nr)SIGKILLSIGSTOP)signal valid_signalssignalsrrrhandlers)rurZsignamesignumririrjry+ s   zSaveSignals.__init__cCs0|jD]$}|j|}|dur q||j|<qdSr)rr getsignalrrurZhandlerririrjsave8 s   zSaveSignals.savecCs&|jD]\}}|j||q dSr)rrrrririrjrestoreD szSaveSignals.restoreN)rerfrgrhryrrriririrjr" s  rcCsddl}|jSr)rZ WITH_PYMALLOC)rririrj with_pymallocI src@s(eZdZdZddZddZddZdS) FakePathz.Simple implementing of the path protocol. cCs ||_dSrr)rurririrjryQ szFakePath.__init__cCsd|jdS)Nz rr~ririrj__repr__T szFakePath.__repr__cCs6t|jts$t|jtr,t|jtr,|jn|jSdSr)rr BaseExceptionrrcr~ririrj __fspath__W s   zFakePath.__fspath__N)rerfrgrhryrrriririrjrN src@s eZdZdZddZddZdS) _ALWAYS_EQz+ Object that is equal to anything. cCsdSrriruotherririrj__eq__d sz_ALWAYS_EQ.__eq__cCsdSNFrirririrj__ne__f sz_ALWAYS_EQ.__ne__N)rerfrgrhrrriririrjr` src@s(eZdZdZddZddZddZdS) _NEVER_EQz/ Object that is not equal to anything. cCsdSrrirririrjro sz_NEVER_EQ.__eq__cCsdSrrirririrjrq sz_NEVER_EQ.__ne__cCsdS)Nrrir~ririrj__hash__s sz_NEVER_EQ.__hash__N)rerfrgrhrrrriririrjrk src@s eZdZdZddZddZdS)_LARGESTz? Object that is greater than anything (except itself). cCs t|tSr)rrrririrjr} sz_LARGEST.__eq__cCsdSrrirririrj__lt__ sz_LARGEST.__lt__N)rerfrgrhrrriririrjrx src@s eZdZdZddZddZdS) _SMALLESTz< Object that is less than anything (except itself). cCs t|tSr)rrrririrjr sz_SMALLEST.__eq__cCsdSrrirririrj__gt__ sz_SMALLEST.__gt__N)rerfrgrhrrriririrjr srcCsddl}|jjS)zDReturn the global event loop policy if one is set, else return None.rN)Zasyncio.eventsZeventsZ_event_loop_policy)Zasyncioririrjmaybe_get_event_loop_policy sr) @c Cs||}}ddl}|}|d}t|d|_||}|d||}||} || } || } ||d|d||| d| } t| t| fWdS1s0YdS)Nrrr)decimalZ localcontext bit_lengthrTZprecZDecimalrZsqrt) ZnbinsZnballsrrrctxbitsrBZp1emptyZ meanemptyZoccupiedZ collisionsvarririrjcollision_stats s     (rc@s0eZdZdZddZddZddZdd Zd S) catch_unraisable_exceptiona Context manager catching unraisable exception using sys.unraisablehook. Storing the exception value (cm.unraisable.exc_value) creates a reference cycle. The reference cycle is broken explicitly when the context manager exits. Storing the object (cm.unraisable.object) can resurrect it if it is set to an object which is being finalized. Exiting the context manager clears the stored object. Usage: with support.catch_unraisable_exception() as cm: # code creating an "unraisable exception" ... # check the unraisable exception: use cm.unraisable ... # cm.unraisable attribute no longer exists at this point # (to break a reference cycle) cCsd|_d|_dSr) unraisable _old_hookr~ririrjry sz#catch_unraisable_exception.__init__cCs ||_dSr)r)rurririrj_hook sz catch_unraisable_exception._hookcCstj|_|jt_|Sr)runraisablehookrrr~ririrjr sz$catch_unraisable_exception.__enter__cGs|jt_|`dSr)rrrrruexc_inforirirjr sz#catch_unraisable_exception.__exit__Nrerfrgrhryrrrriririrjr s rc@s0eZdZdZddZddZddZdd Zd S) catch_threading_exceptiona Context manager catching threading.Thread exception using threading.excepthook. Attributes set when an exception is catched: * exc_type * exc_value * exc_traceback * thread See threading.excepthook() documentation for these attributes. These attributes are deleted at the context manager exit. Usage: with support.catch_threading_exception() as cm: # code spawning a thread which raises an exception ... # check the thread exception, use cm attributes: # exc_type, exc_value, exc_traceback, thread ... # exc_type, exc_value, exc_traceback, thread attributes of cm no longer # exists at this point # (to avoid reference cycles) cCs"d|_d|_d|_d|_d|_dSr)r{r| exc_tracebackrCrr~ririrjry s z"catch_threading_exception.__init__cCs$|j|_|j|_|j|_|j|_dSr)r{r|rrC)rurvririrjr szcatch_threading_exception._hookcCstj|_|jt_|Sr)r; excepthookrrr~ririrjr sz#catch_threading_exception.__enter__cGs|jt_|`|`|`|`dSr)rr;rr{r|rrCrririrjr s z"catch_threading_exception.__exit__Nrriririrjr s rrlc Cs&tjdkrddl}|durt}t}d}d}t|tj\}}|dkrJqt|} | tkrzt||j t|dWnt yYn0t d|d| dd t |d |}t |q.nt|d\}}t|} | |krt d|d | d |d ||kr"t d|d|dS)a Wait until process pid completes and check that the process exit code is exitcode. Raise an AssertionError if the process exit code is not equal to exitcode. If the process runs longer than timeout seconds (SHORT_TIMEOUT by default), kill the process (if signal.SIGKILL is available) and raise an AssertionError. The timeout feature is not available on Windows. r,rNrrzprocess z is still running after rErIrz exited with code z, but exit code z is expectedzpid z != pid )rrrr`rrFrLrMkillrrrminrwaitstatus_to_exitcode) r7ZexitcoderrZt0rZ max_sleepZpid2rNrGZ exitcode2ririrj wait_process$ s<         rcCs ddl}|}|dddkS)NrconfigZ_use_peg_parser)rZ get_configs)rrririrjuse_old_parserY srcCstt |Sr)rrr)rririrjskip_if_new_parser_ src cs<tjdd}zdVW|tjdd<n|tjdd<0dSr)rlr)Z old_filtersririrjsave_restore_warnings_filtersc sr c Csdtdtd}tjdkr`z|jddWn4ty^}ztd|WYd}~n d}~00dS)z Skip tests if the multiprocessing.synchronize module is missing, if there is no available semaphore implementation, or if creating a lock raises an OSError (on Linux only). Z_multiprocessingzmultiprocessing.synchronizerN)rz broken multiprocessing SemLock: )r rrZLockrrr)Z synchronizerririrj*skip_if_broken_multiprocessing_synchronizel s r c cs8t}zt|dVWt|n t|0dS)z>Temporarily change the integer string conversion length limit.N)rget_int_max_str_digitsset_int_max_str_digits)Z max_digitsZcurrentririrjadjust_int_max_str_digits s  r )returncCsddtddDdgS)zReturns a list of C0 control characters as strings. C0 control characters defined as the byte range 0x00-0x1F, and 0x7F. cSsg|] }t|qSri)chr)rJrririrjrK rz)control_characters_c0..rr)r@riririrjcontrol_characters_c0 srKc cs8t}zt|dVWt|n t|0dS)a4Set a lower limit for tests that interact with infinite recursions (e.g test_ast.ASTHelpers_Test.test_recursion_direct) since on some debug windows builds, due to not enough functions being inlined the stack size might not handle the default recursion limit (1000). See bpo-11105 for details.N)rgetrecursionlimitsetrecursionlimit)Z max_depthZoriginal_depthririrjinfinite_recursion s  r)T)F)ririF)F)N)r!)r$)r&)r()NF)F)r<F)N)r)r)F)T)N)NN)Nr)N)N)N)Nriri)F)ri)r(rhrercollections.abc collections contextlibrr-r{rxrimportlib.utilrrrrrrrrr9r;rrrrlZ testresultrrr^machiner_r`rarr r r rr contextmanagerrqr>r rrr9r:rr5rrrrrrrrrrrrrrrrrrrrrrrr r!rr"r#r$r rZ SOCK_MAX_SIZEr#r __getformat__r6r8r/r0r1r?rr@rBrZ TESTFN_ASCIIrr5Z TEST_HTTP_URLZ FS_NONASCII characterfsdecodefsencode UnicodeErrorZTESTFN_UNICODE unicodedataZ normalizegetfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversionencodeUnicodeEncodeErrorrdecodeUnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIrr9rrWrr8r;rrErrrrZTEST_SUPPORT_DIRr@rrorrrUrPr%r&rDobjectrurrKrrMrLrabcMutableMappingrNrr'rZ ETIMEDOUTr(Z ECONNRESETr)r*rrrrrrrrrrrrrrrrOrVrrrZ_4GrrrSrr2r3r+rrr4r r rArrrrrr#r%rrr&r$r,r1rZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr-r6r7r8rArGrHrIrHrKrFrJrQrPrYrZrRrarr.rhr=rkrrr7rrr;r<rrTrrrrXrrCrrYrrrrrZrr[total_orderingrr\rr]r hash_infowidthZ NHASHBITSrrrrrrr r r rrrrriririrjs 8  2   !  L           !        '      6 '   5       $# 0      !         $ $  "   N    ;a "   ;'     ",95