bg dZddlmZmZmZmZddlmZddlm Z m Z m Z m Z m Z mZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZeedsddlZddlZddlZddlZddlZddl Z ddl!Z!n#e"$r ddl#m!Z!YnwxYwddl$Z$ddl%Z&ddl'Z'ddl(Z( ej)r ddl*Z*ddl+Z+nddl,Z*ddl+Z+n#e"$rdZ*dZ+YnwxYw ddl-Z.n #e"$rdZ.YnwxYw ddl/Z/n #e"$rdZ/YnwxYw ddl0Z0n #e"$rdZ0YnwxYw ddl1Z1n #e"$rdZ1YnwxYw ddl2Z2n #e"$rdZ2YnwxYwgdZ3Gd d e4Z5Gd d e5Z6Gd dej7Z8ej9ddZ:ddZ;dZddZ?dZ@dZAdZBdaCdaDdZEdZFdaGdZHdZIdZJejKdrddZLdZMd ZNd!ZOnejPZMejQZNejRZOd"ZPd#ZQd$ZRd%ZSd&ZTejKdr ddlUZUddlVZUd'ZWnd(ZWd)ZXdd*ZYd+ZZd,Z[d-Z\d.Z]d/Z^d0Z_ej`ejafd1Zbe^fd2Zcd3ZdedZed4Zfd5Zgejhe/d6Ziejhe1d7Zjejhe2d8ZkejKd9Zlejmd9krd:Znnd;ZndZseed?rej9d@ZteudfdAZvdBZwdCZxdDZydEZzdFZ{GdGdHe|Z}ddIZ~ej9dJZGdKdLe|Zej)rddlZejjZn ddlZejZGdMdNeZGdOdPe|ZGdQdRe|ZeeejSZeejejSZeeejSZej9ddUZej9dVZdWZdXZdYZdZZej9d[Zd\Zd]Zd^Zeed_rd`ezZdaZedbzZdcZddZdeZdfZdgZdhZdiZdjZdkezZdlezZdmezZejZdnZGdodpe|ZddqZdrZGdsdte|ZduZdvZdwZddxZdyZdzZd{Zd|Zd}Zd~ZdZddZdZdZdZdZdZdZej9dZej9dZdZdZGdde&jjZGdde|ZdadZdZdadZdZejKdrej9dZnej9dZdZdS)zwSupporting definitions for the Python regression tests. Backported for python-future from Python 3.3 test/support.py. )absolute_importdivisionprint_functionunicode_literals)utils)strrangeopenintmaplistNskip) sysconfig)JError TestFailedResourceDenied import_moduleverbose use_resources max_memuserecord_original_stdoutget_original_stdoutunloadunlinkrmtreeforgetis_resource_enabledrequiresrequires_freebsd_versionrequires_linux_versionrequires_mac_verfind_unused_port bind_port IPV6_ENABLED is_jythonTESTFNHOSTSAVEDCWDtemp_cwdfindfilecreate_empty_filesortdictcheck_syntax_erroropen_urlresourcecheck_warnings CleanImportEnvironmentVarGuardTransientResourcecaptured_stdoutcaptured_stdincaptured_stderrtime_outsocket_peer_resetioerror_peer_resetrun_with_locale temp_umasktransient_internet set_memlimit bigmemtestbigaddrspacetestBasicTestRunner run_unittest run_doctestthreading_setupthreading_cleanup reap_children cpython_onlycheck_impl_detail get_attribute swap_item swap_attrrequires_IEEE_754 TestHandlerMatcher can_symlinkskip_unless_symlinkskip_unless_xattrimport_fresh_module requires_zlib PIPE_MAX_SIZEfailfastanticipate_failure run_with_tz requires_gzip requires_bz2 requires_lzmasuppress_crash_popupceZdZdZdS)rz*Base class for regression test exceptions.N__name__ __module__ __qualname____doc__n/builddir/build/BUILD/cloudlinux-venv-1.0.7/venv/lib/python3.11/site-packages/future/backports/test/support.pyrrbs4444rarceZdZdZdS)rz Test failed.Nr[r`rarbrresrarceZdZdZdS)rzTest 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. Nr[r`rarbrrhsrarTc#K|rMtj5tjddtdVddddS#1swxYwYdSdVdS)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)rfs rb_ignore_deprecated_importsrkps   $ & &    #H.C$6 8 8 8 EEE                   s AA  A Fct|5 tj|cdddS#t$r&}t jt |d}~wwxYw#1swxYwYdS)zImport 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.N)rk importlibr ImportErrorunittestSkipTestr)name deprecatedmsgs rbrrs $J / /.. .*400........ . . .#CHH-- - ...........s+A%2 A"!AA""A%%A),A)c|tjvrt|tj|=ttjD]B}||ks||dzr"tj|||<tj|=CdS)zyHelper function to save and remove a module from sys.modules Raise ImportError if the module can't be imported. .N)sysmodules __import__r startswith)rq orig_modulesmodnames rb_save_and_remove_moduler|s  3;4 K  $$%% d??g00<z$anticipate_failure..sQra)roexpectedFailure) conditions rbrTrTs ('' ;rar`cFt|5i}g}t|| |D]}t|||D]'}t||s||(t j|}n#t $rd}YnwxYw|D]\} } | tj | <|D]} tj | =n@#|D]\} } | tj | <|D]} tj | =wxYw|cdddS#1swxYwYdS)aVImport 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. If deprecated is True, any module or package deprecation messages will be suppressed. N) rkr|rappendrmrrnitemsrvrw) rqfreshblockedrrrznames_to_remove fresh_name blocked_name fresh_module orig_namemodulename_to_removes rbrPrPs: $J / / l333 0# B B ' LAAAA ' 9 9 -lLII9#**<888$2488LL   LLL &2%7%7%9%9 0 0! 6)/ I&&"1 0 0K// 0&2%7%7%9%9 0 0! 6)/ I&&"1 0 0K// 0)sGDAA:9C: B CB  C tj|}|r|sn||vsdSt j||dz}|dk>t jd|ztddS)NrugMbP?g?z)tests may fail, delete still pending for  stacklevel) ospathsplitlistdirtimesleeprgwarnRuntimeWarning)funcpathnamewaitalldirnamerqtimeoutLs rb_waitforr s X  %GGGMM(33MGTnGmm 7##A  A  daii Jw    qLGmm  AHL$ 4 4 4 4 4 4rac:ttj|dSr)rrr)filenames rb_unlinkr+sH%%%%%rac:ttj|dSrrrrmdir)rs rb_rmdirr.s7#####racjfdt|dttj|dS)Nc*tj|D]|}tj||}tj|r't |dtj|htj|}dS)NTr)rrrjoinisdirrrr)rrqfullname _rmtree_inners rbrz_rmtree.._rmtree_inner2s 4(( ( (7<<d337==**(]HdCCCCHX&&&&Ih''''  ( (raTrr)rrs @rb_rmtreer1sK ( ( ( ( ( d33334     rac t|dS#t$r+}|jtjtjfvrYd}~dSd}~wwxYwr)rOSErrorerrnoENOENTENOTDIR)rerrors rbrrAsg  ;u|U]; ; ;  < ; ; ; ; ;s A AAc t|dS#t$r!}|jtjkrYd}~dSd}~wwxYwr)rrrr)rrs rbrrIs[w  ;%, & &  ' & & & & & >9>c t|dS#t$r!}|jtjkrYd}~dSd}~wwxYwr)rrrr)rrs rbrrQs[  ;%, & &  ' & & & & &rctj|}tjtj|}tj||dz}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. Tc)impcache_from_sourcerrrabspathrrename)sourcepyc_fileup_one legacy_pycs rbmake_legacy_pycrXsg$V,,H W__RW__V44 5 5Fff&JKKJIh ### rac\t|tjD]}tj||dz}t |dzt |dzt t j|dt t j|ddS)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.pyroT)debug_overrideFN)rrvrrrrrr)r{rrs rbrrhs  7OOO8DDgw77 v|v|s$VDAAABBBs$VEBBBCCCCDDrac d}d}Gddtj}tjj}|}|stj|}tj}|||tj |tj |tj |}|stjt|j |zS)Nrc`eZdZdejjfdejjfdejjfgZdS)*_is_gui_available..USEROBJECTFLAGSfInherit fReserveddwFlagsN)r\r]r^ctypeswintypesBOOLDWORD_fields_r`rarbUSEROBJECTFLAGSrs<#V_%9:$fo&:;"FO$9:.decorator..wrappers  G++&.0066sA>>qA  G#C[->->s-C-C$D$DEEG,,*-((3sK3H3H*I*I&/&wwFGGG-"D4$$$ $s5C CC functoolswrapsr)rrrrs` rb decoratorz)_requires_unix_version..decoratorsK    % % % % % %   %*rar`)rrrs`` rb_requires_unix_versionrs*$ rac"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. FreeBSDrrs rbrrs ")[ 9 99rac"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. Linuxrrs rbr r s "'; 7 77racfd}|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. cXtjfd}|_|S)Nctjdkrtjd} tt t |d}|krBdt t}tj d|d|n#t$rYnwxYw|i|S)Ndarwinrruz Mac OS X r) rvrmac_verr r r rrrrorpr )r rrrrrrs rbrz4requires_mac_ver..decorator..wrappers|x''&.003  >#C[->->s-C-C$D$DEEG,,*-((3sK3H3H*I*I&//. =>>>-"D4$$$ $s5B** B76B7r)rrrs` rbrz#requires_mac_ver..decoratorsF    % % % % %   %*rar`)rrs` rbr!r!s$$ raz 127.0.0.1::1cxtj||}t|}|~|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 socket.error 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)familysocktypetempsockports rbr"r"s;p}VX..H X  D NN Krac|jtjkr|jtjkrt tdr=|tjtjdkrtdt tdrT |tjtj dkrtdn#tj $rYnwxYwt tdr+| tjtj d||df|d}|S)a%Bind the socket to a free port and return the port number. Relies on ephemeral ports in order to ensure we are using an unbound port. This is important as many tests may be running simultaneously, especially in a buildbot environment. This method raises an exception if the sock.family is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR or SO_REUSEPORT set on it. Tests should *never* set these socket options for TCP/IP sockets. The only case for setting these options is testing multicasting via multiple UDP sockets. Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. on Windows), it will be set on the socket. This will prevent anyone else from bind()'ing to our host/port for the duration of the test. SO_REUSEADDRrzHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets! SO_REUSEPORTzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!SO_EXCLUSIVEADDRUSEr)r)r'AF_INETtype SOCK_STREAMhasattr getsockopt SOL_SOCKETr.rr/r setsockoptr0bind getsockname)sockhostr,s rbr#r#9sO {fn$$f6H)H)H 6> * * Ev0&2EFF!KK "DEEE 6> * *  ??6#4f6IJJaOO$&HIIIP<      60 1 1 N OOF-v/I1 M M MIItQi     a D Ks=CC$#C$ctjrd} tjtjtj}|d |r|dSdS#tjtjf$rYnwxYw |r|n#|r|wwxYwdS)z+Check whether IPv6 is enabled on this host.N)r%rTF)r'has_ipv6AF_INET6r3r8r(rgaierror)r:s rb_is_ipv6_enabledr@^s   =&2DEED IIj ! ! !     fo.    D        5s#>A))BB"BB""B;i@iz requires zlibz requires bz2z requires lzmajavaz$testz@testz {0}_{1}_tmptempcwdc#0Ktj}d}|L|} tj|d}n2#t$r%|st jd|zt dYnwxYw tj|n2#t$r%|st jd|zt dYnwxYw tjVtj||rt|dSdS#tj||rt|wwxYw)a Context manager that temporarily changes the CWD. An existing path may be provided as *path*, in which case this function makes no changes to the file system. Otherwise, the new CWD is created in the current directory and it's named *name*. If *quiet* is False (default) and it's not possible to create or change the CWD, an error is raised. If it's True, only a warning is raised and the original CWD is used. FNTz*tests may fail, unable to create temp CWD rz,tests may fail, unable to change the CWD to ) rgetcwdmkdirrrgrrchdirr)rqquietr saved_dir is_temporarys rbr)r)ss IL | 8 HTNNNLL 8 8 8  MFM(Q 8 8 8 8 8 8 8 4  444   DtK$ 4 4 4 4 4 44 ikk    4LLLLL      4LLLL s-4,A#"A#'A<<,B+*B+/C--(Dumaskc#Ktj|} dVtj|dS#tj|wxYw)z8Context manager that temporarily sets the process umask.N)rrK)rKoldmasks rbr:r:<sO(5//  EEE HW     BHW    s 2Acztj|r|S| tj||}tj}tj|g|z}|D]E}tj||}tj|r|cSF|S)zTry to find a file on sys.path and the working 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).)rrisabsrrvrexists)fileheresubdirrdnfns rbr*r*Fs w}}T  w||FD)) 8D GOOD ! ! "T )D)) W\\"d # # 7>>"  (byyy( Kractj|tjtjztjz}tj|dS)z>Create an empty file. If the file already exists, truncate it.N)rr O_WRONLYO_CREATO_TRUNCr()rfds rbr+r+Us4 2;3bj@ A ABHRLLLLLract|}d|D}d|}d|zS)z%Like repr(dict), but in sorted order.cg|]}d|zS)z%r: %rr`).0pairs rb zsortdict..]s333TD333raz, z{%s})sortedrr)dictr reprpairs withcommass rbr,r,ZsF 4::<< E33U333I9%%J J racttd} ||t tS#|t twxYw)z` Create an invalid file descriptor by opening and closing a file and return its fd. wb)r r&filenor(rrQs rb make_bad_fdrhas]   D{{}} v vs A*A=cL|tt|dddS)Nz exec) assertRaises SyntaxErrorcompile)testcase statements rbr-r-ms/ +w )633333rac ddlm}m}dd ||ddd}t jt j td|} fd}t j |r||}||St|td td |zt ||d } t#|d5} |} | r+| | |} | +dddn #1swxYwY|n#|wxYw||}||St+d|z)Nr)requestparsecheckr/datact|gRi}|S|r|d|S|dSNr)r seekr()rUrr rsrs rbcheck_valid_filez*open_urlresource..check_valid_file{s_  !d ! ! !b ! ! =H U1XX  FF1IIIH  raurlfetchz fetching %s ...rg)rrezinvalid resource %r)future.backports.urllibrqrrpopurlparserrrrr__file__rPrrprintrurlopenr readwriter(r) urlr rurllib_request urllib_parserrUrzroutsrss `` @rbr.r.qs3@@@@@@@@ FF7D ! !E$$S))!,22377;H bgooh// B BB w~~b  R  =Hr  Z  #*=*?*?@@@@sB//A "d^^ sA  ! FFHH                   A} *R/ 0 00s1$F"4AF6 F"FF" F F""F8c:eZdZdZdZdZedZdZdS)WarningsRecorderzyConvenience wrapper for the warnings list returned on entry to the warnings.catch_warnings() context manager. c"||_d|_dSrx _warnings_last)self warnings_lists rb__init__zWarningsRecorder.__init__s& ract|j|jkrt|jd|S|tjjvrdSt|d|)Nrur)lenrrrrgWarningMessage_WARNING_DETAILSr)rattrs rb __getattr__zWarningsRecorder.__getattr__s_ t~   + +4>"-t44 4 X,= = =4ttDEEErac*|j|jdSrrrs rbrgzWarningsRecorder.warningss~djkk**rac8t|j|_dSr)rrrrs rbresetzWarningsRecorder.resets(( raN) r\r]r^r_rrpropertyrgrr`rarbrrsiFFF++X+)))))rarc#Ktjd}|jd}|rTtjr|n3tt|D]}| tj d5}tj d dt|Vdddn #1swxYwYt|}g}|D]\}} d} |ddD]b}|j} t#j|t'| t"jr,t+| j| rd} ||c| s|s||| jf|rt5d |d z|rt5d |d zdS) 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. r__warningregistry__T)recordrgalwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)rvrrrrPY3clearr rr~rgrhrw simplefilterrr messagerematchrI issubclass __class__removerr\AssertionError) filtersrHframeregistryiwreraisemissingrscatseenwarnings rb_filterwarningsrs' M!  E""#899H 9  NN    3x==))      - - -" J,,X666q!!!!! """""""""""""""1ggGG 0 0S " "AiGc'llBD11 "7,c22 "q!!! 0E 0 NNC. / / /B3gaj@AAA)H$QZ()) )))s7CC#&C#cl|d}|sdtff}|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) rHNT)rWarningr)rkwargsrHs rbr/r/sC JJw  E =" =E 7E * **rac$eZdZdZdZdZdZdS)r0a,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 ctj|_|D]L}|tjvr@c#t Kgd}gd}td|z | g sd|D d|D fd}tj} |tj|dVn#t$r} |j}t |d kr$t|d tr |d }n8t |d kr$t|d tr |d }nnw||d}~wwxYw tj|dS#tj|wxYw) zReturn a context manager that raises ResourceDenied when various issues with the Internet connection manifest themselves as exceptions.)) ECONNREFUSEDo) ECONNRESETh) EHOSTUNREACHq) ENETUNREACHe) ETIMEDOUTn)) EAI_AGAIN)EAI_FAIL) EAI_NONAME) EAI_NODATA) WSANO_DATAi*zResource %r is not availablec@g|]\}}tt||Sr`)rrr]rqnums rbr_z&transient_internet..s8>>>*c#5$44>>>rac@g|]\}}tt||Sr`)rr'rs rbr_z&transient_internet..s8===%4fdC00===rac t|dd}t|tjs"t|tjr|vs|vr?t s-t jj ddz}||_ |dS)Nrr ) r isinstancer'rr?rrvstderrrr  __cause__)errnrcaptured_errnosdenied gai_errnoss rb filter_errorz(transient_internet..filter_errors C$ ' ' sFN + +  V_ - - 23z//   8   Q$!6777CCMI ! raNTrrr)rr'getdefaulttimeoutsetdefaulttimeoutIOErrorr rr) resource_namererrnosdefault_errnosdefault_gai_errnosr old_timeoutrarrrs @@@rbr;r;sN:]J K KFOJ =>>.<>>>==);===        *,,K.    $W - - -   A1vv{{z!A$88{dQ1AaD'!:!:d   S  (  ----- ----s+A43D!4 D>BDDD!!D7c#Kddl}tt|}tt|| tt|Vtt||dS#tt||wxYw)zReturn a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO.rN)iorrvsetattrStringIO) stream_namer* orig_stdouts rbcaptured_outputr/sIII#{++K Cbkkmm,,,/c;'''''[+.....[+....s A44B c tdS)zCapture the output of sys.stdout: with captured_stdout() as s: print("hello") self.assertEqual(s.getvalue(), "hello") rr/r`rarbr3r3s 8 $ $$rac tdS)Nrr1r`rarbr5r5s 8 $ $$rac tdS)Nstdinr1r`rarbr4r4s 7 # ##ractjtrtjdtjtjdS)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. 皙?N)gccollectr%rrr`rarb gc_collectr9s>JLLL 3JLLLJLLLLLrac#Ktj}tj dV|rtjdSdS#|rtjwwxYwr)r7 isenableddisableenable)have_gcs rb disable_gcr?shlnnGJLLL    IKKKKK  7  IKKKK s AAcddl}|jdpd}d}|D]}|dr|}|dko|dkS)z,Find if Python was built with optimizations.rN PY_CFLAGSrz-Oz-O0)rget_config_varrry)rcflags final_optopts rbpython_is_optimizedrF sq %Y %k 2 2 8bFI||~~ >>$   I ? 1yE11ranP0ngettotalrefcount2P0PrcJtjt|ztzSr)structcalcsize_header_alignfmts rb calcobjsizerSs ?7S=61 2 22racJtjt|ztzSr)rMrN_vheaderrPrQs rb calcvobjsizerV"s ?8c>F2 3 33rai@icZtj|}t|tkr|jtzs4t|tkr+t|jt zr|t jz }dt|||fz}||||dS)Nz&wrong size for %s: got %d, expected %d) rv getsizeofr2 __flags___TPFLAGS_HEAPTYPE_TPFLAGS_HAVE_GC _testcapiSIZEOF_PYGC_HEAD assertEqual)testrsizeresultrss rb check_sizeofrb)s ]1  F aDq{->> q''T//Q 14D D/ ** 2Aww% &CVT3'''''racfd}|S)NcHfd}j|_j|_|S)NcX ddl}t|}||}D]!} |||n#YxYwn#t$rdx}}YnxYw |i||r|r|||SSS#|r|r|||wwwxYwrx)localer setlocaler) r kwdsrfcategory orig_localeloccatstrrlocaless rbinnerz1run_with_locale..decorator..inner9s  "6622$..x88 #C((3777"    ,'++ <tT*T**.decorator8s@ < < < < < < <2   rar`)rlrmrs`` rbr9r97s*: racfd}|S)NcFfd}j|_j|_|S)Nc tj}n"#t$rtjdwxYwdt jvrt jd}nd}t jd<| |i||t jd=n|t jd<tjS#|t jd=n|t jd<tjwxYw)Nztzset requiredTZ)rtzsetrrorprr)r rhrtorig_tzrtzs rbrnz-run_with_tz..decorator..inner]s : ! : : :'(8999 :rz!!*T*!BJt  EGGG tT*T**? 4(('.BJt$ ? 4(('.BJt$ s //B))4Cro)rrnrvs` rbrzrun_with_tz..decorator\s;      ,   rar`)rvrs` rbrUrU[s$4 rairrcdttdtzd}tjd|tjtjz}|t d|tt| d|| d z}|a |tkrt}|tdz krt d|d|adS) Nrw)rmgtz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit rrDz Memory limit z too low to be useful)_1M_1Grr IGNORECASEVERBOSEr r floatgrouplowerreal_max_memuseMAX_Py_ssize_t_2Gr)limitsizesrymemlimits rbr<r<s   #X   E .+ - -Ayjee=>>>5$$uQWWQZZ-=-=-?-?'@@AAHO.  !#'j555JKKKJJJrac$eZdZdZdZdZdZdS)_MemoryWatchdogz`An object which periodically watches the process' memory consumption and prints it out. cldtj|_d|_dS)Nz/proc/{pid}/statm)pidF)formatrgetpidprocfilestartedrs rbrz_MemoryWatchdog.__init__s++22ry{{2CC  rac t|jd}nc#t$rV}tjd|t tj Yd}~dSd}~wwxYwtd}tj tj |g|tj|_|d|_dS)Nrz"/proc not available for stats: {0}zmemory_watchdog.py)r4rT)r rrrgrrrrvrflushr* subprocessPopen executableDEVNULL mem_watchdogr(r)rrewatchdog_scripts rbstartz_MemoryWatchdog.starts T]C((AA    M>EEaHH( * * * J      FFFFF   ##788&,cno-N34Z=OQQQ   s A8A A33A8c||jr4|j|jdSdSr)rr terminatewaitrs rbstopz_MemoryWatchdog.stopsF < %   ' ' ) ) )   " " $ $ $ $ $ % %raN)r\r]r^r_rrrr`rarbrrsK   %%%%%rarcfd}|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. c6fd__S)Ncj}j}tsd}n|}tss+t||zkrtjd||zdz ztrat rZt t d||zdz t}| nd} |||r| SS#|r| wwxYw)Ni'not enough memory: %.1fG minimum needed@z* ... expected peak memory use: {peak:.1f}G)peak) r`memuserrorprrrrrr)rr`rmaxsizewatchdogdry_runrrs rbrz.bigmemtest..decorator..wrappers)v??AAA*,,     $qw''$MMOOOO$8$MMOOOO$s ; CC7)r`r)rrrrr`s`@rbrzbigmemtest..decorators= $ $ $ $ $ $ $: rar`)r`rrrs``` rbr=r=s1       B racfd}|S)z0Decorator for tests that fill the address space.cttkrItdkrtdkrtjdtjdtdz z|S)Nllz-not enough memory: try a 32-bit build insteadrr)rrrorp)rrs rbrz!bigaddrspacetest..wrapperst  & &**zU/B/B'CEEE'=%356661T77Nrar`)rrs` rbr>r>s#      NraceZdZdZdS)r?cBtj}|||Sr)ro TestResult)rr_ras rbrunzBasicTestRunner.runs"$&& V  raN)r\r]r^rr`rarbr?r?s#rar?c|Srr`)rs rb_idrs Jrac|dkr"tstjdSt|rtStjd|S)Nrzresource 'gui' is not availablezresource {0!r} is not enabled)rrorrrrrs rbrequires_resourcers_5!2!4!4}>???8$$O }<CCHMMNNNrac4td|S)z9 Decorator for tests only applicable on CPython. T)cpython) impl_detailr_s rbrErEs %;t $ $ $T * **rac tdi|rtS|bt|\}}|rd}nd}t|}|d|}tj|S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or r`) rFr _parse_guardsr`rrrror)rsguards guardnamesdefaults rbrrs""6""  {+F33 G  :>CC9CJOO--.. jjZ0011 =  rac|sddidfSt|d}t||gt|zksJ|| fS)NrTFr)r valuesr)ris_trues rbrrso *D!5))6==??##A&G   WIF $; ; ; ; ; K  rac t|\}}|tj|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 )rrrpython_implementationr)rrs rbrFrF%s>$F++OFG ::h466<<>> H HHractttdsStjfd}|S)zEDecorator to temporarily turn off tracing for the duration of a test.gettracectj} tjd|i|tj|S#tj|wxYwr)rvrsettrace)r roriginal_tracers rbrzno_tracing..wrapper5s^ \^^N - T"""tT,V,, ^,,,, ^,,,,s AA)r4rvrr)rrs` rb no_tracingr0sO 3 # #     - - - -   -rac: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. )rrErs rb refcount_testr@s l4(( ) ))racg}|jD]b}t|tjr&t ||||B||r||c||_dS)z>Recursively filter test cases in a suite based on a predicate.N)_testsrro TestSuite _filter_suiter)suiteprednewtestsr_s rbrrKsH && dH. / / & $ % % % OOD ! ! ! !tDzz &%%%ELLLractr'tjtjdt }nt }||}|st|j dkr|j s|j dd}nAt|j dkr|j s|j dd}nd}ts|dz }t|dS)z2Run tests from a unittest.TestSuite-derived class.r) verbosityrSrrzmultiple errors occurredz!; run in verbose mode for detailsN) rroTextTestRunnerrvrrSr?r wasSuccessfulrerrorsfailuresr)rrunnerrars rb _run_suiterWs#(q2:<<<!"" ZZ  F    ! ! v}   " "6? "-"1%CC  ! !Q & &v} &/!$Q'CC,C FC#FFCooractjtjf}tj}|D]}t|trU|t jvr8|tjt j|]tdt||r|||tj |d}t||t|dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesctdS|dD]}tj|trdS dS)NTruF) match_testsidrfnmatch fnmatchcase)r_rqs rb case_predzrun_unittest..case_predysV  4GGIIOOC((  D"455 tt uraN) rorTestCaserrrvrwaddTest findTestCasesr  makeSuiterr)classes valid_typesrclsrs rbr@r@ks%x'89K   E 3 3 c3   3ck!! h4S[5EFFGGGG !LMMM [ ) ) 3 MM#     MM(,S11 2 2 2 2%###uracddl}|t}nd}||||\}}|rtd||fztrt d|j|fz||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)doctestrtestmodrrr\)rrrrrr{s rbrArAsNNN  ??69+? N NDAq>3q!f<===$ <"# $ $ $ a4Krac@tjfSr)rvrwrr`rarb modules_setuprs ;     rac`dtjD}tt tjD] }tj!tj|tj|dS)NcFg|]\}}|d||fS)z encodings.)ry)r]rrs rbr_z#modules_cleanup..s@000DAqLL..0!Q000ra)rvrwrr rr~r) oldmodules encodingsrs rbmodules_cleanuprs00CK$5$5$7$7000I 3s{## $ $ Ky!!!Kz"""""rac<trtjfSdS)N)r)_thread_countr`rarbrBrBs ~  rractsdSd}t|D]2}tj}||krdStjd3dS)N r6)rr rrr) nb_threads _MAX_COUNTcountrs rbrCrCsa Jz"" N   ?? EE 3 racXtsStjfd}|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. cZt} |t|S#t|wxYwr)rBrC)r keyrs rbrzreap_threads..decorators< $4; s # # # s # # #s *)rrr)rrs` rb reap_threadsrsH  _T$$$$$ racttdr8d} tj|tj\}}|dkrdSn#YdSxYw5dS)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. waitpidruTrN)r4rrWNOHANG) any_processrstatuss rbrDrDsnr9     jbjAA V!88E    s (AA c#>Kt||rOt||}t||| dVt|||dS#t|||wxYwt||| dVt||dS#t||wxYw)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)r4rr+delattr)rrnew_valreal_vals rbrIrI ssD 3%%T7### ) EEE Cx ( ( ( ( (GCx ( ( ( (T7###  EEE C     GC    sA A4B Bc#K||vr#||}|||< dV|||<dS#|||<wxYw|||< dV||=dS#||=wxYw)akTemporary swap out an item with a new object. Usage: with swap_item(obj, "item", 5): ... This will set obj["item"] to 5 for the duration of the with: block, restoring the old value at the end of the block. If `item` doesn't exist on `obj`, it will be created and then deleted at the end of the block. Nr`)ritemrrs rbrHrH%s s{{t9D  ! EEE CIIICI D   EEED D MMMMs '9>cVtjdd|}|S)zStrip the stderr of a Python process from potential debug output emitted by the interpreter. This will typically be run on the result of the communicate() method of a subprocess.Popen object. s\[\d+ refs\]\r?\n?ra)rsubstrip)rs rbstrip_python_stderrr @s)V*C 8 8 > > @ @F Mrac(tjS)znReturn a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.)r_args_from_interpreter_flagsr`rarbargs_from_interpreter_flagsrJs  2 4 44rac&eZdZdZdZdZdZdS)rKc^tjj|d||_dSrx)logginghandlersBufferingHandlerrmatcher)rrs rbrzTestHandler.__init__Ts+ )224;;; racdS)NFr`rs rb shouldFlushzTestHandler.shouldFlush]suracn|||j|jdSr)rbufferr__dict__)rrs rbemitzTestHandler.emit`s2 F 6?+++++rac Ld}|jD]}|jj|fi|rd}n|S)zW Look for a saved dict whose keys/values match the supplied arguments. FT)rrmatches)rrrads rbrzTestHandler.matchesdsO  A#t|#A0000   raN)r\r]r^rrrrr`rarbrKrKSsP,,,     rarKceZdZdZdZdZdS)rL)rsrc d}|D]:}||}||}||||sd}n;|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)r match_value)rrrrarrdvs rbrzMatcher.matchesss`  Aq AqB##Ar1--   ract|t|krd}n?t|tus ||jvr||k}n||dk}|S)zT Try to match a single stored value (dv) with a supplied value (v). Fr)r2r_partial_matchesfind)rrr"rras rbr!zMatcher.match_valuesc 77d2hh  FF "XXS AT-B$B$B2gFFWWQZZ1_F raN)r\r]r^r$rr!r`rarbrLrLos8)"     rarLcttStdz} tjt|d}tj|n#t t tf$rd}YnwxYw|a|S)NrMTF) _can_symlinkr&rsymlinkrrNotImplementedErrorr) symlink_pathcans rbrMrMsM)L  6<((( , (. 9L JsA A'&A'cdt}d}|r|ntj||S)z8Skip decorator for tests that require functional symlinkz*Requires functional symlink implementation)rMrorr_okrss rbrNrNs4 B 6C 344-8=--d333racttSttdsd}n4tj\}} t t d5} tj|ddtj|ddtj }tj d|}|dup%t|ddk}n#t$rd}YnwxYwdddn #1swxYwYt!t t!|n(#t!t t!|wxYw|a|S) NsetxattrFres user.testraz 2.6.(\d{1,2})r') _can_xattrr4rtempfilemkstempr r&r0rfrr rrr rrr)r+tmp_fptmp_namefpkernel_versionrys rb can_xattrr9s 2z " "#+-- fd## r  K c:::K \3???%-%5%7%7N.AAAt).cleanups9  0 OY : : : : : OY / / / / /ra)rrrr addCleanupr+) test_instancerFrE new_valuerHrDrGs `` @@rbpatchrLs OY'''M#,Y7   H %>>>OY== > 00000000 W%%% OY 22222s ("A  A )T)F)r`r`Fr)rBFN)rr`rx)r_ __future__rrrrfuturerfuture.builtinsrr r r r r contextlibrrr7r'rvrrshutilrgror4 unittest2rmrrrrrrn distutilsrlogging.handlersrrMr3rr threadingthreadmultiprocessing.processmultiprocessingzlibgzipbz2lzma__all__ Exceptionrrrprcontextmanagerrkrr|rrTrPrGrrrrrSrrrrrryrrrrrrrrrrctypes.wintypesrrrrrr r!r'HOSTv6r1r3r"r#r@r$rR SOCK_MAX_SIZE skipUnlessrQrWrXr%rqr&rrrEr(r)r:rr*r+r,rhr-r.objectrrr/r0collections.abc collectionsabcMutableMappingmybaseUserDict DictMixinr1rr2r"rr6rrr7r8r;r/r3r5r4r9r?rFrOrPrUrSrVr[rZrbr9rUr|r}r_4Grrr<rr=r>r?rrrErrrFrrrrr@rArrrBrCrrDrIrHr rrrrKrLr'rMrNr2r9rOrYrLr`rarbrms ::::::::::::<<<<<<<<<<<<<<<<   wx  !      $$$$########$  y,!!!!!!!!!++++++++GIII"""""OOOKKKK DDDKKKK DDDJJJJ CCCKKKK DDD   ,55555I555X&      . . . . % % %   1111h     ***   <5!!64444B&&&$$$ ! ! ! !iG XFmG DDD$<5!!MMM////,CCC """"$6:::888: #NV5G<<<<|####J    !! $ % $#D/:: "x"377 ##D/:: L # #F + + 7f FF F   fibikk 2 2z 29;; $$$$N 72w!        333*1*1*1Z)))))v))).))))))))X +++.22222&222@ 9  _ +FFOOO  F2#2#2#2#2#&2#2#2#j*****F***2NNNNNNNN8  WEO < < <%%fl%:JKKK&&we6FGGG A.A.A.A.H  / / /%%%%%%$$$   2 2 2   73"##WnG F S=333444(((HF Sj#g#g*%%%%%f%%%<++++Z   $f OOO+++    !!!III    ***   (N6###F   "( 4 4555'"38fD    444  6444<5!! - - - - 33333s~6A;; B B B66 CCC CCCC('C(,C11C;:C;?DD DDD! D!