g f:@sdZedkr!ednddlZddlZddlZddlZddlZddl 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 rAdZ&YnXyddl'Z'Wnek rldZ'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@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRgNZ)GdSd d e*Z+GdTd d e+Z,GdUd d ej-Z.ej/dVdWdXZ0dYdZfd[d Z1d\d]Z2d^d_Z3d`d9Z4dad:Z5ffdYdbdZ6dcd5Z7ddZ8dZ9da:da;dYZ<dZ=da>dedZ?dfdZ@dgdZAejjBdhrdYdidjZCdkdlZDdmdnZEdodpZFnejGZDejHZEejIZFdqdZGdrdsZHdtdZIdudvZJdwdZKdxdyZLdzd ZMdd{d!ZNd|d}ZOd~d"ZPdd#ZQdd$ZRdZSdZTejUejVdd?ZWeSdd@ZXddZYeYZZddZ[d)Z\d,Z]ej^e_j`djBddZaej^e$dZbej^e%dZcej^e&dZdej^e'dZeejjBdZfejgdkrdZhndZhdjiehejjZhdZkxDd-D]<ZlyejmejnelWneok rYqXelZkPqWehdZpejdkr*ddlqZqeqjrdepZpnejsZtdZuejgd.krejvjdkrehdZuyeujwetWnexk rYqXeydeuetfdZuqnNejdkrydjzetWqe{k rehdjzetdZuYqXndZ|xHd/D]@ZgyegjzetWq e{k rJejnehegZ|PYq Xq WekrfehdekZ}ndZ}ej~Zej/ddYddZej/dYddZej/ddYddZeedrej/ddBZnejjejjeZejjeZejjedZdddZddZddQZddZdd%ZddAZGdddeZdYddZej/ddIZGdddeZGddJdJejjZGdddeZGdd&d&eZeedejZeedejZeedejZej/dddfdd*Zej/ddZddZddZddZddZej/ddZddZdZdZeedr deZdZnedZddZddZd0Zd1ZddZddKZddRZd2ZdeZdeZdeZejZddOZGdddZdVdd2Zdd3ZGdd+d+ZddZddZdd4ZdddZddZdd<ZddZddZddZddZdd,ZddZeo ejdko ejd Zejdk o e Zej^ed Zddd d-Zd d Zd dZddEZddFZddGZddCZej/dddHZej/ddMZej/ddLZddZddZGddDdDejjZGddNdNeZdaddZdd.ZdaddZd d7Zd!dZGd"dPdPZd#d$Zd%d&ZdS(3z7Supporting 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_tests is_jythoncheck_impl_detailHOST IPV6_ENABLEDfind_unused_port bind_portopen_urlresource temp_umask reap_children TestHandlerthreading_setupthreading_cleanup reap_threads start_threadscheck_warningsEnvironmentVarGuardrun_with_locale swap_item swap_attrMatcher set_memlimitSuppressCrashReportsortdict run_with_tzc@seZdZdZdS)rz*Base class for regression test exceptions.N)__name__ __module__ __qualname____doc__rTrT:/opt/alt/python34/lib64/python3.4/test/support/__init__.pyrls c@seZdZdZdS)rz Test failed.N)rPrQrRrSrTrTrTrUros 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)rPrQrRrSrTrTrTrUr rs Tc cs=|r4tjtjddtdVWdQXndVdS)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)rVrTrTrU_ignore_deprecated_importszs   r[F required_oncCst|qytj|SWnXtk rx}z8tjjt|rQntj t |WYdd}~XnXWdQXdS)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\msgrTrTrUr s cCs|tjkr&t|tj|=nxTttjD]C}||ks[|j|dr6tj|||sz$anticipate_failure..)rcZexpectedFailure)Z conditionrTrTrUr6scCsn|dkrd}ntjjtjjtjjt}|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_testsrtZtop_dirZ package_testsrTrTrUr7s      c Cst|i}g}t||zyax|D]}t||q3Wx-|D]%}t||sQ|j|qQqQWtj|}Wntk rd}YnXWdx'|jD]\} } | tj | ._rmtree_innerrT)rrur)rvrT)rrU_rmtreeRsrc Cs-yt|Wnttfk r(YnXdS)N)rFileNotFoundErrorNotADirectoryError)rrTrTrUrhsc Cs'yt|Wntk r"YnXdS)N)rr)rwrTrTrUrns rc Cs'yt|Wntk r"YnXdS)N)rr)rvrTrTrUrts cCsitjj|}tjjtjj|}tjj||trKdnd}tj |||S)alMove a PEP 3147 pyc/pyo file to its legacy pyc/pyo location. The choice of .pyc or .pyo extension is done based on the __debug__ flag value. :param source: The file system path to the source file. The source file does not need to exist, however the PEP 3147 pyc file must exist. :return: The file system path to the legacy pyc file. co) r]utilcache_from_sourcerurvrwabspathr __debug__rename)sourceZpyc_fileZup_oneZ legacy_pycrTrTrUmake_legacy_pyczs %rcCst|x~tjD]s}tjj||d}t|dt|dttjj|ddttjj|ddqWdS)z'Forget' a module was ever imported. This removes the module from sys.modules and deletes any PEP 3147 or legacy .pyc and .pyo files. z.pyrrdebug_overrideTFN) r r_rvrurrr]rr)rnrwrrTrTrUrs csttdrtjSd}tjjdr ddlddld}d}Gfdddj}j j }|j }|sj n|}j j}|j||j|j|j|}|sj nt|j|@sd}qntjdkrdd lm} mm} m} dd lm} | j| d } | jdkrd }qGfd dd| }|}| |}| j|dks| j|dkrd}qn|sy1ddlm}|}|j|j Wqt!k r}zUt"|}t#|dkry|ddd}ndj$t%|j&|}WYdd}~XqXn|t_'| t_tjS)NresultrrrcsCeZdZdjjfdjjfdjjfgZdS)z*_is_gui_available..USEROBJECTFLAGSZfInheritZ fReserveddwFlagsN)rPrQrRwintypesZBOOLDWORD_fields_rT)ctypesrTrUUSEROBJECTFLAGSs 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)rPrQrRrrT)rrTrUProcessSerialNumbers  rz#cannot run without OS X gui process)Tk2z [...]zTk unavailable due to {}: {})(hasattr_is_gui_availablerr_r`rarZctypes.wintypesrwindllZuser32ZGetProcessWindowStationZWinErrorrrZGetUserObjectInformationWZbyrefsizeofboolrrrrZ ctypes.utilrZ LoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterrupdateZdestroy ExceptionrelenformattyperPreason)rZ UOI_FLAGSZ WSF_VISIBLErZdllhZuofZneededresrrrrZ app_servicesrZpsnZpsn_prrooteZ err_stringrT)rrrUrsf         "         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)resourcerTrTrUrscCs`|dkr(t r(ttjnt|s\|dkrMd|}nt|ndS)z@Raise ResourceDenied if the specified resource is not available.guiNz"Use of the %r resource not enabled)rr rr)rrhrTrTrUrs    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 rdYqX|krdjtt }t j d||fqn||S)N-rrriz(%s version %s or higher required, not %s) r`systemreleaserrbmapint ValueErrorrrercrd)argskw version_txtversionmin_version_txt)r min_versionsysnamerTrUwrappers"  z:_requires_unix_version..decorator..wrapper) functoolswrapsr)rr)rr)rrU decorators' z)_requires_unix_version..decoratorrT)rrrrT)rrrU_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)rrTrTrUrscGs 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)rrTrTrUr scsfdd}|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 rUYqX|krdjtt }t j d||fqn||S)Nrrriz&Mac OS X %s or higher required, not %s) r_r`Zmac_verrbrrrrrrercrd)rrrrr)rrrTrUr*s"  z4requires_mac_ver..decorator..wrapper)rrr)rr)r)rrUr)s$ z#requires_mac_ver..decoratorrT)rrrT)rrUr!"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)familyZsocktypeZtempsockportrTrTrUr<Ds 8  c Cs|jtjkr|jtjkrttdrc|jtjtjdkrct dqcnttdrdt j kry1|jtjtj dkrt dnWqt k rYqXnttdr|jtjtjdqn|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_SOCKETrrruenvironrrZ setsockoptrbindZ getsockname)sockhostrrTrTrUr=s $ cCsytjrud}zLy3tjtjtj}|jtdfdSWntk rYYnXWd|rq|jnXndS)z+Check whether IPv6 is enabled on this host.NrTF)rZhas_ipv6ZAF_INET6rrHOSTv6rr)rrTrTrU_is_ipv6_enableds   rcs%tjfdd}|S)z5Skip the test on TLS certificate validation failures.csdy||WnLtk r_}z,dt|krJtjdnWYdd}~XnXdS)NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)IOErrorrercrd)rkwargsr)rrrTrUdecs z&system_must_validate_cert..dec)rr)rrrrT)rrrUsystem_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|}nRytj|d}Wn8tk r|slntjd|t ddYnXz |VWd|rt j |nXdS)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) tempfileZmkdtemprurvrealpathmkdirrrWrrshutilr)rvquietZ dir_createdrTrTrUtemp_dirks"       rccs|tj}ytj|Wn8tk rW|s9ntjd|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: rr N)rugetcwdchdirrrWrr)rvrZ saved_dirrTrTrU change_cwds   rZtempcwdccsBtd|d|'}t|d| }|VWdQXWdQXdS)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. rvrN)rr)rfrZ temp_pathZcwd_dirrTrTrUrsumaskc cs-tj|}z dVWdtj|XdS)z8Context manager that temporarily sets the process umask.N)rur)rZoldmaskrTrTrUr?s datacCstjj|r|S|dk r:tjj||}ntgtj}x9|D]1}tjj||}tjj|rQ|SqQW|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)rurvisabsr TEST_HOME_DIRr_exists)rZsubdirrvZdnfnrTrTrUrs  cCs4tj|tjtjBtjB}tj|dS)z>Create an empty file. If the file already exists, truncate it.N)ruopenO_WRONLYO_CREATO_TRUNCr)rfdrTrTrUrs#cCs<t|j}dd|D}dj|}d|S)z%Like repr(dict), but in sorted order.cSsg|]}d|qS)z%r: %rrT).0ZpairrTrTrU s zsortdict..z, z{%s})sortedr{r)dictr{Z reprpairsZ withcommasrTrTrUrNsc Cs9ttd}z|jSWd|jttXdS)z` Create an invalid file descriptor by opening and closing a file and return its fd. wbN)rrfilenorr)rrTrTrU make_bad_fds  r'cCs|jtt|dddS)Nz exec)Z assertRaises SyntaxErrorcompile)ZtestcaseZ statementrTrTrUr"sc sddl}ddl}jdd|jj|djdd}tjjt |}fdd}tjj |r||}|dk r|St |nt dt d |d t|jj}tr|jjdn|j|d d}trF|jjdd krFtjd|}nzNt|d9} |j} x#| r| j| |j} qjWWdQXWd|jX||}|dk r|Std|dS)Nrcheckr/rcsMt|}dkr"|S|r?|jd|S|jdS)Nr)rseekr)rrr)rr+rrTrUcheck_valid_files   z*open_urlresource..check_valid_fileZurlfetchz fetching %s ...rAccept-EncodinggziprzContent-EncodingZfileobjr%zinvalid resource %r)r/zgzip)Zurllib.requestZ urllib.parsepopparseZurlparserrurvr TEST_DATA_DIRrrrrrZrequestZ build_openerr0Z addheadersrzrZheadersgetZGzipFilereadwriterr) Zurlrrurllibrrr.rrZopeneroutsrT)rr+rrUr>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_listrTrTrU__init__0s zWarningsRecorder.__init__cCs\t|j|jkr,t|jd|S|tjjkrBdStd||fdS)Nrz%r has no attribute %rr2)rr=r>r}rWWarningMessage_WARNING_DETAILSr~)r?attrrTrTrU __getattr__4s zWarningsRecorder.__getattr__cCs|j|jdS)N)r=r>)r?rTrTrUrW;szWarningsRecorder.warningscCst|j|_dS)N)rr=r>)r?rTrTrUreset?szWarningsRecorder.resetN) rPrQrRrSr@rDpropertyrWrErTrTrTrUr<,s   r<c csltjd}|jjd}|r4|jntjdd&}tjdjdt |VWdQXt |}g}x|D]\}}d} xg|ddD]U}|j } t j |t| t jrt| j|rd} |j|qqW| r| r|j||jfqqW|rKtd |d n|rhtd |d ndS) 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__recordTrWalwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)r_ _getframe f_globalsr6clearrWrXrj simplefilterr<rlmessagerematchreI issubclass __class__removerzrPAssertionError) filtersrZframeregistrywZreraiseZmissingrhcatseenZwarningrTrTrU_filterwarningsCs0   rZcOsI|jd}|s<dtff}|dkr<d}q<nt||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) rNT)r6WarningrZ)rUrrrTrTrUrFjs   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 cGsotjj|_xV|D]N}|tjkrtj|}|j|krZtj|j=ntj|=qqWdS)N)r_rjcopyoriginal_modulesrP)r?Z module_namesZ module_namer|rTrTrUr@s  zCleanImport.__init__cCs|S)NrT)r?rTrTrU __enter__szCleanImport.__enter__cGstjj|jdS)N)r_rjrr^)r? ignore_excrTrTrU__exit__szCleanImport.__exit__N)rPrQrRrSr@r_rarTrTrTrUr s  c@seZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZdS)rGz_Class to help protect the environment variable properly. Can be used as a context manager.cCstj|_i|_dS)N)rur_environ_changed)r?rTrTrUr@s zEnvironmentVarGuard.__init__cCs |j|S)N)rb)r?envvarrTrTrU __getitem__szEnvironmentVarGuard.__getitem__cCs<||jkr+|jj||j|@errnosc #sdd d!d"d#g}d%d'd)d+d,g}td||gsudd|Ddd|Dnfdd}tj}z'y%|dk rtj|ndVWntjk r}z2trtjj j ddn|WYdd}~Xnt k r}zxr|j }t |dkrht |dt rh|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_AGAINr EAI_FAILr EAI_NONAMEr EAI_NODATA WSANO_DATA*zResource %r is not availablecSs(g|]\}}tt||qSrT)r}rx)r!rfnumrTrTrUr")s z&transient_internet..cSs(g|]\}}tt||qSrT)r}r)r!rfrrTrTrUr"+s cst|dd}t|tjst|tjrB|kst|tjjrvd|jkoqdknst|tjj rd|j ksd|j ks|krt st j jjddn|ndS)NrxiiWConnectionRefusedError TimeoutErrorr )r} isinstancerrZgaierrorr9errorZ HTTPErrorcodeZURLErrorrrr_stderrr8r)errn)captured_errnosdenied gai_errnosrTrU filter_error.s z(transient_internet..filter_errorNrrr)rzr{)z ECONNRESETr})r~r)rr)z ETIMEDOUTr)rr)rr)rr)rr)rr)r rZgetdefaulttimeoutZsetdefaulttimeoutnntplibZNNTPTemporaryErrorrr_rr8rrrr) Z resource_namerryZdefault_errnosZdefault_gai_errnosrZ old_timeoutrarT)rrrrUr'sN          % %  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)ior}r_setattrStringIO)Z stream_namerZ orig_stdoutrTrTrUcaptured_output[s  rcCs tdS)zCapture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") r)rrTrTrTrUrgscCs tdS)zCapture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") r)rrTrTrTrUrpscCs 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)rrTrTrTrUrys cCs8tjtr tjdntjtjdS)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)gcZcollectr8rrrTrTrTrU gc_collects  rc cs:tj}tjz dVWd|r5tjnXdS)N)r isenableddisableenable)Zhave_gcrTrTrU disable_gcs    rcCsTtjdpd}d}x,|jD]}|jdr(|}q(q(W|dkS)z,Find if Python was built with optimizations. PY_CFLAGSr[z-O-O0-Og)r[rr) sysconfigget_config_varrra)ZcflagsZ final_optZoptrTrTrUpython_is_optimizeds  rZnPZ0ngettotalrefcountZ2PZ0PrcCstjt|tS)N)structcalcsize_header_align)fmtrTrTrU calcobjsizesrcCstjt|tS)N)rr_vheaderr)rrTrTrU calcvobjsizesr cCsddl}tj|}t|tkr:|jt@s_t|tkrot|jt@ro||j7}ndt|||f}|j|||dS)Nrz&wrong size for %s: got %d, expected %d) _testcapir_ getsizeofr __flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADZ assertEqual)testrsizerrrhrTrTrU 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||nXdS)Nr)localer} setlocaler~)rkwdsrcategoryZ orig_localeloc)catstrrlocalesrTrUinners$     z1run_with_locale..decorator..inner)rPrS)rr)rr)rrUrs  z"run_with_locale..decoratorrT)rrrrT)rrrUrHscsfdd}|S)Ncs1fdd}j|_j|_|S)Ncsy tj}Wn!tk r0tjdYnXdtjkrPtjd}nd}tjd<|z||SWd|dkrtjd=n |tjd.decorator..inner)rPrS)rr)r)rrUrs  zrun_with_tz..decoratorrT)rrrT)rrUrOscCsidd6td6td6dtd6}tjd|tjtjB}|dkrgtd|fntt|j d||j d j }|a |t krt }n|t dkrtd |fn|adS) Niromgtz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rrr z$Memory limit %r too low to be useful)_1M_1GrNrO IGNORECASEVERBOSErrfloatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitZsizesrZmemlimitrTrTrUrLs   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)rrugetpidprocfilestarted)r?rTrTrUr@3sz_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)rrrrWrrrr_rflushr subprocessPopen executableZDEVNULL mem_watchdogrr)r?rrrZwatchdog_scriptrTrTrUstart7s   z_MemoryWatchdog.startcCs*|jr&|jj|jjndS)N)rrZ terminatewait)r?rTrTrUstopFs  z_MemoryWatchdog.stopN)rPrQrRrSr@rrrTrTrTrUr.s   rcsfdd}|S)aADecorator for bigmem tests. 'minsize' is the minimum useful size for the test (in arbitrary, test-interpreted units.) 'memuse' is the number of 'bytes per size' for the test, or a good estimate of it. 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 rbt||krbtjd||dntrtrttdjd||dt}|j nd}z||SWd|r|j nXdS) Niz'not enough memory: %.1fG minimum neededir z* ... expected peak memory use: {peak:.1f}GZpeaki@i@) rmemuserrcrdrrrrrr)r?rrmaxsizeZwatchdog)dry_runrrrrTrUrWs*        z.bigmemtest..decorator..wrapper)rr)rr)rrr)rrrrUrVs  zbigmemtest..decoratorrT)rrrrrT)rrrrUr/Ls !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 neededir llli@)rrrcrd)r?)rrrTrUr{s  z!bigaddrspacetest..wrapperrT)rrrrT)rrrUr0ys c@seZdZddZdS)r(cCstj}|||S)N)rcZ TestResult)r?rrrTrTrUruns  zBasicTestRunner.runN)rPrQrRrrTrTrTrUr(s cCs|S)NrT)rrTrTrU_idsrcCsP|dkr&t r&tjtjSt|r6tStjdj|SdS)Nrzresource {0!r} is not enabled)rrcskiprrrr)rrTrTrUrequires_resources  rcCstdd|S)z9 Decorator for tests only applicable on CPython. cpythonT) impl_detail)rrTrTrUr1scKs}t|rtS|dkrpt|\}}|r=d}nd}t|j}|jdj|}ntj|S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or ) r9r _parse_guardsr#rirrrcr)rhguardsZ guardnamesdefaultrTrTrUrs   rcCs8|sidd6dfSt|jd}|| fS)NTrFr)rlvalues)rZis_truerTrTrUrsrcKs.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 )rr6r`Zpython_implementationr)rrrTrTrUr9scs<ttdsStjfdd}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.gettracec s?tj}ztjd||SWdtj|XdS)N)r_rsettrace)rrZoriginal_trace)rrTrUrs   zno_tracing..wrapperN)rr_rr)rrrT)rrU no_tracings!rcCstt|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. )rr1)rrTrTrU refcount_testsrcCsrg}x\|jD]Q}t|tjrEt|||j|q||r|j|qqW||_dS)z>Recursively filter test cases in a suite based on a predicate.N)Z_testsrrc TestSuite _filter_suiterz)suiteZpredZnewtestsrrTrTrUrs  rcCstr'tjtjdddt}n t}|j|}|jst |j dkr~|j r~|j dd}nLt |j dkr|j r|j dd}nd}ts|d7}nt |ndS) z2Run tests from a unittest.TestSuite-derived class. verbosityrrrrzmultiple errors occurredz!; run in verbose mode for detailsN) rrcZTextTestRunnerr_rrr(rZ wasSuccessfulrerrorsZfailuresr)rZrunnerrrrTrTrU _run_suites    rcGstjtjf}tj}x|D]}t|trx|tjkri|jtjtj|qt dq%t||r|j|q%|jtj |q%Wdd}t ||t |dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulescSsJtdkrdSx3|jjdD]}tj|tr&dSq&WdS)NTriF) match_testsidrfnmatchZ fnmatchcase)rrfrTrTrU case_pred s  zrun_unittest..case_predN) rcrZTestCaserrer_rjZaddTestZ findTestCasesrZ makeSuiterr)ZclassesZ valid_typesrclsrrTrTrUr)s     cCsdS)z,Just used to check if docstrings are enabledNrTrTrTrTrU_check_docstringssrwin32WITH_DOC_STRINGSztest requires docstringscCsddl}|dkr!t}nd}|j|d|d|\}}|rgtd||fntrtd|j|fn||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)doctestrZtestmodrrrP)r|rr r rrrrTrTrUr*.s   !cCstjjfS)N)r_rjr]rTrTrTrU modules_setupIsr cCsMddtjjD}tjjtjj|tjj|dS)NcSs1g|]'\}}|jdr||fqS)z encodings.)ra)r!rorprTrTrUr"Ps z#modules_cleanup..)r_rjr{rKr)Z oldmodules encodingsrTrTrUmodules_cleanupLs rcCs-trtjtjjfSdffSdS)Nr)_thread_count threading _danglingr]rTrTrTrUrBgscGsdts dSd}xMt|D]?}tjtjf}||krHPntjdtqWdS)Ndg{Gz?)rrangerrrrrr)Zoriginal_valuesZ _MAX_COUNTcountrrTrTrUrCms  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)rBrC)rkey)rrTrUrs zreap_threads..decorator)rrr)rrrT)rrUrDys!c Cs^ttdrZd}xBy/tj|tj\}}|dkrFPnWqPYqXqWndS)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. waitpidrrNr2)rrurWNOHANG)Z any_processrZstatusrTrTrUr@s  ccst|}g}zly,x%|D]}|j|j|qWWn4trptdt|t|fnYnXdVWdz|r|ntj}}xtddD]}|d7}x.|D]&}|jt |tjdqWdd|D}|sPntrtdt||fqqWWdd d|D}|rt j t j td t|nXXdS) Nz/Can't start %d threads, only %d threads startedrr<g{Gz?cSs"g|]}|jr|qSrT)isAlive)r!rrTrTrUr"s z!start_threads..z7Unable to join %d threads during a period of %d minutescSs"g|]}|jr|qSrT)r)r!rrTrTrUr"s zUnable to join %d threads)rlrrzrrrrrrmax faulthandlerZdump_tracebackr_rrT)ZthreadsZunlockrrZendtimeZ starttimerrTrTrUrEs>       $c cs|t||rNt||}t|||z dVWdt|||Xn*t|||z dVWdt||XdS)amTemporary 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. N)rr}rdelattr)rrCnew_valreal_valrTrTrUrJs   c cs\||kr:||}|||}||}|j|}|j|||s d}Pq q W|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)r6 match_value)r?r/rrrorpdvrTrTrUr.+s  zMatcher.matchescCsjt|t|kr!d}nEt|tk sB||jkrQ||k}n|j|dk}|S)zT Try to match a single stored value (dv) with a supplied value (v). Fr)rre_partial_matchesfind)r?ror1rprrTrTrUr0<s  !zMatcher.match_valueN)zmsgzmessage)rPrQrRr2r.r0rTrTrTrUrK's  c Csotdk rtStd}ytjt|d}Wn!tttfk rWd}YnXtj||a|S)NrTF) _can_symlinkrrusymlinkrNotImplementedErrorr~rS)Z symlink_pathcanrTrTrUrJs     cCs,t}d}|r|Stj||S)z8Skip decorator for tests that require functional symlinkz*Requires functional symlink implementation)rrcr)rokrhrTrTrUr+Ys cCstdk rtSttds(d}ntj\}}zttd}yutj|ddtj|jddt j }t j d|}|dkpt |jddk}Wntk rd}YnXWdQXWdttt|X|a|S) NsetxattrFr%s user.testr!z 2.6.(\d{1,2})r') _can_xattrrrur Zmkstemprrr9r&r`rrNrOrrrr)r7Ztmp_fpZtmp_namefpZkernel_versionrrTrTrU can_xattr`s&   +   r=cCs,t}d}|r|Stj||S)zDSkip decorator for tests that require functional extended attributesz(no non-broken extended attribute support)r=rcr)rr8rhrTrTrUr4{s cCstjd|g}|j}|j}||krE|j}nytjj||SWntk rtdSYnXWdQXdS)zKDetects if the file system for the specified directory is case-insensitive.dirFN) r ZNamedTemporaryFilerfupperrrurvsamefiler)Z directorybase base_pathZ case_pathrTrTrUrs    c@s4eZdZdZdZddZddZdS)rMzTry 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. NcCs4tjjdrbddl}|jj|_d}|jj||_|jj|j|Bnt dk ry9t j t j |_t j t j d|jdfWqt tfk rYqXntjdkr0tjddd d gd tjjd}|jd kr0td ddddq0n|S)zOn Windows, disable Windows Error Reporting dialogs using SetErrorMode. On UNIX, try to save the previous core file size limit, then set soft limit to 0. rrNrrrz/usr/bin/defaultsr7zcom.apple.CrashReporterZ DialogTypers developerz:this test triggers the Crash Reporter, that is intentionalendr[rT)r_r`rarrZkernel32_k32 SetErrorMode old_valuerZ getrlimit RLIMIT_CORE setrlimitrrrrPIPEZ communicater#r)r?rZSEM_NOGPFAULTERRORBOXrfrTrTrUr_s*      zSuppressCrashReport.__enter__c Gs|jdkrdStjjdr;|jj|jnDtdk rytjtj|jWqt t fk r{YqXndS)zARestore Windows ErrorMode or core file behavior to initial value.Nr) rFr_r`rarDrErrHrGrr)r?r`rTrTrUras zSuppressCrashReport.__exit__)rPrQrRrSrFr_rarTrTrTrUrMs  (c stdyjWn*ttfk rPtdYnXdfdd}|j|t|dS)zOverride 'object_to_patch'.'attr_name' with 'new_value'. Also, add a cleanup procedure to 'test_instance' to restore 'object_to_patch' value for 'attr_name'. The 'attr_name' should be a valid attribute for 'object_to_patch'. FNTcs*rtn tdS)N)rrrT) attr_is_local attr_nameobject_to_patchrFrTrUcleanupszpatch..cleanup)r}r,r~rpZ addCleanupr)Z test_instancerLrKZ new_valuerMrT)rJrKrLrFrUpatchs  rNc Cs\yddl}Wntk r$YnX|jrCtjdnddl}|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) tracemallocr^Z is_tracingrcrdrrun_in_subinterp)rrOrrTrTrUrPs   rPii@i@i@ii) rrrrrrrrrrr)zntr)rrr r r i@ii)rSrPr^Zcollections.abc collections contextlibrxrrrrr]importlib.utilZlogging.handlersr&rrur`rNrrrrrr_rr rrcZ urllib.errorr9rWrrZmultiprocessing.processZmultiprocessingzlibr0bz2Zlzmar__all__rrrrdr contextmanagerr[r rorqr6r7r r2rrrrrrrrrr rarrrrrrrrrrrrrrr r!r:rrrr<r=rr;rrZ SOCK_MAX_SIZEZ skipUnlessr __getformat__r3r5r,r-r.r8rfrrrZ FS_NONASCII characterfsdecodefsencode UnicodeErrorZTESTFN_UNICODEZ unicodedata normalizegetfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversionencodeUnicodeEncodeErrorrdecodeUnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIrrrrrrr?rvrwrrxZTEST_SUPPORT_DIRrrr5rrrNr'r"r>objectr<rZrFr abcMutableMappingrGrqr#rrr$r|r%r&r'rrrrrrrrrrrrrrrrHrOrrrZ_4GrrrLrr/r0r(rrr1rrr9rrrrr)rrZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr*r rrBrCrDr@rErJrIr$r%r'r(rArKr4rr+r;r=r4rrMrNrPrTrTrTrUsb                                                          2    !           I   >&                  !     1' 5 I         $ #     -                # "     ? "