ϪfdZddlZddlZddlZddlmZddlmZmZm Z m Z m Z m Z m Z ddlmZmZddlmZddlmZddlmZ dd lmZeZerej4sdZGd d eZGd d eZGddeZGddeZGddeZdZ Gdde jBZ"ee jFe d dGddeZ$ee jJe d dGddeZ&Gdde jNZ(Gdd e jRZ*Gd!d"eZ+Gd#d$Z,Gd%d&ejZZ.Gd'd(e,Z/Gd)d*eZ0Gd+d,eZ1Gd-d.eZ2y#e$rdZY;wxYw)/zB Tests for lots of functionality provided by L{twisted.internet}. N)skipIf)abstractbasedefererror interfacesprotocolreactor)Deferredpassthru) Connector)util)TestCase)sslceZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZy)ThreePhaseEventTestszQ Tests for the private implementation helpers for system event triggers. cdd|_t|_tj|_y)zR Create a trigger, an argument, and an event to be used by tests. cyN)xs z,ThreePhaseEventTests.setUp..(N)triggerobjectargr_ThreePhaseEventeventselfs rsetUpzThreePhaseEventTests.setUp$s$& 8**, rc|jt|jjd|j|j y)zt L{_ThreePhaseEvent.addTrigger} should raise L{KeyError} when called with an invalid phase. xxxN) assertRaisesKeyErrorr addTriggerrrr!s rtest_addInvalidPhasez)ThreePhaseEventTests.test_addInvalidPhase,s/  djj++UDLL$(( rc|jjd|j|j|j |jj |j|jfifgy)z L{_ThreePhaseEvent.addTrigger} should accept C{'before'} as a phase, a callable, and some arguments and add the callable with the arguments to the before list. beforeN)r r(rr assertEqualr+r!s rtest_addBeforeTriggerz*ThreePhaseEventTests.test_addBeforeTrigger5P h dhh? **dllTXXK-L,MNrc|jjd|j|j|j |jj |j|jfifgy)z L{_ThreePhaseEvent.addTrigger} should accept C{'during'} as a phase, a callable, and some arguments and add the callable with the arguments to the during list. duringN)r r(rrr,r0r!s rtest_addDuringTriggerz*ThreePhaseEventTests.test_addDuringTrigger>r.rc|jjd|j|j|j |jj |j|jfifgy)z L{_ThreePhaseEvent.addTrigger} should accept C{'after'} as a phase, a callable, and some arguments and add the callable with the arguments to the after list. afterN)r r(rrr,r3r!s rtest_addAfterTriggerz)ThreePhaseEventTests.test_addAfterTriggerGsP gt||TXX> ))T\\DHH;,K+LMrc|jjd|j|j}|jj ||j |jj gy)z L{_ThreePhaseEvent.removeTrigger} should accept an opaque object previously returned by L{_ThreePhaseEvent.addTrigger} and remove the associated trigger. r+N)r r(rr removeTriggerr,r+r"handles rtest_removeTriggerz'ThreePhaseEventTests.test_removeTriggerPsP &&xtxxH   ( **B/rcj|jt|jjt y)z L{_ThreePhaseEvent.removeTrigger} should raise L{ValueError} when given an object not previously returned by L{_ThreePhaseEvent.addTrigger}. N)r& ValueErrorr r6rr!s rtest_removeNonexistentTriggerz2ThreePhaseEventTests.test_removeNonexistentTriggerZs" *djj&>&>Irc|jjd|j|j}|jj ||j t |jj|y)z L{_ThreePhaseEvent.removeTrigger} should raise L{ValueError} the second time it is called with an object returned by L{_ThreePhaseEvent.addTrigger}. r+N)r r(rrr6r&r;r7s rtest_removeRemovedTriggerz.ThreePhaseEventTests.test_removeRemovedTriggerasR &&xtxxH   ( *djj&>&>Grc|jt|jjd|j|j fify)z L{_ThreePhaseEvent.removeTrigger} should raise L{ValueError} if it is given a trigger handle which resembles a valid trigger handle aside from its phase being incorrect. r%N)r&r'r r6rrr!s rtest_removeAlmostValidTriggerz2ThreePhaseEventTests.test_removeAlmostValidTriggerks7  djj.. txxkSU0V rc\g}|jjd|jd|jjd|jd|jjd|jd|jjd|jd|jjd|jd|jjd|jd |j|g|jj |j|gd y ) z L{_ThreePhaseEvent.fireEvent} should call I{before}, I{during}, and I{after} phase triggers in that order. r3firstr3r0rCr0r+rCr+secondr+rGr0rGr3)rErFrDrHrBrIN)r r(appendr, fireEventr"eventss rtest_fireEventz#ThreePhaseEventTests.test_fireEventus  gv}}6HI h 7JK h 7JK h 7KL h 7KL gv}}6IJ $     rcg}t|jjdfd|jjd|jd|jjd|jd|j |g|jj |j |gj d|j |ddgy)z L{_ThreePhaseEvent.fireEvent} should wait for any L{Deferred} returned by a I{before} phase trigger before proceeding to I{during} events. r+cSrr beforeResultsrrz>ThreePhaseEventTests.test_asynchronousBefore.. rr0r3N)r r r(rJr,rKcallback)r"rMrRs @rtest_asynchronousBeforez,ThreePhaseEventTests.test_asynchronousBefores z  h(<= h x@ gv}}g> $  $d# (G!45rcg}Gddtfd}|jjd||jjd|jd|jjd|jd|jj |j |ddg|j }|j t|dy)z If a before-phase trigger raises a synchronous exception, it should be logged and the remaining triggers should be run. c eZdZy)HThreePhaseEventTests.test_beforeTriggerException..DummyExceptionN__name__ __module__ __qualname__rrrDummyExceptionrX rr]crrr]srraisingTriggerzHThreePhaseEventTests.test_beforeTriggerException..raisingTrigger  " "rr+r0N Exceptionr r(rJrKr,flushLoggedErrorslenr"rMraerrorsr]s @rtest_beforeTriggerExceptionz0ThreePhaseEventTests.test_beforeTriggerExceptions  Y  # h7 h x@ h x@  (H!56''7 Va(rcg}Gddtfd}|jjd||jjd|jd|jjd|jd|jj |j |ddg|j }|j t|dy)z If a during-phase trigger raises a synchronous exception, it should be logged and the remaining triggers should be run. c eZdZy)HThreePhaseEventTests.test_duringTriggerException..DummyExceptionNrYrrrr]rmr^rr]crrr`srrazHThreePhaseEventTests.test_duringTriggerException..raisingTriggerrbrr0r3rcNrdrhs @rtest_duringTriggerExceptionz0ThreePhaseEventTests.test_duringTriggerExceptions  Y  # h7 h x@ gv}}g>  (G!45''7 Va(rctg}fd}jjd|jdjjd|jjd|jdjtdt jj j|ddgy)z If a before-phase trigger tries to remove another before-phase trigger which has already run, a warning should be emitted. c<jjyrr r6 beforeHandler"srr6zWThreePhaseEventTests.test_synchronousRemoveAlreadyExecutedBefore..removeTriggers JJ $ $\ 2rr+rErFzdRemoving already-fired system event triggers will raise an exception in a future version of Twisted.N)r r(rJ assertWarnsDeprecationWarning__file__rKr,)r"rMr6rts` @r+test_synchronousRemoveAlreadyExecutedBeforez@ThreePhaseEventTests.test_synchronousRemoveAlreadyExecutedBefores  3zz,, fmm%8  h 6 h 7KL   8  JJ   "57K!LMrcBg}jjdfdjjd|jdjjd|jdjjj |dgy)z If a before-phase trigger removes another before-phase trigger which has not yet run, the removed trigger should not be run. r+c:jjSrrrrssrrzJThreePhaseEventTests.test_synchronousRemovePendingBefore.. 0H0H0VrrErFNr r(rJrKr,)r"rMrts` @r#test_synchronousRemovePendingBeforez8ThreePhaseEventTests.test_synchronousRemovePendingBefore  h(VWzz,, fmm%8  h 7KL  "6!78rcBg}jjdfdjjd|jdjjd|jdjjj |dgy)z If a before-phase trigger removes a during-phase trigger, the during-phase trigger should not be run. r+c:jjSrrr duringHandler"srrzJThreePhaseEventTests.test_synchronousBeforeRemovesDuring..r{rr0r3Nr|r"rMrs` @r#test_synchronousBeforeRemovesDuringz8ThreePhaseEventTests.test_synchronousBeforeRemovesDuringsw  h(VWzz,,Xv}}hO  gv}}g>  '+rcg}t|jjdfd|jjd|jd}|jjd|jd|jj |jj |j d|j|dgy)z If a before-phase trigger returns a L{Deferred} and later removes a during-phase trigger before the L{Deferred} fires, the during-phase trigger should not be run. r+cSrrrQsrrzKThreePhaseEventTests.test_asynchronousBeforeRemovesDuring..rSrr0r3N)r r r(rJrKr6rTr,)r"rMrrRs @r$test_asynchronousBeforeRemovesDuringz9ThreePhaseEventTests.test_asynchronousBeforeRemovesDurings z  h(<=zz,,Xv}}hO  gv}}g>    .d# '+rc"gfd}jjd|jjdfdjjd|jjjdgy)a If a before-phase trigger removes a during-phase trigger which is identical to an already-executed before-phase trigger aside from their phases, no warning should be emitted and the during-phase trigger should not be run. c(jdy)NrrJrMsrrz]ThreePhaseEventTests.test_synchronousBeforeRemovesConspicuouslySimilarDuring..triggers MM) $rr+c:jjSrrr) duringTriggerr"srrz^ThreePhaseEventTests.test_synchronousBeforeRemovesConspicuouslySimilarDuring..s 0H0H0Wrr0rN)r r(rKr,)r"rrrMs` @@r7test_synchronousBeforeRemovesConspicuouslySimilarDuringzLThreePhaseEventTests.test_synchronousBeforeRemovesConspicuouslySimilarDuring sr % h0 h(WX --h@   )-rcBg}jjdfdjjd|jdjjd|jdjjj |dgy)z If a during-phase trigger removes another during-phase trigger which has not yet run, the removed trigger should not be run. r0c:jjSrrrrsrrzJThreePhaseEventTests.test_synchronousRemovePendingDuring..%r{rrDrHNr|rs` @r#test_synchronousRemovePendingDuringz8ThreePhaseEventTests.test_synchronousRemovePendingDuringr~rcg}|jjd|jd|jjd|jd|jjd|jd|jj|jj|j |gdy)zm A trigger should only be called on the first call to L{_ThreePhaseEvent.fireEvent}. r+r0r3)r+r0r3Nr|rLs rtest_triggersRunOncez)ThreePhaseEventTests.test_triggersRunOnce-s  h x@ h x@ gv}}g>   !>?rcgfd}jjdjdjjd|jjj ddgy)z The temporary list L{_ThreePhaseEvent.finishedBefore} should be emptied and the state reset to C{'BASE'} before the first during-phase trigger executes. cjdjjjgjjjdy)Nr0BASE)rJr,r finishedBeforestate)rMr"srrzNThreePhaseEventTests.test_finishedBeforeTriggersCleared..duringTriggerBsC MM( #   TZZ66 ;   TZZ--v 6rr+r0Nr|)r"rrMs` @r"test_finishedBeforeTriggersClearedz7ThreePhaseEventTests.test_finishedBeforeTriggersCleared:sd  7 h x@ h 6  (H!56rN)rZr[r\__doc__r#r)r-r1r4r9r<r>r@rNrUrjrorxr}rrrrrrrrrrrsw- OON0JH  66")*)*N0 9 ,, .$ 9 @7rrcveZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZy)SystemEventTestsa Tests for the reactor's implementation of the C{fireSystemEvent}, C{addSystemEventTrigger}, and C{removeSystemEventTrigger} methods of the L{IReactorCore} interface. @ivar triggers: A list of the handles to triggers which have been added to the reactor. cg|_y)zI Create an empty list in which to store trigger handles. N)triggersr!s rr#zSystemEventTests.setUpWs  rc|jr>|jj} tj||jr=yy#tt f$rY wxYw)zA Remove all remaining triggers from the reactor. N)rpopr removeSystemEventTriggerr;r'r"rs rtearDownzSystemEventTests.tearDown]sRmmmm'')G 009mm)  sA AAcjtj|||}|jj||S)zS Add a trigger to the reactor and remember it in C{self.triggers}. )r addSystemEventTriggerrrJ)r"r phasefuncts rr(zSystemEventTests.addTriggerhs/  ) )% = Qrcdtj||jj|y)zd Remove a trigger by its handle from the reactor and from C{self.triggers}. N)r rrremovers rr6zSystemEventTests.removeTriggerps$ ((1 W%rcd}gfd}|j||||jgtj||jdgy)Ntestc(jdyrrrsrrz.trigger| MM$ rr(r,r fireSystemEvent)r"r eventTyperrMs @r_addSystemEventTriggerTestz+SystemEventTests._addSystemEventTriggerTestxsT   y'2 $ * $(rc&|jdy)z L{IReactorCore.addSystemEventTrigger} should accept the C{'before'} phase and not call the given object until the right event is fired. r+Nrr!s rtest_beforePhasez!SystemEventTests.test_beforePhase ''1rc&|jdy)z L{IReactorCore.addSystemEventTrigger} should accept the C{'during'} phase and not call the given object until the right event is fired. r0Nrr!s rtest_duringPhasez!SystemEventTests.test_duringPhaserrc&|jdy)z L{IReactorCore.addSystemEventTrigger} should accept the C{'after'} phase and not call the given object until the right event is fired. r3Nrr!s rtest_afterPhasez SystemEventTests.test_afterPhases ''0rcPd}|jt|jd|dy)z L{IReactorCore.addSystemEventTrigger} should reject phases other than C{'before'}, C{'during'}, or C{'after'}. rr%cyrrrrrrz4SystemEventTests.test_unknownPhase..rrN)r&r'r()r"rs rtest_unknownPhasez"SystemEventTests.test_unknownPhases#   (DOOUI|Trcd}gfd}fd}|jd|||jd|||jgtj||jddgy)z L{IReactorCore.addSystemEventTrigger} should call triggers added to the C{'before'} phase before it calls triggers added to the C{'during'} phase. rc(jdyNr+rrsr beforeTriggerzASystemEventTests.test_beforePreceedsDuring..beforeTrigger MM( #rc(jdyNr0rrsrrzASystemEventTests.test_beforePreceedsDuring..duringTriggerrrr+r0Nr)r"rrrrMs @rtest_beforePreceedsDuringz*SystemEventTests.test_beforePreceedsDuringsn   $ $ )]; )]; $ * (H!56rcd}gfd}fd}|jd|||jd|||jgtj||jddgy)z L{IReactorCore.addSystemEventTrigger} should call triggers added to the C{'during'} phase before it calls triggers added to the C{'after'} phase. rc(jdyrrrsrrz@SystemEventTests.test_duringPreceedsAfter..duringTriggerrrc(jdy)Nr3rrsr afterTriggerz?SystemEventTests.test_duringPreceedsAfter..afterTrigger MM' "rr0r3Nr)r"rrrrMs @rtest_duringPreceedsAfterz)SystemEventTests.test_duringPreceedsAftersn   $ # )]; L9 $ * (G!45rc>td}gfd}fd}|jd|||jd|||jgtj||jgj d|jdgy)z If a trigger added to the C{'before'} phase of an event returns a L{Deferred}, the C{'during'} phase should be delayed until it is called back. rcSrr)triggerDeferredsrrzBSystemEventTests.test_beforeReturnsDeferred..beforeTriggers " "rc(jdyrrrsrrzBSystemEventTests.test_beforeReturnsDeferred..duringTriggerrrr+r0Nr r(r,r rrT)r"rrrrMrs @@rtest_beforeReturnsDeferredz+SystemEventTests.test_beforeReturnsDeferreds #*  # $ )]; )]; $ * $  & (,rcttd}gfd}fd}fd}|jd|||jd|||jd|||jgtj||jgj d|jgj d|jdgy)z If more than one trigger added to the C{'before'} phase of an event return L{Deferred}s, the C{'during'} phase should be delayed until they are all called back. rcSrr firstDeferredsrfirstBeforeTriggerzNSystemEventTests.test_multipleBeforeReturnDeferred..firstBeforeTrigger  rcSrr)secondDeferredsrsecondBeforeTriggerzOSystemEventTests.test_multipleBeforeReturnDeferred..secondBeforeTriggers ! !rc(jdyrrrsrrzISystemEventTests.test_multipleBeforeReturnDeferred..duringTriggerrrr+r0Nr)r"rrrrrMrrs @@@r!test_multipleBeforeReturnDeferredz2SystemEventTests.test_multipleBeforeReturnDeferreds ! !  ! " $ )-?@ )-@A )]; $ * $t$ $% (,rcd}gttfd}fd}fd}fd}|jd|||jd|||jd|||jd|||jgtj||jdgj d|jddgy) aa If a trigger added to the C{'before'} phase of an event calls back a L{Deferred} returned by an earlier trigger in the C{'before'} phase of the same event, the remaining C{'before'} triggers for that event should be run and any further L{Deferred}s waited on before proceeding to the C{'during'} events. rcSrrrsrrzaSystemEventTests.test_subsequentBeforeTriggerFiresPriorBeforeDeferred..firstBeforeTriggerrrc(jdyr)rTrsrrzbSystemEventTests.test_subsequentBeforeTriggerFiresPriorBeforeDeferred..secondBeforeTriggers  " "4 (rc*jdSrrrMrsrthirdBeforeTriggerzaSystemEventTests.test_subsequentBeforeTriggerFiresPriorBeforeDeferred..thirdBeforeTriggers MM( #! !rc(jdyrrrsrrz\SystemEventTests.test_subsequentBeforeTriggerFiresPriorBeforeDeferred..duringTriggerrrr+r0Nr) r"rrrrrrMrrs @@@r4test_subsequentBeforeTriggerFiresPriorBeforeDeferredzESystemEventTests.test_subsequentBeforeTriggerFiresPriorBeforeDeferreds  ! ! ) " $ )-?@ )-@A )-?@ )]; $ * (,% (H!56rcd}gfd}fd}|jd|||j|jd|||jgtj||jdgy)z A trigger removed with L{IReactorCore.removeSystemEventTrigger} should not be called when the event fires. rc(jdy)NrCrrsrrzJSystemEventTests.test_removeSystemEventTrigger..firstBeforeTrigger.rrc(jdy)NrGrrsrrzKSystemEventTests.test_removeSystemEventTrigger..secondBeforeTrigger1rrr+rCN)r(r6r,r r)r"rrrrMs @rtest_removeSystemEventTriggerz.SystemEventTests.test_removeSystemEventTrigger&sx   # $ )-?@ 4??8Y@STU $ * '+rc H|jddd}|j||jttj d|jt tj ||jttj |dd|dddzfy)aM Passing an object to L{IReactorCore.removeSystemEventTrigger} which was not returned by a previous call to L{IReactorCore.addSystemEventTrigger} or which has already been passed to C{removeSystemEventTrigger} should result in L{TypeError}, L{KeyError}, or L{ValueError} being raised. r0rcyrrrrrrzKSystemEventTests.test_removeNonExistentSystemEventTrigger..BrrNr)r%rc)r(r6r& TypeErrorr rr;r')r"bs r(test_removeNonExistentSystemEventTriggerz9SystemEventTests.test_removeNonExistentSystemEventTrigger:s OOHfl ; 1 )W%E%EtL *g&F&FJ  g661x!A$qr(?R8S rc\ gd}tfd}fd}d}t  fd}fd}|jd|||jd|||jd|||jd|||jgtj||jd gtj||jd d gj d |jgd  j d |jgd y )z L{IReactorCore.fireSystemEvent} should behave the same way for a particular system event regardless of whether Deferreds are being waited on for a different system event. z first-eventc*jdS)Nr+rCr)rMrsrbeforeFirstEventzQSystemEventTests.test_interactionBetweenDifferentEvents..beforeFirstEventUs MM- . rc(jdy)Nr3rCrrsrafterFirstEventzPSystemEventTests.test_interactionBetweenDifferentEvents..afterFirstEventYs MM, -rz second-eventc*jdS)Nr+rGrrsrbeforeSecondEventzRSystemEventTests.test_interactionBetweenDifferentEvents..beforeSecondEvent_s MM. /! !rc(jdy)Nr3rGrrsrafterSecondEventzQSystemEventTests.test_interactionBetweenDifferentEvents..afterSecondEventcs MM- .rr+r3rrN)rrr)rrrrr) r" firstEventrr secondEventrrrMrrs @@@r&test_interactionBetweenDifferentEventsz7SystemEventTests.test_interactionBetweenDifferentEventsJs" "   ! .% ! " / *.>? _= +/@A .>? $  + "5!67  , "57K!LM t$  S %    rN)rZr[r\rr#rr(r6rrrrrrrrrrrrrrrrrrMs^ & )221U7*6*-0->"7H,( > rrcXeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd Zy) TimeTestsz9 Tests for the IReactorTime part of the reactor. c\tj}|j||z |z|y)aN L{twisted.internet.reactor.seconds} should return something like a number. 1. This test specifically does not assert any relation to the "system time" as returned by L{time.time} or L{twisted.python.runtime.seconds}, because at some point we may find a better option for scheduling calls than wallclock-time. 2. This test *also* does not assert anything about the type of the result, because operations may not return ints or floats: For example, datetime-datetime == timedelta(0). N)r secondsr,)r"nows r test_secondszTimeTests.test_secondss(oo sS#.rctj}dt_ tjdd}|j|j d|t_|j y#|t_wxYw)z L{reactor.callLater} should use the reactor's seconds factory to produce the time at which the DelayedCall will be called. cyNdrrrrrzITimeTests.test_callLaterUsesReactorSecondsInDelayedCall..rrcyrrrrrrzITimeTests.test_callLaterUsesReactorSecondsInDelayedCall..rriN)r r callLaterr,getTimecancelr"osecondscalls r-test_callLaterUsesReactorSecondsInDelayedCallz7TimeTests.test_callLaterUsesReactorSecondsInDelayedCall\ ??% '$$Q 5D   T\\^S 1&GO 'GO 7A11 A>ctj}dt_ tjdd}|j|jd|t_|j y#|t_wxYw)z L{reactor.callLater} should propagate its own seconds factory to the DelayedCall to use as its own seconds factory. cyrrrrrrzWTimeTests.test_callLaterUsesReactorSecondsAsDelayedCallSecondsFactory..rrrcyrrrrrrzWTimeTests.test_callLaterUsesReactorSecondsAsDelayedCallSecondsFactory..rrrN)r rr r,r rs r;test_callLaterUsesReactorSecondsAsDelayedCallSecondsFactoryzETimeTests.test_callLaterUsesReactorSecondsAsDelayedCallSecondsFactoryrrct}tjd|jd|j |j d|S)zc Test that a DelayedCall really calls the function it is supposed to call. rN)r r r rT addCallbackr,r"ds rtest_callLaterzTimeTests.test_callLaters: J!QZZ. d&&-rctjdtt}|j|j|j }|j d|j|j |y)zS A L{DelayedCall} that is reset will be scheduled at the new time. rcN)r r r addCleanupr timeresetassertNotEqual)r"rorigTimes rtest_callLaterResetzTimeTests.test_callLaterResetsP  Hh7  $99 1  DIIx0rcgfd}tjd|}|jtfd}tjdtjd|S)zL Test that when a DelayedCall is cancelled it does not run. c(jdyrr)calledsrfunctionz2TimeTests.test_cancelDelayedCall..functionrrrc jgjdy#t$rjYywxYwr)r,rT BaseExceptionerrback)r'rr"srcheckz/TimeTests.test_cancelDelayedCall..checks@ !  , 4 !   s'AA)r r r r )r"r(rr,r'rs` @@rtest_cancelDelayedCallz TimeTests.test_cancelDelayedCalls[   H-  J ! !W..59rctjdd}|j|jtj |jy)z Test that cancelling a DelayedCall which has already been cancelled raises the appropriate exception. rcyrrrrrrz;TimeTests.test_cancelCancelledDelayedCall..rrN)r r r r&rAlreadyCancelled)r"rs rtest_cancelCancelledDelayedCallz)TimeTests.test_cancelCancelledDelayedCalls9   L1  %00$++>rcZtfd}tjd|S)z Test that cancelling a DelayedCall in the DelayedCall's function as that function is being invoked by the DelayedCall raises the appropriate exception. c jtjjj dy#t $rj YywxYwrr&r AlreadyCalledr rTr*r+rrr"srlaterz@TimeTests.test_cancelCalledDelayedCallSynchronous..laterJ !!!%"5"5t{{C 4 !   *?AArr r r )r"r7rrs` @@r'test_cancelCalledDelayedCallSynchronousz1TimeTests.test_cancelCalledDelayedCallSynchronouss* J !  E*rcftfdfd}tjd|S)z| Test that cancelling a DelayedCall after it has run its function raises the appropriate exception. c jtjjj dy#t $rj YywxYwrr4r6srr,zATimeTests.test_cancelCalledDelayedCallAsynchronous..checkr8r9c2tjdyNr)r r )r,srr7zATimeTests.test_cancelCalledDelayedCallAsynchronous..laters   a 'rrr:)r"r7rr,rs` @@@r(test_cancelCalledDelayedCallAsynchronousz2TimeTests.test_cancelCalledDelayedCallAsynchronous s/ J ! (  E*rctjdd} |j|jt jdzz dk|j y#|j wxYw)N cyrrrrrrz-TimeTests.testCallLaterTime.. rrrc)r r  assertTruer r r rs rtestCallLaterTimezTimeTests.testCallLaterTimesS   b, /  OOAIIK499;+;.)rrrrB)rHrcyrrrrrrz:TimeTests.testDelayedCallStringification..1rrhelloworldy$@ctyr)str)ignoreddcs r calledBackz.calledBack7s Gr) r r rMr!r ranger rrT)r"rPrrOs @rtestDelayedCallStringificationz(TimeTests.testDelayedCallStringification&s  q"3SB ? B   B  B    | FKBi ")7!3S 97C  B  B  J " ": .   q!**d 3 Brc d}tjdddidd|}|j|jd|j d|j|jdy) z Test that the C{seconds} argument to DelayedCall gets used instead of the default timing function, if it is not None. cy)NrBrrrrrz9TimeTests.testDelayedCallSecondsOverride..secondsEsrrcyrrrrrrz:TimeTests.testDelayedCallSecondsOverride..Irrrcyrr)rOs rrz:TimeTests.testDelayedCallSecondsOverride..Irr N)r DelayedCallr,r r!)r"rrOs rtestDelayedCallSecondsOverridez(TimeTests.testDelayedCallSecondsOverride?sa     |R_ow  q)   r*rN)rZr[r\rrrrrr$r-r1r;r@rErRrZrrrrrsC/"  16?&*2+rrcfeZdZeej ed ddZdZdZ dZ dZ y)!CallFromThreadStopsAndWakeUpTestsNz-Nothing to wake up for without thread supportcPtfd}tj|S)Ncptjdtjjdy)Ng?)r sleepr callFromThreadrT)rsrwakez:CallFromThreadStopsAndWakeUpTests.testWakeUp..wakeYs" JJsO  " "1::t 4r)r r callInThread)r"rars @r testWakeUpz,CallFromThreadStopsAndWakeUpTests.testWakeUpQs& J 5 T"rcd|_y)NT)stoppedr!s r_stopCallFromThreadCallbackz=CallFromThreadStopsAndWakeUpTests._stopCallFromThreadCallbackas  rctj|j|tjd|jyr?)r r`_callFromThreadCallback2r rfrs r_callFromThreadCallbackz9CallFromThreadStopsAndWakeUpTests._callFromThreadCallbackds.t<rc |j|j|jdy#t$r|j YywxYwr)rDrerTr*r+rs rrhz:CallFromThreadStopsAndWakeUpTests._callFromThreadCallback2hs?  OODLL ) JJt    IIK s/A  A c|d|_tj}tj|j ||S)z Ensure that callFromThread from inside a callFromThread callback doesn't sit in an infinite loop and lets other things happen too. F)rerr r r`rirs rtestCallFromThreadStopsz9CallFromThreadStopsAndWakeUpTests.testCallFromThreadStopsqs2  NN t;;Q?r) rZr[r\rrIReactorThreadsr rcrfrirhrlrrrr\r\PsE &J & &w 557   ? rr\cBeZdZdZdZdZdZdZdZdZ dZ d Z y ) DelayedTestsc`d|_d|_i|_tj|_yr?)finishedcountertimersrr deferredr!s rr#zDelayedTests.setUp~s%   ( rcb|jjD]}|jyr)rsvaluesr )r"rs rrzDelayedTests.tearDowns'##% A HHJ rc|jj}ttj}g}|D]}||vs|j ||rd|_|j|dt|zy)Nrcz7Should have been missing no calls, instead was missing ) rsrvlistr getDelayedCallsrJrq assertFalserepr)r"l1l2missingrOs r checkTimerszDelayedTests.checkTimerss~ [[   ! '))+ ,  #B|r" # DM   7m  rc>|j|=|jyr)rsrr"tags rrTzDelayedTests.callbacks KK  rc^|j||jd|jy)N)rTaddTimerrs rrzDelayedTests.addCallbacks  c b$--(rcjd|_|j||jjdy)Nrc)rqrTrtrs rdonezDelayedTests.dones'  c t$rctj|dz||j|j|j<|xjdz c_|j y)N{Gz?rc)r r rrrsr)r"whenrTs rrzDelayedTests.addTimersJ$+$5$5 4K4<<%  DLL!   rcvttdsyjjdjjdj jdj j }jdj jdjjdj j|jj|=jjjfdjS) Nry#c$jSr)r)rr"s rrz2DelayedTests.testGetDelayedCalls..sD,<,<,>r) hasattrr rrrrTrrrrsr rt)r"whichs` rtestGetDelayedCallsz DelayedTests.testGetDelayedCallssw 12   b$))$ b$--( b$--(  b$--( b$**+ b$--( E!!# KK   !!">?}}rctjdjjdj j fd}jj |jS)zM L{IDelayedCall.active} returns False once the call has run. rTcFjj|Sr)rzactive)successdcallr"s rcheckDeferredCallz3DelayedTests.test_active..checkDeferredCalls   U\\^ ,Nr)r r rtrTrDrr)r"rrs` @r test_activezDelayedTests.test_activesY!!$ (>(>E  '  !!"34}}rN) rZr[r\r#rrrTrrrrrrrrroro}s/)  *)% , rroa import %(reactor)s %(reactor)s.install() from twisted.internet import reactor class Foo: def __init__(self): reactor.callWhenRunning(self.start) self.timer = reactor.callLater(3, self.failed) def start(self): reactor.resolve('localhost').addBoth(self.done) def done(self, res): print('done', res) reactor.stop() def failed(self): print('failed') self.timer = None reactor.stop() f = Foo() reactor.run() c*eZdZdZdZdZdZdZy)ChildResolveProtocolc||_yr) onCompletion)r"rs r__init__zChildResolveProtocol.__init__s (rc g|_g|_yr)outputrr!s rconnectionMadez#ChildResolveProtocol.connectionMades  rc:|jj|yr)rrJ)r"outs r outReceivedz ChildResolveProtocol.outReceiveds 3rc:|jj|yr)rrJ)r"errs r errReceivedz ChildResolveProtocol.errReceiveds #rcv|jj||j|jfd|_yr)rrTrr)r"reasons r processEndedz!ChildResolveProtocol.processEndeds- ""FDKK#DE rN)rZr[r\rrrrrrrrrrs) !rrz8cannot run test: reactor doesn't support IReactorProcessceZdZdZy) ResolveTestsc<tjjj}t |d5}t j }|jtd|izdddtjj}tjjtj|d<t}t|}t j |tj"dd|f|fd}|j%||S#1swYxYw)Nwr PYTHONPATHpythonz-uc |\}}}dj|}dtjjdz}||k7r@j dj |j |dj|yy)Nrsdone 127.0.0.1asciizThe child process failed to produce the desired results: Reason for termination was: {!r} Output stream was: {!r} Error stream was: {!r} )joinoslinesepencodefailformatgetErrorMessage)resultrrrexpected_outputr"s r cbFinishedz1ResolveTests.testChildResolve..cbFinishedsw&, #VVUXXf%F/"**2C2CG2LLO( 6 fV335vsxxO)r)rpathabspathmktempopenr r[writeresolve_helperenvironcopypathseprsysr r spawnProcess executabler)r" helperPath helperFile reactorNameenvhelperDeferred helperProtors` rtestChildResolvezResolveTests.testChildResolvesWW__T[[]3 *c " Hj!,,K   ^y+.FF G  H jjooJJOOCHH5L!*>:  (D*)Es  " "":.E H Hs +DDN)rZr[r\rrrrrrs 'rrz&Nothing to test without thread supportc.eZdZdZdZdZdZdZdZy)CallFromThreadTestsz- Task scheduling from threads tests. c0d|_t|_yr?)rrr rtr!s rr#zCallFromThreadTests.setUp9s   rc.tj|i|y)z) Override in subclasses. N)r r`)r"argskwargss rschedulezCallFromThreadTests.schedule=s //rchfd}tdD]}j|jS)z L{IReactorThreads.callFromThread} can be used to schedule a large number of calls in the reactor thread. cxjdz c_jdk(rjjdyy)NrcrTrrrtrTr!sraddAndMaybeFinishzVCallFromThreadTests.test_lotsOfThreadsAreScheduledCorrectly..addAndMaybeFinishIs4 LLA L||s" &&t,#rr)rQrrt)r"ris` r'test_lotsOfThreadsAreScheduledCorrectlyz;CallFromThreadTests.test_lotsOfThreadsAreScheduledCorrectlyCs6  - s -A MM+ , -}}rcvgfd}jj|jjdjjdjjdjtj jj djS)zO Callbacks should be invoked in the order they were scheduled. c.jgdy)N)rcrrW)r,)_orderr"s rr,zECallFromThreadTests.test_threadsAreRunInScheduledOrder..checkYs   UI .rrcrrWN)rtrrrJr r`rT)r"r,rs` @r"test_threadsAreRunInScheduledOrderz6CallFromThreadTests.test_threadsAreRunInScheduledOrderSs / !!%( ellA& ellA& ellA& g,,dmm.D.DdK}}rcfd}j|jjdjS)zU Scheduled tasks should not be run until the reactor starts running. cJd_jjdy)NrcTrr!sr incAndFinishzUCallFromThreadTests.test_scheduledThreadsNotRunUntilReactorRuns..incAndFinishisDL MM " "4 (rr)rr,rrrt)r"rs` r+test_scheduledThreadsNotRunUntilReactorRunsz?CallFromThreadTests.test_scheduledThreadsNotRunUntilReactorRunsds6  ) l# q)}}rN) rZr[r\rr#rrrrrrrrr0s #0  "rrceZdZdZy) MyProtocolz Sample protocol. N)rZr[r\rrrrrrusrrceZdZdZeZy) MyFactoryz Sample factory. N)rZr[r\rrr rrrrr{sHrrceZdZdZy) ProtocolTestsct}|jd}|j|j||j ||j yr)r buildProtocolr,factoryassertIsInstancer )r"rr s r testFactoryzProtocolTests.testFactorysE+((. ))73 h(8(89rN)rZr[r\rrrrrrs:rrc(eZdZdZdZdZdZdZy) DummyProducera Very uninteresting producer implementation used by tests to ensure the right methods are called by the consumer with which it is registered. @type events: C{list} of C{str} @ivar events: The producer/consumer related events which have happened to this producer. Strings in this list may be C{'resume'}, C{'stop'}, or C{'pause'}. Elements are added as they occur. cg|_yrrr!s rrzDummyProducer.__init__s  rc:|jjdy)NresumerMrJr!s rresumeProducingzDummyProducer.resumeProducings 8$rc:|jjdy)Nstoprr!s r stopProducingzDummyProducer.stopProducings 6"rc:|jjdy)Npauserr!s rpauseProducingzDummyProducer.pauseProducings 7#rN)rZr[r\rrrrrrrrrrs%#$rrc(eZdZdZdZdZdZdZeZy)SillyDescriptora A descriptor whose data buffer gets filled very fast. Useful for testing FileDescriptor's IConsumer interface, since the data buffer fills as soon as at least four characters are written to it, and gets emptied in a single doWrite() cycle. rWTct|S)z( Always write all data. )rg)r"datas r writeSomeDatazSillyDescriptor.writeSomeDatas4yrcy)z1 Do nothing: bypass the reactor. Nrr!s r startWritingzSillyDescriptor.startWritingrrN) rZr[r\r bufferSize connectedrr stopWritingrrrrrs$JI  Krrc,eZdZdZfdZfdZxZS)ReentrantProducera Similar to L{DummyProducer}, but with a resumeProducing method which calls back into an L{IConsumer} method of the consumer against which it is registered. @ivar consumer: The consumer with which this producer has been or will be registered. @ivar methodName: The name of the method to call on the consumer inside C{resumeProducing}. @ivar methodArgs: The arguments to pass to the consumer method invoked in C{resumeProducing}. cLt|||_||_||_yr)superrconsumer methodName methodArgs)r"rrr __class__s rrzReentrantProducer.__init__s#   $$rc|t|t|j|j|j yr)rrgetattrrrr)r"rs rrz!ReentrantProducer.resumeProducings+ !/ t/Ar)rZr[r\rrr __classcell__)rs@rr r s % BBrr c@eZdZdZdZdZdZdZdZdZ dZ d Z y ) ProducerTestsz< Test abstract.FileDescriptor's consumer interface. ctj}d|_t}|j |d|j |j dg|jt|jtdy)z Verify that registering a non-streaming producer invokes its resumeProducing() method and that you can only register one producer at a time. rcrrN) rFileDescriptorr rregisterProducerr,rMr& RuntimeErrorr"fddps rtest_doubleProducerz!ProducerTests.test_doubleProducersb  $ $ & _ B" XJ/ ,(;(;]_aPrctj}d|_t}|j |d|j |j dgy)z Verify that registering a producer when the connection has already been closed invokes its stopProducing() method. rcrrN)rr disconnectedrrr,rMrs rtest_unconnectedFileDescriptorz,ProducerTests.test_unconnectedFileDescriptorsF  $ $ & _ B" VH-rc6t}t}|j|d|j|jdg|jdd=|dk(r|j gdn|j d|j|jgy)z Pull consumers don't get their C{pauseProducing} method called if the descriptor buffer fills up. @param _methodName: Either 'write', or 'writeSequence', indicating which transport method to write data to. F streamingrN writeSequence)1234s1234)rrrr,rMr&r)r"r descriptorproducers r_dontPausePullConsumerTestz(ProducerTests._dontPausePullConsumerTests%&  ?##H#> 8*5 OOA   (  $ $%= >   W % "-rc$|jdS)z Verify that FileDescriptor does not call producer.pauseProducing() on a non-streaming pull producer in response to a L{IConsumer.write} call which results in a full write buffer. Issue #2286. rr-r!s r!test_dontPausePullConsumerOnWritez/ProducerTests.test_dontPausePullConsumerOnWrite s ..w77rc$|jdS)a@ Like L{test_dontPausePullConsumerOnWrite}, but for a call to C{writeSequence} rather than L{IConsumer.write}. C{writeSequence} is not part of L{IConsumer}, but L{abstract.FileDescriptor} has supported consumery behavior in response to calls to L{writeSequence} forever. r&r/r!s r)test_dontPausePullConsumerOnWriteSequencez7ProducerTests.test_dontPausePullConsumerOnWriteSequences..??rct}|dk(rgd}nd}t|||}|j|dt||||j |j dg|j dd=|j |j |j ddg|j dd=|j |j |j ddgy)Nr&)spsamsspamTr$rr)rr rrr,rMdoWrite)r"rr+rr,s r_reentrantStreamingProducerTestz-ProducerTests._reentrantStreamingProducerTests$&  (&DD$ZTB##H#= ( J'- 7)4 OOA   8W*=> OOA   8W*=>rc$|jdS)z Verify that FileDescriptor tracks producer's paused state correctly. Issue #811, fixed in revision r12857. rr7r!s r)test_reentrantStreamingProducerUsingWritez7ProducerTests.test_reentrantStreamingProducerUsingWrite?s 33G<&!*L   rzIReactorUDP is neededctjdtj}|j j }|j t|jt|dd||fz|jSr@) r listenUDPr DatagramProtocolrErFr"rMrGrHrIs rtestUDPz PortStringificationTests.testUDP\sm   a!:!:!< =!!  FKKF $b*>&!*L   rzIReactorSSL is neededzSSL support is missingcntjtd}tjdt j |j||}|jj}|jt|jt|dd||fz|jS)Nz server.pemrrArB)rsibpathrwr listenSSLr rDDefaultOpenSSLContextFactoryrErFr"rMrGrH)r"rpemrJrKs rtestSSLz PortStringificationTests.testSSLesll8\2    x%%')I)I#s)S !!  FKKF $b*>&!*L   r) rZr[r\rr IReactorTCPr rL IReactorUDPrP IReactorSSLrrVrrrr>r>Rs & &&w5 57NO!P! & &&w5 57NO!P! & &&w5 57NO G-. !/P !rr>ceZdZdZy)ConnectorReprTestsctddtdt}d}|t||jfz}|j t ||y)N localhostirzA)r ridgetDestinationr,r{)r"cexpects r test_tcp_reprz ConnectorReprTests.test_tcp_reprtsM k3!VX >W2a5!"2"2"455 a&)rN)rZr[r\rbrrrr[r[ss*rr[)3rrrr unittestrtwisted.internetrrrrrr r twisted.internet.deferr r twisted.internet.tcpr twisted.pythonrtwisted.trial.unittestrr_ssl ImportError supportedrrrr\rorProcessProtocolrIReactorProcessrrmrProtocolrFactoryrrrrrr rr>r[rrrrps  XXX5*+, Cs}} Ck78k7\ { x{ | B+B+J**ZW8Wt.!833!&" ""7D11>(8( (V" ""7D11,>(> >B""   :H:$$0h--4B B6wEHwEt!x!B**{* CsE;;FF