o
    bL                     @   s  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 ddl	m
Z
 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZmZ G dd deZG dd deZG dd dZG dd dZG dd deZG dd deZG dd deZG dd deZG dd deZ dS )z!
Tests for L{twisted.trial.util}
    N)StringIO)implementer)DelayedCall)IProcessTransport)filepath)Failure)util)SynchronousTestCase)DirtyReactorAggregateError_JanitoracquireAttributeexcInfoOrFailureToExcInfoc                   @   0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )MktempTestszm
    Tests for L{TestCase.mktemp}, a helper function for creating temporary file
    or directory names.
    c                 C   s8   |   }tj|tjdd }| |g d dS )z
        The path name returned by C{mktemp} is directly beneath a directory
        which identifies the test method which created the name.
        N)ztwisted.trial.test.test_utilr   	test_name)mktempospathdirnamesplitsepassertEqual)selfnamedirs r   >/usr/lib/python3/dist-packages/twisted/trial/test/test_util.pyr   $   s
   zMktempTests.test_namec                 C   s   |   }| ||    dS )zF
        Repeated calls to C{mktemp} return different values.
        N)r   assertNotEqual)r   r   r   r   r   test_unique/   s   zMktempTests.test_uniquec                 C   s<   |   }tj|}| tj| | tj| dS )zS
        The directory part of the path name returned by C{mktemp} exists.
        N)r   r   r   r   
assertTrueexistsassertFalse)r   r   r   r   r   r   test_created6   s   zMktempTests.test_createdc                 C   s(   t j|  }| |t   dS )zZ
        The path returned by C{mktemp} is beneath the current working directory.
        N)r   r   abspathr   r    
startswithgetcwd)r   r   r   r   r   test_location?   s   zMktempTests.test_locationN)__name__
__module____qualname____doc__r   r   r#   r'   r   r   r   r   r      s    	r   c                   @   (   e Zd ZdZdd Zdd Zdd ZdS )	DirtyReactorAggregateErrorTestsz6
    Tests for the L{DirtyReactorAggregateError}.
    c                 C   s    t ddg}| t|d dS )z5
        Delayed calls are formatted nicely.
        FoobarzhReactor was unclean.
DelayedCalls: (set twisted.internet.base.DelayedCall.debug = True to debug)
Foo
barNr
   r   strr   errorr   r   r   test_formatDelayedCallL   s
   z6DirtyReactorAggregateErrorTests.test_formatDelayedCallc                 C   s"   t g ddg}| t|d dS )z3
        Selectables are formatted nicely.
        zselectable 1zselectable 2z;Reactor was unclean.
Selectables:
selectable 1
selectable 2Nr0   r2   r   r   r   test_formatSelectablesZ   s
   z6DirtyReactorAggregateErrorTests.test_formatSelectablesc                 C   s&   t ddgddg}| t|d dS )zR
        Both delayed calls and selectables can appear in the same error.
        bleckBoozoSel1Sel2zReactor was unclean.
DelayedCalls: (set twisted.internet.base.DelayedCall.debug = True to debug)
bleck
Boozo
Selectables:
Sel1
Sel2Nr0   r2   r   r   r   %test_formatDelayedCallsAndSelectablesh   s
   zEDirtyReactorAggregateErrorTests.test_formatDelayedCallsAndSelectablesN)r(   r)   r*   r+   r4   r5   r:   r   r   r   r   r-   G   s
    r-   c                   @   s4   e Zd ZdZdddZdddZdd Zd	d
 ZdS )StubReactora~  
    A reactor stub which contains enough functionality to be used with the
    L{_Janitor}.

    @ivar iterations: A list of the arguments passed to L{iterate}.
    @ivar removeAllCalled: Number of times that L{removeAll} was called.
    @ivar selectables: The value that will be returned from L{removeAll}.
    @ivar delayedCalls: The value to return from L{getDelayedCalls}.
    Nc                 C   s$   || _ g | _d| _|sg }|| _dS )z
        @param delayedCalls: See L{StubReactor.delayedCalls}.
        @param selectables: See L{StubReactor.selectables}.
        r   N)delayedCalls
