o b0@sdZddlmZddlmZmZddlmZddlm Z ddl m Z gdZ e ZdZGd d d eZGd d d Ze Zefd dZddZd"ddZddZGdddeZddZGdddeZddZd#dd Zd!S)$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. ) randrange) interfacesutils)Failure)FilePath)FilesystemLock)DEFAULT_TIMEOUT_DURATIONexcInfoOrFailureToExcInfosuppressacquireAttributeg^@c@s(eZdZdZdddZdefddZdS) 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. NcCs||_||_dSN) delayedCalls selectables)selfrrr4/usr/lib/python3/dist-packages/twisted/trial/util.py__init__2s z#DirtyReactorAggregateError.__init__returncCsPd}|jr|d7}|dtt|j7}|jr&|d7}|dtt|j7}|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)rmsgrrr__str__6sz"DirtyReactorAggregateError.__str__r )__name__ __module__ __qualname____doc__rrrrrrrr (s r c@s`eZdZdZdddZddZddZd d Zd d Ze ed e ddfZddZ ddZ dS)_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. NcCs||_||_||_dS)z @param test: See L{_Janitor.test}. @param result: See L{_Janitor.result}. @param reactor: See L{_Janitor.reactor}. N)testresultreactor)rr r!r"rrrrRs z_Janitor.__init__cCs0|}|rt|}|j|jt|dSdS)z Called by L{unittest.TestCase} after a test to catch any logged errors or pending L{DelayedCall}s. FT) _cleanPendingr r!addErrorr r)rcalls aggregaterrrpostCaseCleanup\s z_Janitor.postCaseCleanupcCsB|}|}|s |rt||}|j|jt||dS)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) _cleanReactorr#r r!r$r r _cleanThreads)rrr%r&rrrpostClassCleanuphs   z_Janitor.postClassCleanupcCs$|jdur |j}|Sddlm}|S)zI Get either the passed-in reactor or the global reactor. Nr)r")r"twisted.internetrr"rrr _getReactorvs  z_Janitor._getReactorcCs^|}|d|dg}|D]}|r#t|}|ntd||q|S)zS Cancel all pending calls and return their string representations. rz)WEIRDNESS! pending timed call not active!)r-iterategetDelayedCallsactivercancelprintappend)rr"delayedCallStringsp delayedStringrrrr#s     z_Janitor._cleanPendingignorez!reactor\.iterate cannot be used.*)categorymessagecCs2|}tj|r|jdur|dSdSdSr )r-rIReactorThreads providedBy threadpool_stopThreadPoolr,rrrr)s    z_Janitor._cleanThreadscCsB|}g}|D]}tj|r|d|t|q |S)z Remove all selectables from the reactor, kill any of them that were processes, and return their string representation. KILL)r- removeAllrIProcessTransportr< signalProcessr3repr)rr"selectableStringsselrrrr(s   z_Janitor._cleanReactorr )rrrrrr'r*r-r#rsuppressWarningsDeprecationWarningr)r(rrrrrHs"     rcCsB|D]}t||rt||Sq|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)objectsattrdefaultobjrrrr s r cCs t|tr|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}. ) isinstancertypevaluegetTracebackObject)errrrrr s r r8cKs |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)actionkwargrrrr s r csfdd}|S)NcsVddl}|}z|jg|Ri|}|Wn ty$Ynw||S)Nr)profileProfileruncall dump_stats SystemExit print_stats)argskwargsrWprofr!f outputFilerr_s zprofiled.._r)rarbrcrr`rprofileds rdc@eZdZdZdS)_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. Nrrrrrrrrrfrfc Cs|dst|dz|WdSty_}z>td||j|jfztdt t d d}| |WntyS}z td|j|jfd}~wwWYd}~dSd}~ww) 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 itz2could not remove %r, caught OSError [Errno %s]: %ss_trial_temp_oldizutf-8z4could not rename path, caught OSError [Errno %s]: %sN) childexistsrfremoveOSErrorr2errnostrerrorrrrencodemoveTo)pathenewPathrrr _removeSafely s:  ruc@re)_WorkingDirectoryBusyzv A working directory was specified to the runner, but another test run is currently using that directory. Nrgrrrrrv+rhrvcCsd} |r|d||f}n|}t|jd}|r6|r&t|||d d||fS|dkrA|d7}nt q) 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-%dz.lockri _trial_temp) siblingbasenamerrrlockrkrumakedirsrj setContentrv)basecountertestdir testDirLockrrr_unusedTestDirectory2s   r, cCst|ttfs td|sdSt|dkrt|dSt|dkr3t|dd|dt|dSg}|D] }|t|q7d||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 tupleryr z {}{}{} {}N) rPlisttuple TypeErrorlenrr3formatr)thingsfinalDelimiter delimiter strThingsthingrrr _listToPhrase`s"   $rNr7)r)rrandomrr+rrtwisted.python.failurertwisted.python.filepathrtwisted.python.lockfiler__all__objectDEFAULT_TIMEOUTr Exceptionr rrJr r r rdrfrurvrrrrrrs*     o   .