Ϫf"@dZddlZddlmZddlmZmZmZddlm Z m Z m Z m Z m Z ddlmZmZddlmZddlmZGd d e j*ZGd d e j.ZGd de j*ZGdde j4ZGddej8ZGddej<ZGddej@Z!GddejDZ"Gddej@Z#Gddej@Z$Gddej@Z%Gdd e j*ejLZ'Gd!d"ej@Z(Gd#d$ej@Z)Gd%d&eZ*Gd'd(ejVZ,Gd)d*ej@Z-y)+z Test code for policies. N)StringIO) Interface implementedBy implementer)addressdeferprotocolreactortask)StringTransport StringTransportWithDisconnection)policies)unittestc0eZdZdxZZdZdZdZdZdZ y)SimpleProtocolrchtj|_tj|_yN)rDeferred dConnected dDisconnectedselfs r?rArCr,r0rrr:r:0s F #rr:ceZdZdZeZy)Serverz8 A simple server factory using L{EchoProtocol}. N)r-r.r/__doc__r:r r0rrrHrH@sHrrHceZdZdZdZdZy)TestableThrottlingFactoryzH L{policies.ThrottlingFactory} using a L{task.Clock} for tests. cXtjj|g|i|||_yz @param clock: object providing a callLater method that can be used for tests. @type clock: C{task.Clock} or alike. N)rThrottlingFactoryrclockrrOargskwargss rrz"TestableThrottlingFactory.__init__Ms) ""++DB4B6B rc:|jj||Sz0 Forward to the testable clock. rO callLaterrperiodfuncs rrVz#TestableThrottlingFactory.callLaterVzz##FD11rNr-r.r/rIrrVr0rrrKrKH2rrKceZdZdZdZdZy)TestableTimeoutFactoryzE L{policies.TimeoutFactory} using a L{task.Clock} for tests. cXtjj|g|i|||_yrM)rTimeoutFactoryrrOrPs rrzTestableTimeoutFactory.__init__bs) ((??? rc:|jj||SrTrUrWs rrVz TestableTimeoutFactory.callLaterkrZrNr[r0rrr^r^]r\rr^cpeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZy) WrapperTestsz> Tests for L{WrappingFactory} and L{ProtocolWrapper}. ct}tj|}|jt j ddd}|j |jj|y)zf Make sure protocol.factory is the wrapped factory, not the wrapping factory. TCP 127.0.0.1#N) rHrWrappingFactoryr8r IPv4AddressassertIswrappedProtocolfactory)rfwfr5s rtest_protocolFactoryAttributez*WrapperTests.test_protocolFactoryAttributewsT H  % %a (   W00 RH I a''//3rc~Gddt}t|Gdd}ttjt j }tjtjd|}|j||j|j|jy)z The transport wrapper passed to the wrapped protocol's C{makeConnection} provides the same interfaces as are provided by the original transport. c eZdZy)=WrapperTests.test_transportInterfaces..IStubTransportNr-r.r/r0rrIStubTransportrr rrtc eZdZy).StubTransportNrsr0rr StubTransportrws rrxN) rrrrProtocolWrapperr ProtocolrhmakeConnection assertTrue providedByrE)rrtrxprotowrappers rtest_transportInterfacesz%WrapperTests.test_transportInterfacess Y  ^ $   %  h../!!#**8+C+CD+I5Q}/ 11%//BCrct}tj|}|jd|j y)z L{WrappingFactory.logPrefix} is customized to mention both the original factory and the wrapping factory. zServer (WrappingFactory)N)rHrrh assertEqual logPrefix)rserverrls rtest_factoryLogPrefixz"WrapperTests.test_factoryLogPrefixs5 **62 3W5F5F5HIrcGdd}|}tj|}|jd|jy)z If the wrapped factory doesn't have a L{logPrefix} method, L{WrappingFactory.logPrefix} falls back to the factory class name. c eZdZy)=WrapperTests.test_factoryLogPrefixFallback..NoFactoryNrsr0rr NoFactoryrrurrzNoFactory (WrappingFactory)N)rrhrr)rrrrls rtest_factoryLogPrefixFallbackz*WrapperTests.test_factoryLogPrefixFallbacks?   **62 68I8I8KLrct}tj|}|jt j ddd}|j d|jy)z{ L{ProtocolWrapper.logPrefix} is customized to mention both the original protocol and the wrapper. rerfrgzEchoProtocol (ProtocolWrapper)N)rHrrhr8rrirr)rrrlr s rtest_protocolLogPrefixz#WrapperTests.test_protocolLogPrefixsX **62(()<).NoProtocolNrsr0rr NoProtocolrrurrrerfrgzNoProtocol (ProtocolWrapper)N) rHr rrhr8rrirr)rrrrlr s rtest_protocolLogPrefixFallbackz+WrapperTests.test_protocolLogPrefixFallbacksi   $**62(()<)z1WrapperTests.test_stopConsuming..s&--2ErTN)rrE stopConsumingr)rrrs @rtest_stopConsumingzWrapperTests.test_stopConsumingsD ""$*E' $(rcgGfdd}tj|}t}|j||j |gy)z} L{policies.WrappingFactory.startedConnecting} calls C{startedConnecting} on the underlying factory. ceZdZfdZy)4WrapperTests.test_startedConnecting..Factoryc(j|yrr)r connectorrs rstartedConnectingzFWrapperTests.test_startedConnecting..Factory.startedConnectings i(rN)r-r.r/rrsrFactoryrs )rrN)rrhrrr)rrrrrs @rtest_startedConnectingz#WrapperTests.test_startedConnecting sO  ) )**795H !!), )-rcgGfdd}tj|}t}t}|j|||j ||fgy)z L{policies.WrappingFactory.clientConnectionLost} calls C{clientConnectionLost} on the underlying factory. ceZdZfdZy)7WrapperTests.test_clientConnectionLost..Factoryc,j||fyrrrrr&rs rclientConnectionLostzLWrapperTests.test_clientConnectionLost..Factory.clientConnectionLost# y&12rN)r-r.r/rrsrrr" 3rrN)rrhrrrrrrrr&rs @rtest_clientConnectionLostz&WrapperTests.test_clientConnectionLosts^  3 3**795H $$Y7 9f"5!67rcgGfdd}tj|}t}t}|j|||j ||fgy)z L{policies.WrappingFactory.clientConnectionFailed} calls C{clientConnectionFailed} on the underlying factory. ceZdZfdZy)9WrapperTests.test_clientConnectionFailed..Factoryc,j||fyrrrs rclientConnectionFailedzPWrapperTests.test_clientConnectionFailed..Factory.clientConnectionFailed4rrN)r-r.r/rrsrrr3rrrN)rrhrrrrs @rtest_clientConnectionFailedz(WrapperTests.test_clientConnectionFailed,s^  3 3**795H &&y&9 9f"5!67rcZtjtjtt j }t }||_|j||j|j|j|j|jy)z L{policies.ProtocolWrapper.connectionLost} sets C{wrappedProtocol} to C{None} in order to break reference cycle between wrapper and wrapped protocols. :return: N) rryrhrHr rzr r{assertIsNotNonerkloseConnectionrrs rtest_breakReferenceCyclez%WrapperTests.test_breakReferenceCycle=s**  $ $VX .0A0A0C 56 $ y) W445  " '112rN)r-r.r/rIrorrrrrrrrrrrrrrrr0rrrcrcrs^4D:J MQ O II 5 7 ). 8"8"3rrcceZdZdZdZy)rhc|Srr0)rrmr5s rr zWrappingFactory.protocolQsrcxtjj||jj dyr)rrh startFactorydeferredr!rs rrzWrappingFactory.startFactoryTs(  --d3 t$rN)r-r.r/r rr0rrrhrhPs %rrhc(eZdZdZdZdZdZdZy)ThrottlingTestsz2 Tests for L{policies.ThrottlingFactory}. c t}dtdD\ tj|dt }t j |_tjd|djj fd} fd} fd } fd } fd } fd }|jj||jj||jj||jj||jj||jj||jS) z Full test using a custom server limiting number of connections. FIXME: https://twistedmatrix.com/trac/ticket/10012 This is a flaky test. c30K|]}tywr)r).0is r z-ThrottlingTests.test_limit..fs=q.*=srrf) interfacectjdtjj fdjj fdj S)NrfcDtjdtSNrfr connectTCPr2)rc2ns rrzAThrottlingTests.test_limit.._connect123..r',,[!\"=MNrcDtjdtSrr)rc3rs rrzAThrottlingTests.test_limit.._connect123..urr)r rr2r addCallbackr)resultsc1rrrs r _connect123z/ThrottlingTests.test_limit.._connect123osT   {A|B/? @ MM % %N  MM % %N ## #rc>jfDcgc]}|jc}gdjfDcgc]}|jc}gdjtjj d|Scc}wcc}w)N)rrr)rrrr)rr r$len protocolskeys)rcrrrrtServers r _check123z-ThrottlingTests.test_limit.._check123ys   BB<@aakk@) L   r2rlCannCY O   S!2!2!7!7!9:A >NACs BBcPjjjSr)rErr)rrs r_lose1z*ThrottlingTests.test_limit.._lose1s LL ' ' )## #rc\tjdtjSr)r rr2r)rc4rs r _connect4z-ThrottlingTests.test_limit.._connect4s$   {A|B/? @== rcxjjdjjd|S)Nrr)rr r$)rrrs r_check4z+ThrottlingTests.test_limit.._check4s0   R\\1 -   R__a 0NrcfD]}|jjtjtjj j j gSr)rErr DeferredList maybeDeferred stopListeningr)rrrrr5s r_cleanupz,ThrottlingTests.test_limit.._cleanupsbV - **, -%%''8$$$$ r) rHrangerrNrhrrrr listenTCPrportr)rr wrapTServerrrrrrrrrrrrr5rs` @@@@@@@r test_limitzThrottlingTests.test_limit^s=E!H=BB,,VQ7%g. $~~/    a D IIK   $    $  !   ((5((3((0((3((1((2###rct}ttj|}|j t j ddd}t}||_|j||jdgdz|j|jd|j|jdy) zZ L{ThrottlingProtocol.writeSequence} is called on the underlying factory. rerfrbytesrsbytesbytesbytesbytesN)rHrKr Clockr8rrir r r{ writeSequencervaluewrittenThisSecond)rrrr rEs rtest_writeSequencez"ThrottlingTests.test_writeSequences+DJJL&A(()<)rOadvancer|rrrrtrs rtest_writeLimitzThrottlingTests.test_writeLimitsO +DJJL&RP$$W%8%8 Q%OP - /  B,,  -( -( %<= 22B7 --445  d# 22A6 ,,334 d# 22A6 --445rct}ttj|d}|j t j ddd}t}||_|j||jd|jd|j|jd|j|jd |jjd |j|jd|j|j d |jjd |j|jd|j|j d |j#|jd|jd|j|jd|j|jd |jjd |j|jd|j|j d |jjd |j|jd|j|j d y )zb Check the readLimit parameter: read data and check for the pause status. r ) readLimitrerfrrrrrrr> producingN)rHrKr rr8rrir r r{r,rrreadThisSecondrOr producerStateclearrs rtest_readLimitzThrottlingTests.test_readLimits +DJJL&BO$$W%8%8 Q%OP - /  B -( -( %<= //4 d# //3 ))84 d# //3 ));7   -( -( %<= //4 d# //3 ))84 d# //3 ));7rN)r-r.r/rIrr rrr0rrrrYs@$D 86<%8rrc.eZdZdZdZdZdZdZdZy)TimeoutProtocolTestsz0 Tests for L{policies.TimeoutProtocol}. ctj}tj}t|_t ||d}|j tjddd}t}||_|j|||fS)z Helper to set up an already connected protocol to be tested. @return: A new protocol with its attached clock. @rtype: Tuple of (L{policies.TimeoutProtocol}, L{task.Clock}) Nrerf90) r rr ServerFactoryrr^r8rrir r{)rrOwrappedFactoryrlr~rEs rgetProtocolAndClockz(TimeoutProtocolTests.getProtocolAndClocksz !//1"0(E%%g&9&9%e&TU46 "  Y'u~rc|j\}}|jd|j|j|j |j j |jd|j|j|j|jd|j |j j y)z2 Will cancel the ongoing timeout. rN) r$ setTimeoutr timeoutCallrrkr$r cancelTimeoutrrsutrOs rtest_cancelTimeoutz'TimeoutProtocolTests.test_cancelTimeouts--/ U q S__- ,,99: a  #//*  a ,,99:rc|j\}}|j|j|j|j |j j y)z< Does nothing if no timeout is already set. N)r$rr(r)rrkr$r*s rtest_cancelTimeoutNoTimeoutz0TimeoutProtocolTests.test_cancelTimeoutNoTimeout#sP--/ U #//*  ,,99:rc|j\}}|j}|jd|jd|j |j |j y)z@ Does nothing if no timeout is already reached. r&N)r$rkr'rr|r$r))rr+rO wrappedProtos rtest_cancelTimeoutAlreadyCalledz4TimeoutProtocolTests.test_cancelTimeoutAlreadyCalled/sY--/ U**  q a  112 rc|j\}}|jd|jj|j |j |j jy)zm Does nothing if the timeout is cancelled from another part. Ex from another thread. r&N)r$r'r(cancelr)rrkr$r*s r"test_cancelTimeoutAlreadyCancelledz7TimeoutProtocolTests.test_cancelTimeoutAlreadyCancelled=sZ --/ U q    ,,99:rN) r-r.r/rIr$r,r.r1r4r0rrrrs ,;& ;  ;rrc(eZdZdZdZdZdZdZy)TimeoutFactoryTestsz/ Tests for L{policies.TimeoutFactory}. ctj|_tj}t |_t |j|d|_|jjtjddd|_ t|_ |j|j_|jj|j|jj|_y)zq Create a testable, deterministic clock, and a set of server factory/protocol/transport. r&rerfr!N)r rrOr r"rr^rlr8rrir~r rEr{rkr0)rr#s rsetUpzTimeoutFactoryTests.setUpRs ZZ\ !//1"0-djj.!L \\//   {E :  :;"&** !!$..1 JJ66rc |jjgd|j|jj|jjddg|j |jjy)z Make sure that when a TimeoutFactory accepts a connection, it will time out that connection if no data is read or written within the timeout period. )??r<g?r:皙?N)rOpumprr0r$r|rs r test_timeoutz TimeoutFactoryTests.test_timeoutcs] 12 **778 c # ))667rc|jjgd|j|jj|j j d|jjgd|j|jj|j jdgdz|jjgd|j|jj|jjddg|j|jjy) z Make sure that writing data to a transport from a protocol constructed by a TimeoutFactory resets the timeout countdown. )r:r;r<bytes bytes bytesr:r<r<rr&r:g@N) rOr>rr0r$r~rFrr|rs rtest_sendAvoidsTimeoutz*TimeoutFactoryTests.test_sendAvoidsTimeoutqs ( **778 -. ( **778   (a0 ( **778 c # ))667rc|jjgd|j|jj|j j d|jjgd|j|jj|jjgd|j|jjy)zR Make sure that receiving data also resets the timeout countdown. )r:r<r;rArBN)rOr>rr0r$r~r,r|rs rtest_receiveAvoidsTimeoutz-TimeoutFactoryTests.test_receiveAvoidsTimeouts ( **778  45 ( **778 ( ))667rN)r-r.r/rIr8r?rCrEr0rrr6r6Ms7" 8888rr6c>eZdZdZdZdZdZdZdZd dZ d Z d Z y) TimeoutTesterz A testable protocol with timeout facility. @ivar timedOut: set to C{True} if a timeout has been detected. @type timedOut: C{bool} r&Fc||_y)zF Initialize the protocol with a C{task.Clock} object. N)rO)rrOs rrzTimeoutTester.__init__s  rc:|j|jy)z3 Upon connection, set the timeout. N)r'timeOutrs rr"zTimeoutTester.connectionMades  %rcd|jtjj||y)z, Reset the timeout on data. N) resetTimeoutr rzr,r*s rr,zTimeoutTester.dataReceiveds& &&tT2rNc&|jdy)zD On connection lost, cancel all timeout operations. N)r'r%s rr'zTimeoutTester.connectionLosts rcd|_y)zX Flags the timedOut variable to indicate the timeout of the connection. TN)timedOutrs rtimeoutConnectionzTimeoutTester.timeoutConnections  rcD|jj||g|i|S)zD Override callLater to use the deterministic clock. rU)rtimeoutrYrQrRs rrVzTimeoutTester.callLaters'$tzz##GTCDCFCCrr) r-r.r/rIrJrOrr"r,r'rPrVr0rrrGrGs2GH & 3  DrrGc@eZdZdZdZdZdZdZdZdZ dZ d Z y ) TimeoutMixinTestsz- Tests for L{policies.TimeoutMixin}. cjtj|_t|j|_y)zY Create a testable, deterministic clock and a C{TimeoutTester} instance. N)r rrOrGr~rs rr8zTimeoutMixinTests.setUps!ZZ\ "4::. rc|jjd|jt|jj dy)z Test that the callLater of the clock is used instead of L{reactor.callLater} r rN)r~r'rrrOcallsrs rtest_overriddenCallLaterz*TimeoutMixinTests.test_overriddenCallLaters5 b! TZZ--.2rcR|jjt|jj gd|j |jj |jj ddg|j|jj y)zq Check that the protocol does timeout at the time specified by its C{timeOut} attribute. rr;r<r<rr<N)r~r{r rOr>rrOr|rs rr?zTimeoutMixinTests.test_timeoutsn !!/"34 *+ ,,- C!  ++,rc |jjt|jj gd|j |jj |jjd|jj gd|j |jj |jj ddg|j|jj y)zV Check that receiving data is delaying the timeout of the connection. rZs hello there)rr<r<r;rr<N) r~r{r rOr>rrOr,r|rs rtest_noTimeoutz TimeoutMixinTests.test_noTimeouts !!/"34 *+ ,,- / *+ ,,- C!  ++,rcd|j_|jjt|jj d|j |jjd|j jddg|j|jj|j jddg|j|jjy)zy Check that setting a new value for timeout cancel the previous value and install a new timeout. Nrrg?r=) r~rJr{r r'rrOr>rrOr|rs rtest_resetTimeoutz#TimeoutMixinTests.test_resetTimeouts "  !!/"34 a  ++Q/ C! ,,- C!  ++,rcpd|j_|jjt|jj d|j |jj|j jgd|j|jjy)zO Setting the timeout to L{None} cancel any timeout operations. N)rr`r`r`) r~rJr{r r'rrOr>rrOrs rr,z$TimeoutMixinTests.test_cancelTimeoutsw  !!/"34 d# $**,,-  % ,,-rcd|j_|j|jjdd|j|jjdd|j |jjd|j|jjd|jjdy)zM setTimeout should return the value of the previous timeout. r`r Nr)r~rJrr'rrs rtest_setTimeoutReturnz'TimeoutMixinTests.test_setTimeoutReturns  ..r2A6 ..t4b9 $**//23 ++Q/ d#rcZ|jjd|jjdj |j |jj |jjd|j|jj y)z When the timeout was already cancelled from an external place, calling setTimeout with C{None} to explicitly cancel it will clean up the timeout without raising any exception. r&rN)r~r'rOgetDelayedCallsr3rrJrrs r%test_setTimeoutCancleAlreadyCancelledz7TimeoutMixinTests.test_setTimeoutCancleAlreadyCancelled-sx a  ""$Q'..0 TZZ//0 d# $**,,-rN) r-r.r/rIr8rXr?r\r^r,rbrer0rrrTrTs//3 - -- . $.rrTceZdZdZdZdZy)!LimitTotalConnectionsFactoryTestsz/Tests for policies.LimitTotalConnectionsFactoryctj}tj|_|j d|j |j d}|j d|j |j d}|j d|j |jd|j d|j |jd|j d|j y)Nrrr)rLimitTotalConnectionsFactoryr rzrconnectionCountr8r')rrlp1p2s rtestConnectionCountingz8LimitTotalConnectionsFactoryTests.testConnectionCountingAs779#,, G334 " "4 ( G334  " "4 ( G334 $ G334 $ G334rctjtj_d_j d}|j ||jdj|jj d|jdjGfddtj}|_ d_ j d}|jd|jj|jdj|jd|jdj|jd|jdjy)NrceZdZfdZy)RLimitTotalConnectionsFactoryTests.testConnectionLimiting..OverflowProtocolcd_yr<) overflowed)rrls rr"zaLimitTotalConnectionsFactoryTests.testConnectionLimiting..OverflowProtocol.connectionMadegs %)"rN)r-r.r/r")rlsrOverflowProtocolrpfs *rrsFrr)rrir rzconnectionLimitr8rrrjroverflowProtocolrrr{r|r')rr5rsoprls @rtestConnectionLimitingz8LimitTotalConnectionsFactoryTests.testConnectionLimitingUsD779#,,"#  ! !$ ' Q G334 '//56 G334 *x00 *$4 "  " "4 ( $ **+ G334  G334 $ G334rN)r-r.r/rIrmrwr0rrrgrg>s95($5rrgceZdZdZy)WriteSequenceEchoProtocolc|jddk7r|jj|gytj ||y)Nsvector!)findrErr:r,)rbytess rr,z&WriteSequenceEchoProtocol.dataReceived}s7 ::j !R ' NN ( (% 1  % %dE 2rN)r-r.r/r,r0rrryry|s3rryceZdZdZdZy)TestLoggingFactoryNc^|jJdt|_|jS)Nzopen() called too many times)openFiler)rnames ropenzTestLoggingFactory.opens+}}$D&DD$  }}r)r-r.r/rrr0rrrrs Hrrc"eZdZdZdZdZdZy)LoggingFactoryTestsz6 Tests for L{policies.TrafficLoggingFactory}. ct}t|_t}t |d}|j d}||_|j ||jj}|jd||j|j|jd|jj}|jdjd||jdjd||j|jd|j|jd|jj}|jdjdg||j|jd|j!|jj}|jd |y ) zQ Check the output produced by L{policies.TrafficLoggingFactory}. test1.2.3.4i.*shere are some bytesz C 1: {!r}z S 1: {!r}s"prepare for vector! to the extremez SV 1: {!r}ConnectionDoneN)rHryr r rr8r{rgetvalueassertInrrr,formatrrr)rr#trmr5vs rtest_thingsGetLoggedz(LoggingFactoryTests.test_thingsGetLoggedss "; , . ~v 6 OO- .   JJ   ! c1 # -. JJ   ! k(()?@!D k(()?@!D $:;   <= JJ   ! l))+P*QRTUV $IJ  JJ   ! &*rct}t|d}|j|jd|j d|j|jdd|_|j d|j|jd|j |j|jdy)zG Test counter management with the resetCounter method. rrrrN)ri/r)rHrr_counterr8r resetCounter)rr#rms r test_counterz LoggingFactoryTests.test_counters  ~v 6 Q' )* Q'  )* Q'  Q'rc gg  fd}|jtd|tj}t|_t j |d}|jtjddd}|jtjddd}dif}d if}|j||g|j|j|jg y ) z When the L{policies.TrafficLoggingFactory} builds a protocol, it automatically opens a unique log file for that protocol and attaches the logfile to the built protocol. cxj||ft}|d|_j||S)zX Mock for the open call to prevent actually opening a log file. r)rrr)rQrRio open_calls open_rvaluess r mocked_openzULoggingFactoryTests.test_loggingFactoryOpensLogfileAutomatically..mocked_opens<   tVn -B1gBG    #Irrrrerfr!i:0)ztest-1w)ztest-2rN) patchbuiltinsr r"rrTrafficLoggingFactoryr8rrirlogfile) rrr#rl first_proto second_proto first_call second_callrrs @@r,test_loggingFactoryOpensLogfileAutomaticallyz@LoggingFactoryTests.test_loggingFactoryOpensLogfileAutomaticallys     8V[1!//1"000H++   {E : ,,   {E : &r* &+  *k2J? +--|/C/CDlSrN)r-r.r/rIrrrr0rrrrs +D("$Trr).rIrrrzope.interfacerrrtwisted.internetrrr r r twisted.internet.testingr r twisted.protocolsr twisted.trialrrzr ClientFactoryr2r:r"rHrNrKr`r^TestCasercrhrrr6 TimeoutMixinrGrTrgryrrrr0rrrsr @@DDV&"X&&(8)) #8$$ # X # #2 : :2*2X442*[38$$[3|%h..%Y8h''Y8xU;8,,U;pR8(++R8j.DH%%x'<'<.Dbh.))h.V;5(9(9;5|3 377\T(++\Tr