o
    b@7                     @   s   U d Z ddlZddlZddlmZ ddlmZ ddlmZm	Z	 ddl
mZ ddlmZmZ ddlmZmZmZ g Zed ed	< eejG d
d deZdS )zP
Things likely to be used by writers of unit tests.

Maintainer: Jonathan Lange
    N)List)implementer)deferutils)failure)itrialutil)FailTestSkipTestSynchronousTestCase_wait_is_runningc                       s   e Zd ZdZd/ fdd	Zdd ZeZdd Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zejdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Z fd'd(Zd)d* Zd+d, Zefd-d.Z  ZS )0TestCasea=  
    A unit test. The atom of the unit testing universe.

    This class extends L{SynchronousTestCase} which extends C{unittest.TestCase}
    from the standard library. The main feature is the ability to return
    C{Deferred}s from tests and fixture methods and to have the suite wait for
    those C{Deferred}s to fire.  Also provides new assertions such as
    L{assertFailure}.

    @ivar timeout: A real number of seconds. If set, the test will
    raise an error if it takes longer than C{timeout} seconds.
    If not set, util.DEFAULT_TIMEOUT_DURATION is used.
    runTestc                    s   t  | dS )a  
        Construct an asynchronous test case for C{methodName}.

        @param methodName: The name of a method on C{self}. This method should
        be a unit test. That is, it should be a short method that calls some of
        the assert* methods. If C{methodName} is unspecified,
        L{SynchronousTestCase.runTest} will be used as the test method. This is
        mostly useful for testing Trial.
        N)super__init__)self
methodName	__class__ :/usr/lib/python3/dist-packages/twisted/trial/_asynctest.pyr   -   s   
zTestCase.__init__c                    s&   fdd} fdd}| ||S )z
        Fail if C{deferred} does not errback with one of C{expectedFailures}.
        Returns the original Deferred with callbacks added. You will need
        to return this Deferred from your test case.
        c                    s     d| )Nz$did not catch an error, instead got )failureException)ignorer   r   r   _cb@   s   z#TestCase.assertFailure.<locals>._cbc                    s*   | j   r| jS d t| }|)Nz
Expected: {!r}
Got:
{})checkvalueformatstrr   )r   outputexpectedFailuresr   r   r   _ebE   s   

z#TestCase.assertFailure.<locals>._eb)addCallbacks)r   deferredr!   r   r"   r   r    r   assertFailure9   s   	zTestCase.assertFailurec                    s   ddl m  fdd}t|tjtd}t}t	
|r4td|}t|S ttj |}|| | fdd |S )	Nr   reactorc                    s   t d  d d}t|}z| | W d S  t jyJ     d_ }|d urA|	|rA
|| Y d S | Y d S w )Nz (z) still running at z secsT)r   TimeoutErrorr   FailureerrbackAlreadyCalledErrorcrash	_timedOutgetTodoexpectedaddExpectedFailureaddError)deftodo)r   r'   resultr   timeoutr   r   	onTimeoutW   s   
z TestCase._run.<locals>.onTimeoutcategoryz9{!r} is a generator function and therefore will never runc                    s      r  p	| S N)activecancel)x)callr   r   <lambda>|   s    zTestCase._run.<locals>.<lambda>)twisted.internetr'   
getTimeoutr   suppressWarningsr   suppressDeprecationWarninggetattrinspectisgeneratorfunction	TypeErrorr   r   failmaybeDeferredrunWithWarningsSuppressed_getSuppress	callLateraddBoth)r   r   r6   r8   methodexcr2   r   )r?   r   r'   r6   r   r7   r   _runR   s(   


zTestCase._runc                 O   s   | j |i |S r;   )run)r   argskwargsr   r   r   __call__   s   zTestCase.__call__c                 C   s*   |  d|}|j| j| j|f|fd |S )NsetUpcallbackArgserrbackArgs)rR   r#   deferTestMethod_ebDeferSetUpr   ignoredr6   r2   r   r   r   
deferSetUp   s   zTestCase.deferSetUpc                 C   sN   | tr|| | | j|j n|| | | tr!|  | 	d |S r;   )
r   r
   addSkip_getSkipReasonrW   r   r1   KeyboardInterruptstopdeferRunCleanupsr   r   r6   r   r   r   r\      s   

zTestCase._ebDeferSetUpc                 C   sH   |  | j|}|j| j| j|f|fd || j| || j| |S )NrX   )rR   _testMethodNamer#   _cbDeferTestMethod_ebDeferTestMethodrO   rd   deferTearDownr]   r   r   r   r[      s   zTestCase.deferTestMethodc                 C   s*   |   d ur|| |    |S d| _|S )NT)r.   addUnexpectedSuccess_passed)r   r^   r6   r   r   r   rg      s
   zTestCase._cbDeferTestMethodc                 C   s   |   }|d ur||r|| || d S || jtr%|| | d S |tr6|| | |	  d S |t
