U
    
W[b4                     @   s  d Z ddlmZmZmZ ddlmZ ddlmZm	Z	m
Z
 ddlmZ ddlmZ ddlmZ dd	d
dgZe ZdZG dd deZG dd deZe ZefddZdd	 Zd&dd
Zdd Zejd'ddZG dd deZdd Z G dd deZ!d d! Z"d(d#d$Z#d%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.
    )divisionabsolute_importprint_function)	randrange)deferutils
interfaces)Failure)FilePath)FilesystemLockDEFAULT_TIMEOUT_DURATIONexcInfoOrFailureToExcInfosuppressacquireAttributeg      ^@c                   @   s"   e Zd ZdZdddZdd ZdS )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<twisted.internet.base.DelayedCall>}
        objects which weren't cleaned up.
    @ivar selectables: The selectables which weren't cleaned up.
    Nc                 C   s   || _ || _d S N)delayedCallsselectables)selfr   r    r   4/usr/lib/python3/dist-packages/twisted/trial/util.py__init__2   s    z#DirtyReactorAggregateError.__init__c                 C   sP   d}| j r(|d7 }|dtt| j 7 }| jrL|d7 }|dtt| j7 }|S )zR
        Return a multi-line message describing all of the unclean state.
        zReactor was unclean.zM
DelayedCalls: (set twisted.internet.base.DelayedCall.debug = True to debug)

z
Selectables:
)r   joinmapstrr   )r   msgr   r   r   __str__7   s    z"DirtyReactorAggregateError.__str__)N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   (   s   	
r   c                   @   s`   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Ze	
ededdfZdd Zdd ZdS )_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                 C   s   || _ || _|| _dS )z
        @param test: See L{_Janitor.test}.
        @param result: See L{_Janitor.result}.
        @param reactor: See L{_Janitor.reactor}.
        N)testresultreactor)r   r#   r$   r%   r   r   r   r   Q   s    z_Janitor.__init__c                 C   s0   |   }|r,t|}| j| jt| dS dS )z
        Called by L{unittest.TestCase} after a test to catch any logged errors
        or pending L{DelayedCall<twisted.internet.base.DelayedCall>}s.
        FT)_cleanPendingr   r$   addErrorr#   r	   )r   calls	aggregater   r   r   postCaseCleanup\   s    z_Janitor.postCaseCleanupc                 C   sB   |   }|  }|s|r6t||}| j| jt| |   dS )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<twisted.internet.base.DelayedCall>}s, open sockets etc.
        N)_cleanReactorr&   r   r$   r'   r#   r	   _cleanThreads)r   r   r(   r)   r   r   r   postClassCleanupi   s    
z_Janitor.postClassCleanupc                 C   s"   | j dk	r| j }nddlm } |S )zI
        Get either the passed-in reactor or the global reactor.
        Nr   )r%   )r%   twisted.internetr   r%   r   r   r   _getReactorx   s    
z_Janitor._getReactorc                 C   s^   |   }|d |d g }| D ]0}| rFt|}|  ntd || q(|S )zS
        Cancel all pending calls and return their string representations.
        r   z)WEIRDNESS! pending timed call not active!)r0   ZiterateZgetDelayedCallsZactiver   Zcancelprintappend)r   r%   ZdelayedCallStringspZdelayedStringr   r   r   r&      s    


z_Janitor._cleanPending)ignorez!reactor\.iterate cannot be used.*)categorymessagec                 C   s*   |   }tj|r&|jd k	r&|  d S r   )r0   r   ZIReactorThreads
providedByZ
threadpoolZ_stopThreadPoolr/   r   r   r   r,      s    
z_Janitor._cleanThreadsc                 C   sB   |   }g }| D ](}tj|r.|d |t| q|S )z
        Remove all selectables from the reactor, kill any of them that were
        processes, and return their string representation.
        ZKILL)r0   Z	removeAllr   ZIProcessTransportr7   ZsignalProcessr2   repr)r   r%   ZselectableStringsZselr   r   r   r+      s    
z_Janitor._cleanReactor)N)r   r   r    r!   r   r*   r-   r0   r&   r   ZsuppressWarningsDeprecationWarningr,   r+   r   r   r   r   r"   H   s   
 r"   c                 C   sB   | D ]}t ||rt||  S q|tk	r.|S td|| f dS )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 %r not found in %rN)hasattrgetattr_DEFAULTAttributeError)Zobjectsattrdefaultobjr   r   r   r      s    
c                 C   s    t | tr| 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	   typevalueZgetTracebackObject)errr   r   r   r      s    	
r4   c                 K   s
   | f|fS )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   )actionZkwargr   r   r   r      s    c                    s    fdd}|S )Nc                     sR   dd l }| }z |j f| |}| W n tk
rD   Y nX |  |S )Nr   )profileZProfileZruncallZ
dump_stats
SystemExitZprint_stats)argskwargsrF   Zprofr$   f
outputFiler   r   _   s    zprofiled.<locals>._r   )rK   rL   rM   r   rJ   r   profiled   s    
rN   Fc              	   c   sr   g }| D ]Z}t |}z|V }|t j|f W q tk
r`   |t jt f |r\Y  qdY qX qt | dS )a$  
    Run the given callables one after the other. If a callable returns a
    Deferred, wait until it has finished before running the next callable.

    @param callables: An iterable of callables that take no parameters.

    @param stopOnFirstError: If True, then stop running callables as soon as
        one raises an exception or fires an errback. False by default.

    @return: A L{Deferred} that fires a list of C{(flag, value)} tuples. Each
        tuple will be either C{(SUCCESS, <return value>)} or C{(FAILURE,
        <Failure>)}.
    N)r   ZmaybeDeferredr2   SUCCESS	ExceptionFAILUREr	   ZreturnValue)Z	callablesZstopOnFirstErrorZresultsrK   dthingr   r   r   _runSequentially  s    
