o *g@sdZedkr edddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlmZzddlmZWn eyOdZYnwgdZd Zejd krcd ejvrcd Znejd krjd ZdZdZdZGdddeZGdddeZGdddeZGdddeZGddde jZddZ ddZ!dd Z"dZ#dZ$da%da&dZ'd!Z(da)d"d#Z*d$d%Z+d&d'Z,d(d)Z-d*d+Z.dd,d-Z/d.d/Z0d0d1Z1d2d3Z2d4d5Z3d!d!d!d6d7d8Z4dd!d!d!d6d9d:Z5d;d<Z6d=Z7d>Z8e 9e:;d?d dFdGZ?d dIdJZ@d dLdMZAe 9edNZBej@gr@c@eZdZdZdS)r z*Base class for regression test exceptions.N__name__ __module__ __qualname____doc__rPrP,/usr/lib/python3.10/test/support/__init__.pyr gr c@rJ)r Test failed.NrKrPrPrPrQr jrRr cs(eZdZdZfddZddZZS)TestFailedWithDetailsrScs&||_||_||_t|||dSN)msgerrorsfailuressuper__init__)selfrVrWrX __class__rPrQrZoszTestFailedWithDetails.__init__cCs|jSrU)rVr[rPrPrQ__str__uszTestFailedWithDetails.__str__)rLrMrNrOrZr_ __classcell__rPrPr\rQrTms rTc@rJ)r zTest did not run any subtests.NrKrPrPrPrQr xrRr c@rJ)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. NrKrPrPrPrQr {rRr cCs|rtjSddS)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. cS|SrUrPfrPrPrQz$anticipate_failure..)unittestexpectedFailure) conditionrPrPrQr%sr%cCsF|durd}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*) start_dir top_level_dirpattern)ospathdirname__file__discoveraddTests)pkg_dirloaderstandard_testsrktop_dir package_testsrPrPrQr&s  r&cCs2zt||}W|Stytd||fw)z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %r)getattrAttributeErrorrfSkipTest)objname attributerPrPrQr"s   r"FcCs|adSrU)_original_stdout)stdoutrPrPrQrsrcCs tptjSrU)r}sysr~rPrPrPrQr rc Gstz||WSty9}z(tdkr$td|jj|ftd|j|ft|tj||WYd}~Sd}~ww)Nz%s: %sz re-run %s%r) OSErrorrprintr]rLrlchmodstatS_IRWXU)rmfuncargserrrPrPrQ _force_runs rc sttdrtjSddl}d}tjdr|rd}ntjdrpddlddld}d}Gfdddj }j j }| }|sF |}j}||||||} | sf t|j|@sod}nHtjd krdd lm} mm} m } dd lm} | | d }|dkrd }n!Gfddd| }|}| |}||dks||dkrd}|szddlm}|}| |!|"Wn-t#y}z!t$|}t%|dkr|ddd}d&t'|j(|}WYd}~nd}~ww|t_)| t_tjS)Nresultrwinz(gui is not available on Windows IoT Corercs.eZdZdjjfdjjfdjjfgZdS)z*_is_gui_available..USEROBJECTFLAGSfInherit fReserveddwFlagsN)rLrMrNwintypesBOOLDWORD_fields_rP)ctypesrPrQUSEROBJECTFLAGSs    rz,gui not available (WSF_VISIBLE flag not set)darwin)cdllc_intpointer Structure) find_libraryApplicationServicesz0gui tests cannot run without OS X window managercseZdZdfdfgZdS)z._is_gui_available..ProcessSerialNumber highLongOfPSN lowLongOfPSNN)rLrMrNrrP)rrPrQProcessSerialNumbersrz#cannot run without OS X gui process)Tk2z [...]zTk unavailable due to {}: {})*hasattr_is_gui_availablerplatformr startswith win32_is_iotrctypes.wintypesrwindlluser32GetProcessWindowStationWinErrorrrGetUserObjectInformationWbyrefsizeofboolrrrr ctypes.utilr LoadLibraryCGMainDisplayIDGetCurrentProcessSetFrontProcesstkinterrwithdrawupdatedestroy ExceptionstrlenformattyperLreason)rr UOI_FLAGS WSF_VISIBLErdllhuofneededresrrrr app_servicesrpsnpsn_prroote err_stringrP)rrrQrsx          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)rresourcerPrPrQrsrcCs@t|s|dur d|}t||dkrtsttjdSdS)z@Raise ResourceDenied if the specified resource is not available.Nz"Use of the %r resource not enabledgui)rr rr)rrVrPrPrQrs rcCsddl}dtt|}|ddd}||kr9z ttt|d}Wn t y3d}Ynw||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. rN.-rFz version z or higher required, not ) rjoinmaprreleasesplitsystemtupleint ValueErrorrfskipIf)sysname min_versionrmin_version_txt version_txtversionskiprPrPrQ_requires_unix_version(s"    rcG 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. FreeBSDrrrPrPrQrC rcGr)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. LinuxrrrPrPrQrLrrcfdd}|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)Ncstjdkr:ddl}|d}z ttt|d}Wn ty$Ynw|kr:dtt }t d||f|i|S)Nrrrz&Mac OS X %s or higher required, not %s) rrmac_verrrrrrrrrfry)rkwrrrr)rrrPrQwrapper]s   z4requires_mac_ver..decorator..wrapper) functoolswrapsrrrrrrQ decorator\sz#requires_mac_ver..decoratorrP)rrrPrrQrUs raddressmemoryubcCsx|s |s |s tdtdpd}tdpd}d|vpd|v}d|vp'd|v}d|vp/d |v}|r4|p;|o7|p;|o;|S) z9Returns True if Python is compiled with sanitizer supportz3At least one of address, memory, or ub must be TrueCFLAGS CONFIG_ARGSz-fsanitize=memoryz--with-memory-sanitizerz-fsanitize=addressz-fsanitize=undefinedz#--with-undefined-behavior-sanitizer)r sysconfigget_config_var)rrr_cflags _config_argsmemory_sanitizeraddress_sanitizer ub_sanitizerrPrPrQr+rs$ r+cCs"|sd}t|||d}t||S)z>Decorator raising SkipTest if running with a sanitizer active.z"not working with sanitizers activer)r+rfr)rrrrrrPrPrQr,s r,cstfdd}|S)z5Skip the test on TLS certificate validation failures.c sFz |i|WdSty"}z dt|vrtdd}~ww)NCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)rrrfry)rkwargsrrbrPrQdecs  z&system_must_validate_cert..dec)rr)rcrrPrbrQsystem_must_validate_certsri@idoubleIEEEztest requires IEEE 754 doubles requires zlibcC0zddl}Wn tyd}Ynwt||SNr)zlib ImportErrorrf skipUnless)rrrPrPrQr$    r$ requires gzipcCrr)gziprrfr )rr rPrPrQrr r requires bz2cCrr)bz2rrfr )rrrPrPrQrr r requires lzmacCrr)lzmarrfr )rrrPrPrQrr rzrequires legacy Unicode C APIjavagetandroidapilevel)rGrIz/system/bin/shz/bin/shzhttp://www.pythontest.netdatacCsXtjdkrdSddl}d}|d}|\}}t||dt|td|dS)zOAssure user that loud errors generated by macOS libc's malloc are expected.rNrz NOTICE z may generate "malloc can't allocate region" warnings on macOS systems. This behavior is known. Do not report a bug unless tests are also failing. See bpo-40928.r)rrshutilget_terminal_sizercenter) test_namerrVdetailpadding_rPrPrQdarwin_malloc_err_warnings   rcCsbtj|r|S|durtj||}tgtj}|D]}tj||}tj|r.|Sq|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)rlrmisabsr TEST_HOME_DIRrexists)filenamesubdirrmdnfnrPrPrQr6s  r6cCs,t|}dd|D}d|}d|S)z%Like repr(dict), but in sorted order.cSsg|]}d|qS)z%r: %rrP).0pairrPrPrQ szsortdict..z, z{%s})sorteditemsr)dictr' reprpairs withcommasrPrPrQr;s  r;r)linenooffsetcCs|t|}t|ddWdn1swY|j}||j|dur0||j|||j|durC||j|dSdS)Nz exec)assertRaisesRegex SyntaxErrorcompile exceptionassertIsNotNoner+ assertEqualr,)testcase statementerrtextr+r,cmrrPrPrQrs  rc sddl}ddl}ddlm}zddl}Wn tyd}Ynwdd|j|d dd}t j t |}fdd }t j |rV||} | durR| S||td tretd |td |j} |rr| jd | j|td} |r| jddkr|j| d} z,t|d} | } | r| | | } | sWdn1swYW| n| w||} | dur| Std|)Nrr)unlinkcheckr/csDt|gRi}dur|S|r|d|S|dSr)openseekclose)r"rcrr9rrPrQcheck_valid_file8s  z*open_urlresource..check_valid_fileurlfetchz fetching %s ...file)zAccept-Encodingr timeoutzContent-Encodingr )fileobjwbzinvalid resource %r) urllib.request urllib.parse os_helperr8r rpopparseurlparserrlrmr TEST_DATA_DIRrrrrrrequest build_opener addheadersappendr<rDheadersgetGzipFilereadwriter>r ) urlrrurllibr8r rr"r@rcopeneroutsrPr?rQr2*sP           r2c csRddl}tt|}tt||ztt|VWtt||dStt||w)zReturn a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO.rN)iorwrsetattrStringIO) stream_namer] orig_stdoutrPrPrQcaptured_outputas rbcCtdS)zCapture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") r~rbrPrPrPrQrmrcCrc)zCapture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") stderrrdrPrPrPrQrvrercCrc)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") stdinrdrPrPrPrQrs rcCs2ddl}|trtd||dS)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. rN皙?)gccollectr-timesleep)rirPrPrQ gc_collects    rmccsHddl}|}|zdVW|r|dSdS|r#|wwr)ri isenableddisableenable)rihave_gcrPrPrQ disable_gcs  rrcCs6tdpd}d}|D] }|dr|}q |dvS)z,Find if Python was built with optimizations. PY_CFLAGSrz-O)rz-O0z-Og)rrrr)cflags final_optoptrPrPrQpython_is_optimizeds  rwnP0n getobjects2P0PncCddl}|t|tSr)structcalcsize_header_alignfmtrrPrPrQ calcobjsizercCr~r)rr_vheaderrrrPrPrQ calcvobjsizerri@icCspddl}t|}t|tkr|jt@s!t|tkr&t|jt@r&||j7}dt|||f}||||dS)Nrz&wrong size for %s: got %d, expected %d) _testinternalcapir getsizeofr __flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCSIZEOF_PYGC_HEADr3)testosizerrrVrPrPrQ check_sizeofs   rc gszddl}t||}||}Wntyd}}Yn|D]}z |||WnYq$zdVW|rF|rH|||dSdSdS|rU|rV|||wwwr)localerw setlocalerx)catstrlocalesrcategory orig_localelocrPrPrQr4s,    r4cr)Ncs"fdd}j|_j|_|S)Nc sztj}Wn tytdwdtjvrtjd}nd}tjd<|z|i|W|dur8tjd=n|tjd<tS|durKtjd=n|tjd<tw)Nztzset requiredTZ)rktzsetrxrfryrlenviron)rkwdsrorig_tz)rtzrPrQinners(            z-run_with_tz..decorator..inner)rLrO)rrrrrQrszrun_with_tz..decoratorrP)rrrPrrQr<s r<ircCsdttdtd}td|tjtjB}|durtd|ftt| d|| d }|a |t kr9t }|t dkrFtd|f|adS)Nr)kmgtz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rrz$Memory limit %r too low to be useful)_1M_1Grematch IGNORECASEVERBOSErrfloatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitsizesrmemlimitrPrPrQr9s" $ r9c@(eZdZdZddZddZddZdS) _MemoryWatchdogz`An object which periodically watches the process' memory consumption and prints it out. cCsdjtd|_d|_dS)Nz/proc/{pid}/statm)pidF)rrlgetpidprocfilestartedr^rPrPrQrZ7s z_MemoryWatchdog.__init__c Csddl}zt|jd}Wn!ty-}z|d|ttj WYd}~dSd}~wwddl }|t d}|j tj |g||jd|_Wdn1sPwYd|_dS)Nrrz!/proc not available for stats: {}zmemory_watchdog.py)rgrfT)warningsr<rrwarnrRuntimeWarningrrfflush subprocessr6Popen executableDEVNULL mem_watchdogr)r[rrcrrwatchdog_scriptrPrPrQstart;s(     z_MemoryWatchdog.startcCs"|jr|j|jdSdSrU)rr terminatewaitr^rPrPrQstopMs z_MemoryWatchdog.stopN)rLrMrNrOrZrrrPrPrPrQr2s  rTcsfdd}|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}ts d}n|}tss"t||kr"td||dtr=tr=ttdj||ddt}| nd}z ||W|rL| SS|rT| ww)Ni'not enough memory: %.1fG minimum needed@z* ... expected peak memory use: {peak:.1f}G)peak) rmemuserrfryrrrrrr)r[rrmaxsizewatchdog)dry_runrcrrPrQras6       z.bigmemtest..decorator..wrapper)rrrbrrrrcrrQr`szbigmemtest..decoratorrP)rrrrrPrrQrSs !rcr)z0Decorator for tests that fill the address space.cs<ttkrtdkrtdkrtdtdtd|S)Nllz-not enough memory: try a 32-bit build insteadrr)rrrfryr^rbrPrQrsz!bigaddrspacetest..wrapperrPrrPrbrQr s  r c@seZdZddZdS)rcCst}|||SrU)rf TestResult)r[rrrPrPrQrunzBasicTestRunner.runN)rLrMrNrrPrPrPrQrs rcCrarUrP)rzrPrPrQ_idrcCs6|dkr ts ttjSt|rtStd|S)Nrzresource {0!r} is not enabled)rrfrrrrrrrPrPrQrequires_resources  rcCstdd|S)z9 Decorator for tests only applicable on CPython. T)cpython) impl_detailrrPrPrQr!sr!cKsZtdi|r tS|dur(t|\}}|rd}nd}t|}|d|}t|S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or rP) r/r _parse_guardsr&keysrrrfr)rVguards guardnamesdefaultrPrPrQrs   rcCsH|sddidfSt|d}t||gt|ksJ|| fS)NrTFr)listvaluesr)ris_truerPrPrQrs   rcKst|\}}|tjj|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 )rrTrimplementationr{)rrrPrPrQr/s r/cs(ttdsStfdd}|S)zEDecorator to temporarily turn off tracing for the duration of a test.gettracec s:t}ztd|i|Wt|St|wrU)rrsettrace)rroriginal_tracerrPrQrs  zno_tracing..wrapper)rrrrrrPrrQ 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. )rr!rrPrPrQ refcount_tests rcCsNg}|jD]}t|tjrt||||q||r!||q||_dS)z>Recursively filter test cases in a suite based on a predicate.N)_tests isinstancerf TestSuite _filter_suiterR)suiteprednewtestsrrPrPrQrs      rcCsttjttdud}||}tdurt||js"|j s"t | sht |j dkr8|js8|j dd}nt |jdkrJ|j sJ|jdd}nd}tsR|d7}dd|j D}d d|jD}t|||dS) z2Run tests from a unittest.TestSuite-derived class.N) verbositycapture_outputrrzmultiple errors occurredz!; run in verbose mode for detailscSg|] \}}t||fqSrPrr#tcexc_strrPrPrQr% z_run_suite..cSrrPrrrPrPrQr% r)rrr~rjunit_xml_listrrRget_xml_elementtestsRunskippedr wasSuccessfulrrWrXrT)rrunnerrrrWrXrPrPrQ _run_suites(    rcCstdurdSt|SNT)_match_test_funcidrrPrPrQ match_tests rcCsd|vo td| S)Nrz[?*\[\]])rsearch)rkrPrPrQ_is_full_match_testsrcs|durd}|dur d}d|tkrt|\}|tkr$t|\}t|at|adus4dur?fdd}|adSdS)NrPcs*d}d}r |}r|}|o| S)NTFrP)test_idacceptignore accept_func ignore_funcrPrQmatch_function=s z'set_match_tests..match_function)_accept_test_patterns_compile_match_function_ignore_test_patternsrr)accept_patternsignore_patternsrrPr rQset_match_tests(s   rcsr|s d}d}||fSttt|rt|j}||fSddl}dt|j|}t |j fdd}|}||fS)NrPr|cs |rdStt|dS)NTr)anyrr)r  regex_matchrPrQmatch_test_regexYsz1_compile_match_function..match_test_regex) allrrset __contains__fnmatchr translaterr0r)patternsrrregexrrPrrQrIs    rcGstjtjf}t}|D]/}t|tr(|tjvr$|ttj|q t dt||r3||q |t |q t |t t |dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesN)rfrTestCaserrrmodulesaddTest findTestCasesr makeSuiterrr)classes valid_typesrclsrPrPrQris       rcCdS)z,Just used to check if docstrings are enabledNrPrPrPrPrQ_check_docstringsrer+WITH_DOC_STRINGSztest requires docstringscCs`ddl}|dur t}nd}|j|||d\}}|r!td||ftr,td|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)doctestrtestmodr rrL)modulerr-r.rcrrPrPrQrsrcCs(|D] }td|tjddqdS)Nz Warning -- T)rCr) splitlinesrr __stderr__)rVlinerPrPrQ print_warnings r4cCsfttdr ttds dS z tdtj\}}Wn ty"YdSw|dkr)dStd|daq )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. waitpidWNOHANGNTr;rz%reap_children() reaped child process )rrlr5r6rr4environment_altered)rstatusrPrPrQr3s  r3c cst||r%t||}t|||z |VWt|||dSt|||wt|||zdVWt||r)zgReturn a list of command-line arguments reproducing the current optimization settings in sys.flags.rN)r"_optim_args_from_interpreter_flagsr@rPrPrQ!optim_args_from_interpreter_flagsrBrDc@ eZdZdZddZddZdS)r8)rVmessagecKs<d}|D]}||}||}||||sd}|Sq|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)rT match_value)r[drrrvdvrPrPrQmatches&s zMatcher.matchescCsLt|t|kr d}|St|tus||jvr||k}|S||dk}|S)zT Try to match a single stored value (dv) with a supplied value (v). Fr)rr_partial_matchesfind)r[rrJrIrrPrPrQrG7szMatcher.match_valueN)rLrMrNrLrKrGrPrPrPrQr8"s r8cCsXddl}tdur!tjdkr|ddkrtjdkrdandatr*t 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 rNrGrcp65001rTFz!buggy MSVC UCRT strptime/strftime) r _buggy_ucrtrrgetdefaultlocalerk localtimetm_zonerfr)rrrPrPrQr)Es  r)c@sjeZdZdZdddZejdkrddZnddZd d Zd d Z d dZ ddddZ ddddZ dS) PythonSymlinkz3Creates a symlink for the current Python executableNcCsLddlm}|p tj||_g|_tjtj |_ g|_ d|_ | dS)Nr)TESTFN)rJrTrlrmabspathlink_linkedrealpathrrreal _also_link_env_platform_specific)r[rVrTrPrPrQrZ\s  zPythonSymlink.__init__rGc Csddl}ddl}tj|jrtj|js|d|_|tj }tj |}tj |j }|j |tj|tj|f|tj||dD]}|j |tj|tj|fqMddtjD|_tj |j|jd<tdrtj tj|jd<dSdS)Nrzvcruntime*.dllcSsi|] }|t|qSrP)upperrlgetenv)r#rrPrPrQ rz4PythonSymlink._platform_specific.. PYTHONHOMET PYTHONPATH)glob_winapirlrmlexistsrYrGetModuleFileNamer dllhandlernrVrZrRrbasenameescaperr[ris_python_buildro)r[rbrcrsrc_dirdest_dirruntimerPrPrQr\is*    z PythonSymlink._platform_specificcCsdSrUrPr^rPrPrQr\rcCsJt|j|j|j|j|jD]\}}t|||j|q|SrU)rlsymlinkrYrVrWrRrZ)r[rYrVrPrPrQ __enter__s  zPythonSymlink.__enter__c CsV|jD]%}zt|Wqty(}ztrtd||WYd}~qd}~wwdS)Nzfailed to clean up {}: {})rWrlremoveIOErrorrrr)r[exc_type exc_valueexc_tbrVexrPrPrQ__exit__s zPythonSymlink.__exit__c Csxddl}|g|}|j||j|j|d}|}|j|kr:tr2tt|dtt|dtj dt d |j|S)Nr)r~rfenvrrBz'unexpected return code: {0} (0x{0:08X})) rrPIPE communicate returncoderrreprrrf RuntimeErrorr) r[pythonrrvryrcmdprrPrPrQ_calls    zPythonSymlink._callr)rycGs||j|d|SrU)rrYr[ryrrPrPrQ call_realszPythonSymlink.call_realcGs||j||j|SrU)rrVr[rrPrPrQ call_linkszPythonSymlink.call_linkrU) rLrMrNrOrZrrr\rnrurrrrPrPrPrQrSZs  rScCs$t pt}d}|r |St||S)z;Skip decorator for tests not run in (non-extended) PGO taskz#Not run for (non-extended) PGO task)r= PGO_EXTENDEDrfr)rokrVrPrPrQskip_if_pgo_tasks rrP)r cCs>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(|]}|dr|dr|VqdS)r__N)rendswith)r#rrPrPrQ s z&detect_api_mismatch..)rdir)ref_api other_apir  missing_itemsrPrPrQr's  r'cCs|dur |jf}nt|tr|f}t|}t|D])}|ds$||vr%qt||}t|dd|vs=t|dsBt|tj sB| |q| |j |dS)a)Assert 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 'not_exported' 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'} not_exported = {'baz'} # Undocumented name. # bar imports part of its API from _bar. support.check__all__(self, bar, ('bar', '_bar'), extra=extra, not_exported=not_exported) NrrM) rLrrrrrrwrtypes ModuleTypeaddassertCountEqual__all__) test_caser0name_of_moduleextra not_exportedexpectedr{rzrPrPrQr(s")      r(cCszddl}Wn tyYdSw||j|jB|jB|jBt|drG|j|j |j fD]}|r@| ||j | ||jq-| |dq-dSdS)NrCrtSetReportMode)msvcrtr SetErrorModeSEM_FAILCRITICALERRORSSEM_NOALIGNMENTFAULTEXCEPTSEM_NOGPFAULTERRORBOXSEM_NOOPENFILEERRORBOXrCRT_WARN CRT_ERROR CRT_ASSERTrCRTDBG_MODE_FILECrtSetReportFileCRTDBG_FILE_STDERR)rrrrPrPrQsuppress_msvcrt_assertss(   rc@s(eZdZdZdZdZddZddZdS)r:zTry 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 CstjdrOzddl}Wn tyYdSw||_||j|jBt |drMi|_ |j |j |j fD]}|||j}|||j}||f|j |<q5|Sz ddl}||_Wn tydd|_Ynw|jdurz|j|jj|_|j|jjd|jdfWn ttfyYnwtjdkrddl}gd}|j||j|jd}||d} Wdn1swY| 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/defaultsrVzcom.apple.CrashReporter DialogType)r~rfs developerz:this test triggers the Crash Reporter, that is intentionalrT)endr)rrrrr GetErrorMode old_valuerrr old_modesrrrrrrrr getrlimit RLIMIT_CORE setrlimitrrrrrwrxstripr) r[r report_typeold_modeold_filerrr}procr~rPrPrQrnsh     #        zSuppressCrashReport.__enter__c Gs|jdurdStjdr6ddl}||j|jr2|jD]\}\}}|||| ||qdSdS|j durUz |j |j j |jWdSt tfyTYdSwdS)zARestore Windows ErrorMode or core file behavior to initial value.Nrr)rrrrrrrr'rrrrrrr)r[ ignore_excrrrrrPrPrQru]s$     zSuppressCrashReport.__exit__)rLrMrNrOrrrnrurPrPrPrQr:s  Br:c sptdzjWnttfytdYnwdfdd}||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"r tdStdSrU)r^r9rP attr_is_local attr_nameobject_to_patchrrPrQcleanupszpatch..cleanup)rw__dict__rxKeyError addCleanupr^) test_instancerr new_valuerrPrrQpatchrs  rc cs6z|dd}dVW||dd<dS||dd<w)z-Like unittest.mock.patch.dict, but for lists.NrP)origsavedrPrPrQ patch_lists  rcCsDzddl}Wn tyYn w|rtdddl}||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_tracingrfry _testcapirun_in_subinterp)coderrrPrPrQrs    rcsHGfddd|}d||||ttt|dS)NcseZdZfddZdS)z%check_free_after_iterating..Acs(dztWdStyYdSwr)next StopIterationr^doneitrPrQ__del__s  z-check_free_after_iterating..A.__del__N)rLrMrNrrPrrPrQAsrF) assertRaisesrrrm assertTrue)riterr)rrrPrrQcheck_free_after_iteratings  rcCsddlm}m}m}m}|}|||jdkr,z|Wn |j y+YdSw|j D]-}|r8||vr8q/t ||}|rJ|dusIJd|n|sMq/| |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) ccompilerrspawnrWmsvcNz%the '%s' executable is not configured) distutilsrrrrW new_compilercustomize_compiler compiler_type initializeDistutilsPlatformError executablesrwfind_executable) cmd_namesrrrrWcompilerr{r}rPrPrQr>s.         r>cCsHd}tr||krtdurddl}|ddgdkatr|}t|S)Ngh㈵>rgetpropzro.kernel.qemu1)r._is_android_emulatorr check_outputrrr1)intervalminimum_intervalrrPrPrQr1s  r1c cs^ddl}tj}|}z|dVW|r"|j|dddSdS|r.|j|ddww)NrT)rC all_threads) faulthandlerrr2fileno is_enabledrorp)rfdrrPrPrQdisable_faulthandlers rc@r) 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 CsZddl}||_||_dD]}zt||}Wn ty Yqw|j|qi|_dS)Nr)SIGKILLSIGSTOP)signal valid_signalssignalsrwrxrohandlers)r[rsignamesignumrPrPrQrZs   zSaveSignals.__init__cCs0|jD]}|j|}|durq||j|<qdSrU)rr getsignalrr[rhandlerrPrPrQsaves   zSaveSignals.savecCs&|jD] \}}|j||qdSrU)rr'rrrPrPrQrestore)szSaveSignals.restoreN)rLrMrNrOrZrrrPrPrPrQrs  rcCsddl}|jSr)r WITH_PYMALLOC)rrPrPrQ with_pymalloc.src@rE) _ALWAYS_EQz+ Object that is equal to anything. cCr*rrPr[otherrPrPrQ__eq__7rz_ALWAYS_EQ.__eq__cCr*NFrPrrPrPrQ__ne__9rz_ALWAYS_EQ.__ne__N)rLrMrNrOrrrPrPrPrQr3s rc@r) _NEVER_EQz/ Object that is not equal to anything. cCr*rrPrrPrPrQrBrz_NEVER_EQ.__eq__cCr*rrPrrPrPrQrDrz_NEVER_EQ.__ne__cCr*)NrrPr^rPrPrQ__hash__Frz_NEVER_EQ.__hash__N)rLrMrNrOrrrrPrPrPrQr>s  rc@rE)_LARGESTz? Object that is greater than anything (except itself). cC t|tSrU)rrrrPrPrQrPrz_LARGEST.__eq__cCr*rrPrrPrPrQ__lt__Rrz_LARGEST.__lt__N)rLrMrNrOrrrPrPrPrQrK rc@rE) _SMALLESTz< Object that is less than anything (except itself). cCrrU)rrrrPrPrQr\rz_SMALLEST.__eq__cCr*rrPrrPrPrQ__gt__^rz_SMALLEST.__gt__N)rLrMrNrOrrrPrPrPrQrWrrcCsddl}|jjS)zDReturn the global event loop policy if one is set, else return None.rN)asyncio.eventsevents_event_loop_policy)asynciorPrPrQmaybe_get_event_loop_policycsr ) @c Cs||}}ddl}|K}|d}t|d|_||}|d||}||} || } || } ||d|d||| d| } t| t| fWdS1s[wYdS)Nrrr)decimal localcontext bit_lengthmaxprecDecimalrsqrt) nbinsnballsr}rrctxbitsr!p1empty meanemptyoccupied collisionsvarrPrPrQcollision_statsps     ($r c@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|_dSrU) unraisable _old_hookr^rPrPrQrZs z#catch_unraisable_exception.__init__cCs ||_dSrU)r")r[r"rPrPrQ_hooks z catch_unraisable_exception._hookcCstj|_|jt_|SrU)runraisablehookr#r$r^rPrPrQrnrz$catch_unraisable_exception.__enter__cGs|jt_|`dSrU)r#rr%r")r[exc_inforPrPrQrusz#catch_unraisable_exception.__exit__N)rLrMrNrOrZr$rnrurPrPrPrQr!s  r!rDc Cs$tjdkrcddl}|durt}t}d}d} t|tj\}}|dkr&n.r r) rrrfiltersrMrrPatternrkrrR_filters_mutated) rP new_filtersractionrFrr0r+rVrPrPrQclear_ignored_deprecations0s     rVc cs8t}zt|dVWt|dSt|w)z>Temporarily change the integer string conversion length limit.N)rget_int_max_str_digitsset_int_max_str_digits) max_digitscurrentrPrPrQadjust_int_max_str_digitsDs  r[rU)r)r )r )r)r)T)NNr)NrPrP)F)rP)r<)rOrLr contextlibrrlrrrrrkrrfr testresultrrrrrCrrrDrErFrr r rTr ryr r%r&r"rrrrrr r}rrrrrrrrrrr+r,rr SOCK_MAX_SIZEr r __getformat__rr#r$rrrrequires_legacy_unicode_capir-rr.r0 TEST_HTTP_URLr=rrmrnrUroTEST_SUPPORT_DIRrrrNrr6r;rr2contextmanagerrbrrrrmrrrwrrrrrrrrr4r<rrr_4Grrr9rrr rrrr!rrr/rrrrrrrrrrrrr+rMISSING_C_DOCSTRINGSHAVE_DOCSTRINGSrequires_docstringsrr4r7r3r7r5rArDrKr8rOr)rSrr'r(rr:rrrrr>rr1rrrrr?rr@total_orderingrrArrBr  hash_infowidth NHASHBITSr r!r3r;rAr*rrOrVr[rPrPrPrQs  ,     M              7          # !0       !       "R ;`"     '    ",4