3 48eJ@s> dZedkredddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZ ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl!Z"ddl#Z#ddl$m%Z%yddl&Z&ddl'Z'Wnek rBdZ&dZ'YnXy ddl(Z)Wnek rjdZ)YnXy ddl*Z*Wnek rdZ*YnXy ddl+Z+Wnek rdZ+YnXy ddl,Z,Wnek rdZ,YnXy ddl-Z-Wnek r dZ-YnXy ddl.Z.Wnek r2dZ.YnXy ddl/Z/Wnek rZdZ/YnXddd 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`dadbg\Z0Gdcd d e1Z2Gddd d e2Z3Gdedde2Z4Gdfdde j5Z6ej7dcdhdiZ8ddfdkdldZ9dmdnZ:dodpZ;dqd=ZZ=ffdjfdsdZ>dtd9Z?dZ@dZAdaBdaCdZDdjZEdaFdudZGdvdZHdwdZIdxdyZJejjKdzr.ded{d|ZLd}d~ZMddZNddZOddZPnejQZMejRZNddZOddZPddZQddZRddZSddZTddZUddZVdd#ZWdfdd$ZXddZYdd%ZZdd&Z[dd'Z\dgdd(Z]dZ^dZ_ej`ejafddJZbe^fddKZcddMZdddZeeeZfddZgdjZhdmZie jjekjldjKddZme jje*dZne jje+dZoe jje,dZpe jje-dZqejjKdZrejsdZtetdk oxetdkZuejdkreurdndZvndZvejwdkrdZxndZxdjyexejzZxdZ{xLdnD]BZ|yej}ej~e|e|kreWnek rYnXe|Z{PqWexdZejdkr:ddlZejdeZejZdZejwdkrejjdkrexdZyejeWnek rYnXedeefdZnBejdkrydjeWn&ek rexdjedǃZYnXdZxFdoD]d?Zd@dAZdBdCZGdDdPdPejjZGdEd[d[eZdadFd!ZdGd2ZdadHdIZdJd;ZdKdLZdMd"ZfdNdOd?ZdfffdPd@ZGdQd]d]Z dRdSZ dTdUZ ffdVdWZ gfdXdaZ dadYdGZej7dZd[Zd\dbZGd]d^d^ZGd_d`d`Zej7dadbZdS(}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_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_mismatch check__all__requires_android_levelrequires_multiprocessing_queue 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_warningEnvironmentVarGuardrun_with_locale swap_item swap_attrMatcher set_memlimitSuppressCrashReportsortdict run_with_tzPGOmissing_compiler_executablefd_countc@seZdZdZdS)r z*Base class for regression test exceptions.N)__name__ __module__ __qualname____doc__rdrd-/usr/lib64/python3.6/test/support/__init__.pyr |sc@seZdZdZdS)r z Test failed.N)r`rarbrcrdrdrdrer sc@seZdZdZdS)r zTest did not run any subtests.N)r`rarbrcrdrdrdrer 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. N)r`rarbrcrdrdrdrer sTc cs8|r.tjtjddtdVWdQRXndVdS)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)rfrdrdre_ignore_deprecated_importss  rkF) required_oncCsft|Ty tj|Stk rV}z&tjjt|r8tj 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) rk importlibr ImportErrorsysplatform startswithtupleunittestSkipTeststr)name deprecatedrlmsgrdrdrer s  cCs^|tjkrt|tj|=x>ttjD]0}||ks@|j|dr&tj|||<tj|=q&WdS)zyHelper function to save and remove a module from sys.modules Raise ImportError if the module can't be imported. .N)romodules __import__listrq)rv orig_modulesmodnamerdrdre_save_and_remove_modules rc Cs>d}ytj|||<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. TFN)rorzKeyError)rvr}Zsavedrdrdre_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|S)Nrd)frdrdresz$anticipate_failure..)rsZexpectedFailure)Z conditionrdrdrer:scCsF|dkr d}tjjtjjtjjt}|j|||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_testsrZtop_dirZ package_testsrdrdrer;s c Cst|i}g}t||zfyHx|D]}t||q&Wx |D]}t||s>|j|q>Wtj|}Wntk r~d}YnXWdx|jD]\} } | tj | <qWx|D] } tj | =qWX|SQRXdS)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) rkrrappendrmr rnitemsrorz) rvZfreshZblockedrwr}Znames_to_removeZ fresh_nameZ blocked_nameZ fresh_moduleZ orig_namemoduleZname_to_removerdrdrers$      c Cs>yt||}Wn&tk r4tjd||fYnX|SdS)z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %rN)getattrAttributeErrorrsrt)objrvZ attributerdrdrer6s cCs|adS)N)_original_stdout)stdoutrdrdrer0scCs tptjS)N)rrorrdrdrdrer4sc Cs&y tj|=Wntk r YnXdS)N)rorzr)rvrdrdrer7s cGsny||Stk rh}zDtdkrHtd|jj|ftd|j|ftj|tj||Sd}~XnXdS)Nz%s: %sz re-run %s%r) OSErrorrprint __class__r`rchmodstatS_IRWXU)rfuncargserrrdrdre _force_run=srwincCs|||r|}ntjj|\}}|p(d}d}x<|dkrjtj|}|rJ|n||ksVdStj||d9}q0Wtjd|tdddS)NrygMbP?g?rz)tests may fail, delete still pending for ) stacklevel) rrsplitlistdirtimesleeprgwarnRuntimeWarning)rpathnamewaitallrrvtimeoutLrdrdre_waitforHs     rcCsttj|dS)N)rrr)filenamerdrdre_unlinkisrcCsttj|dS)N)rrrmdir)rrdrdre_rmdirlsrcs,fddt|ddtdd|dS)Ncsxt|tj|D]}tjj||}ytj|j}Wn<tk rn}z td||ft j dd}WYdd}~XnXt j |rt |ddt|tj|qt|tj|qWdS)Nz-support.rmtree(): os.lstat(%r) failed with %s)filerT)r)rrrrjoinlstatst_moderrro __stderr__rS_ISDIRrrr)rrvfullnamemodeexc) _rmtree_innerrdrerps   z_rmtree.._rmtree_innerT)rcSst|tj|S)N)rrr)prdrdrersz_rmtree..)r)rrd)rre_rmtreeos rc Cs^y ddl}Wntk r Yn:X|jt|d}|jjj||t|}|rZ|d|S|S)Nrr)ctypesrnZcreate_unicode_bufferlenwindllkernel32ZGetLongPathNameW)rrbufferZlengthrdrdre _longpaths    rc sFytj|dStk r"YnXfdd|tj|dS)Nc sx~t|tj|D]l}tjj||}ytj|j}Wntk rJd}YnXtj |rn|t|tj |qt|tj |qWdS)Nr) rrrrrrrrrrrr)rrvrr)rrdrers  z_rmtree.._rmtree_inner)shutilrrrr)rrd)rrers  cCs|S)Nrd)rrdrdrersc Cs*y t|Wnttfk r$YnXdS)N)rFileNotFoundErrorNotADirectoryError)rrdrdrers c Cs&y t|Wntk r YnXdS)N)rr)rrdrdrers rc Cs&y t|Wntk r YnXdS)N)rr)rrdrdrers cCsBtjj|}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) rmutilcache_from_sourcerrrabspathrrename)sourceZpyc_fileZup_oneZ legacy_pycrdrdremake_legacy_pycs   rcCs\t|xNtjD]D}tjj||d}t|dx dD]}ttjj||dq8WqWdS) 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) rrorrrrrmrr)r~rroptrdrdrers    csttdrtjSd}tjjdrddlddld}d}Gfdddj}j j }|j }|sjj |}j j}|j||j|j|j|}|sj t|j|@sd}ntjdkrVdd lm} mm} m} dd lm} | j| d } | jdkrd }nFGfd dd| }|}| |}| j|dksR| j|dkrVd}|sy.ddlm}|}|j|j |j!Wn\t"k r}z>t#|}t$|dkr|ddd}dj%t&|j'|}WYdd}~XnX|t_(| t_tjS)Nresultrrrcs.eZdZdjjfdjjfdjjfgZdS)z*_is_gui_available..USEROBJECTFLAGSZfInheritZ fReserveddwFlagsN)r`rarbwintypesZBOOLDWORD_fields_rd)rrdreUSEROBJECTFLAGSs  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)r`rarbrrd)rrdreProcessSerialNumbersrz#cannot run without OS X gui process)Tk2z [...]zTk unavailable due to {}: {}))hasattr_is_gui_availablerrorprqrZctypes.wintypesrrZuser32ZGetProcessWindowStationZWinErrorrrZGetUserObjectInformationWZbyrefZsizeofboolrrrrZ ctypes.utilrZ LoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterrZwithdrawupdateZdestroy Exceptionrurformattyper`reason)rZ UOI_FLAGSZ WSF_VISIBLErZdllhZuofZneededresrrrrZ app_servicesrZpsnZpsn_prrooteZ err_stringrd)rrrersh         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)resourcerdrdrer $scCs>t|s |dkrd|}t||dkr:t r:ttjdS)z@Raise ResourceDenied if the specified resource is not available.Nz"Use of the %r resource not enabledgui)r r rr)rrxrdrdrer!,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. cs$tjfdd}|_|S)Nc stjkrztjjddd}yttt|jd}Wntk rLYn.X|krzdjtt }t j d||f||S)N-rrryz(%s version %s or higher required, not %s) rpsystemreleaserrrmapint ValueErrorrrursrt)rkw version_txtversionmin_version_txt)r min_versionsysnamerdrewrapper=s z:_requires_unix_version..decorator..wrapper) functoolswrapsr)rr)rr)rre decorator<sz)_requires_unix_version..decoratorrd)rrrrd)rrre_requires_unix_version5srcGs 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)rrdrdrer"PscGs 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)rrdrdrer#Yscsfdd}|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"tjfdd}|_|S)Nc sxtjdkrntjd}yttt|jd}Wntk rBYn,X|krndjtt }t j d||f||S)Nrrryz&Mac OS X %s or higher required, not %s) rorpZmac_verrrrrrrrrursrt)rrrrr)rrrdrerjs   z4requires_mac_ver..decorator..wrapper)rrr)rr)r)rrerisz#requires_mac_ver..decoratorrd)rrrd)rrer$bs 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 cstjfdd}|S)Nc sXy&rtdk rtjn tjWn&tk rLtjddYnX||S)Nz hash digest 'z' is not available.)_hashlibnewhashlibrrsrt)rkwargs) digestnameropensslrdrers  z7requires_hashdigest..decorator..wrapper)rr)rr)rr)rrers z&requires_hashdigest..decoratorrd)rrrrd)rrrer%}s z 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. )socketrHclose)familyZsocktypeZtempsockportrdrdrerGs 8 c Cs|jtjkr|jtjkrttdr>|jtjtjdkr>t dttdr~y |jtjtj dkrft dWnt k r|YnXttdr|j tjtj d|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_REUSEPORTzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!SO_EXCLUSIVEADDRUSEr)rrAF_INETr SOCK_STREAMrZ getsockoptZ SOL_SOCKETrr rrZ setsockoptrbindZ getsockname)sockhostrrdrdrerHs     c CsJ|jtjksty|j|Wn&tk rD|jtjdYnXdS)zBBind a unix socket, raising SkipTest if PermissionError is raised.zcannot bind AF_UNIX socketsN) rrZAF_UNIXAssertionErrorr PermissionErrorrrsrt)r ZaddrrdrdrerJs cCsZtjrVd}z.dec)rr)rrrd)rresystem_must_validate_certs rriZdoubleZIEEEztest requires IEEE 754 doublesz requires zlibz requires gzipz requires bz2z requires lzmajavaANDROID_API_LEVELwin32z/system/bin/shz/bin/shz$testz@testz {}_{}_tmpæİŁφКא،تก €u -àòɘŁğrZNFDntru-共Ł♡ͣztWARNING: The filename %r CAN be encoded by the filesystem encoding (%s). Unicode filename tests may not be effectives-surrogateescapewrccsd}|dkr&tj}d}tjj|}nBytj|d}Wn.tk rf|sNtjd|t ddYnX|rttj }z |VWd|r|tj 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. FNTz+tests may fail, unable to create temp dir: )r) tempfilemkdtemprrrealpathmkdirrrgrrgetpidr)rquietZ dir_createdpidrdrdretemp_dirs&   r3ccsftj}ytj|Wn.tk rD|s,tjd|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: r+)rN)rgetcwdchdirrrgrr)rr1Z saved_dirrdrdre change_cwd s  r6tempcwdccs:t||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. )rr1)r1N)r3r6)rvr1Z temp_pathZcwd_dirrdrdrer$sumaskc cs&tj|}z dVWdtj|XdS)z8Context manager that temporarily sets the process umask.N)rr8)r8ZoldmaskrdrdrerK8s  datacCsbtjj|r|S|dk r&tjj||}tgtj}x*|D]"}tjj||}tjj|r8|Sq8W|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_DIRroexists)rZsubdirrZdnfnrdrdrerIs    cCs(tj|tjtjBtjB}tj|dS)z>Create an empty file. If the file already exists, truncate it.N)ropenO_WRONLYO_CREATO_TRUNCr)rfdrdrdrer[scCs,t|j}dd|D}dj|}d|S)z%Like repr(dict), but in sorted order.cSsg|] }d|qS)z%r: %rrd).0Zpairrdrdre cszsortdict..z, z{%s})sortedrr)dictrZ reprpairsZ withcommasrdrdrer[`s  c Cs*ttd}z|jS|jttXdS)z` Create an invalid file descriptor by opening and closing a file and return its fd. wbN)r>rfilenorr)rrdrdre make_bad_fdgs  rI)linenooffsetc Csp|jt}t|ddWdQRX|j}|j|j|dk rJ|j|j||j|j|dk rl|j|j|dS)Nz exec) assertRaises SyntaxErrorcompileZ exceptionZassertIsNotNonerJ assertEqualrK)testcaseZ statementrJrKcmrrdrdrer&ss   c sVddl}ddl}jdd|jj|djdd}tjjt |}fdd}tjj |r|||}|dk rt|St |t dt rtd |td |jj}tr|jjd|j|d d}tr|jjdd krtj|d}zBt|d.} |j} x| r| j| |j} qWWdQRXWd|jX||}|dk rF|Std|dS)Nrcheckr/rcs>t|f}dkr|S|r2|jd|S|jdS)Nr)r>seekr)r=r)rrSrrdrecheck_valid_files z*open_urlresource..check_valid_fileZurlfetchz fetching %s ...)rAccept-Encodinggzip)rzContent-Encoding)ZfileobjrGzinvalid resource %r)rWrX)Zurllib.requestZ urllib.parsepopparseZurlparserrrr TEST_DATA_DIRr<rr!rrrZrequestZ build_openerrXZ addheadersrr>ZheadersgetZGzipFilereadwriterr ) Zurlrrurllibrr=rVropeneroutsrd)rrSrrerI~s<         c@s4eZdZdZddZddZeddZdd 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_listrdrdre__init__szWarningsRecorder.__init__cCsDt|j|jkr t|jd|S|tjjkr0dStd||fdS)Nrz%r has no attribute %rrZ)rrfrgrrgWarningMessage_WARNING_DETAILSr)rhattrrdrdre __getattr__s  zWarningsRecorder.__getattr__cCs|j|jdS)N)rfrg)rhrdrdrergszWarningsRecorder.warningscCst|j|_dS)N)rrfrg)rhrdrdreresetszWarningsRecorder.resetN) r`rarbrcrirmpropertyrgrnrdrdrdreres  rec cs tjd}|jjd}|r"|jtjdd }tjdjdt |VWdQRXt |}g}xz|D]r\}}d} xH|ddD]8}|j } t j |t| t jrt| j|rd} |j|qW| rf| rf|j||jfqfW|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__T)recordrgalwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)ro _getframe f_globalsr^clearrgrhrz simplefilterrer|messagerematchruI issubclassrremoverr`r) filtersr1frameregistrywZreraiseZmissingrxcatseenZwarningrdrdre_filterwarningss0    rcOs.|jd}|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) r1rNT)r^Warningr)r|rr1rdrdrerRs   c csBtjdd }tjdtddVtWdQRX|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. T)rprq)categoryN)rgrhriResourceWarning gc_collectrP)rQZwarnsrdrdrerSs c@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 cGsNtjj|_x<|D]4}|tjkrtj|}|j|kr>tj|j=tj|=qWdS)N)rorzcopyoriginal_modulesr`)rhZ module_namesZ module_namerrdrdreri's      zCleanImport.__init__cCs|S)Nrd)rhrdrdre __enter__4szCleanImport.__enter__cGstjj|jdS)N)rorzrr)rh ignore_excrdrdre__exit__7szCleanImport.__exit__N)r`rarbrcrirrrdrdrdrers  c@sheZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZdS)rTz_Class to help protect the environment variable properly. Can be used as a context manager.cCstj|_i|_dS)N)renviron_environ_changed)rhrdrdreri@szEnvironmentVarGuard.__init__cCs |j|S)N)r)rhenvvarrdrdre __getitem__DszEnvironmentVarGuard.__getitem__cCs*||jkr|jj||j|<||j|<dS)N)rrr^)rhrvaluerdrdre __setitem__Gs zEnvironmentVarGuard.__setitem__cCs2||jkr|jj||j|<||jkr.|j|=dS)N)rrr^)rhrrdrdre __delitem__Ms  zEnvironmentVarGuard.__delitem__cCs |jjS)N)rkeys)rhrdrdrerTszEnvironmentVarGuard.keyscCs t|jS)N)iterr)rhrdrdre__iter__WszEnvironmentVarGuard.__iter__cCs t|jS)N)rr)rhrdrdre__len__ZszEnvironmentVarGuard.__len__cCs |||<dS)Nrd)rhrrrdrdreset]szEnvironmentVarGuard.setcCs ||=dS)Nrd)rhrrdrdreunset`szEnvironmentVarGuard.unsetcCs|S)Nrd)rhrdrdrercszEnvironmentVarGuard.__enter__cGsJx<|jjD].\}}|dkr0||jkr:|j|=q ||j|<q W|jt_dS)N)rrrrr)rhrkvrdrdrerfs   zEnvironmentVarGuard.__exit__N)r`rarbrcrirrrrrrrrrrrdrdrdrerT;sc@s(eZdZdZddZddZddZdS) DirsOnSysPathaContext manager to temporarily add directories to sys.path. This makes a copy of sys.path, appends any directories given as positional arguments, then reverts sys.path to the copied settings when the context ends. Note that *all* sys.path modifications in the body of the context manager, including replacement of the object, will be reverted at the end of the block. cGs(tjdd|_tj|_tjj|dS)N)rororiginal_valueoriginal_objectextend)rhpathsrdrdreri|szDirsOnSysPath.__init__cCs|S)Nrd)rhrdrdrerszDirsOnSysPath.__enter__cGs|jt_|jtjdd<dS)N)rrorr)rhrrdrdrerszDirsOnSysPath.__exit__N)r`rarbrcrirrrdrdrdrerps rc@s*eZdZdZddZddZd ddZdS) r'zRaise ResourceDenied if an exception is raised while the context manager is in effect that matches the specified exception and attributes.cKs||_||_dS)N)rattrs)rhrrrdrdreriszTransientResource.__init__cCs|S)Nrd)rhrdrdrerszTransientResource.__enter__NcCsT|dk rPt|j|rPx:|jjD]$\}}t||s4Pt|||kr Pq WtddS)zIf type_ is a subclass of self.exc and value has attributes matching self.attrs, raise ResourceDenied. Otherwise let the exception propagate (if any).Nz%an optional resource is not available)rzrrrrrr )rhZtype_r tracebackrlZ attr_valuerdrdrers zTransientResource.__exit__)NNN)r`rarbrcrirrrdrdrdrer's)errnog>@)rerrnosc #spd!d"d#d$d%d&g}d(d*d,d.d/g}td||gsRdd|Ddd|Dfdd}tj}zy|dk rtj|dVWntjk r}z&trtjj j dd|WYdd}~Xnt k rZ}zpx^|j }t |d krt |dt r|d}n*t |dkr8t |d t r8|d }nPqW||WYdd}~XnXWdtj|XdS)0zReturn a context manager that raises ResourceDenied when various issues with the Internet connection manifest themselves as exceptions. ECONNREFUSEDo ECONNRESETh EHOSTUNREACHq ENETUNREACHe ETIMEDOUTn EADDRNOTAVAILc EAI_AGAINr+EAI_FAILr EAI_NONAMEr EAI_NODATA WSANO_DATA*zResource %r is not availablecSsg|]\}}tt||qSrd)rr)rCrvnumrdrdrerDsz&transient_internet..cSsg|]\}}tt||qSrd)rr)rCrvrrdrdrerDscst|dd}t|tjst|tjr,|kst|tjjrTd|jkoNdknst|tjj rd|j ksd|j ksd|j ks|krt st j jjdd|dS) NriiWConnectionRefusedError TimeoutErrorEOFErrorr )r isinstancerrZgaierrorraerrorZ HTTPErrorcodeZURLErrorrrrostderrr`r)rn)captured_errnosdenied gai_errnosrdre filter_errors     z(transient_internet..filter_errorNrrr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)r rZgetdefaulttimeoutZsetdefaulttimeoutnntplibZNNTPTemporaryErrorrrorr`rrrr) Z resource_namerrZdefault_errnosZdefault_gai_errnosrZ old_timeoutrard)rrrrer+sP     c csFddl}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)iorrosetattrStringIO)Z stream_namerZ orig_stdoutrdrdrecaptured_outputs  rcCstdS)zCapture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") r)rrdrdrdrerscCstdS)zCapture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") r)rrdrdrdrer scCstdS)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)rrdrdrdrers cCs*tjtrtjdtjtjdS)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@rrrdrdrdrer#s  rc cs.tj}tjz dVWd|r(tjXdS)N)r isenableddisableenable)Zhave_gcrdrdre disable_gc3s  rcCs:tjdp d}d}x|jD]}|jdr|}qW|dkS)z,Find if Python was built with optimizations. PY_CFLAGSrz-O-O0-Og)rrr) sysconfigget_config_varrrq)ZcflagsZ final_optrrdrdrepython_is_optimized>s  rZnPZ0ngettotalrefcountZ2PZ0PrcCstjt|tS)N)structcalcsize_header_align)fmtrdrdre calcobjsizeOsrcCstjt|tS)N)rr_vheaderr)rrdrdre calcvobjsizeRsr cCspddl}tj|}t|tkr(|jt@sBt|tkrLt|jt@rL||j7}dt|||f}|j|||dS)Nrz&wrong size for %s: got %d, expected %d) _testcapiro getsizeofr __flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADrP)testosizerrrxrdrdre check_sizeofYs  rcsfdd}|S)Ncs$fdd}j|_j|_|S)Ncsy ddl}t|}|j|}Wn(tk r6YnBd}}Yn0Xx,D]$}y|j||PWqPYqPXqPWz ||S|r|r|j||XdS)Nr)localer setlocaler)rkwdsrrZ orig_localeloc)catstrrlocalesrdreinnerjs$     z1run_with_locale..decorator..inner)r`rc)rr)rr)rrerisz"run_with_locale..decoratorrd)rrrrd)rrrerUhscsfdd}|S)Ncs"fdd}j|_j|_|S)Ncsy tj}Wntk r(tjdYnXdtjkr@tjd}nd}tjd<|z ||S|dkrrtjd=n |tjd<tjXdS)Nztzset requiredZTZ)rtzsetrrsrtrr)rrrZorig_tz)rtzrdrers       z-run_with_tz..decorator..inner)r`rc)rr)r)rrerszrun_with_tz..decoratorrd)rrrd)rrer\s cCsdttdtd}tjd|tjtjB}|dkr>td|ftt|j d||j dj }|a |t krrt }|t dkrtd|f|adS)Ni)rmgtz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rrr+z$Memory limit %r too low to be useful)_1M_1Grwrx IGNORECASEVERBOSErrfloatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitZsizesrZmemlimitrdrdrerYs $ c@s(eZdZdZddZddZddZdS) _MemoryWatchdogz`An object which periodically watches the process' memory consumption and prints it out. cCsdjtjd|_d|_dS)Nz/proc/{pid}/statm)r2F)rrr0procfilestarted)rhrdrdrerisz_MemoryWatchdog.__init__cCsyt|jd}Wn<tk rL}z tjdj|ttjj dSd}~XnXt d}t j tj |g|t jd|_|jd|_dS)Nrz!/proc not available for stats: {}zmemory_watchdog.py)rrT)r>rrrgrrrrorflushr subprocessPopen executableZDEVNULL mem_watchdogrr )rhrrZwatchdog_scriptrdrdrestarts   z_MemoryWatchdog.startcCs|jr|jj|jjdS)N)r rZ terminatewait)rhrdrdrestops z_MemoryWatchdog.stopN)r`rarbrcrirrrdrdrdrersrcsfdd}|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}tsd}n|}ts$ rFt||krFtjd||dtr|tr|ttdj||ddt}|j nd}z ||S|r|j XdS) Niz'not enough memory: %.1fG minimum neededir+z* ... expected peak memory use: {peak:.1f}G)Zpeaki@i@) rmemuserrsrtrrrrrr)rhrrmaxsizeZwatchdog)dry_runrrrdrers*    z.bigmemtest..decorator..wrapper)rr)r)rrr)rrrerszbigmemtest..decoratorrd)rrrrrd)rrrrer3s !csfdd}|S)z0Decorator for tests that fill the address space.csDttkr8td kr$td kr$tjdq@tjdtd n|SdS) Nr?rz-not enough memory: try a 32-bit build insteadz'not enough memory: %.1fG minimum neededir+llli@)rrrsrt)rh)rrdrersz!bigaddrspacetest..wrapperrd)rrrd)rrer4s c@seZdZddZdS)r,cCstj}|||S)N)rsZ TestResult)rhrrrdrdrerun,szBasicTestRunner.runN)r`rarbrrdrdrdrer,+scCs|S)Nrd)rrdrdre_id1srcCs<|dkrt rtjtjSt|r(tStjdj|SdS)Nrzresource {0!r} is not enabled)rrsskiprr rr)rrdrdrerequires_resource4s  rcCs&trt|krtjd|tfStSdS)Nz%s at Android API level %d)rA_ANDROID_API_LEVELrsrr)levelrrdrdrer><s  cCstdd|S)z9 Decorator for tests only applicable on CPython. T)cpython) impl_detail)rrdrdrer5CscKsVtf|rtS|dkrLt|\}}|r,d}nd}t|j}|jdj|}tj|S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or ) rBr _parse_guardsrErrrrsr)rxguardsZ guardnamesdefaultrdrdrerIs   rc CsTtdkr:ddl}y|jdaWntk r8daYnXd}trF|Stj||S)z8Skip decorator for tests that use multiprocessing.Queue.NrTFz6requires a functioning shared semaphore implementation)_have_mp_queuemultiprocessingZQueuernrsr)rr$rxrdrdrer?Ws cCsH|sddidfSt|jd}t|j|gt|ks>t|| fS)NrTFr)r|valuesrr)r!Zis_truerdrdrer fs  r cKs 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 )r r^rpZpython_implementationr)r!r"rdrdrerBps cs,ttdsStjfdd}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.gettracec s.tj}ztjd||Stj|XdS)N)ror&settrace)rrZoriginal_trace)rrdrers   zno_tracing..wrapperN)rrorr)rrrd)rre no_tracing{s 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(r5)rrdrdre refcount_testsr)cCsRg}xB|jD]8}t|tjr2t|||j|q ||r |j|q W||_dS)z>Recursively filter test cases in a suite based on a predicate.N)Z_testsrrs TestSuite _filter_suiter)suiteZpredZnewtestsrrdrdrer+s    r+cCsttjttdk d}|j|}tdk r4tj|j|js>t |j st |j dkrl|j rl|j dd}n6t |j dkr|j r|j dd}nd}ts|d7}t|dS)z2Run tests from a unittest.TestSuite-derived class.N) verbosityZcapture_outputrrzmultiple errors occurredz!; run in verbose mode for details)rrorrjunit_xml_listrrZget_xml_elementZtestsRunr Z wasSuccessfulrerrorsZfailuresr )r,Zrunnerrrrdrdre _run_suites"  r0cCstdkr dSt|jSdS)NT)_match_test_funcid)rrdrdre match_testsr3cCsd|kotjd| S)Nryz[?*\[\]])rwsearch)rrdrdre_is_full_match_testsr5csr|tkr dS|sd}f}nHttt|r4t|j}n.djttj|}t j |j fdd}|}t |a|a dS)N|cs$|r dStt|jdSdS)NTry)anyrr)Ztest_id) regex_matchrdrematch_test_regexsz)set_match_tests..match_test_regex)_match_test_patternsallrr5r __contains__rfnmatch translaterwrOrxrrr1)ZpatternsrZregexr9rd)r8reset_match_testss   r?cGstjtjf}tj}xh|D]`}t|trT|tjkrJ|jtjtj|qzt dqt||rj|j|q|jtj |qWt |t t |dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesN)rsr*ZTestCaserrurorzZaddTestZ findTestCasesrZ makeSuiter+r3r0)classesZ valid_typesr,clsrdrdrer-s        cCsdS)z,Just used to check if docstrings are enabledNrdrdrdrdre_check_docstringssrBWITH_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 rr`)rr-rDrErrrdrdrer.!scCs tjjfS)N)rorzrrdrdrdre modules_setup<srFcCs:ddtjjD}tjjtjj|tjj|dS)NcSs"g|]\}}|jdr||fqS)z encodings.)rq)rCrrrdrdrerDCsz#modules_cleanup..)rorzrrtr)Z oldmodulesZ encodingsrdrdremodules_cleanup?s  rGcCs"trtjtjjfSdffSdS)Nr)_thread_count threading _danglingrrdrdrdrerNbscGsJtsdSd}x8t|D],}tjtjf}||kr2PtjdtqWdS)Ndg{Gz?)rHrangerIrJrKrrr)Zoriginal_valuesZ _MAX_COUNTcountr%rdrdrerOhs cs"tsStjfdd}|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 st}z|St|XdS)N)rNrO)rkey)rrdrer|szreap_threads..decorator)rHrr)rrrd)rrerPtsN@ccstj}z dVWdtj}||}xjtj}||kr8Ptj|kr|tj|}d||d|dd|d|d }t|tjdtq&WXdS) aH bpo-31234: Context manager to wait until all threads created in the with statement exit. Use _thread.count() to check if threads exited. Indirectly, wait until threads exit the internal t_bootstrap() C function of the _thread module. threading_setup() and threading_cleanup() are designed to emit a warning if a test leaves running threads in the background. This context manager is designed to cleanup threads started by the _thread.start_new_thread() which doesn't allow to wait for thread exit, whereas thread.Thread has a join() method. Nz!wait_threads() failed to cleanup z threads after z.1fz seconds (count: z , old count: )g{Gz?)rHrIrZ monotonicrrr)rZ old_countZ start_timeZdeadlinerNZdtrxrdrdrewait_threads_exits   $ rRc CsZttdrVd}xFy2tj|tj\}}|dkr.Ptd|tjdWqPYqXqWdS)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. waitpidrrz2Warning -- reap_children() reaped child process %s)rNrZ)rrrSWNOHANGrror)Z any_processr2ZstatusrdrdrerLs ccs*t|}g}zZy$x|D]}|j|j|qWWn*trVtdt|t|fYnXdVWdz|rt|tj}}xltddD]^}|d7}x$|D]}|jt |tjdqWdd|D}|sPtrtdt||fqWWdd d|D}|r"t j t j td t|XXdS) Nz/Can't start %d threads, only %d threads startedrr<g{Gz?cSsg|]}|jr|qSrd)isAlive)rCrrdrdrerDsz!start_threads..z7Unable to join %d threads during a period of %d minutescSsg|]}|jr|qSrd)rV)rCrrdrdrerDszUnable to join %d threads)r|rrrrrrrMrmax faulthandlerZdump_tracebackrorr)ZthreadsZunlockr rZendtimeZ starttimerrdrdrerQs>     c csnt||rrrurHrprrwrxrrrrr)rsZtmp_dirZtmp_fpZtmp_namefpZkernel_versionrrdrdre can_xattr s,    rzcCs t}d}|r|Stj||S)zDSkip decorator for tests that require functional extended attributesz(no non-broken extended attribute support)rzrsr)rrtrxrdrdrer8 scCs$t pt}d}|r|Stj||S)z;Skip decorator for tests not run in (non-extended) PGO taskz#Not run for (non-extended) PGO task)r] PGO_EXTENDEDrsr)rrtrxrdrdreskip_if_pgo_task s r|cCs^tj|dH}|j}|j}||kr,|j}ytjj||Stk rNdSXWdQRXdS)zKDetects if the file system for the specified directory is case-insensitive.)rvFN) r,ZNamedTemporaryFilervupperrrrsamefiler)Z directorybase base_pathZ case_pathrdrdrer s)rfcCs>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(|] }|jd s|jdr|VqdS)___N)rqendswith)rCrrdrdre sz&detect_api_mismatch..)rrv)Zref_apiZ other_apirfZ missing_itemsrdrdrer< s  cCs|dkr|jf}nt|tr"|f}t|}xbt|D]V}|jds4||krLq4t||}t|dd|kst|d r4t|tj  r4|j |q4W|j |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) Nrra) r`rrurrvrqrrtypes ModuleTypeaddZassertCountEqual__all__)Z test_caserZname_of_moduleZextraZ blacklistZexpectedrvrrdrdrer= s)    c@s(eZdZdZdZdZddZddZdS)rZzTry 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 Csrtjjdrddl}|jj|_d}|jj||_|jj|j|Byddl }|j Wnt t fk rlYnLXi|_ x|j|j|jgD].}|j ||j}|j||j}||f|j |<qWntdk r y*tjtj|_tjtjd|jdfWnttfk rYnXtjdkrnddd d g}tj|tjtjd }||jd} WdQRX| jd krntd ddd|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/defaultsr_zcom.apple.CrashReporterZ DialogType)rrs developerz:this test triggers the Crash Reporter, that is intentionalrT)endr ) rorprqrrr_k32 SetErrorMode old_valuemsvcrtCrtSetReportModerrn old_modesCRT_WARN CRT_ERROR CRT_ASSERTZCRTDBG_MODE_FILECrtSetReportFileZCRTDBG_FILE_STDERRrZ getrlimit RLIMIT_CORE setrlimitrrr r PIPEZ communicater_r) rhrZSEM_NOGPFAULTERRORBOXr report_typeold_modeold_filecmdprocrrdrdrer sN        zSuppressCrashReport.__enter__c Gs|jdkrdStjjdrl|jj|j|jrddl}xj|jjD]$\}\}}|j |||j ||qBWn6t dk ryt j t j |jWnttfk rYnXdS)zARestore Windows ErrorMode or core file behavior to initial value.Nrr)rrorprqrrrrrrrrrrrr)rhrrrrrrdrdrer[ s   zSuppressCrashReport.__exit__)r`rarbrcrrrrrdrdrdrerZ s Ac srtdyjWn$ttfk r@tdYnXdfdd}|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)rrYrd) attr_is_local attr_nameobject_to_patchrrdrecleanup szpatch..cleanup)rrhrrZ addCleanupr)Z test_instancerrZ new_valuerrd)rrrrrepatchp s  rc CsFy ddl}Wntk r YnX|jr4tjdddl}|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) tracemallocrnZ is_tracingrsrtrrun_in_subinterp)rrrrdrdrer s  rcsHGfddd|}d||||jttt|jdS)NcseZdZfddZdS)z%check_free_after_iterating..Ac s*dy tWntk r$YnXdS)NT)next StopIteration)rh)doneitrdre__del__ s  z-check_free_after_iterating..A.__del__N)r`rarbrrd)rrrdreA srF)rMrrrZ assertTrue)rrrArrrd)rrrecheck_free_after_iterating s   rcCsddlm}m}m}|j}|j|xd|jD]Z}|r@||kr@q.t||}|rd|dk sntd|n |dkrnq.|j |ddkr.|dSq.WdS)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 executablesrrZfind_executable)Z cmd_namesrrrZcompilerrvrrdrdrer^ s       cCs@d}tr6||kr6tdkr.tjddgjdkatr6|}tj|S)Ngh㈵>Zgetpropzro.kernel.qemu1)rA_is_android_emulatorr Z check_outputr_rorD)ZintervalZminimum_intervalrdrdrerD s c cs>tjj}tj}ztjdVWd|r8tj|ddXdS)NT)rZ all_threads)rorrHrX is_enabledrr)rBrrdrdredisable_faulthandler s  rc /Cstjjd r8ytjd}t|dStk r6YnXd}ttdrjytjd}Wnt k rhYnXd}tjd kryd dl }|j Wnt t fk rYn0Xi}x(|j|j|jfD]}|j |d ||<qWzpd }xft|D]Z}ytj|}Wn4t k r(}z|jtjkrWYdd}~XqXtj||d7}qWWd|dk rzx*|j|j|jfD]}|j |||q`WX|S) z/Count the number of open file descriptors. linuxfreebsdz /proc/self/fdrsysconf SC_OPEN_MAXNrr)rr)rorprqrrrrrrrrrrrnrrrrMduprZEBADFr) namesZMAXFDrrrrNrBZfd2rrdrdrer_ sP          c@s(eZdZdZddZddZddZdS) SaveSignalsz Save an 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 Csjddl}||_ttd|j|_x>dD]6}yt||}Wntk rNw&YnX|jj|q&Wi|_dS)NrrSIGKILLSIGSTOP)rr) signalr|rMNSIGsignalsrrr{rd)rhrZsignamesignumrdrdreri5 s zSaveSignals.__init__cCs4x.|jD]$}|jj|}|dkr"q||j|<qWdS)N)rr getsignalrd)rhrhandlerrdrdresaveB s   zSaveSignals.savecCs*x$|jjD]\}}|jj||q WdS)N)rdrr)rhrrrdrdrerestoreN szSaveSignals.restoreN)r`rarbrcrirrrdrdrdrer, s  rc@s(eZdZdZddZddZddZdS) FakePathz.Simple implementing of the path protocol. cCs ||_dS)N)r)rhrrdrdreriV szFakePath.__init__cCsd|jdS)Nz )r)rhrdrdre__repr__Y szFakePath.__repr__cCs6t|jts$t|jtr,t|jtr,|jn|jSdS)N)rr BaseExceptionrrz)rhrdrdre __fspath__\ s    zFakePath.__fspath__N)r`rarbrcrirrrdrdrdrerS src cs.tj}ztj|dVWdtj|XdS)z>Temporarily change the integer string conversion length limit.N)roget_int_max_str_digitsset_int_max_str_digits)Z max_digitsZcurrentrdrdreadjust_int_max_str_digitsd s   r)T)F)F)N)Nii@i@i@ii) rrrrrrrr r!r"r#)r'r%r(r)r*)NF)F)r7F)N)Fi@ii)T)N)Nr)rP)N(rcr`rncollections.abc collections contextlibZdatetimerrXr=rrrrmimportlib.utilrZlogging.handlersrcrrrprwrrrrr rorr,rrrsZ urllib.errorrargZ testresultrrHrJZmultiprocessing.processr$zlibrXbz2Zlzmarrrrr r r rtr contextmanagerrkr rrr:r;rr6rrrrr.rrrrrrrqrrrrrrrrrrrr r!rr"r#r$r%rErr r rGrHrJrrFrrZ SOCK_MAX_SIZEZ skipUnlessr __getformat__r7r9r0r1r2r@rrrArCrvrrr0Z FS_NONASCII characterfsdecodefsencode UnicodeErrorZTESTFN_UNICODEZ unicodedataZ normalizegetfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversionencodeUnicodeEncodeErrorrdecodeUnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIr4rr]r{r3r6rrrKrrrrZTEST_SUPPORT_DIRr;rr]rrr[rIr&rIobjectrerrRrSrabcMutableMappingrTrr'rrr(rr)r*r+rrrrrrrrrrrrrrrrUr\rrrZ_4GrrrYrr3r4r,rrr>r5rr#r?r rBr(r)r+r0r1r:r3r5r?r-rBZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr.rFrGZenvironment_alteredrNrOrPrRrLrQrWrVr`ZskipIfZrequires_type_collectingrarbrdrerMrXrprr/rxrzr8r|rr<r=rZrrrr^rrDrr_rrrrdrdrdres                      2   !  J    > %                 %      2 ' 5M          $ # 0           (        " #   "    :_"  ;'