U kglb@sdZedkredddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl!Z!ddl"Z"ddl#Z#ddl$Z$ddl%Z&ddl'Z'ddl(m)Z)z ddl*Z+Wnek rNdZ+YnXz ddl,Z,Wnek rvdZ,YnXz ddl-Z-Wnek rdZ-YnXz ddl.Z.Wnek rdZ.YnXz ddl/Z/Wnek rdZ/YnXz ddl0Z0Wnek rdZ0YnXz ddl1Z1Wnek r>dZ1YnXddd 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`dadbdcdddedfdgdhgbZ2Gdid d e3Z4Gdjd d e4Z5Gdkdde4Z6Gdldde$j7Z8ej9ddndoZ:dpdDZ;ddrdsdtdZdyd>Z?dzd?Z@dd{dZAd|d:ZBdZCdZDdaEdaFdZGdqZHdaId}dZJd~dZKddZLddZMejNdr"dddZOddZPddZQddZRddZSnejTZPejUZQddZRddZSddZTddZUddZVddZWddZXddZYdd#ZZddd$Z[ddZ\dd%Z]dd&Z^dd'Z_ddd(Z`dZadZbdZcejdejefddLZfeafddMZgddOZhddZieiZjddZkdZldZme$neopdNddZqe$ne,dZre$ne-dZse$ne.dZte$ne/dZuejNdZvewedZxejdkrxexrrdndZyndZyejzdkrdZ{ndZ{d|e{e}Z{dZ~dZdD]FZzeeeekreWnek rYn XeZqqe{dZejdkrddlZedeZeZdZejzdkrejdkre{dZzeeWnek rrYnXedeefdZnBejdkrzdĠeWn&ek re{dŠedơZYnXdZdD]BZzzezeWn,ek ree{ezZYqYnXqer,e{deZndZeZdqZdqZej9dddʄZej9ddd̄Zej9dddZewedσrej9ddPZejejeZejeZejedѡZdddZdd ZddaZddքZdddd؜dd)Zdddd؜dd*ZddNZGdd݄deZddd߄Zej9ddWZej9dedqfddYZej9ddXZGdddeZGddZdZejjZGdddeZGdd+d+eZeeejdZeeejdZeeejdZddZej9ddrddd/Zej9ddZddZddZddZddZej9ddZddZdZdZewed rPdeZdZedZddZȐddZɐdZʐdZːddZ̐dd[Z͐ddbZΐd Zϐd eZdeZѐd eZejZԐd d_ZGd ddZ֐ddd7Zאdd8ZGdd0d0ZِddZڐddZېdd9ZܐdddZݐddZސddGZߐddZddZd d!Zd"d#Zdadadad$d%Zd&d'Zdd(d)Zd*d+Zd,d1Zd-d.Ze߃ oejdk oed/ Zejdk oe Ze$ned0Zdd1d2Zd2d3Zd4d5Zd6d7Zdqad8dSZd9dTZd:dUZej9dd<d=Zdd>d?Zd@dQZej9ddAdVZej9dBd]Zej9dCd\ZdDdEZe$ewedFdGZdHdIZdJdKZGdLdRdRejjZGdMd^d^eZdadNd!Z dOd3Z da dPdCZ GdQdRdRZ dadSdTZdUd<ZdVdWZdadXdBZdYd"ZdrdZd[d@Zdd\dAZdd]d^ZGd_d`d`Zd`daZdbdcZddddeZgfdfddZdadgdIZej9dhdiZdjdeZ GdkdldlZ!dmdnZ"GdodpdpZ#GdqdrdrZ$e$Z%e j&GdsdtdtZ'e'Z(e j&GdudvdvZ)e)Z*dwdxZ+ej,j-Z.e.dyksft/dzd{Z0Gd|d}d}Z1Gd~ddZ2ej9ddZ3ddZ4dS(z7Supporting definitions for the Python regression tests.z test.supportz.support must be imported from the test packageN)get_test_runner PIPE_MAX_SIZEverbose max_memuse use_resourcesfailfastError TestFailed TestDidNotRunResourceDenied import_moduleimport_fresh_module CleanImportunloadforgetrecord_original_stdoutget_original_stdoutcaptured_stdoutcaptured_stdincaptured_stderrTESTFNSAVEDCWDunlinkrmtreetemp_cwdfindfilecreate_empty_file can_symlinkfs_is_case_insensitiveis_resource_enabledrequiresrequires_freebsd_versionrequires_linux_versionrequires_mac_verrequires_hashdigestcheck_syntax_errorcheck_syntax_warningTransientResourcetime_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__skip_unless_bind_unix_socketskip_if_buggy_ucrt_strfptimeignore_warnings 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_warningcheck_no_warningsEnvironmentVarGuardrun_with_locale swap_item swap_attrMatcher set_memlimitSuppressCrashReportsortdict run_with_tzPGOmissing_compiler_executablefd_count ALWAYS_EQLARGESTSMALLESTc@seZdZdZdS)r z*Base class for regression test exceptions.N__name__ __module__ __qualname____doc__rkrk+/usr/lib/python3.8/test/support/__init__.pyr }sc@seZdZdZdS)r z Test failed.Nrfrkrkrkrlr sc@seZdZdZdS)r zTest did not run any subtests.Nrfrkrkrkrlr 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. Nrfrkrkrkrlr sTc cs8|r.ttddtdVW5QRXndVdS)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_warningsfilterwarningsDeprecationWarningrmrkrkrl_ignore_deprecated_importss rscsfdd}|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)Nc s>t,tjdd|f||W5QRSQRXdS)Nrmcategory)rnro simplefilter)selfargskwargs)rutestrkrlwrappers z3ignore_warnings..decorator..wrapper functoolswraps)rzr{rtrzrl decoratorsz"ignore_warnings..decoratorrk)rurrkrtrlrAs Frk) required_onc Cstt|bzt|WW5QRStk rd}z$tjt|rFt t |W5d}~XYnXW5QRXdS)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) rs importlibr ImportErrorsysplatform startswithtupleunittestSkipTeststr)name deprecatedrmsgrkrkrlr s cCsZ|tjkrt|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_modulesmodnamerkrkrl_save_and_remove_modules rcCs>d}ztj|||<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. TFNrrKeyError)rrZsavedrkrkrl_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|SNrkfrkrkrlz$anticipate_failure..)rZexpectedFailure)Z conditionrkrkrlr;scCsF|dkr 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_testsrkrkrlr<s  c Cst|i}g}t||z^z@|D]} t| |q$|D]} t| |s8|| q8t|} Wnt k rvd} YnXW5|D]\}}|tj|<q|D] }tj|=qX| W5QRSQRXdS)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) rsritemsrrrappendrr r) rZfreshZblockedrrZnames_to_removeZ orig_namemoduleZname_to_removeZ fresh_nameZ blocked_nameZ fresh_modulerkrkrlrs$       cCs>zt||}Wn&tk r4td||fYnX|SdS)z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %rN)getattrAttributeErrorrr)objrZ attributerkrkrlr7,s cCs|adSr)_original_stdout)stdoutrkrkrlrAscCs tptjSr)rrrrkrkrkrlrEscCs&z tj|=Wntk r YnXdSrr)rrkrkrlrHs c Gszz ||WStk rt}zLtdkrJtd|jj|ftd|j|ft|tj||WYSd}~XYnXdS)Nz%s: %sz re-run %s%r) OSErrorrprint __class__rgrchmodstatS_IRWXU)rfuncrxerrrkrkrl _force_runNs rwincCs|||r|}ntj|\}}|p(d}d}|dkrjt|}|rJ|sVn||ksVdSt||d9}q.tjd|tdddS)NrgMbP?g?rz)tests may fail, delete still pending for  stacklevel) rrsplitlistdirtimesleeprnwarnRuntimeWarning)rpathnamewaitallrrtimeoutLrkrkrl_waitforYs     rcCsttj|dSr)rrrfilenamerkrkrl_unlinkzsrcCsttj|dSr)rrrmdirrrkrkrl_rmdir}srcs,fddt|ddtdd|dS)Nc st|tj|D]}tj||}zt|j}Wn<tk rl}ztd||ft j dd}W5d}~XYnXt |rt |ddt|tj|qt|tj|qdS)Nz-support.rmtree(): os.lstat(%r) failed with %sfilerTr)rrrrjoinlstatst_moderrr __stderr__rS_ISDIRrrr)rrfullnamemodeexc _rmtree_innerrkrlrs  _rmtree.._rmtree_innerTrcSst|tj|Sr)rrr)prkrkrlrrz_rmtree..)rrrkrrl_rmtrees rcCs^z ddl}Wntk r Yn:X|t|d}|jj||t|}|rZ|d|S|S)Nrr)ctypesrZcreate_unicode_bufferlenwindllZkernel32ZGetLongPathNameW)rrbufferZlengthrkrkrl _longpaths   rcsHzt|WdStk r$YnXfdd|t|dS)Nc st|tj|D]l}tj||}zt|j}Wntk rHd}YnXt |rl|t|tj |qt|tj |qdSNr) rrrrrrrrrrrr)rrrrrrkrlrs  r)shutilrrrrrrkrrlrs  cCs|Srrkrrkrkrlrsc Cs*z t|Wnttfk r$YnXdSr)rFileNotFoundErrorNotADirectoryErrorrrkrkrlrs cCs&z t|Wntk r YnXdSr)rrrrkrkrlrs rcCs&z t|Wntk r YnXdSr)rrrrkrkrlrs cCsBtj|}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_pycrkrkrlmake_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)rrroptrkrkrlrs   c sttdrtjSd}tjdrddlddld}d}Gfdddj}j j }| }|sj |}j }||||||}|s t|j|@sd}ntjdkrVdd lm} mm} m} dd lm} | | d } | dkrd }nFGfd dd| }|}| |}| |dksR| |dkrVd}|sz.ddlm}|}|| |!Wn\t"k r}z.USEROBJECTFLAGSZfInheritZ fReserveddwFlagsN)rgrhriwintypesZBOOLDWORD_fields_rk)rrkrlUSEROBJECTFLAGSs   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)rgrhrirrk)rrkrlProcessSerialNumbersrz#cannot run without OS X gui process)Tk2z [...]zTk unavailable due to {}: {}))hasattr_is_gui_availablerrrrrZctypes.wintypesrrZuser32ZGetProcessWindowStationZWinErrorrrZGetUserObjectInformationWZbyrefZsizeofboolrrrrZ ctypes.utilrZ LoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterrZwithdrawupdateZdestroy Exceptionrrformattypergreason)rZ UOI_FLAGSZ WSF_VISIBLErdllhZuofZneededresrrrrZ app_servicesrZpsnZpsn_prrooteZ err_stringrk)rrrlrsn         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)rresourcerkrkrlr 5scCs<t|s |dkrd|}t||dkr8ts8ttjdS)z@Raise ResourceDenied if the specified resource is not available.Nz"Use of the %r resource not enabledgui)r r rr)r rrkrkrlr!=s cCsddl}dtt|}|ddd}||krtzttt|d}Wnt k rhd}YqxX||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_txtversionskiprkrkrl_requires_unix_versionFs   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. ZFreeBSDrrrkrkrlr"ascGs 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. ZLinuxrrrkrkrlr#jscsfdd}|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)Ncsxtjdkrntd}zttt|d}Wntk rBYn,X|krndtt }t d||f||S)Nrrrz&Mac OS X %s or higher required, not %s) rrZmac_verrrrrrrrrr)rxkwrrr)rrrkrlr{{s  z4requires_mac_ver..decorator..wrapper)r}r~rrr{rrrlrzsz#requires_mac_ver..decoratorrk)rrrkrrlr$ss csfdd}|S)aDecorator raising SkipTest if a hashing algorithm is not available The hashing algorithm could be missing or blocked by a strict crypto policy. If 'openssl' is True, then the decorator checks that OpenSSL provides the algorithm. Otherwise the check falls back to built-in implementations. ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS ValueError: unsupported hash type md4 cstfdd}|S)NcsXz&rtdk rtn tWn&tk rLtddYnX||S)Nz hash digest 'z' is not available.)_hashlibnewhashlibrrr)rxry) digestnameropensslrkrlr{s   z7requires_hashdigest..decorator..wrapperr|rr#r$rrlrs z&requires_hashdigest..decoratorrk)r#r$rrkr%rlr%s Z localhostz 127.0.0.1z::1c Cs&t||}t|}W5QRX~|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. )socketrJ)familyZsocktypeZtempsockportrkrkrlrIs8cCs|jtjkr|jtjkrttdr>|tjtjdkr>t dttdr~z |tjtj dkrft dWnt k r|YnXttdr| tjtj d||df|d}|S)a%Bind the socket to a free port and return the port number. Relies on ephemeral ports in order to ensure we are using an unbound port. This is important as many tests may be running simultaneously, especially in a buildbot environment. This method raises an exception if the sock.family is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR or SO_REUSEPORT set on it. Tests should *never* set these socket options for TCP/IP sockets. The only case for setting these options is testing multicasting via multiple UDP sockets. Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. on Windows), it will be set on the socket. This will prevent anyone else from bind()'ing to our host/port for the duration of the test. SO_REUSEADDRrzHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets! SO_REUSEPORTzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!SO_EXCLUSIVEADDRUSEr)r'r&AF_INETr SOCK_STREAMrZ getsockoptZ SOL_SOCKETr)r r*rZ setsockoptr+bindZ getsockname)sockZhostr(rkrkrlrJs     cCsJ|jtjkstz||Wn&tk rD|tdYnXdS)zBBind a unix socket, raising SkipTest if PermissionError is raised.zcannot bind AF_UNIX socketsN) r'r&AF_UNIXAssertionErrorr.PermissionErrorcloserr)r/ZaddrrkrkrlrLs cCs`tjr\d}zBz(ttjtj}|tdfWWdStk rHYnXW5|rZ|XdS)z+Check whether IPv6 is enabled on this host.NrTF)r&Zhas_ipv6r3ZAF_INET6r-r.HOSTv6r)r/rkrkrl_is_ipv6_enableds   r5cstfdd}|S)z5Skip the test on TLS certificate validation failures.c sNz||Wn:tk rH}zdt|kr6tdW5d}~XYnXdS)NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)rrrr)rxryr rrkrldec0s   z&system_must_validate_cert..decr|)rr6rkrrlsystem_must_validate_cert.sr7i@iZdoubleZIEEEztest requires IEEE 754 doublesz requires zlibz requires gzipz requires bz2z requires lzmaZjavaZgetandroidapilevelwin32z/system/bin/shz/bin/shz$testz@testz {}_{}_tmpzhttp://www.pythontest.net) æ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<sssr c csd}|dkr&t}d}tj|}nXzt|d}WnDtk r|}z&|sPtjd|d|t ddW5d}~XYnX|rt }z |VW5|r|t 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. FNTz5tests may fail, unable to create temporary directory : r) tempfilemkdtemprrrealpathmkdirrrnrrgetpidr)rquietZ dir_createdrpidrkrkrltemp_dirs*  rGc cst}zttj|WnDtk rb}z&|s6tjd|d|tddW5d}~XYnXztVW5t|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. zBtests may fail, unable to change the current working directory to r>r?rN) rgetcwdchdirrrBrrnrr)rrEZ saved_dirrrkrkrl change_cwds rJtempcwdc cs:t||d$}t||d }|VW5QRXW5QRXdS)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. )rrE)rEN)rGrJ)rrEZ temp_pathZcwd_dirrkrkrlr:sumaskc cs&t|}z dVW5t|XdS)z8Context manager that temporarily sets the process umask.N)rrL)rLZoldmaskrkrkrlrMNs  datacCsbtj|r|S|dk r&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)rZsubdirrdnfnrkrkrlr_s   cCs(t|tjtjBtjB}t|dS)z>Create an empty file. If the file already exists, truncate it.N)ropenO_WRONLYO_CREATO_TRUNCr3)rfdrkrkrlrqscCs,t|}dd|D}d|}d|S)z%Like repr(dict), but in sorted order.cSsg|] }d|qS)z%r: %rrk).0Zpairrkrkrl yszsortdict..z, z{%s})sortedrr)dictrZ reprpairsZ withcommasrkrkrlr^vs  cCs.ttd}z |WS|ttXdS)z` Create an invalid file descriptor by opening and closing a file and return its fd. wbN)rSrr3rfilenorrkrkrl make_bad_fd}s   r^rlinenooffsetc Csr|t|}t|ddW5QRX|j}||j|dk rL||j|||j|dk rn||j|dS)Nz exec)ZassertRaisesRegex SyntaxErrorcompileZ exceptionassertIsNotNoner` assertEqualra)testcase statementerrtextr`racmrrkrkrlr&s  c Cstjdd}tdtt|ddW5QRX|t|d||\}|t|j t|j |rt| t |j |||j d||j|dk r||j|tjdd$}tdtt|||||dW5QRX||gdS) NTrecordalwaysz rbrerrorr_)rnrorv SyntaxWarningrdrfr assertTrue issubclassruZ assertRegexrmessagerrer`r&)rgrhrir`rawarnsrrkrkrlr's&   c sPddl}ddl}dd|j|ddd}tjt |}fdd}tj |r|||}|dk rt|St |t dt rtd |td |j}tr|jd |j|d d }tr|jddkrtj|d}zt|f}dkr|S|r2|d|S|dSr)rSseekr3)rRrrxrtrrkrlcheck_valid_files z*open_urlresource..check_valid_fileZurlfetchz fetching %s ...r)zAccept-Encodinggzip)rzContent-Encodingrz)Zfileobjr\zinvalid resource %r)Zurllib.requestZ urllib.parsepopparseZurlparserrrr TEST_DATA_DIRrPrr!rrrZrequestZ build_openerrzZ addheadersrrSZheadersgetZGzipFiler3readwriter ) ZurlrxrurllibrrRryrZopeneroutsrkrxrlrKs<         c@s4eZdZdZddZddZeddZdd Zd S) WarningsRecorderzyConvenience wrapper for the warnings list returned on entry to the warnings.catch_warnings() context manager. cCs||_d|_dSr _warnings_last)rwZ warnings_listrkrkrl__init__szWarningsRecorder.__init__cCsDt|j|jkr t|jd|S|tjjkr0dStd||fdS)Nrvz%r has no attribute %r)rrrrrnWarningMessage_WARNING_DETAILSr)rwattrrkrkrl __getattr__s  zWarningsRecorder.__getattr__cCs|j|jdSrrrwrkrkrlrnszWarningsRecorder.warningscCst|j|_dSr)rrrrrkrkrlresetszWarningsRecorder.resetN) rgrhrirjrrpropertyrnrrkrkrkrlrs  rc cstd}|jd}|r"|tjdd }tjddt |VW5QRXt |}g}|D]j\}}d} |ddD]8}|j } t |t| t jr|t| j|r|d} ||q|| sd|sd|||jfqd|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__TrkrnrmFNzunhandled warning %srz)filter (%r, %s) did not catch any warning)r _getframe f_globalsrclearrnrorrvrrrrrematchrIrqrremoverrgr1) filtersrEframeregistrywZreraiseZmissingrcatseenZwarningrkrkrl_filterwarningss4     rcOs.|d}|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) rErNT)rWarningr)rryrErkrkrlrT s   c csHtjdd&}tjd||ddV|r.tW5QRX||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(). Trkrm)rrruN)rnrorp gc_collectrf)rgrrruforce_gcrsrkrkrlrV8sc cs$t|tdd dVW5QRXdS)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)rurN)rVResourceWarning)rgrkrkrlrUPsc@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}|tjkrtj|}|j|kr@)rerrnosc #sjddddddg}ddd d d g}td ||gsRd d|Ddd|Dfdd}t}zz|dk rt|dVWntjk r}z$trtj j dd|W5d}~XYnt k rT}zj|j }t |dkr t |dt r |d}qt |dkr:t |dt r:|d}qސq:q||W5d}~XYnXW5t|XdS)zReturn a context manager that raises ResourceDenied when various issues with the Internet connection manifest themselves as exceptions.)ro) ECONNRESETh)rq)re) ETIMEDOUTn)rc)Z EAI_AGAIN)ZEAI_FAIL)Z EAI_NONAME)Z EAI_NODATA)Z WSANO_DATAi*zResource %r is not availablecSsg|]\}}tt||qSrk)rrrXrZnumrkrkrlrY!sz&transient_internet..cSsg|]\}}tt||qSrk)rr&rrkrkrlrY#scst|dd}t|tjst|tjr,|kst|tjjrRd|jkrPdksnt|tjj r~d|j ksd|j ksd|j ks|krt st j jdd|dS) NriiWConnectionRefusedError TimeoutErrorEOFErrorr )r isinstancer&rZgaierrorrrnZ HTTPErrorcodeZURLErrorrrrstderrrrx)rnZcaptured_errnosZdeniedZ gai_errnosrkrl filter_error&s4      z(transient_internet..filter_errorNrrrr)r r&ZgetdefaulttimeoutZsetdefaulttimeoutnntplibZNNTPTemporaryErrorrrrrrxrrr) Z resource_namerrZdefault_errnosZdefault_gai_errnosrZ old_timeoutrarkrrlr,sV      c csFddl}tt|}tt||ztt|VW5tt||XdS)zReturn a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO.rN)iorrsetattrStringIO)Z stream_namerZ orig_stdoutrkrkrlcaptured_outputTs  rcCstdS)zCapture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") rrrkrkrkrlr`scCstdS)zCapture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") rrrkrkrkrlriscCstdS)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") stdinrrkrkrkrlrrs cCs*ttrtdttdS)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)gcZcollectrBrrrkrkrkrlrs  rccs.t}tz dVW5|r(tXdSr)rZ isenableddisableenable)Zhave_gcrkrkrl disable_gcs  rcCs6tdp d}d}|D]}|dr|}q|dkS)z,Find if Python was built with optimizations.Z PY_CFLAGSrz-O)rz-O0z-Og) sysconfigget_config_varrr)ZcflagsZ final_optrrkrkrlpython_is_optimizeds   rZnPZ0nZ getobjectsZ2PZ0PrcCstt|tSr)structcalcsize_header_alignZfmtrkrkrl calcobjsizesrcCstt|tSr)rr_vheaderrrrkrkrl calcvobjsizesri@icCspddl}t|}t|tkr(|jt@sBt|tkrLt|jt@rL||j7}dt|||f}||||dS)Nrz&wrong size for %s: got %d, expected %d) _testcapir getsizeofr __flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADrf)rzosizerrrrkrkrl check_sizeofs     rcsfdd}|S)Ncs$fdd}j|_j|_|S)Nc sz ddl}t|}||}Wn(tk r6YnBd}}Yn0XD](}z|||WqxWqNYqNXqNz||WS|r|r|||XdSr)localer setlocaler)rxkwdsrruZ orig_localeZloc)catstrrlocalesrkrlinners$   z1run_with_locale..decorator..innerrgrjrrrrrrlrsz"run_with_locale..decoratorrk)rrrrkr rlrXscsfdd}|S)Ncs"fdd}j|_j|_|S)Nc sz tj}Wntk r(tdYnXdtjkr@tjd}nd}tjd<|z||WS|dkrvtjd=n |tjd<tXdS)Nztzset requiredZTZ)rtzsetrrrrr)rxrr Zorig_tz)rtzrkrlrs      z-run_with_tz..decorator..innerr r r rrlrszrun_with_tz..decoratorrk)r rrkrrlr_s ircCsdttdtd}td|tjtjB}|dkr>td|ftt| d|| d }|a |t krrt }|t dkrtd|f|adS)Nr)rmgtz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rrr?z$Memory limit %r too low to be useful)_1M_1Grr IGNORECASEVERBOSErrfloatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitZsizesrZmemlimitrkrkrlr\s" $ c@s(eZdZdZddZddZddZdS) _MemoryWatchdogz`An object which periodically watches the process' memory consumption and prints it out. cCsdjtd|_d|_dS)Nz/proc/{pid}/statm)rFF)rrrDprocfilestartedrrkrkrlr,sz_MemoryWatchdog.__init__c Cszt|jd}WnDtk rT}z&td|ttj WYdSd}~XYnX|(t d}t j tj |g|t jd|_W5QRXd|_dS)Nrz!/proc not available for stats: {}zmemory_watchdog.py)rrT)rSrrrnrrrrrflushr subprocessPopen executableZDEVNULL mem_watchdogr )rwrr Zwatchdog_scriptrkrkrlstart0s   z_MemoryWatchdog.startcCs|jr|j|jdSr)r r&Z terminatewaitrrkrkrlstop@s z_MemoryWatchdog.stopN)rgrhrirjrr'r)rkrkrkrlr'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||WS|r| XdS)Ni'not enough memory: %.1fG minimum needed@z* ... expected peak memory use: {peak:.1f}G)Zpeak) rmemuserrrrrrrr'r))rwrr,maxsizeZwatchdog)dry_runrr{rkrlr{Ts2    z.bigmemtest..decorator..wrapper)rr,rr.r,rrr{rlrSszbigmemtest..decoratorrk)rr,r.rrkr/rlr4Fs !csfdd}|S)z0Decorator for tests that fill the address space.csDttkr8tdkr$tdkr$tdq@tdtdn|SdS)Nllz-not enough memory: try a 32-bit build insteadr*r+)rrrrrrrkrlr{xsz!bigaddrspacetest..wrapperrkr0rkrrlr5vs c@seZdZddZdS)r-cCst}|||Sr)rZ TestResult)rwrzrrkrkrlrunszBasicTestRunner.runN)rgrhrir1rkrkrkrlr-scCs|Srrk)rrkrkrl_idsr2cCs:|dkrtsttjSt|r&tStd|SdS)Nr zresource {0!r} is not enabled)rrrrr r2rr rkrkrlrequires_resources  r3cCstdd|S)z9 Decorator for tests only applicable on CPython. T)cpython) impl_detailrrkrkrlr6scKsVtf|rtS|dkrLt|\}}|r,d}nd}t|}|d|}t|S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or ) rDr2 _parse_guardsrZrrrrr)rguardsZ guardnamesdefaultrkrkrlr5s   r5cCsH|sddidfSt|d}t||gt|ks>t|| fS)Nr4TFr)rvaluesrr1)r7Zis_truerkrkrlr6s  r6cKs 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 )r6rrZpython_implementationr)r7r8rkrkrlrDs cs,ttdsStfdd}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.gettracec s2t}ztd||WSt|XdSr)rr:settrace)rxryZoriginal_tracerrkrlr{s  zno_tracing..wrapperN)rrr}r~rrkrrl no_tracings  r<cCs tt|S)aDecorator for tests which involve reference counting. To start, the decorator does not run the test if is not run by CPython. After that, any trace function is unset during the test to prevent unexpected refcounts caused by the trace function. )r<r6rrkrkrl refcount_testsr=cCsNg}|jD]8}t|tjr0t||||q ||r ||q ||_dS)z>Recursively filter test cases in a suite based on a predicate.N)Z_testsrr TestSuite _filter_suiter)suiteZpredZnewtestsrzrkrkrlr?s     r?cCsttjttdk d}||}tdk r4t||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_listr1rZget_xml_elementZtestsRunZskippedr Z wasSuccessfulrrZfailuresr )r@Zrunnerrrrkrkrl _run_suites$  rCcCstdkr dSt|SdSNT)_match_test_funcidrrkrkrl match_testsrGcCsd|kotd| S)Nrz[?*\[\]])rsearch)rrkrkrl_is_full_match_testsrIcs~|dkr d}|dkrd}d|tkr4t|\}|tkrHt|\}t|at|adk shdk rzfdd}|adS)Nrkcs*d}d}r|}r |}|o(| S)NTFrk)test_idZacceptrmZ accept_funcZ ignore_funcrkrlmatch_function.sz'set_match_tests..match_function)_accept_test_patterns_compile_match_function_ignore_test_patternsrrE)Zaccept_patternsZignore_patternsrLrkrKrlset_match_testss   rPcs^|sd}d}nHttt|r(t|j}n.dttj|}t |j fdd}|}||fS)Nrk|cs$|r dStt|dSdS)NTr)anyrr)rJZ regex_matchrkrlmatch_test_regexIsz1_compile_match_function..match_test_regex) allrrIr __contains__rfnmatch translaterrdr)ZpatternsrZregexrTrkrSrlrN:s   rNcGstjtjf}t}|D]`}t|trR|tjkrH|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)rr>ZTestCaserrrrZaddTestZ findTestCasesrZ makeSuiter?rGrC)classesZ valid_typesr@clsrkrkrlr.Ys       cCsdS)z,Just used to check if docstrings are enabledNrkrkrkrkrl_check_docstringspsr[ZWITH_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 rrg)rrAr\r]rrrkrkrlr/scCs(|D]}td|tjddqdS)Nz Warning -- T)rr") splitlinesrrr)rlinerkrkrl print_warnings r`cCs tjfSr)rrrrkrkrkrl modules_setupsracCs:ddtjD}tjtj|tj|dS)NcSs"g|]\}}|dr||fqS)z encodings.)r)rXrrrkrkrlrYs z#modules_cleanup..)rrrrr)Z oldmodulesZ encodingsrkrkrlmodules_cleanups  rbcCsttjfSr)_thread_count threading _danglingrrkrkrkrlrPsc 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?) rangercrdrerfenvironment_alteredr`rrrr)Zoriginal_valuesZ _MAX_COUNTcountr9Zdangling_threadsthreadrkrkrlrQs 0 cstfdd}|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 |WSt|XdSr)rPrQ)rxkeyrrkrlrs zreap_threads..decoratorr|)rrrkrrlrRsN@ccst}z dVW5t}||}t}||kr6qt|krzt|}d||d|dd|d|d }t|tdtq$XdS) 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. z!wait_threads() failed to cleanup z threads after .1fz seconds (count: z , old count: rhriN)rcrdr monotonicr1rr)rZ old_countZ start_timeZdeadlinerlZdtrrkrkrlwait_threads_exits   $ rrcCs,|||r(d|dd}t|dS)zcJoin a thread. Raise an AssertionError if the thread is still alive after timeout seconds. zfailed to join the thread in rpz secondsN)ris_aliver1)rmrrrkrkrl join_thread s rtcCsjttdrttdsdSztdtj\}}Wntk rFYqfYnX|dkrRqftd|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. waitpidWNOHANGNrvrz%reap_children() reaped child process T)rrrurvrr`rk)rFZstatusrkrkrlrN# s  ccs t|}g}zVz |D]}|||qWn*t rRt d t|t|fYnXdVW5z|rp|t}}t ddD]\}|d7}|D]}| t |tdqdd|D}|sqt rt d t||fqW5dd|D}|rttjtdt|XXdS) NcSsg|]}|r|qSrkrsrXrrkrkrlrY^ sz!start_threads..zUnable to join %d threadsr<ricSsg|]}|r|qSrkrwrxrkrkrlrYW sz7Unable to join %d threads during a period of %d minutesz/Can't start %d threads, only %d threads started)r faulthandlerZdump_tracebackrrr1rrrqrjrmaxrrr'r)ZthreadsZunlockr ZendtimeZ starttimerrrkrkrlrS? sB    c csnt||rJ sz4PythonSymlink._platform_specific..Z PYTHONHOMETZ PYTHONPATH)_winapirrlexistsrrPZGetModuleFileNamerZ dllhandlerrrrrbasenameglobescaperrrZis_python_buildr)rwrrZsrc_dirZdest_dirZruntimerkrkrlr5 s&    cCsJt|j|j|j|j|jD] \}}t|||j|q$|Sr)rrrrrrr)rwrrrkrkrlrO s  zPythonSymlink.__enter__c CsV|jD]J}zt|Wqtk rN}ztr>td||W5d}~XYqXqdS)Nzfailed to clean up {}: {})rrrIOErrorrrr)rwexc_type exc_valueZexc_tbrZexrkrkrlrW s  zPythonSymlink.__exit__cCsp|f|}tj|tjtj|d}|}|j|krltr\tt|dtt|dtj dt d |j|S)N)rrenvrrrz'unexpected return code: {0} (0x{0:08X})) r#r$PIPE communicate returncoderrreprrr RuntimeErrorr)rwZpythonrxrrcmdrr!rkrkrl_call_ s    zPythonSymlink._callr)rcGs||j|d|Sr)rrrwrrxrkrkrl call_reall szPythonSymlink.call_realcGs||j||j|Sr)rrrrrkrkrl call_linko szPythonSymlink.call_link)N) rgrhrirjrrrrrrrrrrkrkrkrlr% s   rc Cstdk r tSttdsd}nt}tj|d\}}zt td}z`t |ddt |ddt | ddt }td |}|dkpt|d d k}Wntk rd}YnXW5QRXW5ttt|t|X|a|S) NsetxattrFdirr\s user.testrs trusted.foos42z 2.6.(\d{1,2})r') _can_xattrrrr@rAZmkstemprrrrSrr]rrrrrrr)rZtmp_dirZtmp_fpZtmp_namefpZkernel_versionrrkrkrl can_xattrt s,    rcCs t}d}|r|St||S)zDSkip decorator for tests that require functional extended attributesz(no non-broken extended attribute support)rrrrrkrkrlr9 scCs$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_EXTENDEDrrrrkrkrlskip_if_pgo_task s rc Csttdstd|Stdkrtd}ttjP}z>z||daWn&t k rp}z|aW5d}~XYnXW5t|XW5QRXtrdt}t||S|SdS)zCDecorator for tests requiring a functional bind() for unix sockets.r0zNo UNIX SocketsNZcan_bind_unix_socketFz%Requires a functional unix bind(): %s) rr&rr_bind_nix_socket_errorrr0rr.r)rzrr/r rrkrkrlr? s  c Csxtj|db}|j}|}||kr,|}ztj||WW5QRStk rhYW5QRdSXW5QRXdS)zKDetects if the file system for the specified directory is case-insensitive.rFN) r@ZNamedTemporaryFilerrrrrsamefiler)Z directorybase base_pathZ case_pathrkrkrlr srrcCs>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)___N)rendswith)rXrrkrkrl s z&detect_api_mismatch..)rr)Zref_apiZ other_apirmZ missing_itemsrkrkrlr= s  cCs|dkr|jf}nt|tr"|f}t|}t|D]R}|ds2||krJq2t||}t|dd|kszt|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) Nrrh) rgrrrrrrrtypes ModuleTypeaddZassertCountEqual__all__)Z test_caserZname_of_moduleZextraZ blacklistZexpectedrrrkrkrlr> s )      cCsz ddl}Wntk r"YdSX||j|jB|jB|jBt|dr|j|j |j fD]2}|r| ||j | ||jq\| |dq\dS)NrCrtSetReportMode)msvcrtr SetErrorModeZSEM_FAILCRITICALERRORSZSEM_NOALIGNMENTFAULTEXCEPTSEM_NOGPFAULTERRORBOXZSEM_NOOPENFILEERRORBOXrCRT_WARN CRT_ERROR CRT_ASSERTrCRTDBG_MODE_FILECrtSetReportFileCRTDBG_FILE_STDERR)rrrrkrkrlsuppress_msvcrt_asserts s"  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 CsVtjdrz ddl}Wntk r.YdSX||j|_||j|jBt|dri|_ |j |j |j fD].}| ||j}|||j}||f|j |<qpntdk rz*ttj|_ttjd|jdfWnttfk rYnXtjdkrRddd d g}tj|tjtjd }||d}W5QRX|d krRtd ddd|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. rrNrrrz/usr/bin/defaultsrzcom.apple.CrashReporterZ DialogType)rrs developerz:this test triggers the Crash Reporter, that is intentionalrT)endr")rrrrrrr old_valuer old_modesrrrrrrrr Z getrlimit RLIMIT_CORE setrlimitrrr#r$rrrr)rwr report_typeold_modeold_filerprocrrkrkrlr* sZ     zSuppressCrashReport.__enter__c Gs|jdkrdStjdrfddl}||j|jr|jD]$\}\}}|||| ||q>n6t dk rzt t j |jWnt tfk rYnXdS)zARestore Windows ErrorMode or core file behavior to initial value.Nrr)rrrrrrrrrrr rrrr)rwrrrrrrkrkrlrh s    zSuppressCrashReport.__exit__)rgrhrirjrrrrrkrkrkrlr]! s >c srtdzjWn$ttfk r@tdYnXdfdd}||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)rr}rkZ attr_is_local attr_nameobject_to_patchrrkrlcleanup szpatch..cleanup)rrrrZ addCleanupr)Z test_instancerrZ new_valuerrkrrlpatch} s  rcCsFz ddl}Wntk r YnX|r4tdddl}||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_tracingrrrrun_in_subinterp)rrrrkrkrlr s  rcsHGfddd|}d||||ttt|dS)NcseZdZfddZdS)z%check_free_after_iterating..Acs*dz tWntk r$YnXdSrD)next StopIterationrZdoneitrkrl__del__ s  z-check_free_after_iterating..A.__del__N)rgrhrirrkrrkrlA srF)Z assertRaisesrrrrp)rzrrZrxrrkrrlcheck_free_after_iterating s   rcCsddlm}m}m}|}|||jD]Z}|r>||kr>q,t||}|rb|dk shtd|n|shq,| |ddkr,|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) ccompilerrspawnNz%the '%s' executable is not configured) Z distutilsrrrZ new_compilerZcustomize_compilerZ executablesrr1Zfind_executable)Z cmd_namesrrrZcompilerrrrkrkrlra s      cCs@d}tr6||kr6tdkr.tddgdkatr6|}t|S)Ngh㈵>Zgetpropzro.kernel.qemu1)rC_is_android_emulatorr#Z check_outputrrrF)ZintervalZminimum_intervalrkrkrlrF s c cs>tj}t}ztdVW5|r8tj|ddXdS)NT)rZ all_threads)rrr]r{ is_enabledrr)rWrrkrkrldisable_faulthandler s  rc Csvtjdr:ztd}t|dWStk r8YnXd}ttdrlztd}Wnt k rjYnXd}tjdkrzd dl }|j Wnt t fk rYn,Xi}|j|j|jfD]}| |d ||<qzld }t|D]Z}zt|}Wn4t k r$}z|jtjkrW5d}~XYqXt||d7}qW5|dk rp|j|j|jfD]}| |||qXX|S) z/Count the number of open file descriptors. )linuxZfreebsdz /proc/self/fdrsysconf SC_OPEN_MAXNr8r)rrrrrrrrrrrrrrrrrrjduprZEBADFr3) namesZMAXFDrrrrlrWZfd2r rkrkrlrb sT        c@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]8}zt||}Wntk rFYqYnX|j|qi|_dS)Nr)SIGKILLSIGSTOP)signal valid_signalssignalsrrrr)rwrZsignamesignumrkrkrlrB s  zSaveSignals.__init__cCs0|jD]$}|j|}|dkr q||j|<qdSr)rr getsignalrrwrZhandlerrkrkrlsaveO s   zSaveSignals.savecCs&|jD]\}}|j||q dSr)rrrrrkrkrlrestore[ szSaveSignals.restoreN)rgrhrirjrrr rkrkrkrlr9 s  rcCsddl}|jSr)rZ WITH_PYMALLOC)rrkrkrl with_pymalloc` sr c@s(eZdZdZddZddZddZdS) FakePathz.Simple implementing of the path protocol. cCs ||_dSrr)rwrrkrkrlrh szFakePath.__init__cCsd|jdS)Nz rrrkrkrl__repr__k szFakePath.__repr__cCs6t|jts$t|jtr,t|jtr,|jn|jSdSr)rr BaseExceptionrrqrrkrkrl __fspath__n s   zFakePath.__fspath__N)rgrhrirjrr rrkrkrkrlr e sr c@s eZdZdZddZddZdS) _ALWAYS_EQz+ Object that is equal to anything. cCsdSrDrkrwotherrkrkrl__eq__{ sz_ALWAYS_EQ.__eq__cCsdSrrkrrkrkrl__ne__} sz_ALWAYS_EQ.__ne__N)rgrhrirjrrrkrkrkrlrw src@s eZdZdZddZddZdS)_LARGESTz? Object that is greater than anything (except itself). cCs t|tSr)rrrrkrkrlr sz_LARGEST.__eq__cCsdSrrkrrkrkrl__lt__ sz_LARGEST.__lt__N)rgrhrirjrrrkrkrkrlr src@s eZdZdZddZddZdS) _SMALLESTz< Object that is less than anything (except itself). cCs t|tSr)rrrrkrkrlr sz_SMALLEST.__eq__cCsdSrrkrrkrkrl__gt__ sz_SMALLEST.__gt__N)rgrhrirjrrrkrkrkrlr srcCstjjS)zDReturn the global event loop policy if one is set, else return None.)asyncioZeventsZ_event_loop_policyrkrkrkrlmaybe_get_event_loop_policy sr) @c Cs||}}ddl}|}|d}t|d|_||}|d||}||} || } || } ||d|d||| d| } t| t| fW5QRSQRXdS)Nrrr)decimalZ localcontext bit_lengthr|ZprecZDecimalrZsqrt) ZnbinsZnballsrrrctxbitsrQZp1emptyZ meanemptyZoccupiedZ collisionsvarrkrkrlcollision_stats s     (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|_dSr) unraisable _old_hookrrkrkrlr sz#catch_unraisable_exception.__init__cCs ||_dSr)r%)rwr%rkrkrl_hook sz catch_unraisable_exception._hookcCstj|_|jt_|Sr)runraisablehookr&r'rrkrkrlr sz$catch_unraisable_exception.__enter__cGs|jt_|`dSr)r&rr(r%rwexc_inforkrkrlr sz#catch_unraisable_exception.__exit__Nrgrhrirjrr'rrrkrkrkrlr$ s r$c@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)rr exc_tracebackrmr&rrkrkrlr s z"catch_threading_exception.__init__cCs$|j|_|j|_|j|_|j|_dSr)rrr-rm)rwrxrkrkrlr' szcatch_threading_exception._hookcCstj|_|jt_|Sr)re excepthookr&r'rrkrkrlr sz#catch_threading_exception.__enter__cGs|jt_|`|`|`|`dSr)r&rer.rrr-rmr)rkrkrlr% s z"catch_threading_exception.__exit__Nr+rkrkrkrlr, s r,c cs.tjdd}z dVW5|tjdd<XdSr)rnr)Z old_filtersrkrkrlsave_restore_warnings_filters- s r/c Csbtdtd}tjdkr^z|jddWn2tk r\}ztd|W5d}~XYnXdS)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)r z broken multiprocessing SemLock: )r rrZLockrrr)Z synchronizerrkrkrl*skip_if_broken_multiprocessing_synchronize6 s r0)T)F)rkrkF)F)N)N)NF)F)rKF)N)r)r)F)T)N)NN)Nr)ro)r)N)Nrkrk)F)rk(5rjrgrZasyncio.eventsrZcollections.abc collections contextlibrr{rWr}rrr"rimportlib.utilrZlogging.handlersrrrrrrr&rrr#rrr@rcrerrrZ urllib.errorrrnZ testresultrZmultiprocessing.processZmultiprocessingzlibrzbz2Zlzmar r rrr r r rr contextmanagerrsrAr rrr;r<rr7rrrrrBrrrrrrrrrrrrrrrrrrr r!rr"r#r$r%rGZHOSTv4r4r,r-rIrJrLr5rHr7rZ SOCK_MAX_SIZEZ skipUnlessr __getformat__r8r:r1r2r3rBrrCrErrrrDZ TEST_HTTP_URLZ FS_NONASCII characterfsdecodefsencode UnicodeErrorZTESTFN_UNICODE unicodedataZ normalizegetfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversionencodeUnicodeEncodeErrorrdecodeUnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIrHrr`rrGrJrrMrrrrZTEST_SUPPORT_DIRrOrr~rrr^r^r&r'rKobjectrrrTrrVrUrabcMutableMappingrWrr(rrr)rr*r+rr,rrrrrrrrrrrrrrrrXr_rrrZ_4Gr-rr\rr4r5r-r2r3r6r5r6rDr<r=r?rCrErMrOrGrIrPrNr.r[rZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr/r`rarbrkrPrQrRrrrtrNrSrZrYrrZrequires_type_collectingrrrrrOr[rrr0rr@rrrr9rrr?rr=r>rr]rrrrarrFrrbrr r rrctotal_orderingrrdrrer hash_infowidthZ NHASHBITSr1r#r$r,r/r0rkrkrkrls               0  2   !  J    = %         !      &      2 '   5M           $ #   0        !           " #    "   N   ;\"  ;'   ",9