iterationsremoveAllCalledselectables)r   r<   r?   r   r   r   __init__   s   
zStubReactor.__init__c                 C      | j | dS )z/
        Increment C{self.iterations}.
        N)r=   append)r   timeoutr   r   r   iterate      zStubReactor.iteratec                 C   s   | j S )z.
        Return C{self.delayedCalls}.
        )r<   r   r   r   r   getDelayedCalls   s   zStubReactor.getDelayedCallsc                 C   s   |  j d7  _ | jS )zS
        Increment C{self.removeAllCalled} and return C{self.selectables}.
           )r>   r?   rF   r   r   r   	removeAll   s   zStubReactor.removeAllN)r(   r)   r*   r+   r@   rD   rG   rI   r   r   r   r   r;   z   s    


r;   c                   @       e Zd ZdZdd Zdd ZdS )StubErrorReporterz
    A subset of L{twisted.trial.itrial.IReporter} which records L{addError}
    calls.

    @ivar errors: List of two-tuples of (test, error) which were passed to
        L{addError}.
    c                 C   
   g | _ d S rJ   )errorsrF   r   r   r   r@         
zStubErrorReporter.__init__c                 C   s   | j ||f dS )z6
        Record parameters in C{self.errors}.
        N)rN   rB   )r   testr3   r   r   r   addError   s   zStubErrorReporter.addErrorN)r(   r)   r*   r+   r@   rQ   r   r   r   r   rL      s    rL   c                   @   sh   e Zd Z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dd Zdd Zdd ZdS )JanitorTestsz 
    Tests for L{_Janitor}!
    c                 C   s4   t g }tdd|d}|  | |jddg dS )a  
        During pending-call cleanup, the reactor will be spun twice with an
        instant timeout. This is not a requirement, it is only a test for
        current behavior. Hopefully Trial will eventually not do this kind of
        reactor stuff.
        Nreactorr   )r;   r   _cleanPendingr   r=   r   rT   janr   r   r   test_cleanPendingSpinsReactor   s   z*JanitorTests.test_cleanPendingSpinsReactorc                 C   sV   dd }g }t d|di |jdd }t|g}tdd|d}|  | ||g dS )	zW
        During pending-call cleanup, the janitor cancels pending timed calls.
        c                   S      dS )NLulzr   r   r   r   r   func      z8JanitorTests.test_cleanPendingCancelsCalls.<locals>.func,  r   c                 S      d S rJ   r   xr   r   r   <lambda>       z<JanitorTests.test_cleanPendingCancelsCalls.<locals>.<lambda>NrS   )r   rB   r;   r   rU   r   )r   r[   	cancelleddelayedCallrT   rW   r   r   r   test_cleanPendingCancelsCalls   s   
z*JanitorTests.test_cleanPendingCancelsCallsc              	   C   s`   t ddd di dd dd dd d}t|}t|g}tdd|d	}| }| ||g dS )
aK  
        The Janitor produces string representations of delayed calls from the
        delayed call cleanup method. It gets the string representations
        *before* cancelling the calls; this is important because cancelling the
        call removes critical debugging information from the string
        representation.
        r]   c                   S   r^   rJ   r   r   r   r   r   ra      rb   zIJanitorTests.test_cleanPendingReturnsDelayedCallStrings.<locals>.<lambda>r   c                 S   r^   rJ   r   r_   r   r   r   ra      rb   c                   S   rY   Nr   r   r   r   r   r   ra      rb   secondsNrS   )r   r1   r;   r   rU   r   )r   rd   delayedCallStringrT   rW   stringsr   r   r   *test_cleanPendingReturnsDelayedCallStrings   s   
z7JanitorTests.test_cleanPendingReturnsDelayedCallStringsc                 C   s0   t g }tdd|d}|  | |jd dS )zM
        The Janitor will remove selectables during reactor cleanup.
        NrS   rH   )r;   r   _cleanReactorr   r>   rV   r   r   r   #test_cleanReactorRemovesSelectables   s   z0JanitorTests.test_cleanReactorRemovesSelectablesc                 C   sR   t tG dd d}| }tg |g}tdd|d}|  | |jdg dS )zI
        The Janitor will kill processes during reactor cleanup.
        c                   @   rK   )zJJanitorTests.test_cleanReactorKillsProcesses.<locals>.StubProcessTransportz
            A stub L{IProcessTransport} provider which records signals.
            @ivar signals: The signals passed to L{signalProcess}.
            c                 S   rM   rJ   )signalsrF   r   r   r   r@      rO   zSJanitorTests.test_cleanReactorKillsProcesses.<locals>.StubProcessTransport.__init__c                 S   rA   )zF
                Append C{signal} to C{self.signals}.
                N)rn   rB   )r   signalr   r   r   signalProcess  rE   zXJanitorTests.test_cleanReactorKillsProcesses.<locals>.StubProcessTransport.signalProcessN)r(   r)   r*   r+   r@   rp   r   r   r   r   StubProcessTransport   s    rq   NrS   KILL)r   r   r;   r   rl   r   rn   )r   rq   ptrT   rW   r   r   r   test_cleanReactorKillsProcesses   s   z,JanitorTests.test_cleanReactorKillsProcessesc                 C   s@   G dd d}t g | g}tdd|d}| | dg dS )z
        The Janitor returns string representations of the selectables that it
        cleaned up from the reactor cleanup method.
        c                   @   s   e Zd ZdZdefddZdS )zJJanitorTests.test_cleanReactorReturnsSelectableStrings.<locals>.Selectablezl
            A stub Selectable which only has an interesting string
            representation.
            returnc                 S   rY   )N(SELECTABLE!)r   rF   r   r   r   __repr__  r\   zSJanitorTests.test_cleanReactorReturnsSelectableStrings.<locals>.Selectable.__repr__N)r(   r)   r*   r+   r1   rw   r   r   r   r   
Selectable  s    rx   NrS   rv   )r;   r   r   rl   )r   rx   rT   rW   r   r   r   )test_cleanReactorReturnsSelectableStrings  s   	z6JanitorTests.test_cleanReactorReturnsSelectableStringsc                 C   sB   t g }t }t }t|||d}| |  | |jg  dS )z
        The post-case cleanup method will return True and not call C{addError}
        on the result if there are no pending calls.
        rS   N)r;   objectrL   r   r    postCaseCleanupr   rN   r   rT   rP   reporterrW   r   r   r   test_postCaseCleanupNoErrors   s   z)JanitorTests.test_postCaseCleanupNoErrorsc              	   C   s   t ddd di dd dd dd d}t|}t|gg }t }t }t|||d}| |  | t	|j
d	 | |j
d
 d	 jj|g dS )z
        The post-case cleanup method will return False and call C{addError} on
        the result with a L{DirtyReactorAggregateError} Failure if there are
        pending calls.
        r]   c                   S   r^   rJ   r   r   r   r   r   ra   3  rb   z=JanitorTests.test_postCaseCleanupWithErrors.<locals>.<lambda>r   c                 S   r^   rJ   r   r_   r   r   r   ra   3  rb   c                   S   rY   rf   r   r   r   r   r   ra   3  rb   rg   rS   rH   r   N)r   r1   r;   rz   rL   r   r"   r{   r   lenrN   valuer<   r   rd   ri   rT   rP   r}   rW   r   r   r   test_postCaseCleanupWithErrors,  s    z+JanitorTests.test_postCaseCleanupWithErrorsc                 C   s<   t g }t }t }t|||d}|  | |jg  dS )z
        The post-class cleanup method will not call C{addError} on the result
        if there are no pending calls or selectables.
        rS   N)r;   rz   rL   r   postClassCleanupr   rN   r|   r   r   r   test_postClassCleanupNoErrors>  s   z*JanitorTests.test_postClassCleanupNoErrorsc              	   C   s   t ddd di dd dd dd d}t|}t|gg }t }t }t|||d}|  | t|j	d	 | |j	d
 d	 j
j|g dS )z
        The post-class cleanup method call C{addError} on the result with a
        L{DirtyReactorAggregateError} Failure if there are pending calls.
        r]   c                   S   r^   rJ   r   r   r   r   r   ra   P  rb   zIJanitorTests.test_postClassCleanupWithPendingCallErrors.<locals>.<lambda>r   c                 S   r^   rJ   r   r_   r   r   r   ra   P  rb   c                   S   rY   rf   r   r   r   r   r   ra   P  rb   rg   rS   rH   r   N)r   r1   r;   rz   rL   r   r   r   r   rN   r   r<   r   r   r   r   *test_postClassCleanupWithPendingCallErrorsJ  s    z7JanitorTests.test_postClassCleanupWithPendingCallErrorsc                 C   sh   d}t g |g}t }t }t|||d}|  | t|jd | |jd d jj	t
|g dS )z
        The post-class cleanup method call C{addError} on the result with a
        L{DirtyReactorAggregateError} Failure if there are selectables.
        zSELECTABLE HERErS   rH   r   N)r;   rz   rL   r   r   r   r   rN   r   r?   repr)r   
selectablerT   rP   r}   rW   r   r   r   )test_postClassCleanupWithSelectableErrors[  s   $z6JanitorTests.test_postClassCleanupWithSelectableErrorsN)r(   r)   r*   r+   rX   re   rk   rm   rt   ry   r~   r   r   r   r   r   r   r   r   rR      s    	rR   c                   @   r,   )	RemoveSafelyTestsz*
    Tests for L{util._removeSafely}.
    c                 C   s8   |   d}t| t|}| tjtj	| dS )z
        If a path doesn't contain a node named C{"_trial_marker"}, that path is
        not removed by L{util._removeSafely} and a L{util._NoTrialMarker}
        exception is raised instead.
        utf-8N)
r   encoder   mkdirr   FilePathassertRaisesr   _NoTrialMarker_removeSafely)r   	directorydirPathr   r   r   test_removeSafelyNoTrialMarkero  s   

z0RemoveSafelyTests.test_removeSafelyNoTrialMarkerc                 C   sp   dd }t  }| td| |  d}t| t|}|	d
  ||_t| | d|  dS )z
        If an L{OSError} is raised while removing a path in
        L{util._removeSafely}, an attempt is made to move the path to a new
        name.
        c                   S   s   t  )
            Raise an C{OSError} to emulate the branch of L{util._removeSafely}
            in which path removal fails.
            OSErrorr   r   r   r   dummyRemove  s   zORemoveSafelyTests.test_removeSafelyRemoveFailsMoveSucceeds.<locals>.dummyRemovestdoutr      _trial_markercould not remove FilePathN)r   patchsysr   r   r   r   r   r   childtouchremover   r   assertIngetvalue)r   r   outr   r   r   r   r   (test_removeSafelyRemoveFailsMoveSucceedsz  s   


z:RemoveSafelyTests.test_removeSafelyRemoveFailsMoveSucceedsc                 C   s   dd }dd }t  }| td| |  d}t| t|}|	d
  ||_||_| ttj|}| t|d | d	|  d
S )z
        If an L{OSError} is raised while removing a path in
        L{util._removeSafely}, an attempt is made to move the path to a new
        name. If that attempt fails, the L{OSError} is re-raised.
        c                   S      t d)r   zpath removal failedr   r   r   r   r   r        zLRemoveSafelyTests.test_removeSafelyRemoveFailsMoveFails.<locals>.dummyRemovec                 S   r   )z
            Raise an C{OSError} to emulate the branch of L{util._removeSafely}
            in which path movement fails.
            path movement failedr   )r   r   r   r   dummyMoveTo  r   zLRemoveSafelyTests.test_removeSafelyRemoveFailsMoveFails.<locals>.dummyMoveTor   r   r   r   r   N)r   r   r   r   r   r   r   r   r   r   r   r   moveTor   r   r   r   r   r1   r   r   )r   r   r   r   r   r   r3   r   r   r   %test_removeSafelyRemoveFailsMoveFails  s   

z7RemoveSafelyTests.test_removeSafelyRemoveFailsMoveFailsN)r(   r)   r*   r+   r   r   r   r   r   r   r   r   j  s
    r   c                   @   rK   )ExcInfoTestsz1
    Tests for L{excInfoOrFailureToExcInfo}.
    c                 C   s$   t t ddf}| |t|u  dS )z
        L{excInfoOrFailureToExcInfo} returns exactly what it is passed, if it is
        passed a tuple like the one returned by L{sys.exc_info}.
        fooN)
ValueErrorr    r   )r   infor   r   r   test_excInfo  s   zExcInfoTests.test_excInfoc                 C   sF   zdd  W n t y   t }Y nw | |j|j|jft| dS )z
        When called with a L{Failure} instance, L{excInfoOrFailureToExcInfo}
        returns a tuple like the one returned by L{sys.exc_info}, with the
        elements taken from the type, value, and traceback of the failure.
        rH   r   N)BaseExceptionr   r   typer   tbr   )r   fr   r   r   test_failure  s   
 zExcInfoTests.test_failureN)r(   r)   r*   r+   r   r   r   r   r   r   r     s    r   c                   @   r   )AcquireAttributeTestsz(
    Tests for L{acquireAttribute}.
    c                 C   s*   t   | _}| |t| t  gdu  dS )z
        The value returned by L{acquireAttribute} is the value of the requested
        attribute on the first object in the list passed in which has that
        attribute.
        r   Nrz   r   r    r   r   r   r   r   r   test_foundOnEarlierObject  s   z/AcquireAttributeTests.test_foundOnEarlierObjectc                 C   s*   t   | _}| |tt  | gdu  dS )z
        The same as L{test_foundOnEarlierObject}, but for the case where the 2nd
        element in the object list has the attribute and the first does not.
        r   Nr   r   r   r   r   test_foundOnLaterObject  s   z-AcquireAttributeTests.test_foundOnLaterObjectc                 C   s   |  ttt gd dS )z
        If none of the objects passed in the list to L{acquireAttribute} have
        the requested attribute, L{AttributeError} is raised.
        r   N)r   AttributeErrorr   rz   rF   r   r   r   test_notFoundException  s   z,AcquireAttributeTests.test_notFoundExceptionc                 C   s$   t  }| |tt  gd|u  dS )z
        If none of the objects passed in the list to L{acquireAttribute} have
        the requested attribute and a default value is given, the default value
        is returned.
        r   N)rz   r    r   )r   defaultr   r   r   test_notFoundDefault  s   z*AcquireAttributeTests.test_notFoundDefaultN)r(   r)   r*   r+   r   r   r   r   r   r   r   r   r     s    	r   c                   @   sX   e Zd Z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dd ZdS )ListToPhraseTestsz
    Input is transformed into a string representation of the list,
    with each item separated by delimiter (defaulting to a comma) and the final
    two being separated by a final delimiter.
    c                 C   s$   g }d}t |d}| || dS )zB
        If things is empty, an empty string is returned.
         andNr   _listToPhraser   r   sampleexpectedresultr   r   r   
test_empty  s   zListToPhraseTests.test_emptyc                 C   s&   dg}d}t |d}| || dS )z;
        With a single item, the item is returned.
        Oner   Nr   r   r   r   r   test_oneWord  s   zListToPhraseTests.test_oneWordc                 C   s(   ddg}d}t |d}| || dS )zA
        Two words are separated by the final delimiter.
        r   TwozOne and Twor   Nr   r   r   r   r   test_twoWords     zListToPhraseTests.test_twoWordsc                 C   (   g d}d}t |d}| || dS )zY
        With more than two words, the first two are separated by the delimiter.
        )r   r   ThreezOne, Two, and Threer   Nr   r   r   r   r   test_threeWords"  r   z!ListToPhraseTests.test_threeWordsc                 C   s,   g d}d}t j|ddd}| || dS )zW
        If a delimiter is specified, it is used instead of the default comma.
        )r   r   r   FourzOne; Two; Three; or Fourorz; )	delimiterNr   r   r   r   r   test_fourWords+  s   z ListToPhraseTests.test_fourWordsc                 C   r   )zS
        If something in things is not a string, it is converted into one.
        )rH      threez1, 2, and threer   Nr   r   r   r   r   test_notString4  r   z ListToPhraseTests.test_notStringc                 C   s*   d}|  ttj|d}| t|d dS )z?
        If things is a string, a TypeError is raised.
        zOne, two, threer    Things must be a list or a tupleNr   	TypeErrorr   r   r   r1   r   r   r3   r   r   r   test_stringTypeError=  s   z&ListToPhraseTests.test_stringTypeErrorc                 C   s2   t g d}| ttj|d}| t|d dS )zB
        If things is an iterator, a TypeError is raised.
        )rH   r      r   r   N)iterr   r   r   r   r   r1   r   r   r   r   test_iteratorTypeErrorE  s   z(ListToPhraseTests.test_iteratorTypeErrorc                 C   s.   dd }|  ttj|d}| t|d dS )zB
        If things is a generator, a TypeError is raised.
        c                   s   s    t dE d H  d S )Nr   )ranger   r   r   r   r   R  s   z9ListToPhraseTests.test_generatorTypeError.<locals>.sampler   r   Nr   r   r   r   r   test_generatorTypeErrorM  s   z)ListToPhraseTests.test_generatorTypeErrorN)r(   r)   r*   r+   r   r   r   r   r   r   r   r   r   r   r   r   r   r      s    						r   )!r+   r   r   ior   zope.interfacer   twisted.internet.baser   twisted.internet.interfacesr   twisted.pythonr   twisted.python.failurer   twisted.trialr   twisted.trial.unittestr	   twisted.trial.utilr
   r   r   r   r   r-   r;   rL   rR   r   r   r   r   r   r   r   r   <module>   s,   )3+ 3U'