o
    9Bin<                     @  s   U d Z ddlmZ ddlZddlZddlmZm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 dd
lmZmZ ddlmZmZmZ edZg Zded< e	ejG dd deZdS )z4
Things likely to be used by writers of unit tests.
    )annotationsN)CallableList)implementer)	ParamSpec)deferutils)_T)failure)itrialutil)FailTestSkipTestSynchronousTestCase_Pz
List[None]_wait_is_runningc                      s   e Zd ZdZd5 fdd	Zd6d
dZe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d7 fd-d.Zd/d0 Zd1d2 Zefd3d4Z  ZS )8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dlm} || _d| _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.
        r   reactorFN)super__init__twisted.internetr   _twistedPrivateScheduler_twistedPrivateNeedsTearDown)self
methodNamer   	__class__ X/var/www/html/Trade-python/venv/lib/python3.10/site-packages/twisted/trial/_asynctest.pyr   1   s   

zTestCase.__init__deferreddefer.Deferred[_T]expectedFailurestype[BaseException]returnc                   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    _cbR   s   z#TestCase.assertFailure.<locals>._cbc                   s*   | j   r| jS d t| }|)Nz
Expected: {!r}
Got:
{})checkvalueformatstrr&   )r
   outputr#   r   r   r    _ebW   s   

z#TestCase.assertFailure.<locals>._eb)addCallbacks)r   r!   r#   r)   r0   r   r/   r    assertFailureI   s   		zTestCase.assertFailurec                   s     fdd}t|tjtd}t|r(td	|}t
|S t
tj |}j|| | fdd |S )Nc                   s   t d  d d}t|}z| | W d S  t jyK   j  d_	 }|d urB|
|rB|| Y d S | Y d S w )Nz (z) still running at z secsT)r   TimeoutErrorr
   FailureerrbackAlreadyCalledErrorr   crash	_timedOutgetTodoexpectedaddExpectedFailureaddError)deftodo)funcDescriptionresultr   timeoutr   r    	onTimeoutg   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>)
getTimeoutr   suppressWarningsr   suppressDeprecationWarninginspectisgeneratorfunction	TypeErrorr,   r   failmaybeDeferredrunWithWarningsSuppressed_getSuppressr   	callLateraddBoth)r   funcrA   rB   rD   excr=   r   )rK   rA   rB   r   rC   r    _rund   s    

zTestCase._runc                 O  s   | j |i |S rG   )run)r   argskwargsr   r   r    __call__   s   zTestCase.__call__c              	     sv   z,z|  |I d H  W | |I d H  n	| |I d H  w W | jr,| |I d H  d S d S | jr:| |I d H  w w rG   )_deferSetUpAndRun_deferRunCleanupsr   _deferTearDownr   rB   r   r   r    _deferSetUp   s   &
zTestCase._deferSetUpc              
     sN  z|  | jd|I dH  W nX ty, } z|| | | j| W Y d}~dS d}~w tyK } z|| t| |	  W Y d}~dS d}~w t
yf } z|| t| W Y d}~dS d}~ww d| _z&|  t| | j| j|I dH  |  dur|| |   W dS d| _W dS  t
y } z
| t||  d}~ww )zc
        Execute the setUp and run part of a test. Teardown and cleanups are not executed.
        setUpNT)r\   rf   r   addSkip_getSkipReasonKeyboardInterruptr<   r
   r4   stopBaseExceptionr   getattr_testMethodNamer9   addUnexpectedSuccess_passed_ebDeferTestMethodr   rB   r>   r   r   r    ra      s<   
zTestCase._deferSetUpAndRunc                 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 rG   )r9   r:   r;   r*   r&   r   
addFailureri   r<   rj   r   rg   rh   rl   rm   r+   )r   r?   rB   r@   r   r   r    rp      s   

zTestCase._ebDeferTestMethodc              
     s   z|  | jd|I d H  W d S  ty2 } z|| t| |  d| _W Y d }~d S d }~w tyP } z|| t| d| _W Y d }~d S d }~ww )NtearDownF)	r\   rs   ri   r<   r
   r4   rj   ro   rk   rq   r   r   r    rc      s   zTestCase._deferTearDownc                 #  s    g }t | jdkr>| j \ z|  fdddj |V  W n ty6   |t  Y nw t | jdks
|D ]}|	| | d| _
q@dS )zf
        Run any scheduled cleanups and report errors (if any) to the result.
        object.
        r   c                     s    i S rG   r   r   r^   rZ   r_   r   r    rL      s    z,TestCase._deferRunCleanups.<locals>.<lambda>zcleanup function FN)len	_cleanupspopr\   __name__	Exceptionappendr
   r4   r<   ro   )r   rB   failuresr?   r   rt   r    rb      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 )NF)r   _JanitorpostCaseCleanupro   rk   r<   r
   r4   	_observer	getErrorsflushLoggedErrors_removeObserver
addSuccess)r   rB   cleanerrorr   r   r    _cleanUp   s"   
zTestCase._cleanUpc                 C  s<   zt | |  W d S  ty   || t  Y d S w rG   )r   r|   postClassCleanuprk   r<   r
   r4   rd   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.   )
stacklevelrF   )warningswarnrP   _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.
        )r7   iteraterj   N)r   rl   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   methodr   r   r    _undeprecateReactor  s   
zTestCase._undeprecateReactorc              	   C  s   ddl m} | | d| _z.tj| |}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)r   r   r   r8   r   DeferredfromCoroutinere   _waitr   r   r   )r   rB   r   r=   r   r   r    _runFixturesAndTest)  s   


zTestCase._runFixturesAndTestr?   Callable[_P, object]r^   _P.argsr_   	_P.kwargsNonec                   s   t  j|g|R i |S )ar  
        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.

        If the function takes more than C{timeout} settings, then the test will
        raise an error.
        )r   
addCleanup)r   r?   r^   r_   r   r   r    r   @  s   zTestCase.addCleanupc                 C  s   |   S rG   )rW   r(   r   r   r    getSuppressO  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.
        rC   z)'timeout' attribute needs to be a number.rE   )
r   acquireAttribute_parentsDEFAULT_TIMEOUT_DURATIONfloat
ValueErrorrS   r   r   rP   )r   rC   r   r   r    rM   R  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 rG   )rz   )any)resultsr   r    rz   r  s   zTestCase._wait.<locals>.appendc                   s   d ur
    d S d S rG   r7   )ignr   r   r   r    r7   v  s   zTestCase._wait.<locals>.crashzreactor\.crash cannot be used.*)messagerF   c                     s       d S rG   r   r   r   r   r    rj     s   zTestCase._wait.<locals>.stopN)RuntimeErrorr   r   r   rN   r   rO   rP   rz   rY   rw   rj   r]   r8   ri   )r   r=   runningrz   r7   rj   r   r   r    r   i  sL   





zTestCase._wait)r   )r!   r"   r#   r$   r%   r"   )r?   r   r^   r   r_   r   r%   r   )rx   
__module____qualname____doc__r   r2   failUnlessFailurer\   r`   re   ra   rp   rc   r   inlineCallbacksrb   r   r   r   r   r   r   r   r   rM   r   r   __classcell__r   r   r   r    r   !   s.    
(

r   )r   
__future__r   rQ   r   typingr   r   zope.interfacer   typing_extensionsr   r   r   r   twisted.internet.deferr	   twisted.pythonr
   twisted.trialr   r   twisted.trial._synctestr   r   r   r   r   __annotations__	ITestCaser   r   r   r   r    <module>   s    