rT   c                   @   s   e Zd ZdZdS )_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.
    Nr   r   r    r!   r   r   r   r   rU     s   rU   c                 C   s   |  d std| f z|   W n tk
r } z|td| |j|jf  z(tdt	t
dd }| | W n8 tk
r } ztd|j|jf   W 5 d}~X Y nX W 5 d}~X Y nX dS )	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_markerz7%r is not a trial temporary path, refusing to remove itz2could not remove %r, caught OSError [Errno %s]: %ss   _trial_temp_oldi zutf-8z4could not rename path, caught OSError [Errno %s]: %sN)childexistsrU   removeOSErrorr1   errnostrerrorr
   r   r   encodeZmoveTo)patheZnewPathr   r   r   _removeSafely(  s,    
ra   c                   @   s   e Zd ZdZdS )_WorkingDirectoryBusyzv
    A working directory was specified to the runner, but another test run is
    currently using that directory.
    NrV   r   r   r   r   rb   C  s   rb   c                 C   s   d}|r |  d|  |f }n| }t|jd }| rj| rJt| |  |d	d ||fS |  dkr|d7 }qt
 qdS )	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<twisted.python.lockfile.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.
    r   z%s-%dz.lockrW       Z_trial_temp   N)Zsiblingbasenamer   r_   lockrY   ra   makedirsrX   Z
setContentrb   )baseZcounterZtestdirZtestDirLockr   r   r   _unusedTestDirectoryK  s    
ri   , c                 C   s   t | ttfstd| sdS t| dkr6t| d S t| dkr`dt| d |t| d f S g }| D ]}|t| qhd||dd	 |||d	 f S 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 tuple rd   r      z%s %s %sz	%s%s%s %sN)rA   listtuple	TypeErrorlenr   r2   r   )ZthingsZfinalDelimiterZ	delimiterZ	strThingsrS   r   r   r   _listToPhrasez  s       rr   N)r4   )F)rj   )$r!   Z
__future__r   r   r   Zrandomr   r.   r   r   r   Ztwisted.python.failurer	   Ztwisted.python.filepathr
   Ztwisted.python.lockfiler   __all__objectZDEFAULT_TIMEOUTr   rP   r   r"   r<   r   r   r   rN   ZinlineCallbacksrT   rU   ra   rb   ri   rr   r   r   r   r   <module>   s6      m

/