Yf Q@sdZedkredddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl ZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZyddl Z ddl!Z!Wnek rdZ dZ!YnXyddl"Z#Wnek rdZ#YnXyddl$Z$Wnek rdZ$YnXyddl%Z%Wnek rdZ%YnXyddl&Z&Wnek r>dZ&YnXyddl'Z'Wnek ridZ'YnXyddl(Z(Wnek rdZ(YnXddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUgQZ)GdVd d e*Z+GdWd d e+Z,GdXd d ej-Z.ej/dYdZd[Z0d\d]fd^d Z1d_d`Z2dadbZ3dcd9Z4ddd:Z5ffd\dedZ6dfd5Z7dgZ8dZ9da:da;d\Z<da=da>dhdZ?didZ@djdZAdkdlZBejjCdmrd\dndoZDdpdqZEdrdsZFdtduZGnejHZEejIZFdvduZGdwdZHdxdyZIdzdZJd{d|ZKd}dZLd~dZMdd ZNddd!ZOddZPdd"ZQdd#ZRdd$ZSdZTdZUejVejWddAZXeTddBZYddZZeZZ[ddZ\d;Z]d>Z^ej_e`jadjCddZbej_e$dZcej_e%dZdej_e&dZeej_e'dZfejjCdZgejhdkrdZindZidjjeiejkZidZlxDd?D]<ZmyejnejoemWnepk rYqXemZlPqWeidZqejdkr<ddlrZrerjsdeqZqejtZudZvejhd@krejwjdkr eidZvyevjxeuWneyk rYq XezdeveufdZvnKejdkr ydj{euWn(e|k r eidj{eudZvYnXdZ}xHdAD]@Zhyehj{euWqe|k rVejoeiehZ}PYqXqWelrreidelZ~ndZ~ejZej/dd\ddZej/d\ddZej/dd\ddZeedrej/ddDZejjejjeZejjeZejjedZdddZddZddTZddZdddddd%ZddCZGdddeZd\ddZej/ddKZej/ddLZGdddeZGddMdMejjZGdddeZGdd&d&eZeedejZeedejZeedejZej/dddfdd*Zej/ddZddZddZddZddZej/ddZddZdZdZeedr0 deZdZedZddZddZdBZdCZddZddNZddUZdDZdeZdeZdeZejZddRZGdddZdYdd2Zdd3ZGdd+d+ZddZddZdd4ZdddZdadd<ZddZdd>ZddZdd Zd d Zd d ZddZdd,ZddZeo ejdko ejd Zejdk o e Zej_edZdddd-ZddZddZddGZddHZddIZddEZej/dddJZej/d dPZej/d!dOZd"d#Zejeed$d%Zd&d'ZGd(dFdFejjZGd)dQdQeZdad*dZd+d.Zdad,d-Zd.d7Zd/dZd0fd1d;ZGd2dSdSZd3d4Zd5d6Zfd7d8ZdS(Ez7Supporting definitions for the Python regression tests.z test.supportz.support must be imported from the test packageN PIPE_MAX_SIZEverbose max_memuse use_resourcesfailfastError TestFailedResourceDenied import_moduleimport_fresh_module CleanImportunloadforgetrecord_original_stdoutget_original_stdoutcaptured_stdoutcaptured_stdincaptured_stderrTESTFNSAVEDCWDunlinkrmtreetemp_cwdfindfilecreate_empty_file can_symlinkfs_is_case_insensitiveis_resource_enabledrequiresrequires_freebsd_versionrequires_linux_versionrequires_mac_vercheck_syntax_errorTransientResourcetime_outsocket_peer_resetioerror_peer_resettransient_internetBasicTestRunner run_unittest run_doctestskip_unless_symlink requires_gzip requires_bz2 requires_lzma bigmemtestbigaddrspacetest cpython_only get_attributerequires_IEEE_754skip_unless_xattr requires_zlibanticipate_failureload_package_testsdetect_api_mismatchrequires_multiprocessing_queue is_jythoncheck_impl_detailHOST IPV6_ENABLEDfind_unused_port bind_portopen_urlresource temp_umask reap_children TestHandlerthreading_setupthreading_cleanup reap_threads start_threadscheck_warningscheck_no_resource_warningEnvironmentVarGuardrun_with_locale swap_item swap_attrMatcher set_memlimitSuppressCrashReportsortdict run_with_tzc@seZdZdZdS)rz*Base class for regression test exceptions.N)__name__ __module__ __qualname____doc__rWrW:/opt/alt/python35/lib64/python3.5/test/support/__init__.pyrns c@seZdZdZdS)rz Test failed.N)rSrTrUrVrWrWrWrXrqs 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. N)rSrTrUrVrWrWrWrXr ts Tc cs>|r5tjtjddtdVWdQRXndVdS)zContext manager to suppress package and module deprecation warnings when importing them. If ignore is False, this context manager has no effect. ignorez.+ (module|package)N)warningscatch_warningsfilterwarningsDeprecationWarning)rYrWrWrX_ignore_deprecated_imports|s   r^F required_oncCst|nytj|SWnUtk ru}z5tjjt|rNtj t |WYdd}~XnXWdQRXdS)acImport and return the module to be tested, raising SkipTest if it is not available. If deprecated is True, any module or package deprecation messages will be suppressed. If a module is required on a platform but optional for others, set required_on to an iterable of platform prefixes which will be compared against sys.platform. N) r^ importlibr ImportErrorsysplatform startswithtupleunittestSkipTeststr)name deprecatedr_msgrWrWrXr s cCs{|tjkr#t|tj|=xQttjD]@}||ksX|j|dr3tj|||sz$anticipate_failure..)rfZexpectedFailure)Z conditionrWrWrXr6scCsk|dkrd}tjjtjjtjjt}|jd|d|d|}|j||S)zGeneric load_tests implementation for simple test packages. Most packages can implement load_tests using this function as follows: def load_tests(*args): return load_package_tests(os.path.dirname(__file__), *args) Nztest*Z start_dirZ top_level_dirpattern)ospathdirname__file__ZdiscoverZaddTests)Zpkg_dirloaderZstandard_testsrwZtop_dirZ package_testsrWrWrXr7s     c Cst|i}g}t||z}y^x|D]}t||q3Wx*|D]"}t||sQ|j|qQWtj|}Wntk rd}YnXWdx'|jD]\} } | tj | ._rmtree_innerrTcSst|tj|S)N)rrxr)prWrWrXrvnsz_rmtree..)r)ryrW)rrX_rmtree^src sWytj|dSWntk r)YnXfdd|tj|dS)Nc sxt|tj|D]}tjj||}ytj|j}Wntk rad}YnXtj |r|t|tj |qt|tj |qWdS)Nr) rrxrryrrrrrrrr)ryrirr)rrWrXrzs   z_rmtree.._rmtree_inner)shutilrrrxr)ryrW)rrXrss   c Cs-yt|Wnttfk r(YnXdS)N)rFileNotFoundErrorNotADirectoryError)rrWrWrXrsc Cs'yt|Wntk r"YnXdS)N)rr)rzrWrWrXrs rc Cs'yt|Wntk r"YnXdS)N)rr)ryrWrWrXrs cCs]tjj|}tjjtjj|}tjj||d}tj|||S)aMove a PEP 3147/488 pyc file to its legacy pyc location. :param source: The file system path to the source file. The source file does not need to exist, however the PEP 3147/488 pyc file must exist. :return: The file system path to the legacy pyc file. c) r`utilcache_from_sourcerxryrzabspathrrename)sourceZpyc_fileZup_oneZ legacy_pycrWrWrXmake_legacy_pycs rcCsvt|xetjD]Z}tjj||d}t|dx*dD]"}ttjj|d|qHWqWdS) z'Forget' a module was ever imported. This removes the module from sys.modules and deletes any PEP 3147/488 or legacy .pyc files. z.pyrrr optimizationN)rrr) r rbryrxrrr`rr)rqrzroptrWrWrXrs   csttdrtjSd}tjjdrddlddld}d}Gfdddj}j j }|j }|sj |}j j}|j||j|j|j|}|sj t|j|@sd}ntjdkrdd lm} mm} m} dd lm} | j| d } | jdkrd }naGfd dd| }|}| |}| j|dks| j|dkrd}|sy;ddlm}|}|j|j |j!Wnrt"k r}zRt#|}t$|dkrq|ddd}dj%t&|j'|}WYdd}~XnX|t_(| t_tjS)NresultrrrcsCeZdZdjjfdjjfdjjfgZdS)z*_is_gui_available..USEROBJECTFLAGSZfInheritZ fReserveddwFlagsN)rSrTrUwintypesZBOOLDWORD_fields_rW)ctypesrWrXUSEROBJECTFLAGSs rz,gui not available (WSF_VISIBLE flag not set)darwin)cdllc_intpointer Structure) find_libraryZApplicationServicesz0gui tests cannot run without OS X window managercs(eZdZdfdfgZdS)z._is_gui_available..ProcessSerialNumberZ highLongOfPSNZ lowLongOfPSNN)rSrTrUrrW)rrWrXProcessSerialNumbers  rz#cannot run without OS X gui process)Tk2z [...]zTk unavailable due to {}: {}))hasattr_is_gui_availablerrbrcrdrZctypes.wintypesrwindllZuser32ZGetProcessWindowStationZWinErrorrrZGetUserObjectInformationWZbyrefZsizeofboolrrrrZ ctypes.utilrZ LoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterrZwithdrawupdateZdestroy ExceptionrhlenformattyperSreason)rZ UOI_FLAGSZ WSF_VISIBLErZdllhZuofZneededresrrrrZ app_servicesrZpsnZpsn_prrooteZ err_stringrW)rrrXrsh           "         rcCstdkp|tkS)zTest whether a resource is enabled. Known resources are set by regrtest.py. If not running under regrtest.py, all resources are assumed enabled unless use_resources has been set. N)r)resourcerWrWrXrscCsWt|s.|dkr"d|}t||dkrSt rSttjdS)z@Raise ResourceDenied if the specified resource is not available.Nz"Use of the %r resource not enabledgui)rr rr)rrkrWrWrXr s     csfdd}|S)zDecorator raising SkipTest if the OS is `sysname` and the version is less than `min_version`. For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if the FreeBSD version is less than 7.2. cs4tjfdd}|_|S)Nc stjkrtjjddd}y"ttt|jd}Wntk rdYnAX|krdjtt }t j d||f||S)N-rrrlz(%s version %s or higher required, not %s) rcsystemreleaserremapint ValueErrorrrhrfrg)rkw version_txtversionmin_version_txt)r min_versionsysnamerWrXwrappers"  z:_requires_unix_version..decorator..wrapper) functoolswrapsr)rr)rr)rrX decorators' z)_requires_unix_version..decoratorrW)rrrrW)rrrX_requires_unix_versionsrcGs td|S)zDecorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is less than `min_version`. For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD version is less than 7.2. ZFreeBSD)r)rrWrWrXr.scGs td|S)zDecorator raising SkipTest if the OS is Linux and the Linux version is less than `min_version`. For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux version is less than 2.6.32. ZLinux)r)rrWrWrXr 7scsfdd}|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. cs1tjfdd}|_|S)Nc stjdkrtjd}y"ttt|jd}Wntk rUYn>X|krdjtt }t j d||f||S)Nrrrlz&Mac OS X %s or higher required, not %s) rbrcZmac_verrerrrrrrhrfrg)rrrrr)rrrWrXrHs"  z4requires_mac_ver..decorator..wrapper)rrr)rr)r)rrXrGs$ z#requires_mac_ver..decoratorrW)rrrW)rrXr!@sz 127.0.0.1z::1cCs/tj||}t|}|j~|S)a Returns an unused port that should be suitable for binding. This is achieved by creating a temporary socket with the same family and type as the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to the specified host address (defaults to 0.0.0.0) with the port set to 0, eliciting an unused ephemeral port from the OS. The temporary socket is then closed and deleted, and the ephemeral port is returned. Either this method or bind_port() should be used for any tests where a server socket needs to be bound to a particular port for the duration of the test. Which one to use depends on whether the calling code is creating a python socket, or if an unused port needs to be provided in a constructor or passed to an external program (i.e. the -accept argument to openssl's s_server mode). Always prefer bind_port() over find_unused_port() where possible. Hard coded ports should *NEVER* be used. As soon as a server socket is bound to a hard coded port, the ability to run multiple instances of the test simultaneously on the same host is compromised, which makes the test a ticking time bomb in a buildbot environment. On Unix buildbots, this may simply manifest as a failed test, which can be recovered from without intervention in most cases, but on Windows, the entire python process can completely and utterly wedge, requiring someone to log in to the buildbot and manually kill the affected process. (This is easy to reproduce on Windows, unfortunately, and can be traced to the SO_REUSEADDR socket option having different semantics on Windows versus Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind, listen and then accept connections on identical host/ports. An EADDRINUSE OSError will be raised at some point (depending on the platform and the order bind and listen were called on each socket). However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE will ever be raised when attempting to bind two identical host/ports. When accept() is called on each socket, the second caller's process will steal the port from the first caller, leaving them both in an awkwardly wedged state where they'll no longer respond to any signals or graceful kills, and must be forcibly killed via OpenProcess()/TerminateProcess(). The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option instead of SO_REUSEADDR, which effectively affords the same semantics as SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open Source world compared to Windows ones, this is a common mistake. A quick look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when openssl.exe is called with the 's_server' option, for example. See http://bugs.python.org/issue2550 for more info. The following site also has a very thorough description about the implications of both REUSEADDR and EXCLUSIVEADDRUSE on Windows: http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx) XXX: although this approach is a vast improvement on previous attempts to elicit unused ports, it rests heavily on the assumption that the ephemeral port returned to us by the OS won't immediately be dished back out to some other process when we close and delete our temporary socket but before our calling code has a chance to bind the returned port. We can deal with this issue if/when we come across it. )socketr?close)familyZsocktypeZtempsockportrWrWrXr>bs 8  c Cs |jtjkr|jtjkrttdr]|jtjtjdkr]t dttdrdt j kry.|jtjtj dkrt dWnt k rYnXttdr|jtjtjd|j|df|jd}|S) a%Bind the socket to a free port and return the port number. Relies on ephemeral ports in order to ensure we are using an unbound port. This is important as many tests may be running simultaneously, especially in a buildbot environment. This method raises an exception if the sock.family is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR or SO_REUSEPORT set on it. Tests should *never* set these socket options for TCP/IP sockets. The only case for setting these options is testing multicasting via multiple UDP sockets. Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. on Windows), it will be set on the socket. This will prevent anyone else from bind()'ing to our host/port for the duration of the test. SO_REUSEADDRrzHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets! SO_REUSEPORTZWITHIN_PYTHON_RPM_BUILDzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!SO_EXCLUSIVEADDRUSEr)rrAF_INETr SOCK_STREAMrZ getsockoptZ SOL_SOCKETrrrxenvironrrZ setsockoptrbindZ getsockname)sockhostrrWrWrXr?s $  cCsstjrod}zLy3tjtjtj}|jtdfdSWntk rYYnXWd|rn|jXdS)z+Check whether IPv6 is enabled on this host.NrTF)rZhas_ipv6ZAF_INET6rrHOSTv6rr)rrWrWrX_is_ipv6_enableds    rcs%tjfdd}|S)z5Skip the test on TLS certificate validation failures.csay||WnItk r\}z)dt|krGtjdWYdd}~XnXdS)NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)IOErrorrhrfrg)rkwargsr)rurWrXdecs z&system_must_validate_cert..dec)rr)rurrW)rurXsystem_must_validate_certs! rriZdoubleZIEEEztest requires IEEE 754 doublesz requires zlibz requires gzipz requires bz2z requires lzmajavaz$testz@testz {}_{}_tmpæİŁφКא،تก €u -àòɘŁğrZNFDntceru-共Ł♡ͣztWARNING: The filename %r CAN be encoded by the filesystem encoding (%s). Unicode filename tests may not be effectives-surrogateescapewrccsd}|dkr9tj}d}tjj|}nOytj|d}Wn5tk r|sitjd|t ddYnXz |VWd|rt |XdS)aReturn a context manager that creates a temporary directory. Arguments: path: the directory to create temporarily. If omitted or None, defaults to creating a temporary directory using tempfile.mkdtemp. quiet: if False (the default), the context manager raises an exception on error. Otherwise, if the path is specified and cannot be created, only a warning is issued. FNTz+tests may fail, unable to create temp dir: r) tempfileZmkdtemprxryrealpathmkdirrrZrrr)ryquietZ dir_createdrWrWrXtemp_dirs"       rccsytj}ytj|Wn5tk rT|s6tjd|tddYnXztjVWdtj|XdS)agReturn a context manager that changes the current working directory. Arguments: path: the directory to use as the temporary current working directory. quiet: if False (the default), the context manager raises an exception on error. Otherwise, it issues only a warning and keeps the current working directory the same. z)tests may fail, unable to change CWD to: rrN)rxgetcwdchdirrrZrr)ryrZ saved_dirrWrWrX change_cwds   rZtempcwdccsDtd|d|(}t|d| }|VWdQRXWdQRXdS)a Context manager that temporarily creates and changes the CWD. The function temporarily changes the current working directory after creating a temporary directory in the current directory with name *name*. If *name* is None, the temporary directory is created using tempfile.mkdtemp. If *quiet* is False (default) and it is not possible to create or change the CWD, an error is raised. If *quiet* is True, only a warning is raised and the original CWD is used. ryrN)rr)rirZ temp_pathZcwd_dirrWrWrXrsumaskc cs-tj|}z dVWdtj|XdS)z8Context manager that temporarily sets the process umask.N)rxr)rZoldmaskrWrWrXrAs datacCstjj|r|S|dk r7tjj||}tgtj}x9|D]1}tjj||}tjj|rN|SqNW|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)rxryisabsr TEST_HOME_DIRrbexists)rZsubdirryZdnfnrWrWrXrs  cCs4tj|tjtjBtjB}tj|dS)z>Create an empty file. If the file already exists, truncate it.N)rxopenO_WRONLYO_CREATO_TRUNCr)rfdrWrWrXrs#cCs<t|j}dd|D}dj|}d|S)z%Like repr(dict), but in sorted order.cSsg|]}d|qS)z%r: %rrW).0ZpairrWrWrX s zsortdict..z, z{%s})sortedr~r)dictr~Z reprpairsZ withcommasrWrWrXrQsc Cs9ttd}z|jSWd|jttXdS)z` Create an invalid file descriptor by opening and closing a file and return its fd. wbN)r$rfilenorr)rrWrWrX make_bad_fd s  r/linenooffsetc Cs|jt}t|ddWdQRX|j}|j|j|dk ra|j|j||j|j|dk r|j|j|dS)Nz exec) assertRaises SyntaxErrorcompileZ exceptionZassertIsNotNoner0 assertEqualr1)testcaseZ statementr0r1cmrrWrWrXr"s   c sddl}ddl}jdd|jj|djdd}tjjt |}fdd}tjj |r||}|dk r|St |t dt rtd |d t|jj}tr|jjd|j|d d}trC|jjdd krCtjd|}zOt|d9} |j} x#| r| j| |j} qgWWdQRXWd|jX||}|dk r|Std|dS)Nrcheckr/rcsMt|}dkr"|S|r?|jd|S|jdS)Nr)r$seekr)r#ru)rr9rrWrXcheck_valid_file)s   z*open_urlresource..check_valid_fileZurlfetchz fetching %s ...rAccept-EncodinggziprzContent-EncodingZfileobjr-zinvalid resource %r)r=r>)Zurllib.requestZ urllib.parsepopparseZurlparserrxryr TEST_DATA_DIRr"rrrrrZrequestZ build_openerr>Z addheadersr}r$ZheadersgetZGzipFilereadwriterr) Zurlrrurllibrr#r<ruZopeneroutsrW)rr9rrXr@ s<#           c@sLeZdZdZddZddZeddZdd Zd S) WarningsRecorderzyConvenience wrapper for the warnings list returned on entry to the warnings.catch_warnings() context manager. cCs||_d|_dS)Nr) _warnings_last)selfZ warnings_listrWrWrX__init__Vs zWarningsRecorder.__init__cCs\t|j|jkr,t|jd|S|tjjkrBdStd||fdS)Nrz%r has no attribute %rr@)rrKrLrrZWarningMessage_WARNING_DETAILSr)rMattrrWrWrX __getattr__Zs zWarningsRecorder.__getattr__cCs|j|jdS)N)rKrL)rMrWrWrXrZaszWarningsRecorder.warningscCst|j|_dS)N)rrKrL)rMrWrWrXreseteszWarningsRecorder.resetN) rSrTrUrVrNrRpropertyrZrSrWrWrWrXrJRs   rJc cs^tjd}|jjd}|r1|jtjdd&}tjdjdt |VWdQRXt |}g}x|D]\}}d} xd|ddD]R}|j } t j |t| t jrt| j|rd} |j|qW| r| r|j||jfqW|r@td |d |rZtd |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__recordTrZalwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)rb _getframe f_globalsrDclearrZr[rm simplefilterrJromessagerematchrhI issubclassrremover}rSAssertionError) filtersrframeregistrywZreraiseZmissingrkcatseenZwarningrWrWrX_filterwarningsis0   rhcOsC|jd}|s6dtff}|dkr6d}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) rrNT)rDWarningrh)rbrrrWrWrXrHs  c csOtjdd&}tjddtdVtWdQRX|j|gdS)a"Context manager to check that no ResourceWarning is emitted. Usage: with check_no_resource_warning(self): f = open(...) ... del f You must remove the object which may emit ResourceWarning before the end of the context manager. rUTrVcategoryN)rZr[r\ResourceWarning gc_collectr6)r7ZwarnsrWrWrXrIs c@s:eZdZdZddZddZddZdS) r a,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 cGsitjj|_xP|D]H}|tjkrtj|}|j|krWtj|j=tj|=qWdS)N)rbrmcopyoriginal_modulesrS)rMZ module_namesZ module_namerrWrWrXrNs   zCleanImport.__init__cCs|S)NrW)rMrWrWrX __enter__szCleanImport.__enter__cGstjj|jdS)N)rbrmrrn)rM ignore_excrWrWrX__exit__szCleanImport.__exit__N)rSrTrUrVrNrorqrWrWrWrXr s  c@seZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZdS)rJz_Class to help protect the environment variable properly. Can be used as a context manager.cCstj|_i|_dS)N)rxr_environ_changed)rMrWrWrXrNs zEnvironmentVarGuard.__init__cCs |j|S)N)rr)rMenvvarrWrWrX __getitem__szEnvironmentVarGuard.__getitem__cCs9||jkr(|jj||j|<||j|@errnosc #sdd d!d"d#g}d%d'd)d+d,g}td||gsrdd|Ddd|Dfdd}tj}z!y"|dk rtj|dVWntjk r}z/trtjj j dd|WYdd}~Xnt k r}zxr|j }t |dkr_t |dt r_|d}q$t |dkrt |dt r|d}q$Pq$W||WYdd}~XnXWdtj|XdS)-zReturn a context manager that raises ResourceDenied when various issues with the Internet connection manifest themselves as exceptions. ECONNREFUSEDo ECONNRESETh EHOSTUNREACHq ENETUNREACHe ETIMEDOUTn EAI_AGAINrEAI_FAILr EAI_NONAMEr EAI_NODATA WSANO_DATA*zResource %r is not availablecSs(g|]\}}tt||qSrW)rr)r)rinumrWrWrXr*ds z&transient_internet..cSs(g|]\}}tt||qSrW)rr)r)rirrWrWrXr*fs cst|dd}t|tjst|tjrB|kst|tjjrvd|jkoqdknst|tjj rd|j ksd|j ksd|j ks|krt st j jjdd|dS) NriiWConnectionRefusedError TimeoutErrorEOFErrorr )r isinstancerrZgaierrorrGerrorZ HTTPErrorcodeZURLErrorrrrbstderrrFr)rn)captured_errnosdenied gai_errnosrWrX filter_erroris z(transient_internet..filter_errorNrrr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)r rZgetdefaulttimeoutZsetdefaulttimeoutnntplibZNNTPTemporaryErrorrrbrrFrrrr) Z resource_namerrZdefault_errnosZdefault_gai_errnosrZ old_timeoutrarW)rrrrXr'LsN           % %  c cs[ddl}tt|}tt||jztt|VWdtt||XdS)zReturn a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO.rN)iorrbsetattrStringIO)Z stream_namerZ orig_stdoutrWrWrXcaptured_outputs  rcCs tdS)zCapture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") r)rrWrWrWrXrscCs tdS)zCapture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") r)rrWrWrWrXrscCs tdS)a Capture the input to sys.stdin: with captured_stdin() as stdin: stdin.write('hello\n') stdin.seek(0) # call test code that consumes from sys.stdin captured = input() self.assertEqual(captured, "hello") stdin)rrWrWrWrXrs cCs5tjtrtjdtjtjdS)aForce as many objects as possible to be collected. In non-CPython implementations of Python, this is needed because timely deallocation is not guaranteed by the garbage collector. (Even in CPython this can be the case in case of reference cycles.) This means that __del__ methods may be called later than expected and weakrefs may remain alive for longer than expected. This function tries its best to force all garbage objects to disappear. g?N)gcZcollectr:rrrWrWrWrXrls   rlc cs7tj}tjz dVWd|r2tjXdS)N)r isenableddisableenable)Zhave_gcrWrWrX disable_gcs    rcCsQtjdpd}d}x)|jD]}|jdr(|}q(W|dkS)z,Find if Python was built with optimizations. PY_CFLAGSrz-O-O0-Og)rrr) sysconfigget_config_varrrd)ZcflagsZ final_optrrWrWrXpython_is_optimizeds  rZnPZ0ngettotalrefcountZ2PZ0PrcCstjt|tS)N)structcalcsize_header_align)fmtrWrWrX calcobjsizesrcCstjt|tS)N)rr_vheaderr)rrWrWrX calcvobjsizesr cCsddl}tj|}t|tkr:|jt@s_t|tkrlt|jt@rl||j7}dt|||f}|j|||dS)Nrz&wrong size for %s: got %d, expected %d) _testcapirb getsizeofr __flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADr6)testosizerrrkrWrWrX check_sizeofs % rcsfdd}|S)Ncs4fdd}j|_j|_|S)Ncsy.ddl}t|}|j|}Wn&tk rEYnCd}}Yn2Xx.D]&}y|j||PWq^Yq^Xq^Wz||SWd|r|r|j||XdS)Nr)localer setlocaler)rkwdsrrjZ orig_localeloc)catstrrlocalesrWrXinner s$     z1run_with_locale..decorator..inner)rSrV)rr)rr)rrXrs  z"run_with_locale..decoratorrW)rrrrW)rrrXrKscsfdd}|S)Ncs1fdd}j|_j|_|S)Ncsy tj}Wn!tk r0tjdYnXdtjkrPtjd}nd}tjd<|z||SWd|dkrtjd=n |tjd.decorator..inner)rSrV)rr)r)rrXr,s  zrun_with_tz..decoratorrW)rrrW)rrXrR+sc Csdddtdtddti}tjd|tjtjB}|dkr`td|ftt|j d||j d j }|a |t krt }|t dkrtd |f|adS) Nrimgtz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rrrz$Memory limit %r too low to be useful)_1M_1Gr\r] IGNORECASEVERBOSErrfloatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitZsizesrZmemlimitrWrWrXrOUs  2 c@s:eZdZdZddZddZddZdS) _MemoryWatchdogz`An object which periodically watches the process' memory consumption and prints it out. cCs(djdtj|_d|_dS)Nz/proc/{pid}/statmpidF)rrxgetpidprocfilestarted)rMrWrWrXrNosz_MemoryWatchdog.__init__cCsyt|jd}WnOtk rg}z/tjdj|ttjj dSWYdd}~XnXt d}t j tj |gd|dt j|_|jd|_dS)Nrz!/proc not available for stats: {}zmemory_watchdog.pyrrT)r$rrrZrrrrbrflushr subprocessPopen executableZDEVNULL mem_watchdogrr)rMrurZwatchdog_scriptrWrWrXstartss   z_MemoryWatchdog.startcCs'|jr#|jj|jjdS)N)rrZ terminatewait)rMrWrWrXstops  z_MemoryWatchdog.stopN)rSrTrUrVrNrrrWrWrWrXrjs   rcsfdd}|S)atDecorator for bigmem tests. 'size' is a requested size for the test (in arbitrary, test-interpreted units.) 'memuse' is the number of bytes per unit for the test, or a good estimate of it. For example, a test that needs two byte buffers, of 4 GiB each, could be decorated with @bigmemtest(size=_4G, memuse=2). The 'size' argument is normally passed to the decorated test method as an extra argument. If 'dry_run' is true, the value passed to the test method may be less than the requested value. If 'dry_run' is false, it means the test doesn't support dummy runs when -M is not specified. cs.fdd__S)Nc sj}j}ts!d}n|}ts4 r_t||kr_tjd||dtrtrttdjd||dt}|j nd}z||SWd|r|j XdS) Niz'not enough memory: %.1fG minimum neededirz* ... expected peak memory use: {peak:.1f}GZpeaki@i@) rmemuserrfrgrrrrrr)rMrrmaxsizeZwatchdog)dry_runrurrWrXrs*        z.bigmemtest..decorator..wrapper)rr)ru)rrr)rurrXrs  zbigmemtest..decoratorrW)rrrrrW)rrrrXr/s !csfdd}|S)z0Decorator for tests that fill the address space.cs^ttkrPtd kr6td kr6tjdqZtjdtd n |SdS) Nr?rz-not enough memory: try a 32-bit build insteadz'not enough memory: %.1fG minimum neededirllli@)rrrfrg)rM)rurWrXrs  z!bigaddrspacetest..wrapperrW)rurrW)rurXr0s c@seZdZddZdS)r(cCstj}|||S)N)rfZ TestResult)rMrrrWrWrXruns  zBasicTestRunner.runN)rSrTrUrrWrWrWrXr(s cCs|S)NrW)rrWrWrX_idsrcCsP|dkr&t r&tjtjSt|r6tStjdj|SdS)Nrzresource {0!r} is not enabled)rrfskiprrrr)rrWrWrXrequires_resources  rcCstdd|S)z9 Decorator for tests only applicable on CPython. cpythonT) impl_detail)rrWrWrXr1scKszt|rtS|dkrmt|\}}|r=d}nd}t|j}|jdj|}tj|S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or ) r;r _parse_guardsr+ryrrrfr)rkguardsZ guardnamesdefaultrWrWrXrs   rc CsjtdkrGddl}y|jdaWntk rFdaYnXd}trW|Stj||S)z8Skip decorator for tests that use multiprocessing.Queue.NrTFz6requires a functioning shared semaphore implementation)_have_mp_queuemultiprocessingZQueuerarfr)rrrkrWrWrXr9s      cCs7|sddidfSt|jd}|| fS)NrTFr)rovalues)rZis_truerWrWrXrsrcKs.t|\}}|jtjj|S)a5This function returns True or False depending on the host platform. Examples: if check_impl_detail(): # only on CPython (default) if check_impl_detail(jython=True): # only on Jython if check_impl_detail(cpython=False): # everywhere except on CPython )rrDrcZpython_implementationr)rrrWrWrXr;scs<ttdsStjfdd}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.gettracec s?tj}ztjd||SWdtj|XdS)N)rbr settrace)rrZoriginal_trace)rrWrXrs   zno_tracing..wrapperN)rrbrr)rrrW)rrX no_tracings!r cCstt|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 r1)rrWrWrX refcount_test#sr cCsog}xY|jD]N}t|tjrEt|||j|q||r|j|qW||_dS)z>Recursively filter test cases in a suite based on a predicate.N)Z_testsrrf TestSuite _filter_suiter})suiteZpredZnewtestsrrWrWrXr.s  rcCstr'tjtjdddt}n t}|j|}|jst |j dkr~|j r~|j dd}nIt |j dkr|j r|j dd}nd}ts|d7}t |dS) z2Run tests from a unittest.TestSuite-derived class. verbosityrrrrzmultiple errors occurredz!; run in verbose mode for detailsN) rrfZTextTestRunnerrbrrr(rZ wasSuccessfulrerrorsZfailuresr)rZrunnerrrrWrWrX _run_suite:s    rcCswtdkrdS|j}xTtD]L}tj||r?dSx-|jdD]}tj||rOdSqOWq#WdS)NTrlF) match_testsidfnmatchZ fnmatchcaser)rZtest_idZ match_testrirWrWrX _match_testNs    rcGstjtjf}tj}x|D]}t|trx|tjkri|jtjtj|qt dq%t||r|j|q%|jtj |q%Wt |t t |dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesN)rfr ZTestCaserrhrbrmZaddTestZ findTestCasesrZ makeSuiterrr)classesZ valid_typesrclsrWrWrXr)_s    cCsdS)z,Just used to check if docstrings are enabledNrWrWrWrWrX_check_docstringsvsrwin32WITH_DOC_STRINGSztest requires docstringscCsddl}|dkr!t}nd}|j|d|d|\}}|rdtd||ftrtd|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). rNr optionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)doctestrZtestmodrrrS)rrrrrurrWrWrXr*s   !cCstjjfS)N)rbrmrmrWrWrWrX modules_setupsrcCsMddtjjD}tjjtjj|tjj|dS)NcSs1g|]'\}}|jdr||fqS)z encodings.)rd)r)rrrWrWrXr*s z#modules_cleanup..)rbrmr~rYr)Z oldmodules encodingsrWrWrXmodules_cleanups r cCs-trtjtjjfSdffSdS)Nr)_thread_count threading _danglingrmrWrWrWrXrDscGsats dSd}xJt|D]<}tjtjf}||krEPtjdtqWdS)Ndg{Gz?)r!ranger"r#r$rrrl)Zoriginal_valuesZ _MAX_COUNTcountrrWrWrXrEs  cs/ts Stjfdd}|S)zUse this function when threads are being used. This will ensure that the threads are cleaned up even when the test fails. If threading is unavailable this function does nothing. c s)t}z|SWdt|XdS)N)rDrE)rkey)rrWrXrs zreap_threads..decorator)r!rr)rrrW)rrXrFs!c CsXttdrTd}x<y,tj|tj\}}|dkrCPWqPYqXqWdS)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. waitpidrrNr@)rrxr)WNOHANG)Z any_processrZstatusrWrWrXrBs  ccsvt|}g}ziy,x%|D]}|j|j|qWWn1trmtdt|t|fYnXdVWdz|r|tj}}xtddD]{}|d7}x.|D]&}|jt |tjdqWdd|D}|s Ptrtdt||fqWWdd d|D}|rpt j t j td t|XXdS) Nz/Can't start %d threads, only %d threads startedrr<g{Gz?cSs"g|]}|jr|qSrW)isAlive)r)rrWrWrXr*s z!start_threads..z7Unable to join %d threads during a period of %d minutescSs"g|]}|jr|qSrW)r,)r)rrWrWrXr*s zUnable to join %d threads)rorr}rrrrr&rmax faulthandlerZdump_tracebackrbrra)ZthreadsZunlockrrZendtimeZ starttimerrWrWrXrGs>      $c cst||rNt||}t|||z |VWdt|||Xn9t|||z dVWdt||rt||XdS)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)rrQnew_valreal_valrWrWrXrMs  c csh||kr:||}|||sz&detect_api_mismatch..)r}rP)Zref_apiZ other_apirYZ missing_itemsrWrWrXr8s "c@s:eZdZdZdZdZddZddZdS)rPzTry 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 Cstjjdrddl}|jj|_d}|jj||_|jj|j|Byddl }|j Wnt t fk rYqXi|_ xH|j|j|jgD]C}|j ||j}|j||j}||f|j |.cleanup)rr>rrsZ addCleanupr)Z test_instancerkrjZ new_valuerlrW)rirjrkr\rXpatcha s  rmc CsYyddl}Wntk r$YnX|jr@tjdddl}|j|S)zi Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc module is enabled. rNzUrun_in_subinterp() cannot be used if tracemalloc module is tracing memory allocations) tracemallocraZ is_tracingrfrgrrun_in_subinterp)rrnrrWrWrXro s   rocsbGfddd|}d||||jttt|jdS)Ncs%eZdZfddZdS)z%check_free_after_iterating..Ac s-dytWntk r(YnXdS)NT)next StopIteration)rM)doneitrWrX__del__ s  z-check_free_after_iterating..A.__del__N)rSrTrUrtrW)rrrsrWrXA s ruF)r3rqrprlZ assertTrue)rrzrrrurW)rrrsrXcheck_free_after_iterating s  rvii@i@i@ii) rrrrrrrr r r r )r r)rrrrri@ii)rVrSracollections.abc collections contextlibrr.rrrr`importlib.utilZlogging.handlersr8rrxrcr\rrrrrrbrrrrfZ urllib.errorrGrZr!r#Zmultiprocessing.processrzlibr>bz2Zlzmar__all__rrrrgr contextmanagerr^r rrrtr6r7r r2rrrrrrrrrr rrdrrrrrrrrrrrrrrr r!r<rrrr>r?rr=rrZ SOCK_MAX_SIZEZ skipUnlessr __getformat__r3r5r,r-r.r:rirrrZ FS_NONASCII characterfsdecodefsencode UnicodeErrorZTESTFN_UNICODEZ unicodedata normalizegetfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversionencodeUnicodeEncodeErrorrdecodeUnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIrrrrrrrAryrzrr{ZTEST_SUPPORT_DIRr!rrCrrrQr/r"r@objectrJrhrHrIr abcMutableMappingrJrr#rrr$rr%r&r'rrrrrlrrrrrrrrrrrKrRrrrZ_4GrrrOrr/r0r(rrr1rrr9rr;r r rrrr)rrZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr*rr rDrErFrBrGrMrLr6ZskipIfZrequires_type_collectingr7r9r:rCrNrFrr+rMrOr4rr8rPrmrorvrWrWrWrXsv                                                            2     !          J   >&                   !     2' 5 J        $ #     0                   #   "     _ "