rL|| | t| | j|j d S || | d S r;   )r.   r/   r0   r   r   r	   
addFailurerb   r1   rc   r
   r`   ra   rF   rf   r   )r   r4   r6   r5   r   r   r   rh      s   

zTestCase._ebDeferTestMethodc                 C   s   |  d|}|| j| |S )NtearDown)rR   
addErrback_ebDeferTearDownr]   r   r   r   ri      s   zTestCase.deferTearDownc                 C   s(   | | | |tr|  d| _d S NF)r1   r   rb   rc   rk   re   r   r   r   ro      s   

zTestCase._ebDeferTearDownc              	   c   sv    g }| j ddd D ]\}}}z
||i |V  W q ty*   |t  Y qw |D ]}|| | d| _q-dS )zf
        Run any scheduled cleanups and report errors (if any) to the result.
        object.
        NF)	_cleanups	Exceptionappendr   r)   r1   rk   )r   r^   r6   failuresfuncrT   rU   r4   r   r   r   rd      s   zTestCase.deferRunCleanupsc                 C   s   zt | | }|sd| _W n ty#   || t  d| _Y nw | j	 D ]}|| | d| _q)| 
  |   | jrG||  d S d S rp   )r   _JanitorpostCaseCleanuprk   BaseExceptionr1   r   r)   	_observer	getErrorsflushLoggedErrors_removeObserver
addSuccess)r   r6   cleanerrorr   r   r   _cleanUp   s"   
zTestCase._cleanUpc                 C   s<   zt | |  W d S  ty   || t  Y d S w r;   )r   rw   postClassCleanupry   r1   r   r)   )r   r6   r   r   r   _classCleanUp   s
   zTestCase._classCleanUpc                    s    fdd}|S )z
        Create a method which wraps the reactor method C{name}. The new
        method issues a deprecation warning and calls the original.
        c                     s,   t jd  f dtd j  | i |S )Nz{reactor.%s cannot be used inside unit tests. In the future, using %s will fail the test and may crash or hang the test run.   )
stacklevelr:   )warningswarnrE   _reactorMethods)akwnamer   r   r   _   s   z&TestCase._makeReactorMethod.<locals>._r   )r   r   r   r   r   r   _makeReactorMethod   s   
zTestCase._makeReactorMethodc                 C   s6   i | _ dD ]}t||| j |< t||| | qdS )z
        Deprecate C{iterate}, C{crash} and C{stop} on C{reactor}. That is,
        each method is wrapped in a function that issues a deprecation
        warning, then calls the original.

        @param reactor: The Twisted reactor.
        )r,   iteraterc   N)r   rF   setattrr   )r   r'   r   r   r   r   _deprecateReactor   s
   zTestCase._deprecateReactorc                 C   s*   | j  D ]
\}}t||| qi | _ dS )z
        Restore the deprecated reactor methods. Undoes what
        L{_deprecateReactor} did.

        @param reactor: The Twisted reactor.
        N)r   itemsr   )r   r'   r   rP   r   r   r   _undeprecateReactor	  s   
zTestCase._undeprecateReactorc              	   C   s   ddl m} | | d| _z+| d|}z| | W | | | | n| | | | w W | | dS | | w )z
        Really run C{setUp}, the test method, and C{tearDown}.  Any of these may
        return L{defer.Deferred}s. After they complete, do some reactor cleanup.

        @param result: A L{TestResult} object.
        r   r&   FN)	rA   r'   r   r-   r_   _waitr   r   r   )r   r6   r'   r2   r   r   r   _runFixturesAndTest  s   


zTestCase._runFixturesAndTestc                    s   t  j|g|R i |S )a	  
        Extend the base cleanup feature with support for cleanup functions which
        return Deferreds.

        If the function C{f} returns a Deferred, C{TestCase} will wait until the
        Deferred has fired before proceeding to the next function.
        )r   
addCleanup)r   r4   rT   rU   r   r   r   r   )  s   zTestCase.addCleanupc                 C   s   |   S r;   )rM   r   r   r   r   getSuppress3  s   zTestCase.getSuppressc              	   C   sH   t | jdt j}zt|W S  ttfy#   tjdt	d t j Y S w )ae  
        Returns the timeout value set on this test. Checks on the instance
        first, then the class, then the module, then packages. As soon as it
        finds something with a C{timeout} attribute, returns that. Returns
        L{util.DEFAULT_TIMEOUT_DURATION} if it cannot find anything. See
        L{TestCase} docstring for more details.
        r7   z)'timeout' attribute needs to be a number.r9   )
r   acquireAttribute_parentsDEFAULT_TIMEOUT_DURATIONfloat
ValueErrorrI   r   r   rE   )r   r7   r   r   r   rB   6  s   


zTestCase.getTimeoutc                    s   |rt dddlm  g fdd} fdd}t|tjdtd	} fd
d}t|tjdtd	}|d z5|	| rMW d|
  dS |	| | _z   W  `n `w sf| jroW d|
  dS t d|
  w )zATake a Deferred that only ever callbacks. Block until it happens.z_wait is not reentrantr   r&   c                    s    d ur  |  d S d S r;   )rt   )any)resultsr   r   rt   V  s   zTestCase._wait.<locals>.appendc                    s   d ur
    d S d S r;   r,   )ignr'   r   r   r   r,   Z  s   zTestCase._wait.<locals>.crashzreactor\.crash cannot be used.*)messager:   c                      s       d S r;   r   r   r&   r   r   rc   e  s   zTestCase._wait.<locals>.stopN)RuntimeErrorrA   r'   r   rC   r   rD   rE   rt   rO   poprc   rS   r-   rb   )r   r2   runningrt   r,   rc   r   r   r   r   M  sL   





zTestCase._wait)r   )__name__
__module____qualname____doc__r   r%   failUnlessFailurerR   rV   r_   r\   r[   rg   rh   ri   ro   r   inlineCallbacksrd   r   r   r   r   r   r   r   r   rB   r   r   __classcell__r   r   r   r   r      s4    -
	

r   )r   rG   r   typingr   zope.interfacer   rA   r   r   twisted.pythonr   twisted.trialr   r   twisted.trial._synctestr	   r
   r   r   __annotations__	ITestCaser   r   r   r   r   <module>   s   