Ϫf3RdZddlmZddlmZddlmZmZmZm Z ddlm Z ddl m Z m Z ddlmZddlmZdd lmZgd ZeZd ZGd d eZGddZeZefdZdZddZe dZe dZ d dZ!GddeZ"dZ#GddeZ$dZ%d!dZ&d"dZ'y)#a A collection of utility functions and classes, used internally by Trial. This code is for Trial's internal use. Do NOT use this code if you are writing tests. It is subject to change at the Trial maintainer's whim. There is nothing here in this module for you to use unless you are maintaining Trial. Any non-Trial Twisted code that uses this module will be shot. Maintainer: Jonathan Lange @var DEFAULT_TIMEOUT_DURATION: The default timeout which will be applied to asynchronous (ie, Deferred-returning) test methods, in seconds. ) annotations) randrange)AnyCallableTextIOTypeVar) ParamSpec) interfacesutils)Failure)FilePath)FilesystemLock)DEFAULT_TIMEOUT_DURATIONexcInfoOrFailureToExcInfosuppressacquireAttributeg^@c eZdZdZddZddZy)DirtyReactorAggregateErrora7 Passed to L{twisted.trial.itrial.IReporter.addError} when the reactor is left in an unclean state after a test. @ivar delayedCalls: The L{DelayedCall} objects which weren't cleaned up. @ivar selectables: The selectables which weren't cleaned up. Nc ||_||_yN) delayedCalls selectables)selfrrs 4/usr/lib/python3/dist-packages/twisted/trial/util.py__init__z#DirtyReactorAggregateError.__init__5s(&cd}|jr1|dz }|djtt|jz }|jr1|dz }|djtt|jz }|S)zR Return a multi-line message describing all of the unclean state. zReactor was unclean.zM DelayedCalls: (set twisted.internet.base.DelayedCall.debug = True to debug)  z Selectables: )rjoinmapstrr)rmsgs r__str__z"DirtyReactorAggregateError.__str__9s|%     C 499Sd&7&789 9C    % %C 499Sd&6&678 8C rr)returnr!)__name__ __module__ __qualname____doc__rr#rrrr+s'rrcleZdZdZd dZdZdZdZdZe jede d d fZd Z d Z y)_Janitorz The guy that cleans up after you. @ivar test: The L{TestCase} to report errors about. @ivar result: The L{IReporter} to report errors to. @ivar reactor: The reactor to use. If None, the global reactor will be used. Nc.||_||_||_y)z @param test: See L{_Janitor.test}. @param result: See L{_Janitor.result}. @param reactor: See L{_Janitor.reactor}. N)testresultreactor)rr-r.r/s rrz_Janitor.__init__Us    rc|j}|r;t|}|jj|jt |yy)z Called by L{unittest.TestCase} after a test to catch any logged errors or pending L{DelayedCall}s. FT) _cleanPendingrr.addErrorr-r )rcalls aggregates rpostCaseCleanupz_Janitor.postCaseCleanup_sB ""$ 259I KK GI,> ?rc|j}|j}|s|r;t||}|jj |j t ||jy)a  Called by L{unittest.TestCase} after the last test in a C{TestCase} subclass. Ensures the reactor is clean by murdering the threadpool, catching any pending L{DelayedCall}s, open sockets etc. N) _cleanReactorr1rr.r2r-r _cleanThreads)rrr3r4s rpostClassCleanupz_Janitor.postClassCleanupksZ((* ""$ %25+FI KK GI,> ? rcF|j|j}|Sddlm}|S)zI Get either the passed-in reactor or the global reactor. r)r/)r/twisted.internetrr/s r _getReactorz_Janitor._getReactorys( << #llG 1rc(|j}|jd|jdg}|jD]J}|jrt |}|j n t d|jL|S)zS Cancel all pending calls and return their string representations. rz)WEIRDNESS! pending timed call not active!)r=iterategetDelayedCallsactiver!cancelprintappend)rr/delayedCallStringsp delayedStrings rr1z_Janitor._cleanPendings""$ ((* 5Axxz #A  AB  % %m 4  5"!rignorez!reactor\.iterate cannot be used.*)categorymessagec|j}tjj|r|j|j yyyr)r=r IReactorThreads providedBy threadpool_stopThreadPoolr<s rr8z_Janitor._cleanThreadssH""$  % % 0 0 9!!- '') . :rc|j}g}|jD]L}tjj |r|j d|j t|N|S)z Remove all selectables from the reactor, kill any of them that were processes, and return their string representation. KILL)r= removeAllr IProcessTransportrN signalProcessrDrepr)rr/selectableStringssels rr7z_Janitor._cleanReactorsl ""$$$& 0C++66s;!!&)  $ $T#Y / 0! rr)r%r&r'r(rr5r9r=r1r suppressWarningsDeprecationWarningr8r7r)rrr+r+KsT  "(+E** .?   M* !rr+cz|D]}t||st||cS|tur|Std|d|)z Go through the list 'objects' sequentially until we find one which has attribute 'attr', then return the value of that attribute. If not found, return 'default' if set, otherwise, raise AttributeError. z attribute z not found in )hasattrgetattr_DEFAULTAttributeError)objectsattrdefaultobjs rrrsQ & 3 3% %&h :dX^G;G HHrctt|tr'|j|j|j f}|S)a' Coerce a Failure to an _exc_info, if err is a Failure. @param err: Either a tuple such as returned by L{sys.exc_info} or a L{Failure} object. @return: A tuple like the one returned by L{sys.exc_info}. e.g. C{exception_type, exception_object, traceback_object}. ) isinstancer typevaluegetTracebackObject)errs rrrs0#wxxC$:$:$<= Jrc  |f|fS)a: Sets up the .suppress tuple properly, pass options to this method as you would the stdlib warnings.filterwarnings() So, to use this with a .suppress magic attribute you would do the following: >>> from twisted.trial import unittest, util >>> import warnings >>> >>> class TestFoo(unittest.TestCase): ... def testFooBar(self): ... warnings.warn("i am deprecated", DeprecationWarning) ... testFooBar.suppress = [util.suppress(message='i am deprecated')] ... >>> Note that as with the todo and timeout attributes: the module level attribute acts as a default for the class attribute which acts as a default for the method attribute. The suppress attribute can be overridden at any level by specifying C{.suppress = []} r))actionkwargs rrrs.Iu r_P_Tcdfd }|S)Ncddl}|j} |jg|i|}|j|j S#t$rYwxYw)Nr)profileProfileruncall dump_stats SystemExit print_stats)argskwargsrqprofr.f outputFiles r_zprofiled.._sd  !T\\!5d5f5F OOJ '     s'A AA)rwz_P.argsrxz _P.kwargsr$rnr))rzr{r|s`` rprofiledr}s  HrceZdZdZy)_NoTrialMarkerz No trial marker file could be found. Raised when trial attempts to remove a trial temporary working directory that does not contain a marker file. Nr%r&r'r(r)rrrr srrc |jdjst|d |jy #t$r}t d|d|j d|j tdttdjdz}|j|n7#t$r+}t d |j d|jd }~wwxYwYd }~y d }~wwxYw) z Safely remove a path, recursively. If C{path} does not contain a node named C{_trial_marker}, a L{_NoTrialMarker} exception is raised and the path is not removed. _trial_markerz5 is not a trial temporary path, refusing to remove itzcould not remove z, caught OSError [Errno z]: s_trial_temp_oldiutf-8z-could not rename path, caught OSError [Errno N) childexistsrremoveOSErrorrCerrnostrerrorr r!rencodemoveTo)pathenewPaths r _removeSafelyrs ::& ' . . 0hK L    QWWajj *  "S8)<%=%D%DW%MMG KK   77AJJ(     !s<A C4 (C/2AB32C/3 C'<&C""C''C//C4ceZdZdZy)_WorkingDirectoryBusyzv A working directory was specified to the runner, but another test run is currently using that directory. Nrr)rrrr2srrcd} |r%|jd|j|fz}n|}|jjdt |j dz}|j rO|jr t||j|jdjd||fS|jdk(r|d z }n t) a0 Find an unused directory named similarly to C{base}. Once a directory is found, it will be locked and a marker dropped into it to identify it as a trial temporary directory. @param base: A template path for the discovery process. If this path exactly cannot be used, a path which varies only in a suffix of the basename will be used instead. @type base: L{FilePath} @return: A two-tuple. The first element is a L{FilePath} representing the directory which was found and created. The second element is a locked L{FilesystemLock}. Another call to C{_unusedTestDirectory} will not be able to reused the same name until the lock is released, either explicitly or by this process exiting. rTz%s-%dignoreExistingDirectoryz.lockrr _trial_temp) siblingbasenameparentmakedirsrrlockrrr setContentr)basecountertestdir testDirLocks r_unusedTestDirectoryr9s&G  ll7dmmow-G#GHGG!!$!?$W\\G%;<    ~~g&     MM* + 6 6s ;K' '}}-/1 +--1 rczt|ttfs td|syt |dk(rt |dSt |dk(r"t |dd|dt |dSg}|D]}|j t |dj|j|dd |||d S) ad Produce a string containing each thing in C{things}, separated by a C{delimiter}, with the last couple being separated by C{finalDelimiter} @param things: The elements of the resulting phrase @type things: L{list} or L{tuple} @param finalDelimiter: What to put between the last two things (typically 'and' or 'or') @type finalDelimiter: L{str} @param delimiter: The separator to use between each thing, not including the last two. Should typically include a trailing space. @type delimiter: L{str} @return: The resulting phrase @rtype: L{str} z Things must be a list or a tuplerr z {}{}{} {}N) relisttuple TypeErrorlenr!rDformatr)thingsfinalDelimiter delimiter strThingsthings r _listToPhraserhs( ftUm ,:;;  6{a6!9~ 6{afQi.!>"2!Cq N3CDD  )E   SZ ( )!! NN9Sb> *   bM   rct|jjdt|jdddS)zO Open the given path such that test log messages can be written to it. Trarstrict)encodingerrors)rropenr)rs r openTestLogrs2 KKM48  3 BBrNrH)rzCallable[_P, _T]r{r!r$r)z, )rz FilePath[Any]r$r)(r( __future__rrandomrtypingrrrrr r;r r twisted.python.failurer twisted.python.filepathr twisted.python.lockfiler__all__objectDEFAULT_TIMEOUTr Exceptionrr+r^rrrrmrnr}rrrrrrr)rrrs #11.*,2 ( @l!l!^ 8-5 I 8t_ T]  Y>I,.^% PCr