ϪfLdZddlmZddlmZmZmZmZmZm Z ddl m Z ddl m Z ddlmZddlmZmZmZddlmZdd lmZmZdd lmZdd lmZmZmZmZm Z m!Z!m"Z"m#Z#dd l$m%Z%dd l&m'Z'm(Z(m)Z)m*Z*m+Z+ddl,m-Z-ddl.m/Z/ddl0m1Z1m2Z2m3Z3m4Z4m5Z5ddl6m7Z7m8Z8m9Z9ddl:m;Z;ddlm?Z@mAZAmBZBmCZCddlDmEZEmFZFddlGmHZHddlImJZJmKZKddlLmMZMddlNmOZOddlPmQZQddlRmSZSddlTmUZUddlVmWZWddlXmYZYddlZm[Z[m\Z\dd l]mZeWd!jjd"Z`eWd!jjd#ZaeWd!jjd$ZbeWecjjd%Zdedjd&Zfeje`jZiejeajZjejebjZkejedjZlejefjZm dd'lnmoZompZqmrZrmsZsdd(ltmuZumvZvmwZwmxZxmyZydd)lzm{Z{dd*l|m}Z}euje`jZeyje`jZd+Zd,ZGd/d0e9ZeejGd1d2eZeejGd3d4eZeejGd5d6eZGd7d8e7ZGd9d:e7ZGd;dZGd?d@ZGdAdBeeZGdCdDe8ZGdEdFZGdGdHej ZGdIdJe jrZeej2GdKdLeCZeejbeeejfeeej2eeej6GdMdNZGdOdPej ZGdQdRej ZGdSdTej ZGdUdVeej ZGdWdXeej ZGdYdZeej ZGd[d\eAe=Zdd]ZGd^d_ejJZGd`daej ZGdbdceZGdddeeej ZGdfdgeej ZGdhdieej ZGdjdkeej ZGdldmejJZGdndoejJZGdpdqej ZGdrdsej ZeeeGdtdueej ZGdvdweej ZGdxdyej ZGdzd{ej Zdd|ZGd}d~ej ZeeeGddej ZGddeej ZGddej ZGddej ZGddej ZGddej ZGddeKjzZGddeKj~ZGddeJjZGddeëZGddej ZdZeeeGddej ZdZGddej Zy.#e$rZd-ZeeZYd.Z[d.Z[wwxYw)z Test the C{I...Endpoint} implementations that wrap the L{IReactorTCP}, L{IReactorSSL}, and L{IReactorUNIX} interfaces found in L{twisted.internet.endpoints}. )EPERM)AF_INETAF_INET6 IPPROTO_TCP SOCK_STREAM AddressFamilygaierror) FunctionType) normalize)skipIf) implementer providedByprovider)InterfaceClass) verifyClass verifyObject)plugins)defer endpointserror interfacesprotocolreactorstdiothreads) isIPv6Address)HostnameAddress IPv4Address IPv6Address UNIXAddress_ProcessAddress)StandardErrorBehavior)ConnectingCancelledError) IConsumerIHostnameResolver IPushProducerIReactorPluggableNameResolver ITransport) ClientFactoryFactoryProtocol) PipeAddress)Clock)MemoryReactorClockRaisingMemoryReactorStringTransport StringTransportWithDisconnection) ILogObserverglobalLogPublisher) getPlugins)basicpolicies)log) nativeString)proxyForInterface)Failure)FilePath) getModule) ListenFDs)connectableEndpointconnectedServerAndClient)unittestz twisted.testz server.pemzkey.pem.no_trailing_newlinezcert.pem.no_trailing_newlinefake_CAsz chain.pem) TLS_METHODContext OP_NO_SSLv3TLSv1_2_METHOD) CertificateCertificateOptionsDiffieHellmanParametersKeyPairPrivateCertificateTLSMemoryBIOFactory)makeCertificateFTNc.eZdZdZdZdZdZdZdZy) TestProtocolzx Protocol whose only function is to callback deferreds on the factory when it is connected or disconnected. c.g|_g|_d|_yNr)dataconnectionsLostconnectionMadeCallsselfs F/usr/lib/python3/dist-packages/twisted/internet/test/test_endpoints.py__init__zTestProtocol.__init__|s !#$ cy)NA Test ProtocolrVs rX logPrefixzTestProtocol.logPrefixs rZc.|xjdz c_yN)rUrVs rXconnectionMadezTestProtocol.connectionMades   A% rZc:|jj|yN)rSappendrWrSs rX dataReceivedzTestProtocol.dataReceiveds rZc:|jj|yrd)rTrerWreasons rXconnectionLostzTestProtocol.connectionLosts ##F+rZN) __name__ __module__ __qualname____doc__rYr^rbrgrkr]rZrXrPrPvs  % !&,rZrPc"eZdZdZdZdZdZy)TestHalfCloseableProtocolab A Protocol that implements L{IHalfCloseableProtocol} and records whether its C{readConnectionLost} and {writeConnectionLost} methods are called. @ivar readLost: A C{bool} indicating whether C{readConnectionLost} has been called. @ivar writeLost: A C{bool} indicating whether C{writeConnectionLost} has been called. cJtj|d|_d|_y)NF)rPrYreadLost writeLostrVs rXrYz"TestHalfCloseableProtocol.__init__sd# rZcd|_yNT)rsrVs rXreadConnectionLostz,TestHalfCloseableProtocol.readConnectionLosts  rZcd|_yrv)rtrVs rXwriteConnectionLostz-TestHalfCloseableProtocol.writeConnectionLosts rZN)rlrmrnrorYrwryr]rZrXrqrqs  rZrqceZdZdZdZdZy)"TestFileDescriptorReceiverProtocola A Protocol that implements L{IFileDescriptorReceiver} and records how its C{fileDescriptorReceived} method is called. @ivar receivedDescriptors: A C{list} containing all of the file descriptors passed to C{fileDescriptorReceived} calls made on this instance. c<tj|g|_yrd)rPrbreceivedDescriptorsrVs rXrbz1TestFileDescriptorReceiverProtocol.connectionMades##D)#% rZc:|jj|yrd)r}re)rW descriptors rXfileDescriptorReceivedz9TestFileDescriptorReceiverProtocol.fileDescriptorReceiveds   '' 3rZN)rlrmrnrorbrr]rZrXr{r{s&4rZr{ceZdZdZdZdZy)TestHandshakeListenera A Protocol that implements L{IHandshakeListener} and records the number of times its C{handshakeCompleted} method has been called. @ivar handshakeCompletedCalls: The number of times C{handshakeCompleted} @type handshakeCompletedCalls: L{int} c<tj|d|_yrR)rPrYhandshakeCompletedCallsrVs rXrYzTestHandshakeListener.__init__sd#'($rZc.|xjdz c_y)zk Called when a TLS handshake has completed. Implemented per L{IHandshakeListener} raN)rrVs rXhandshakeCompletedz(TestHandshakeListener.handshakeCompleteds $$)$rZN)rlrmrnrorYrr]rZrXrrs)*rZrceZdZdZeZy) TestFactoryz Simple factory to be used both when connecting and listening. It contains two deferreds which are called back when my protocol connects and disconnects. N)rlrmrnrorPrr]rZrXrrs HrZrceZdZdZdZy) NoneFactoryzC A one off factory whose C{buildProtocol} returns L{None}. cyrdr]rWaddrs rX buildProtocolzNoneFactory.buildProtocolsrZNrlrmrnrorr]rZrXrrs rZrceZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZy)WrappingFactoryTestszS Test the behaviour of our ugly implementation detail C{_WrappingFactory}. ct}tj|}|j|j d|j y)z L{_WrappingFactory.doStart} passes through to the wrapped factory's C{doStart} method, allowing application-specific setup and logging. raN)r)r_WrappingFactorydoStart assertEqualnumPortsrWfactorywfs rX test_doStartz!WrappingFactoryTests.test_doStarts:  /  ' ' 0  G,,-rZct}d|_tj|}|j |j d|jy)z L{_WrappingFactory.doStop} passes through to the wrapped factory's C{doStop} method, allowing application-specific cleanup and logging. N)r)rrrdoStoprrs rX test_doStopz WrappingFactoryTests.test_doStopsB  /  ' ' 0  G,,-rZcGddt}tj|}|jdj |j t }|jfd|S)z An exception raised in C{buildProtocol} of our wrappedFactory results in our C{onConnection} errback being fired. ceZdZdZdZy)CWrappingFactoryTests.test_failedBuildProtocol..BogusFactoryzZ A one off factory whose C{buildProtocol} raises an C{Exception}. ctd)NMy protocol is poorly defined.) ValueErrorrs rXrzQWrappingFactoryTests.test_failedBuildProtocol..BogusFactory.buildProtocols !ABBrZNrr]rZrX BogusFactoryrs   CrZrNc<j|jdS)N)r)rargs)erWs rXz?WrappingFactoryTests.test_failedBuildProtocol..sd&&qvv/RSrZ)r)rrr assertFailure _onConnectionr addCallback)rWrrds` rXtest_failedBuildProtocolz-WrappingFactoryTests.test_failedBuildProtocolsa  C= C ' '  7    r// < S rZctjt}|jd|j |j t jy)z If the wrapped factory's C{buildProtocol} returns L{None} the C{onConnection} errback fires with L{error.NoProtocol}. N)rrrrfailureResultOfrr NoProtocolrWwrappingFactorys rXtest_buildNoneProtocolz+WrappingFactoryTests.test_buildNoneProtocols@ $44[]C%%d+ _::E.&rZN)rrrr addErrback assertIsNonerrs rXtest_buildProtocolReturnsNonez2WrappingFactoryTests.test_buildProtocolReturnsNonesD $44[]C%%001DE /77=>rZctjt}|jd}|j |j dy)z If the wrapped protocol provides L{ILoggingContext}, whatever is returned from the wrapped C{logPrefix} method is returned from L{_WrappingProtocol.logPrefix}. Nr\)rrrrrr^)rWrwps rXtest_logPrefixPassthroughz.WrappingFactoryTests.test_logPrefixPassthrough*s=  ' ' 6   d # ):;rZcGdd}t}||_tj|}|j d}|j |j dy)z If the wrapped protocol does not provide L{ILoggingContext}, the wrapped protocol's class name is returned from L{_WrappingProtocol.logPrefix}. c eZdZy)>WrappingFactoryTests.test_logPrefixDefault..NoProtocolNrlrmrnr]rZrXrr;s rZrN)rrrrrrr^)rWrrrrs rXtest_logPrefixDefaultz*WrappingFactoryTests.test_logPrefixDefault4sS  -%  ' ' 0   d # 6rZcdtjt}|jd}|j d|j d|j |jjdg|j d|j |jjddgy)z The wrapped C{Protocol}'s C{dataReceived} will get called when our C{_WrappingProtocol}'s C{dataReceived} gets called. Nsfoosbar) rrrrmakeConnectionrgr_wrappedProtocolrS)rWrps rX test_wrappedProtocolDataReceivedz5WrappingFactoryTests.test_wrappedProtocolDataReceivedDs  ' ' 6   T "  v ++006(; v ++00662BCrZctjt}|jd}t }|j ||j |j||j |jj|y)zo Our transport is properly hooked up to the wrappedProtocol when a connection is made. N) rrrrobjectrr transportr)rWrrdummyTransports rXtest_wrappedProtocolTransportz2WrappingFactoryTests.test_wrappedProtocolTransportSsk  ' ' 6   T " ( n5 ++55~FrZct}tj|}|jd}|j d|j |j jdgy)z Our wrappedProtocol's connectionLost method is called when L{_WrappingProtocol.connectionLost} is called. Nfail)rrrrrkrrrT)rWtfrrs rX"test_wrappedProtocolConnectionLostz7WrappingFactoryTests.test_wrappedProtocolConnectionLostcsW ]  ' ' +   T "   ++;;fXFrZc tjt}tt j d}|j d|gfd}|jj||j|gy)z Calls to L{_WrappingFactory.clientConnectionLost} should errback the L{_WrappingFactory._onConnection} L{Deferred} rstringNc(j|yrdre)ferrorss rXgotErrorzBWrappingFactoryTests.test_clientConnectionFailed..gotError|s MM! rZ) rrrr:r ConnectErrorclientConnectionFailedrrr)rWrexpectedFailurerrs @rXtest_clientConnectionFailedz0WrappingFactoryTests.test_clientConnectionFailedpso  ' ' 6!%"4"4F"CD !!$8  ##H- /!23rZcd}t}tj||}|jtj j ||jttj |y)zv Our L{_WrappingProtocol} should be an L{IFileDescriptorReceiver} if the wrapped protocol is. N)r{r_WrappingProtocol assertTruerIFileDescriptorReceiverrr)rWconnectedDeferredapplicationProtocolwrappers rX+test_wrappingProtocolFileDescriptorReceiverz@WrappingFactoryTests.test_wrappingProtocolFileDescriptorReceivers] !@B--.?ATU  ::EEgNO  Z%G%GQRrZct}tjd|}|jtj j |y)z~ Our L{_WrappingProtocol} does not provide L{IHalfCloseableProtocol} if the wrapped protocol doesn't. N)rPrr assertFalserrrrWtprs rX.test_wrappingProtocolNotFileDescriptorReceiverzCWrappingFactoryTests.test_wrappingProtocolNotFileDescriptorReceivers< ^  ' 'b 1 ;;FFqIJrZct}tjtj|}|j t |jd|j|jdgy)z L{_WrappingProtocol.fileDescriptorReceived} calls the wrapped protocol's C{fileDescriptorReceived} method. *N) r{rrrDeferredrr0rrr})rWwrappedProtocolrs rX*test_wrappedProtocolFileDescriptorReceivedz?WrappingFactoryTests.test_wrappedProtocolFileDescriptorReceiveds\ =>--enn.>P01&&r* < ^  ' 'b 1 ::EEaH%PrZct}tjd|}|jtj j |y)zs Our L{_WrappingProtocol} should be an L{IHandshakeListener} if the C{wrappedProtocol} is. N)rrrrrIHandshakeListenerr)rWhandshakeListenerwrappeds rX&test_wrappingProtocolHandshakeListenerz;WrappingFactoryTests.test_wrappingProtocolHandshakeListeners= 23--d4EF  55@@IJrZct}tjd|}|jtj j |y)z~ Our L{_WrappingProtocol} should not provide L{IHandshakeListener} if the C{wrappedProtocol} doesn't. N)rPrrrrrrrs rX)test_wrappingProtocolNotHandshakeListenerz>WrappingFactoryTests.test_wrappingProtocolNotHandshakeListeners< ^  ' 'b 1 66AA!DErZct}tjd|}|j|j |j y)z~ L{_WrappingProtocol.readConnectionLost} should proxy to the wrapped protocol's C{readConnectionLost} N)rqrrrwrrsrWrrs rX&test_wrappedProtocolReadConnectionLostz;WrappingFactoryTests.test_wrappedProtocolReadConnectionLosts: ()  ' 'c 2   %rZct}tjd|}|j|j |j y)z L{_WrappingProtocol.writeConnectionLost} should proxy to the wrapped protocol's C{writeConnectionLost} N)rqrrryrrtrs rX'test_wrappedProtocolWriteConnectionLostzrZrc4eZdZdZdZdZdZdZdZdZ y) ClientEndpointTestCaseMixinQ Generic test methods to be mixed into all client endpoint test classes. ct}|jt|\}}}|jt t j |y)zK The endpoint provides L{interfaces.IStreamClientEndpoint} N)rcreateClientEndpoint MemoryReactorrrrIStreamClientEndpoint)rW clientFactoryep ignoredArgsaddresss rXtest_interfacez*ClientEndpointTestCaseMixin.test_interfacesD #'#<#< O]$  K  Z%E%ErJKrZc0|j|ddS)z Retrieve a single factory that has connected using the given reactor. (This behavior is valid for TCP and SSL but needs to be overridden for UNIX.) @param reactor: a L{MemoryReactor} rrexpectedClientsrWrs rXretrieveConnectedFactoryz4ClientEndpointTestCaseMixin.retrieveConnectedFactorys##G,Q/22rZc t}t}t}|j||\}}}|j|}g fd}|j ||j |} | j j||j |g|j|} |jt| d|j| d|y)z} A client endpoint can connect and returns a deferred who gets called back with a protocol instance. c(j|yrdrrreceivedProtoss rX checkProtozKClientEndpointTestCaseMixin.test_endpointConnectSuccess..checkProto  ! !! $rZrarN) rr r connectrrrcallbackrrlenassertConnectArgs rWprotomreactorrr expectedArgs ignoredDestrrrrrs @rXtest_endpointConnectSuccessz7ClientEndpointTestCaseMixin.test_endpointConnectSuccesss  ? (,(A(A m) %L+ JJ} % % j!//9&&u- %1..x8 _-q1 q1<@rZc tjd}t|}t}|j ||\}}}|j |}g fd}|j ||j |gy)t If an endpoint tries to connect to a non-listening port it gets a C{ConnectError} failure. Connection FailedrconnectExceptionc<j|jyrdrevaluerreceivedExceptionss rX checkFailurezMClientEndpointTestCaseMixin.test_endpointConnectFailure..checkFailure2  % %agg .rZN)rrr/rr rrr) rW expectedErrorr$rrrr&rr2r1s @rXtest_endpointConnectFailurez7ClientEndpointTestCaseMixin.test_endpointConnectFailures **2EF 'G '+'@'@ m( $K JJ} % / \" +m_=rZc( t}t}|j||\}}}|j|}g fd}|j ||j |j |}|jdttj|jt d d} |j| jtj|j| jj |y) Calling L{Deferred.cancel} on the L{Deferred} returned from L{IStreamClientEndpoint.connect} is errbacked with an expected L{ConnectingCancelledError} exception. c(j|yrdr)rreceivedFailuress rXr2zRClientEndpointTestCaseMixin.test_endpointConnectingCancelled..checkFailureIs  # #A &rZNrar)r rr rrcancelrrr:r UserErrorrr assertIsInstancer/r#r) rWr$rrrrrr2attemptFactoryfailurer9s @rX test_endpointConnectingCancelledzClientEndpointTestCaseMixin.test_endpointConnectNonDefaultArgs\s ( ?(A(A(A g) !%!1!1!3) %L+ 7..x8 _-q1 q1<@rZN) rlrmrnrorrr'r5r?rCr]rZrXrrs*L3A@>4!9FArZrc(eZdZdZdZdZdZdZy)ServerEndpointTestCaseMixinr ct}|jt|\}}}|jt t j |y)zL The endpoint provides L{interfaces.IStreamServerEndpoint}. N)rcreateServerEndpointr rrrIStreamServerEndpoint)rWrrrr&s rXrz*ServerEndpointTestCaseMixin.test_interfacevsD('+'@'@ OW( $K  Z%E%ErJKrZct}t}|j||\}}}|j|}gfd}|j ||j |g|j |j ||gy)zs An endpoint can listen and returns a deferred that gets called back with a port instance. cDj|jyrd)regetHost)port receivedHostss rXcheckPortAndServerzRServerEndpointTestCaseMixin.test_endpointListenSuccess..checkPortAndServers   0rZN)r rrGlistenrrexpectedServers) rWr$rrr% expectedHostrrNrMs @rXtest_endpointListenSuccessz6ServerEndpointTestCaseMixin.test_endpointListenSuccesss !?()-)B)B8W)U&L, IIg   1 () 7 --h7,HrZc t}tjdd|}t|}|j ||\}}}|j t}g fd}|j ||j |gy)z When an endpoint tries to listen on an already listening port, a C{CannotListenError} failure is errbacked. rNP)listenExceptionc<j|jyrdr.r0s rXr2zLServerEndpointTestCaseMixin.test_endpointListenFailure..checkFailurer3rZN)rrCannotListenErrorr/rGrOrr) rWr exceptionr$rrr&rr2r1s @rXtest_endpointListenFailurez6ServerEndpointTestCaseMixin.test_endpointListenFailures (++BG< ' B'+'@'@7'S$K IIfh  / \" +i[9rZct}t}|j||fi|j\}}}|j ||j |}|j ||gy)zm The endpoint should pass it's listenArgs parameter to the reactor's listen methods. N)rr rG listenArgsrOrPr)rWrr$rr%rBrPs rX!test_endpointListenNonDefaultArgsz=ServerEndpointTestCaseMixin.test_endpointListenNonDefaultArgsso ( ?(A(A(A g) !%!2) %L+ '..x8 <.9rZN)rlrmrnrorrRrYr\r]rZrXrErEqsLI.:,:rZrEceZdZdZy)EndpointTestCaseMixinzJ Generic test methods to be mixed into all endpoint test classes. Nrlrmrnror]rZrXr^r^srZr^ceZdZdZdZdZy)SpecificFactoryz An L{IProtocolFactory} whose C{buildProtocol} always returns its C{specificProtocol} and sets C{passedAddress}. Raising an exception if C{specificProtocol} has already been used. c||_yrd)specificProtocol)rWrcs rXrYzSpecificFactory.__init__s 0rZc~t|jdr td||j_|jS)N passedAddresszspecificProtocol already used.)hasattrrcrrers rXrzSpecificFactory.buildProtocols8 4((/ :=> >.2+$$$rZN)rlrmrnrorYrr]rZrXraras1%rZraceZdZdZddZy) FakeStdioz_ A L{stdio.StandardIO} like object that simply captures its constructor arguments. Nc ||_||_y)z @param protocolInstance: like the first argument of L{stdio.StandardIO} @param reactor: like the reactor keyword argument of L{stdio.StandardIO} N)protocolInstancer)rWrjrs rXrYzFakeStdio.__init__s!1 rZrdrlrmrnrorYr]rZrXrhrhs  rZrhc"eZdZdZdZdZdZy)StandardIOEndpointsTestsz* Tests for Standard I/O Endpoints cXt|_tj|j}|j |j t jt|_t|_ |j|jt|j|_y)z Construct a L{StandardIOEndpoint} with a dummy reactor and a fake L{stdio.StandardIO} like object. Listening on it with a L{SpecificFactory}. N)rrrStandardIOEndpointassertIs_stdior StandardIOrhr+rcsuccessResultOfrOra fakeStdiorWendpoints rXsetUpzStandardIOEndpointsTests.setUpss x // = hoou'7'78# ( -- OOOD,A,AB C rZc|j|jj|j|j |jjj t y)z L{StandardIOEndpoint} returns a L{Deferred} that fires with an instance of a L{stdio.StandardIO} like object that was passed the result of L{SpecificFactory.buildProtocol} which was passed a L{PipeAddress}. N)rprtrjrcr<rer,rVs rXtest_protocolCreationz.StandardIOEndpointsTests.test_protocolCreationsE dnn55t7L7LM  NN + + 9 9; rZcd|j|jj|jy)z L{StandardIOEndpoint} passes its C{reactor} argument to the constructor of its L{stdio.StandardIO} like object. N)rprtrrVs rXtest_passedReactorz+StandardIOEndpointsTests.test_passedReactor s dnn,,dll;rZN)rlrmrnrorwryr{r]rZrXrmrms "   #67 !$ !$  # 333'?@ &;&@&@ArZc|jj|j}|j||jj }|j |tjy)z The wrapper function _WrapIProtocol gives an IProcessProtocol implementation that wraps over an IProtocol. N) rrrrsrrr<r_WrapIProtocolrWrwpps rXtest_wrappedProtocolz*ProcessEndpointsTests.test_wrappedProtocolsM GGOODLL ) Qll** c9#;#;>B ++RXX6 **BGG4 ++RXX6 **BGG4 **BGG4 --rzz: //>rZcGddtj}|}|jj|}|j ||j |j ty)zz The address passed to the factory's buildProtocol in the endpoint is a _ProcessAddress instance. ceZdZeZdZdZy)BProcessEndpointsTests.test_processAddress..TestAddrFactoryNcB||_|j}||_|Srd)rrr)rWrrs rXrzPProcessEndpointsTests.test_processAddress..TestAddrFactory.buildProtocols # MMO  rZ)rlrmrnr}rrrr]rZrXTestAddrFactoryrs.HG rZrN)rr*rrrsr<rr!)rWr myFactoryrs rXtest_processAddressz)ProcessEndpointsTests.test_processAddresssT  h.. $% GGOOI & Q i//ArZc|j|jj|j}|j |t y)zd L{ProcessEndpoint.connect} returns a Deferred with the connected protocol. N)rsrrrr<r})rWr#s rX test_connectz"ProcessEndpointsTests.test_connects6 $$TWW__T\\%BC e%<=rZcd}||j_|jj|j}|j |}|j t y)zg In case of failure, L{ProcessEndpoint.connect} returns a Deferred that fails. c trd) Exception) pprrrrrrrrs rXtestSpawnProcesszCProcessEndpointsTests.test_connectFailure..testSpawnProcesss + rZN)r _spawnProcessrrrtrapr)rWrrrs rXtest_connectFailurez)ProcessEndpointsTests.test_connectFailuresI   !1 GGOODLL )$$Q' 9rZN) rlrmrnrorwrrrrrrrr]rZrXrrts38 FB:=?@B*>rZrcpeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZy)ProcessEndpointTransportTestsze Test the behaviour of the implementation detail L{endpoints._ProcessEndpointTransport}. cFt|_tj|jd|_|j |jj tjt}|jj|_ |j|_ yr)rrrrrvrsrr* forProtocolr+rprocessrendpointTransport)rWrs rXrwz#ProcessEndpointTransportTests.setUp ss+- !11$,,@RS '' MM ! !'"5"5h"? @ ||44 !)!3!3rZc8tt|jy)zE L{_ProcessEndpointTransport}s provide L{IConsumer}. N)rr$rrVs rXtest_verifyConsumerz1ProcessEndpointTransportTests.test_verifyConsumers Y 6 67rZc8tt|jy)zI L{_ProcessEndpointTransport}s provide L{IPushProducer}. N)rr&rrVs rXtest_verifyProducerz1ProcessEndpointTransportTests.test_verifyProducers ]D$:$:;rZc8tt|jy)zF L{_ProcessEndpointTransport}s provide L{ITransport}. N)rr(rrVs rXtest_verifyTransportz2ProcessEndpointTransportTests.test_verifyTransports Z!7!78rZcd|j|jj|jy)zd The L{_ProcessEndpointTransport} instance stores the process passed to it. N)rpr_processrrVs rXtest_constructorz.ProcessEndpointTransportTests.test_constructor$s" d,,55t||DrZcttGdd}|}|jj|d|j |j j |y)z Registering a producer with the endpoint transport registers it with the underlying process transport. c eZdZy)FProcessEndpointTransportTests.test_registerProducer..AProducerNrr]rZrX AProducerr1s rZrFN)r r&rregisterProducerrprproducer)rWr aProducers rXtest_registerProducerz3ProcessEndpointTransportTests.test_registerProducer+sW ] #   $ K  // 5A dll++Y7rZc|jj|j|jjdy)zY Pausing the endpoint transport pauses the underlying process transport. pausedN)rpauseProducingrr producerStaterVs rXtest_pauseProducingz1ProcessEndpointTransportTests.test_pauseProducing9s0 --/ 33X>rZc|j|jj|j|jj dy)zc Resuming the endpoint transport resumes the underlying process transport. producingN)rrresumeProducingrrrrVs rXtest_resumeProducingz2ProcessEndpointTransportTests.test_resumeProducing@s<   " ..0 33[ArZc|jj|j|jjdy)zo Stopping the endpoint transport as a producer stops the underlying process transport. stoppedN)r stopProducingrrrrVs rXtest_stopProducingz0ProcessEndpointTransportTests.test_stopProducingIs0 ,,. 33Y?rZc|j|jj|j|jj y)z Unregistring the endpoint transport's producer unregisters the underlying process transport's producer. N)rrunregisterProducerrrrrVs rXtest_unregisterProducerz5ProcessEndpointTransportTests.test_unregisterProducerQs: ""$ 113 $,,//0rZcrg|j_|jtt|j dy)z L{endpoints._ProcessEndpointTransport} filters out extraneous attributes of its underlying transport, to present a more consistent cross-platform view of subprocesses and prevent accidental dependencies. pipesN)rr assertRaisesAttributeErrorgetattrrrVs rXtest_extraneousAttributesz7ProcessEndpointTransportTests.test_extraneousAttributesZs*   .'43I3I7SrZc|jjgd|j|jjj dy)z The writeSequence method of L{_ProcessEndpointTransport} writes a list of string passed to it to the transport's stdin. )stest1stest2stest3stest1test2test3N)r writeSequencerriogetvaluerVs rXtest_writeSequencez0ProcessEndpointTransportTests.test_writeSequenceds; ,,-KL 1135GHrZc|jjd|j|jjj dy)z The write method of L{_ProcessEndpointTransport} writes a string of data passed to it to the child process's stdin. stestN)rrrrrrrVs rX test_writez(ProcessEndpointTransportTests.test_writels9 $$W- 113W=rZc|jj|j|jjy)z A call to the loseConnection method of a L{_ProcessEndpointTransport} instance returns a call to the process transport's loseConnection. N)rloseConnectionrr connectedrVs rXtest_loseConnectionz1ProcessEndpointTransportTests.test_loseConnectionts. --/ //0rZc|jj}|j|t|j ||j jy)z L{_ProcessEndpointTransport.getHost} returns a L{_ProcessAddress} instance matching the process C{getHost}. N)rrKr<r!rpr)rWhosts rX test_getHostz*ProcessEndpointTransportTests.test_getHost|C %%--/ dO4 dDLL0023rZc|jj}|j|t|j ||j jy)z L{_ProcessEndpointTransport.getPeer} returns a L{_ProcessAddress} instance matching the process C{getPeer}. N)rgetPeerr<r!rpr)rWpeers rX test_getPeerz*ProcessEndpointTransportTests.test_getPeerr!rZN)rlrmrnrorwrrrrrrrr r rrrrr r%r]rZrXrrs\ 48 < 9 E 8?B@1TI>144rZrcFeZdZdZdZdZdZdZdZdZ dZ d Z d Z y ) WrappedIProtocolTestszL Test the behaviour of the implementation detail C{_WrapIProtocol}. ct|_tj|jd|_d|_t j|_t|j_yr) rrrrreventLogrr*rr}rVs rXrwzWrappedIProtocolTests.setUpsH+- ++DLL:LM '') 7 rZc<|jj|j}|j||jj }|j |jt|j|j|jjy)zQ Stores an L{IProtocol} provider and the flag to log/drop stderr N) rrrrsrrr<rr}rerrFlagrrs rXrz&WrappedIProtocolTests.test_constructorsj GGOODLL ) Qll** cll,CD dgg&6&67rZc|jj|j}|j||jj }|j |jj|jy)zx Our process transport is properly hooked up to the wrappedIProtocol when a connection is made. N) rrrrsrrrrrrs rXtest_makeConnectionz)WrappedIProtocolTests.test_makeConnectionsU GGOODLL ) Qll** //?rZc||_y)z! A log observer. N)r))rW eventDicts rX_stdLogzWrappedIProtocolTests._stdLogs " rZc|jj|j}|j||jj }t j|j|jt j|j|jdd|j|jd|j|j|jdd|j|jd|j|j!dt j"|jy)z When the _errFlag is set to L{StandardErrorBehavior.LOG}, L{endpoints._WrapIProtocol} logs stderr (in childDataReceived). rsstderr1rrSrzwrote stderr unhandled byN)rrrrsrrr7 addObserverr0 addCleanupremoveObserverchildDataReceivedrr)rrassertIntextFromEventDictrs rXtest_logStderrz$WrappedIProtocolTests.test_logStderrs GGOODLL ) Qll**  % **DLL9 a, |4cnnE v. ; z2CLLA 133H3H3WXrZctj|j_|jj |j }|j ||jj}tj|j|jtj|j|jdd|j|j y)z When the _errFlag is set to L{StandardErrorBehavior.DROP}, L{endpoints._WrapIProtocol} ignores stderr. rsstderr2N)r"rrrrrrsrrr7r2r0r3r4r5rr)rs rXtest_stderrSkipz%WrappedIProtocolTests.test_stderrSkips 155 GGOODLL ) Qll**  % **DLL9 a, $--(rZc |jj|j}|j||jj }|j dd|j|jjdy)z In childDataReceived of L{_WrappedIProtocol} instance, the protocol's dataReceived is called when stdout is generated. rasstdoutN) rrrrsrrr5rrrSrs rX test_stdoutz!WrappedIProtocolTests.test_stdoutsa GGOODLL ) Qll** a+ **I6rZc|jj|j}|j||jj }|j ttjd|j|jjjtjtjy)z L{error.ProcessDone} with status=0 is turned into a clean disconnect type, i.e. L{error.ConnectionDone}. rN)rrrrsrr processEndedr:r ProcessDonerrrjcheckConnectionDoners rXtest_processDonez&WrappedIProtocolTests.test_processDones GGOODLL ) Qll** !2!21!567  LL   % %e&:&: ;U=Q=Q rZc|jj|j}|j||jj }|j ttj|j|jjjtjtjy)z{ Exceptions other than L{error.ProcessDone} with status=0 are turned into L{error.ConnectionLost}. N)rrrrsrrr>r:rProcessTerminatedrrrjr@ConnectionLostrs rXtest_processEndedz'WrappedIProtocolTests.test_processEndeds GGOODLL ) Qll** !8!8!:;<  LL   % %e&:&: ;U=Q=Q rZN) rlrmrnrorwrr-r0r8r:r<rBrFr]rZrXr'r's688@" Y" ) 7    rZr'c:eZdZdZdZdZdZdZdZdZ dZ y ) TCP4EndpointsTestsz' Tests for TCP IPv4 Endpoints. c|jSzD @return: List of calls to L{IReactorTCP.listenTCP}  tcpServersrs rXrPz"TCP4EndpointsTests.expectedServers!!!rZc|jSzE @return: List of calls to L{IReactorTCP.connectTCP}  tcpClientsrs rXrz"TCP4EndpointsTests.expectedClients rMrZc|\}}}}}|\}} } } } |j|||j|| |j|| |j|| ya] Compare host, port, timeout, and bindAddress in C{receivedArgs} to C{expectedArgs}. We ignore the factory because we don't only care what protocol comes out of the C{IStreamClientEndpoint.connect} call. @param receivedArgs: C{tuple} of (C{host}, C{port}, C{factory}, C{timeout}, C{bindAddress}) that was passed to L{IReactorTCP.connectTCP}. @param expectedArgs: C{tuple} of (C{host}, C{port}, C{factory}, C{timeout}, C{bindAddress}) that we expect to have been passed to L{IReactorTCP.connectTCP}. Nr rW receivedArgsr%rrLignoredFactorytimeout bindAddressrQ expectedPort_ignoredFactoryexpectedTimeoutexpectedBindAddresss rXr!z$TCP4EndpointsTests.assertConnectArgsq>J:t^Wk        |, |, /2 &9:rZc dddSK @return: C{dict} of keyword arguments to pass to connect.  localhostirXrYr]rVs rXrAzTCP4EndpointsTests.connectArgs+.BCCrZc dddSI @return: C{dict} of keyword arguments to pass to listen d 127.0.0.1backlog interfacer]rVs rXr[zTCP4EndpointsTests.listenArgs1[99rZc tddd}tj||jfi||j||j dd|j ddf|fS)a Create an L{TCP4ServerEndpoint} and return the values needed to verify its behaviour. @param reactor: A fake L{IReactorTCP} that L{TCP4ServerEndpoint} can call L{IReactorTCP.listenTCP} on. @param factory: The thing that we expect to be passed to our L{IStreamServerEndpoint.listen} implementation. @param listenArgs: Optional dictionary of arguments to L{IReactorTCP.listenTCP}. TCP0.0.0.0rrm2rnrN)rrTCP4ServerEndpointrLgetrWrrr[rs rXrGz'TCP4EndpointsTests.createServerEndpoint7sgeY2  ( (',, M* M y"-{B/     rZc tddd}tj||j|jfi||j|j||j dd|j ddf|fS)a Create an L{TCP4ClientEndpoint} and return the values needed to verify its behavior. @param reactor: A fake L{IReactorTCP} that L{TCP4ClientEndpoint} can call L{IReactorTCP.connectTCP} on. @param clientFactory: The thing that we expect to be passed to our L{IStreamClientEndpoint.connect} implementation. @param connectArgs: Optional dictionary of arguments to L{IReactorTCP.connectTCP} rqrdrTrXrYN)rrTCP4ClientEndpointrrLrurWrrrArs rXr z'TCP4EndpointsTests.createClientEndpointPs|e["5  ( (w|| 7B    2. t4     rZN rlrmrnrorPrr!rAr[rGr r]rZrXrHrHs+" " ;8D :  2 rZrHc:eZdZdZdZdZdZdZdZdZ dZ y ) TCP6EndpointsTestsz' Tests for TCP IPv6 Endpoints. c|jSrJrKrs rXrPz"TCP6EndpointsTests.expectedServersrrMrZc|jSrOrPrs rXrz"TCP6EndpointsTests.expectedClientsxrMrZc|\}}}}}|\}} } } } |j|||j|| |j|| |j|| yrSrTrUs rXr!z$TCP6EndpointsTests.assertConnectArgs~r^rZc dddSr`r]rVs rXrAzTCP6EndpointsTests.connectArgsrfrZc dddS)rirj::1rlr]rVs rXr[zTCP6EndpointsTests.listenArgssU33rZc |jdd}td|d}tj||jfi||j||jdd|f|fS)a Create a L{TCP6ServerEndpoint} and return the values needed to verify its behaviour. @param reactor: A fake L{IReactorTCP} that L{TCP6ServerEndpoint} can call L{IReactorTCP.listenTCP} on. @param factory: The thing that we expect to be passed to our L{IStreamServerEndpoint.listen} implementation. @param listenArgs: Optional dictionary of arguments to L{IReactorTCP.listenTCP}. rnz::rqrrmrs)rurrTCP6ServerEndpointrL)rWrrr[rnrs rXrGz'TCP6EndpointsTests.createServerEndpointseNN;5 eY2  ( (',, M* M \\7JNN9b$A9 M   rZc tddd}tj||j|jfi||j|j||j dd|j ddf|fS) Create a L{TCP6ClientEndpoint} and return the values needed to verify its behavior. @param reactor: A fake L{IReactorTCP} that L{TCP6ClientEndpoint} can call L{IReactorTCP.connectTCP} on. @param clientFactory: The thing that we expect to be passed to our L{IStreamClientEndpoint.connect} implementation. @param connectArgs: Optional dictionary of arguments to L{IReactorTCP.connectTCP} rqrrTrXrxrYN)rrTCP6ClientEndpointrrLrurzs rXr z'TCP6EndpointsTests.createClientEndpoints|eUB/  ( (w|| 7B    2. t4     rZNr{r]rZrXr}r}ms+" " ;8D 4  * rZr}c4eZdZdZdZdZdZdZdZdZ y) TCP6EndpointNameResolutionTestszl Tests for a TCP IPv6 Client Endpoint pointed at a hostname instead of an IPv6 address literal. c (tddd}tj|d|jfi|_fd}|j_j|j |j||jdd|jdd f|fS) rrq::2rTipv6.example.comcjd|tttddftttddftttddfg}t j |S)NrrN)rrrr)z::3rrr)z::4rrr)rrrrrsucceed)rrSrWs rXtestNameResolutionzPTCP6EndpointNameResolutionTests.createClientEndpoint..testNameResolutionsY   / 6; R9IJ; R9IJ; R9IJD ==& &rZrXrxrYN)rrrrLr_nameResolutionrru)rWrrrArrs` rXr z4TCP6EndpointNameResolutionTests.createClientEndpointseUB/.. ' 9D  '#5 GG   2. t4     rZc dddSr`r]rVs rXrAz+TCP6EndpointNameResolutionTests.connectArgsrfrZc|jSrOrPrs rXrz/TCP6EndpointNameResolutionTests.expectedClients rMrZc|\}}}}}|\}} } } } |j|||j|| |j|| |j|| yrSrTrUs rXr!z1TCP6EndpointNameResolutionTests.assertConnectArgsr^rZctjddd}|j|jtj y)zg By default, L{TCP6ClientEndpoint._deferToThread} is L{threads.deferToThread}. Nzwww.example.com)rrr_deferToThreadr deferToThreadrWrs rXtest_freeFunctionDeferToThreadz>TCP6EndpointNameResolutionTests.test_freeFunctionDeferToThread.s5  ) )$0A4 H **G,A,ABrZcgfd}tjtdd}t}||_||_|j t|j|ddtfifgy)zl While resolving hostnames, _nameResolution calls _deferToThread with _getaddrinfo. cTj|||ftjSrd)rerr)rrkwargscallss rXfakeDeferToThreadzNTCP6EndpointNameResolutionTests.test_nameResolution..fakeDeferToThread=s# LL!T6* +>># #rZrrrN) rrrr _getaddrinforrrrr)rWrrvfakegetaddrinfors @rXtest_nameResolutionz3TCP6EndpointNameResolutionTests.test_nameResolution6sr  $//9KTR ( /"3'  2Ax@" E F rZN) rlrmrnror rArr!rrr]rZrXrrs( & PD " ;8C rZrceZdZdZddZy)RaisingMemoryReactorWithClockzE An extension of L{RaisingMemoryReactor} with L{task.Clock}. Nc\tj|tj|||yrd)r-rYr/)rWrUr,s rXrYz&RaisingMemoryReactorWithClock.__init__Ps! t%%dO=MNrZ)NNrkr]rZrXrrKs OrZrcijttGfddttGfddt t dt t|}||S)ap Create a reactor that will deterministically resolve all hostnames it is passed to the list of addresses given. @param reactor: An object that we wish to add an L{IReactorPluggableNameResolver} to. @type reactor: Any object with some formally-declared interfaces (i.e. one where C{list(providedBy(reactor))} is not empty); usually C{IReactor*} interfaces. @param expectedAddresses: (optional); the addresses expected to be returned for every address. If these are strings, they should be IPv4 or IPv6 literals, and they will be wrapped in L{IPv4Address} and L{IPv6Address} objects in the resolution result. @type expectedAddresses: iterable of C{object} or C{str} @param hostMap: (optional); the names (unicode) mapped to lists of addresses (str or L{IAddress}); in the same format as expectedAddress, which map the results for I{specific} hostnames to addresses. @return: A new reactor which provides all the interfaces previously provided by C{reactor} as well as L{IReactorPluggableNameResolver}. All name resolutions performed with its C{nameResolver} attribute will resolve reentrantly and synchronously with the given C{expectedAddresses}. However, it is not a complete implementation as it does not have an C{installNameResolver} method. c,eZdZe dfd Zy)9deterministicResolvingReactor..SimpleNameResolverNc|jdj|D]B}t|trt t gt |d||}|j|D|jy)Nrq) resolutionBeganru isinstancestrrrraddressResolvedresolutionComplete)resolutionReceiverhostName portNumber addressTypestransportSemanticsexpectedAddressexpectedAddresseshostMaps rXresolveHostNamezIdeterministicResolvingReactor..SimpleNameResolver.resolveHostNamews{  . .t 4#*;;x9J#K Dos3'2K&@%o6'_j':O#22?C  D  1 1 3rZ)rNrq)rlrmrn staticmethodr)rrsrXSimpleNameResolverrus $  4  4rZrceZdZWZy)3deterministicResolvingReactor..WithResolverN)rlrmrn nameResolver)rsrX WithResolverrs *+ rZr*)copyr r%r'r9rtupler)rrrrrs `` @rXdeterministicResolvingReactorrUs|8llnG"#44$4$./,.eJw4G.HIJ,0,   rZc.eZdZdZdZdZdZdZdZy)SimpleHostnameResolverTestsa Tests for L{endpoints._SimpleHostnameResolver}. @ivar fakeResolverCalls: Arguments with which L{fakeResolver} was called. @type fakeResolverCalls: L{list} of C{(hostName, port)} L{tuple}s. @ivar fakeResolverReturns: The return value of L{fakeResolver}. @type fakeResolverReturns: L{Deferred} @ivar resolver: The instance to test. @type resolver: L{endpoints._SimpleHostnameResolver} @ivar resolutionBeganCalls: Arguments with which receiver's C{resolutionBegan} method was called. @type resolutionBeganCalls: L{list} @ivar addressResolved: Arguments with which C{addressResolved} was called. @type addressResolved: L{list} @ivar resolutionCompleteCallCount: The number of calls to the receiver's C{resolutionComplete} method. @type resolutionCompleteCallCount: L{int} @ivar receiver: A L{interfaces.IResolutionReceiver} provider. cg_tj_t j j _g_g_ d_ ttjGfdd}|_y)NrcJeZdZefdZefdZefdZy)4SimpleHostnameResolverTests.setUp.._Receiverc<jj|yrd)resolutionBeganCallsre)resolutionInProgressrWs rXrzDSimpleHostnameResolverTests.setUp.._Receiver.resolutionBegans))001EFrZc<jj|yrd)addressResolvedCallsre)rrWs rXrzDSimpleHostnameResolverTests.setUp.._Receiver.addressResolveds))009rZc0xjdz c_yr`)resolutionCompleteCallCountrVsrXrzGSimpleHostnameResolverTests.setUp.._Receiver.resolutionCompletes00A50rZN)rlrmrnrrrrrVsrX _Receiverrs?  G G : : 6 6rZr)fakeResolverCallsrrfakeResolverReturnsr_SimpleHostnameResolver fakeResolverresolverrrrrrIResolutionReceiverreceiver)rWrs` rXrwz!SimpleHostnameResolverTests.setUpsu!##(>>#3 !99$:K:KL $&!$&!+,( *00 1 6 6 2 6" rZcT|jj||f|jS)z A fake resolver callable. @param hostName: The hostname to resolve. @param portNumber: The port number the returned address should include. @return: L{fakeResolverCalls} @rtype: L{Deferred} )rrer)rWrrs rXrz(SimpleHostnameResolverTests.fakeResolvers) %%x&<='''rZcj|jttj|jy)zs A L{endpoints._SimpleHostnameResolver} instance provides L{interfaces.IHostnameResolver}. N)rrrr%rrVs rXrz*SimpleHostnameResolverTests.test_interfaces!  Z%A%A4==QRrZcgttfdtj|j fd|j j |jd|jjt|jdt|jdt|jt\}|j|jd|j|jdd|j|jdt!|j"|jdt|j$|j|j$dj&d|j)|j*|jd|j,y ) z A resolution failure is logged with the name that failed to resolve and the callable that tried to resolve it. The resolution receiver begins, receives no addresses, and completes. c(j|yrdr)eventlogss rX captureLogszHSimpleHostnameResolverTests.test_resolveNameFailure..captureLogss KK rZc.tjSrd)r3r4)rsrXrzESimpleHostnameResolverTests.test_resolveNameFailure..s 2 A A+ NrZ example.comraisErrornamecallablerN)rr2r3r2r3rrrrerrbackrrr flushLoggedErrorsrrureprrrrrrr)rWrrrs @@rXtest_resolveNameFailurez3SimpleHostnameResolverTests.test_resolveNameFailures[ ,     &&{3 NO %%dmm]C   ((5 CI& C 6 6y ABC  ),-  &-89  *d43D3D.EFG C 9 9:; 2215::MJ 223 D<<=rZc d}d}d}|jj|jd|jj t t td||fftt td||ffg|jdt|j|j|jdjd|j|jtd||td||g|j|j dy ) zs The resolution receiver begins, and resolved hostnames are delivered before it completes. rT1.2.3.4z 1::2::3::4rrNrarrqN)rrrrrrrrrrr rrrrrr)rWrLipv4Hostipv6Hosts rXtest_resolveNameDeliversz4SimpleHostnameResolverTests.test_resolveNameDeliverss  %%dmm]C   ))+{B48HI; R(D9IJ   C 9 9:; 2215::MJ   % % $ /UHd1S T  991=rZN) rlrmrnrorwrrrrr]rZrXrrs"8"2 (S>B>rZrceZdZdZdZy)+HostnameEndpointFallbackNameResolutionTestszd L{HostnameEndpoint._fallbackNameResolution} defers a name resolution call to a thread. cddlm}tj|dd}d\|j }fd}|j |S)z L{_fallbackNameResolution} returns a L{Deferred} that fires with the resoution of the the host and request port. r)rignored)rrL)rracjt|d|\\}}}}}j|tj|tj|fyr`)rr rr)resultfamilysocktype_sockaddrrrLrWs rXassertHostPortFamilySockTypezmHostnameEndpointFallbackNameResolutionTests.test_fallbackNameResolution..assertHostPortFamilySockType,s^   S[! ,39 0 /fh1h   VW -   X{ 3   Xd| 4rZ)twisted.internetrrHostnameEndpoint_fallbackNameResolutionr)rWrrresolutionDeferredrrrLs` @@rXtest_fallbackNameResolutionzGHostnameEndpointFallbackNameResolutionTests.test_fallbackNameResolutionsQ -  ' 'ia H# d77dC 5"--.JKKrZN)rlrmrnrorr]rZrXrrs  LrZrc:eZdZdZdZdZdZdZdZdZ dZ y ) #_HostnameEndpointMemoryReactorMixinz Common methods for testing L{HostnameEndpoint} against L{MemoryReactor} instances that do not provide L{IReactorPluggableNameResolver}. c ||i|}tj|S#t$rtjcYSwxYw)a A synchronous version of L{deferToThread}. @param f: The callable to invoke. @type f: L{callable} @param args: Positional arguments to the callable. @param kwargs: Keyword arguments to the callable. @return: A L{Deferred} that fires with the result of applying C{f} to C{args} and C{kwargs} or the exception raised. )rr BaseExceptionr)rWrrrrs rXsynchronousDeferredToThreadz?_HostnameEndpointMemoryReactorMixin.synchronousDeferredToThread=sD )''F==( ( ::<  s ??c|jS)z Extract expected clients from the reactor. @param reactor: The L{MemoryReactor} under test. @return: List of calls to L{IReactorTCP.connectTCP} rPrs rXrz3_HostnameEndpointMemoryReactorMixin.expectedClientsRs!!!rZc dddS)zL @return: C{dict} of keyword arguments to pass to connect. g$@rcrer]rVs rXrAz/_HostnameEndpointMemoryReactorMixin.connectArgs\s  0DEErZc|\}}}}}|\}} } } } |j|||j|| |j|| |j|| yrSrTrUs rXr!z5_HostnameEndpointMemoryReactorMixin.assertConnectArgscr^rZctjd}t|}t}|j ||\}}}|j |}|j tjj|j|j|j||jg|jy)z When L{HostnameEndpoint.connect} cannot connect to its destination, the returned L{Deferred} will fail with C{ConnectError}. r*rr+Nrrrrr radvancerr_DEFAULT_ATTEMPT_DELAYrrr/getDelayedCallsrWr4r$rrrr&rs rXr5z?_HostnameEndpointMemoryReactorMixin.test_endpointConnectFailure **2EF 0-P '+'@'@ m( $K JJ} %33JJK --a066 F X5578rZc*t}t}|j|||j}|j dt ||j t|dd|j|ddjdy)z Instantiating L{HostnameEndpoint} with a reactor that does not provide L{IReactorPluggableResolver} emits a deprecation warning. rarcategorymessagezPassing HostnameEndpoint a reactor that does not provide IReactorPluggableNameResolver (twisted.internet.testing.MemoryReactorClock) was deprecated in Twisted 17.5.0; please use a reactor that provides IReactorPluggableNameResolver insteadN) r rr  flushWarningsrr rpDeprecationWarningr startswith)rWr$rwarningss rXtest_deprecationz4_HostnameEndpointMemoryReactorMixin.test_deprecations !?  !!(M:%%' CM* ((1+j*AB  QK " - -9  rZc\t}t}|j||\}}}d}||_|j |}|j |j |jtj|jdt|jty)z8 Hostname resolution errors are logged. ctdd)Nz#No address associated with hostname)r )rrs rXgetaddrinfoThatFailszS_HostnameEndpointMemoryReactorMixin.test_errorsLogged..getaddrinfoThatFailss2DE ErZraN)r rr rrr<rr/rDNSLookupErrorrr rr )rWr$rrrr&rrs rXtest_errorsLoggedz5_HostnameEndpointMemoryReactorMixin.test_errorsLoggeds!? '+'@'@ m( $K F/ JJ} % d2215;;U=Q=QR C 6 6x @ABrZN) rlrmrnrorrrAr!r5rrr]rZrXrr6s, )*"F;89* 4CrZrceZdZdZdZy)&HostnameEndpointMemoryIPv4ReactorTestsz IPv4 resolution tests for L{HostnameEndpoint} with L{MemoryReactor} subclasses that do not provide L{IReactorPluggableNameResolver}. c dtdd}tj|d|jfi|}fd}||_|j |_||j||jdd|jddf|fS) a Creates a L{HostnameEndpoint} instance where the hostname is resolved into a single IPv4 address. @param reactor: The L{MemoryReactor} @param clientFactory: The client L{IProtocolFactory} @param connectArgs: Additional arguments to L{HostnameEndpoint.connect} @return: A L{tuple} of the form C{(endpoint, (expectedAddress, expectedPort, clientFactory, timeout, localBindAddress, hostnameAddress))} r example.comrTc0tttddffgSNrNrT)rrrrrLrrrs rXrzTHostnameEndpointMemoryIPv4ReactorTests.createClientEndpoint..fakegetaddrinfos +{B"8MN rZrXrxrYNrrrrLrrrrurWrrrArrvrrs @rXr z;HostnameEndpointMemoryIPv4ReactorTests.createClientEndpoints $!."5-- ^W\\ 5@   !0"&"B"B   2. t4     rZNrlrmrnror r]rZrXrr  ( rZrceZdZdZdZy)&HostnameEndpointMemoryIPv6ReactorTestsz IPv6 resolution tests for L{HostnameEndpoint} with L{MemoryReactor} subclasses that do not provide L{IReactorPluggableNameResolver}. c dtdd}tj|d|jfi|}fd}||_|j |_||j||jdd|jddf|fS) a Creates a L{HostnameEndpoint} instance where the hostname is resolved into a single IPv6 address. @param reactor: The L{MemoryReactor} @param clientFactory: The client L{IProtocolFactory} @param connectArgs: Additional arguments to L{HostnameEndpoint.connect} @return: A L{tuple} of the form C{(endpoint, (expectedAddress, expectedPort, clientFactory, timeout, localBindAddress, hostnameAddress))} 1:2::3:4ipv6.example.comrTc0tttddffgSr)rrrrs rXrzTHostnameEndpointMemoryIPv6ReactorTests.createClientEndpoint..fakegetaddrinfos ; R/29NO rZrXrxrYNrr s @rXr z;HostnameEndpointMemoryIPv6ReactorTests.createClientEndpoints %!"5r:-- (',, :E   !0"&"B"B   2. t4     rZNr!r]rZrXr$r$r"rZr$cHeZdZdZdZdZdZdZd dZdZ d Z d Z d Z y) HostnameEndpointsOneIPv4Testsz^ Tests for the hostname based endpoints when GAI returns only one (IPv4) address. c d}tdd}tjt||gd|jfi|}|||j||j dd|j ddf|fS)z{ Creates a L{HostnameEndpoint} instance where the hostname is resolved into a single IPv4 address. rrrTrXrxrYNrrrrrLru)rWrrrArrrvs rXr z2HostnameEndpointsOneIPv4Tests.createClientEndpoint3s $!."5-- )'O3D E  LL      2. t4     rZc|jSrOrPrs rXrz-HostnameEndpointsOneIPv4Tests.expectedClientsMrMrZc|\}}}}}|\}} } } } |j|||j|| |j|| |j|| yrSrTrUs rXr!z/HostnameEndpointsOneIPv4Tests.assertConnectArgsSr^rZc dddSr`r]rVs rXrAz)HostnameEndpointsOneIPv4Tests.connectArgsorfrZNct}tj}tj|_|j ||\}}}|j |}||j ||j|j|}|jdttj|j|} |j| jtj |j#| jj$||j'|j(ddj*j,|j#g|j/y)z Calling L{Deferred.cancel} on the L{Deferred} returned from L{IStreamClientEndpoint.connect} will cause it to be errbacked with a L{ConnectingCancelledError} exception. Nrr)r rr*r+r rrr:rrr:rr;rr<r/r#rrrrQ _connectorstoppedConnectingr) rWrr$rrrrrr=r>s rXr?z>HostnameEndpointsOneIPv4Tests.test_endpointConnectingCancelledus  !? ((* !)!2!2 #'#<#rZctjd}t|}t}|j ||\}}}|j |}|j tjj|j|j|j||jg|jy)z If L{HostnameEndpoint.connect} is invoked and there is no server listening for connections, the returned L{Deferred} will fail with C{ConnectError}. r*rr+Nrrs rXr5z9HostnameEndpointsOneIPv4Tests.test_endpointConnectFailurer rZctjd}t}t}|j ||\}}}|j |}|j d|jd\}} } } } | j|jd||j|j|j||jg|jy)a If a connection attempt initiated by L{HostnameEndpoint.connect} fails only after L{HostnameEndpoint} has exhausted the list of possible server addresses, the returned L{Deferred} will fail with C{ConnectError}. r*r333333?rN)rrr rr rrrQr connectorsrrr/r) rWr4r$rrrr&rrrLrrXrYs rX)test_endpointConnectFailureAfterIterationzGHostnameEndpointsOneIPv4Tests.test_endpointConnectFailureAfterIterations**2EF  ? '+'@'@ m( $K JJ} %4<4G4G4J1dGWk&&x':':1'=}M --a066 F X5578rZc" t}t}t}|j||\}}}|j|}g fd}|j ||j |} |j d| jj||j |g|j|} |jt| d|j| d||jg|jy)a\ If a connection attempt initiated by L{HostnameEndpoint.connect} succeeds only after L{HostnameEndpoint} has exhausted the list of possible server addresses, the returned L{Deferred} will fire with the connected protocol instance and the endpoint will leave no delayed calls in the reactor. c(j|yrdrrs rXrz[HostnameEndpointsOneIPv4Tests.test_endpointConnectSuccessAfterIteration..checkProtorrZr8rarN)rr r rrrrrrrrr r!rr"s @rX)test_endpointConnectSuccessAfterIterationzGHostnameEndpointsOneIPv4Tests.test_endpointConnectSuccessAfterIterations ? (,(A(A m) %L+ JJ} % % j!//9&&u- %1..x8 _-q1 q1<@ X5578rZrd) rlrmrnror rr!rAr?r5r5r:r=r]rZrXr*r*-s5  4" ;8D 9< ?9*92&9rZr*c4eZdZdZdZdZdZdZdZdZ y) HostnameEndpointsOneIPv6Testsz^ Tests for the hostname based endpoints when GAI returns only one (IPv6) address. c tdd}tjt|dgd|jfi|}|d|j||j dd|j ddf|fS)z{ Creates a L{HostnameEndpoint} instance where the hostname is resolved into a single IPv6 address. r'rTr&rXrxrYNr,)rWrrrArrvs rXr z2HostnameEndpointsOneIPv6Tests.createClientEndpoints ""5r:-- )'J< @  LL      2. t4     rZc|jSrOrPrs rXrz-HostnameEndpointsOneIPv6Tests.expectedClients rMrZc|\}}}}}|\}} } } } |j|||j|| |j|| |j|| yrSrTrUs rXr!z/HostnameEndpointsOneIPv6Tests.assertConnectArgs r^rZc dddSr`r]rVs rXrAz)HostnameEndpointsOneIPv6Tests.connectArgs5 rfrZct}tj}tj|_|j t |dg|\}}}|j |}|j|j|}|jdttj|j|}|j|jtj |j#|jj$||j'|j(ddj*j,|j#g|j/y)r7rkNrr)r rr*r+r rrr:rrr:rr;rr<r/r#rrrrQr1r2r) rWr$rrrrrr=r>s rXr?z>HostnameEndpointsOneIPv6Tests.test_endpointConnectingCancelled; s !? ((* !)!2!2 #'#<#< )([M BM$  K JJ} %  66x@--dGEOON rrrr-rrrprtyperWrvreps rX test_allASCIIz'HostnameEndpointReprTests.test_allASCII sT -- )%'2 6    8n Nr^r`s rXtest_idnaHostnamez+HostnameEndpointReprTests.test_idnaHostname sT -- )%'2 6    8n BCH c49%rZctjttgdd}t |}|j d||j tt|y)z When the host passed to L{HostnameEndpoint} is an IPv6 address it is wrapped in brackets in the string representation, like in a URI. This prevents the colon separating the host from the port from being ambiguous. s::1zNr^r`s rXtest_hostIPv6Addressz.HostnameEndpointReprTests.test_hostIPv6Address sT-- )%'2 6    8n 6< c49%rZctjttgdd}|j dt |y)z When a bad hostname is passed to L{HostnameEndpoint}, the string representation displays invalid characters in backslash-escaped form. rWrTz'N)rrrr-rrrus rXtest_badEncodingz*HostnameEndpointReprTests.test_badEncoding s? -- )%'2 68Lb   7 N rZN)rlrmrnrorbrerhrjr]rZrXr\r\ s& & &$  rZr\ceZdZdZdZy) HostnameEndpointsGAIFailureTestszM Tests for the hostname based endpoints when GAI returns no address. ctjttgdd}t }|j |}|j |tj}|jdt|y)z If no address is returned by GAI for a hostname, the connection attempt fails with L{error.DNSLookupError}. rrTrN) rrrr-rrrrrr6r)rWrvrdConnectexcs rX test_failurez-HostnameEndpointsGAIFailureTests.test_failure sg -- )%'2 6  ##M2""8U-A-AB mSX.rZN)rlrmrnrorpr]rZrXrlrl s  /rZrlc.eZdZdZdZdZdZdZdZy)&HostnameEndpointsFasterConnectionTestsz Tests for the hostname based endpoints when gai returns an IPv4 and an IPv6 address, and one connection takes less time than the other. ct|_tjt |jddgdd|_y)Nrr&www.example.comrT)r r$rrrrvrVs rXrwz,HostnameEndpointsFasterConnectionTests.setUp s6% !22 )$--)Z9P Q    rZct|_tjt |jdt dgdd|_d}|j j||jjd|jjd\}}}}}|jt|jjd|j|d|j|dy) z If an address type other than L{IPv4Address} and L{IPv6Address} is returned by on address resolution, the endpoint ignores that address. rr&rtrTNr8rar) r r$rrrrrvrrrQrr )rWrrrLrrXrYs rXtest_ignoreUnknownAddressTypeszEHostnameEndpointsFasterConnectionTests.test_ignoreUnknownAddressTypes s & !22 ) 68Z@        m, c"6:mm6N6Nq6Q3tWg{ T]]556: z* r"rZctj}tj|_|jj |}g}|j |j |jjd\}}}}}|j|d|j|d|j||f} t} |j|g| j| |jt|d|j|dj||jg|jjy)a= The endpoint returns a connection to the IPv4 address. IPv4 ought to be the first attempt, since nameResolution (standing in for GAI here) returns it first. The IPv4 attempt succeeds, the connection is established, and a Deferred fires with the protocol constructed. rrrTraN)rr*r+rvrrrer$rQrrrrr rr rWrrresultsrrLrrXrYr# fakeTransports rXtest_IPv4IsFasterz8HostnameEndpointsFasterConnectionTests.test_IPv4IsFaster1 s !((* !)!2!2  MM ! !- 0 gnn%6:mm6N6Nq6Q3tWg{ y) r"%%tTl3  "% ]+ Wq) ++]; T]]::<=rZctj}tj|_|jj |}g}|j |j |jjd|jjd\}}}}}|j|d|j|d|j||f} t} |j|g| j| |jt|d|j|dj||jg|jj!y)a= The endpoint returns a connection to the IPv6 address. IPv6 ought to be the second attempt, since nameResolution (standing in for GAI here) returns it second. The IPv6 attempt succeeds, a connection is established, and a Deferred fires with the protocol constructed. r8rar&rTrN)rr*r+rvrrrer$rrQrrrrr rrrxs rXtest_IPv6IsFasterz8HostnameEndpointsFasterConnectionTests.test_IPv6IsFasterP s!((* !)!2!2  MM ! !- 0 gnn% c"6:mm6N6Nq6Q3tWg{ z* r"%%tTl3  "% ]+ Wq) ++]; T]]::<=rZcjtj}tj|_|jj |}g}|j |j |jjd|jjd\}}}}}|j||f} t} | j| |jd|jjddjj|jg|jj!y)a Once the endpoint returns a successful connection, all the other pending connections are cancelled. Here, the second connection attempt, i.e. IPv6, succeeds, and the pending first attempt, i.e. IPv4, is cancelled. r8raTrrN)rr*r+rvrrrer$rrQrrrrr1r2rrxs rXtest_otherConnectionsCancelledzEHostnameEndpointsFasterConnectionTests.test_otherConnectionsCancelledq s!((* !)!2!2  MM ! !- 0 gnn% c"6:mm6N6Nq6Q3tWg{%%tTl3  ]+  $--**1-a0;;MM  T]]::<=rZN) rlrmrnrorwrvr{r}rr]rZrXrrrr s!  #.>>>B>rZrrc@eZdZdZdZdZdZdZdZdZ dZ d Z y ) SSL4EndpointsTestsz" Tests for SSL Endpoints. c|jS)zD @return: List of calls to L{IReactorSSL.listenSSL} ) sslServersrs rXrPz"SSL4EndpointsTests.expectedServers rMrZc|jS)zE @return: List of calls to L{IReactorSSL.connectSSL} ) sslClientsrs rXrz"SSL4EndpointsTests.expectedClients rMrZc|\}}}}}}|\} } } } } }|j|| |j|| |j|| |j|| |j||y)a Compare host, port, contextFactory, timeout, and bindAddress in C{receivedArgs} to C{expectedArgs}. We ignore the factory because we don't only care what protocol comes out of the C{IStreamClientEndpoint.connect} call. @param receivedArgs: C{tuple} of (C{host}, C{port}, C{factory}, C{contextFactory}, C{timeout}, C{bindAddress}) that was passed to L{IReactorSSL.connectSSL}. @param expectedArgs: C{tuple} of (C{host}, C{port}, C{factory}, C{contextFactory}, C{timeout}, C{bindAddress}) that we expect to have been passed to L{IReactorSSL.connectSSL}. NrT)rWrVr%rrLrWcontextFactoryrXrYrQrZr[expectedContextFactoryr\r]s rXr!z$SSL4EndpointsTests.assertConnectArgs s*            "   |, |, )?@ /2 &9:rZc dddSr`r]rVs rXrAzSSL4EndpointsTests.connectArgs rfrZc dddSrhr]rVs rXr[zSSL4EndpointsTests.listenArgs rorZctdd\|_|_tdd\|_|_t |j|jd|_t d|_y ) zF Set up client and server SSL contexts for use later. zServer Test Certificateserver)OCNzClient Test CertificateclientF) privateKey certificaterequireCertificate)rN)rMsKeysCertcKeycCertrGserverSSLContextclientSSLContextrVs rXrwzSSL4EndpointsTests.setUp sc!0'H!  4:!0'H!  4:!3yydjjU! !3e LrZc tddd}tj||j|jfi||j||j|j dd|j ddf|fS)a Create an L{SSL4ServerEndpoint} and return the tools to verify its behaviour. @param factory: The thing that we expect to be passed to our L{IStreamServerEndpoint.listen} implementation. @param reactor: A fake L{IReactorSSL} that L{SSL4ServerEndpoint} can call L{IReactorSSL.listenSSL} on. @param listenArgs: Optional dictionary of arguments to L{IReactorSSL.listenSSL}. rqrrrrmrsrnrN)rrSSL4ServerEndpointrLrrurvs rXrGz'SSL4EndpointsTests.createServerEndpoint seY2  ( (t'<'< @J  %%y"-{B/     rZc tddd}tj||j|j|j fi||j|j||j |j dd|j ddf|fS)a Create an L{SSL4ClientEndpoint} and return the values needed to verify its behaviour. @param reactor: A fake L{IReactorSSL} that L{SSL4ClientEndpoint} can call L{IReactorSSL.connectSSL} on. @param clientFactory: The thing that we expect to be passed to our L{IStreamClientEndpoint.connect} implementation. @param connectArgs: Optional dictionary of arguments to L{IReactorSSL.connectSSL} rqrdrTrXrxrYN)rrSSL4ClientEndpointrrLrrurzs rXr z'SSL4EndpointsTests.createClientEndpoint se["5  ( (  %%       %% 2. t4   !  rZN) rlrmrnrorPrr!rAr[rwrGr r]rZrXrr s2" " $;LD : M 8 rZrc@eZdZdZdZdZdZdZdZdZ dZ d Z y ) UNIXEndpointsTestsz) Tests for UnixSocket Endpoints. c0|j|ddS)z Override L{EndpointTestCaseMixin.retrieveConnectedFactory} to account for different index of 'factory' in C{connectUNIX} args. rrarrs rXrz+UNIXEndpointsTests.retrieveConnectedFactory$ s ##G,Q/22rZc|jS)zF @return: List of calls to L{IReactorUNIX.listenUNIX} ) unixServersrs rXrPz"UNIXEndpointsTests.expectedServers+ """rZc|jS)zG @return: List of calls to L{IReactorUNIX.connectUNIX} ) unixClientsrs rXrz"UNIXEndpointsTests.expectedClients1 rrZc|\}}}}|\}}} } |j|||j|| |j|| y)a Compare path, timeout, checkPID in C{receivedArgs} to C{expectedArgs}. We ignore the factory because we don't only care what protocol comes out of the C{IStreamClientEndpoint.connect} call. @param receivedArgs: C{tuple} of (C{path}, C{timeout}, C{checkPID}) that was passed to L{IReactorUNIX.connectUNIX}. @param expectedArgs: C{tuple} of (C{path}, C{timeout}, C{checkPID}) that we expect to have been passed to L{IReactorUNIX.connectUNIX}. NrT) rWrVr%rrWrXcheckPID expectedPathr[r\expectedCheckPIDs rXr!z$UNIXEndpointsTests.assertConnectArgs7 s\5A1~w       |, /2 #34rZc dddS)rarbra)rXrr]rVs rXrAzUNIXEndpointsTests.connectArgsP s1--rZcddddS)rirjira)rmmodewantPIDr]rVs rXr[zUNIXEndpointsTests.listenArgsV s!<"}. zunix:/var/run/finger:mode=0660rrirsTrNrrVs rX test_modeUNIXzParserTests.test_modeUNIX sC  JJ7 @"DFF+2$?  rZc |j|jd|jdd|jfddddfy) zM C{wantPID} can be set to false by included C{"lockfile=0"}. zunix:/var/run/finger:lockfile=0rrrrsFrNrrVs rXtest_wantPIDUNIXzParserTests.test_wantPIDUNIX sC  JJ8$&& A"DFF+2%@  rZc |j|jd|jdd|jfddddfy) zf Backslash can be used to escape colons and backslashes in port descriptions. zunix:foo\:bar\=baz\:qux\\rzfoo:bar=baz:qux\rrsTrNrrVs rX test_escapezParserTests.test_escape sC  JJA466 J&/2$?  rZcN|jtjddy)z L{endpoints.quoteStringArgument} should quote backslashes and colons for interpolation into L{endpoints.serverFromString} and L{endpoints.clientFactory} arguments. zsome : stuff \zsome \: stuff \\N)rrquoteStringArgumentrVs rXtest_quoteStringArgumentz$ParserTests.test_quoteStringArgument s$   ) )*= > ' rZc |j|jd|jdd|jfddddfy) z In strports descriptions, '=' in a parameter value does not need to be quoted; it will simply be parsed as part of the value. zunix:address=foo=barrzfoo=barrrsTrNrrVs rXtest_impliedEscapezParserTests.test_impliedEscape sC  JJ. 7DFF#2$?  rZc\|jt|jd|jy)ze L{strports.parse} raises C{ValueError} when given an unknown endpoint type. zbogus-type:nothingN)rrrrrVs rXtest_unknownTypezParserTests.test_unknownType s! *djj2FOrZN)rlrmrnrorrrrrrrrrrrrr]rZrXrr sF A0                PrZrceZdZdZdZeeedZeeedZ dZ eeedZ eeedZ eeedZ eeed Zd Zd Zd Zy )ServerStringTestszC Tests for L{twisted.internet.endpoints.serverFromString}. cdt}tj|d}|j|tj|j |j ||j|jd|j|jd|j|jdy)z When passed a TCP strports description, L{endpoints.serverFromString} returns a L{TCP4ServerEndpoint} instance initialized with the values from the string. z&tcp:1234:backlog=12:interface=10.0.0.1r 10.0.0.1N) rrserverFromStringr<rtrprr_port_backlog _interface)rWrrs rXtest_tcpzServerStringTests.test_tcp s (++ =  fi&B&BC foow/ t, "- **J7rZc6t}tj|dtdtd}|j |tj |j |j||j|jd|j|jd|j|jd|j|jjt|jj}|j |t y)z When passed an SSL strports description, L{endpoints.serverFromString} returns a L{SSL4ServerEndpoint} instance initialized with the values from the string. ssl:1234:backlog=12:privateKey= :certKey=,:sslmethod=TLSv1_2_METHOD:interface=10.0.0.1rrrN)rrrescapedPEMPathNamer<rrprrrrr_sslContextFactorymethodrE getContext ContextTyperWrrctxs rXtest_sslzServerStringTests.test_ssl% s(++ "#5 7  fi&B&BC foow/ t, "- **J7 2299>J''224 c;/rZc~t}tj|dt}|j |tj |j |j||j|jd|j|jd|j|jd|j|jjt|j|jj t"z|jj%}|j |t&y)z An SSL string endpoint description with minimal arguments returns a properly initialized L{SSL4ServerEndpoint} instance. zssl:4321:privateKey=rsrNN)rrrrr<rrprrrrrrrrBr_optionsrDrrrs rXtest_sslWithDefaultsz&ServerStringTests.test_sslWithDefaults< s (++ +,>+?@  fi&B&BC foow/ t, "- **B/ 2299:F   % % . . < ''224 c;/rZz(ssl:1234:privateKey=%s:extraCertChain=%sc tjt|jtt fz}dDcgc]<}t jtjd|fzj>}}|j}|j|jdjd|djd|j|jdjd|djdycc}w)zf Specifying a chain file loads the contained certificates in the right order. )rarz thing%d.pemrsha1raN)rrrSSL_CHAIN_TEMPLATErescapedChainPathNamerFloadPEMcasPathchild getContentrrextraCertChaindigest)rWrnexpectedChainCertscfs rXtest_sslChainLoadsz$ServerStringTests.test_sslChainLoadsV s ++ H  # #"$       mqd.B C N N P Q   & &    a ' ' /1CA1F1M1Mf1U     a ' ' /1CA1F1M1Mf1U  sAD c t|j}|jj|j t 5}t jt|jtt j|jfzddd|jtjd|jdy#1swY=xYw)zy If C{extraCertChain} is passed, it has to contain at least one valid certificate in PEM format. NzSpecified chain file 'z7' doesn't contain any valid certificates in PEM format.)r;rcreatecloserrrrrrrrrrrrX)rWfpcaughts rX test_sslChainFileMustContainCertz2ServerStringTests.test_sslChainFileMustContainCerts s dkkm $   z * f  & &''&11"'':      ! ww     s ACC!c0d}t}tj|djtt|}|j }|j |jt|jt||jjy)z If C{dhParameters} are specified, they are passed as L{DiffieHellmanParameters} into L{CertificateOptions}. someFilez1ssl:4321:privateKey={}:certKey={}:dhParameters={}N) rrrformatrrr< dhParametersrHrr;_dhFile)rWfileNamerrrs rXtest_sslDHparametersz&ServerStringTests.test_sslDHparameters sz (++  ? F F"$6    & & boo/FG (+R__-D-DErZc6t}tj|dtdtd}|j |tj |j|j||j|jd|j|jd|j|jd|j|jjt|jj!}|j |t"y)zq Lack of a trailing newline in key and cert .pem files should not generate an exception. rrrrrrN)rrr&escapedNoTrailingNewlineKeyPEMPathName'escapedNoTrailingNewlineCertPEMPathNamer<rrprrrrrrrrErrrs rXtest_sslNoTrailingNewlinePemz.ServerStringTests.test_sslNoTrailingNewlinePem s (++ 77    fi&B&BC foow/ t, "- **J7 2299>J''224 c;/rZct}tj|d}|j|tj|j |j ||j|jd|j|jd|j|jd|j|jy)z When passed a UNIX strports description, L{endpoint.serverFromString} returns a L{UNIXServerEndpoint} instance initialized with the values from the string. z0unix:/var/foo/bar:backlog=7:mode=0123:lockfile=1 /var/foo/barSN) rrrr<rrprr_addressr_moder_wantPID)rWrrvs rX test_unixzServerStringTests.test_unix s (-- G  h (D(DE h''1 **N; **A. / ))*rZc|jttjdd}|j t |dy)zq L{endpoints.serverFromString} raises C{ValueError} when given an unknown endpoint type. Nftl:andromeda/carcosa/hali/2387Unknown endpoint type: 'ftl')rrrrrrrWr/s rXrz"ServerStringTests.test_unknownType = !!   & &  -   U%CDrZc*t|t}tj|d}ddlm}|j |j||j|j|ddf|j|jtddy ) z L{endpoints.serverFromString} looks up plugins of type L{IStreamServerEndpoint} and constructs endpoints from them. zfake:hello:world:yes=no:up=downr)fakehelloworldnodown)yesupN) addFakePluginrrrtwisted.plugins.fakeendpointrrpparserrrrdict)rW notAReactor fakeEndpointrs rXtest_typeFromPluginz%ServerStringTests.test_typeFromPlugin s| dh  11 :  6 l))40 **['7,KL ,,dt.GHrZN)rlrmrnrorr skipSSL skipSSLReasonrrrrrr r rrr)r]rZrXrr s8  G]#0$0, G]#0$0.D G]# $ 8 G]# $ > G]#F$F" G]#0$00+" EIrZrcddljjttj fd}|j |t|j}|jttjj|j|j|tj j!|j"y)z For the duration of C{testCase}, add a fake plugin to twisted.plugins which contains some sample endpoint parsers. rNcjjjjtjddyrd)modulesclearupdater__path__) savedModulessavedPluginPathsyssrXcleanupzaddFakePlugin..cleanup s5  <(-rZ)r4r.rlistrr1r3r;rcreateDirectoryr<rlfilePathsiblingcopyTorrer)testCase dropinSourcer5rr2r3r4s @@@rXr#r# s ;;##%L7++,O.   (//# $B h  ((6==bhh|>TU BGG$rZcReZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zy )ClientStringTestszC Tests for L{twisted.internet.endpoints.clientFromString}. ct}tj|d}|j|tj|j |j ||j|jd|j|jd|j|jd|j|jdy)z When passed a TCP strports description, L{endpoints.clientFromString} returns a L{TCP4ClientEndpoint} instance initialized with the values from the string. z=tcp:host=example.com:port=1234:timeout=7:bindAddress=10.0.0.2rrrz10.0.0.2rN rrclientFromStringr<ryrprr_hostr_timeout _bindAddressrWrrs rXrzClientStringTests.test_tcp s (++ T  fi&B&BC foow/ }5 t, !, ,,o>rZct}tj|d}|j|tj|j |j ||j|jd|j|jd|j|jd|j|jdy)z When passed a TCP strports description using positional arguments, L{endpoints.clientFromString} returns a L{TCP4ClientEndpoint} instance initialized with the values from the string. z3tcp:example.com:1234:timeout=7:bindAddress=10.0.0.2rrrr@NrArFs rXtest_tcpPositionalArgsz(ClientStringTests.test_tcpPositionalArgs s (++ J  fi&B&BC foow/ }5 t, !, ,,o>rZct}tj|d}|j|jd|j|j dy)z When passed a TCP strports description specifying host as a positional argument, L{endpoints.clientFromString} returns a L{TCP4ClientEndpoint} instance initialized with the values from the string. z8tcp:example.com:port=1234:timeout=7:bindAddress=10.0.0.2rrNrrrBrrCrrFs rXtest_tcpHostPositionalArgz+ClientStringTests.test_tcpHostPositionalArg. sK (++ O  }5 t,rZct}tj|d}|j|jd|j|j dy)z When passed a TCP strports description specifying port as a positional argument, L{endpoints.clientFromString} returns a L{TCP4ClientEndpoint} instance initialized with the values from the string. z8tcp:host=example.com:1234:timeout=7:bindAddress=10.0.0.2rrNrJrFs rXtest_tcpPortPositionalArgz+ClientStringTests.test_tcpPortPositionalArg< sK (++ O  }5 t,rZct}tj|d}|j|jd|j |j y)z{ A TCP strports description may omit I{timeout} or I{bindAddress} to allow the default to be used. ztcp:host=example.com:port=1234rxN)rrrBrrDrrErFs rXtest_tcpDefaultsz"ClientStringTests.test_tcpDefaultsI sF (++G5UV "- &--.rZcbt}tj|d}|j|tj|j |j ||j|jd|j|jd|j|jy)z When passed a UNIX strports description, L{endpoints.clientFromString} returns a L{UNIXClientEndpoint} instance initialized with the values from the string. z+unix:path=/var/foo/bar:lockfile=1:timeout=9r N rrrBr<rrprrrrDr _checkPIDrFs rXrzClientStringTests.test_unixS s (++ B  fi&B&BC foow/ ~6 !, (()rZctjtd}|j|jd|j |j y)zz A UNIX strports description may omit I{lockfile} or I{timeout} to allow the defaults to be used. zunix:path=/var/foo/barrxN)rrBrrrDrrS)rWrs rXtest_unixDefaultsz#ClientStringTests.test_unixDefaultsc sA ++FH6NO "- ))*rZcbt}tj|d}|j|tj|j |j ||j|jd|j|jd|j|jy)z When passed a UNIX strports description specifying path as a positional argument, L{endpoints.clientFromString} returns a L{UNIXClientEndpoint} instance initialized with the values from the string. z&unix:/var/foo/bar:lockfile=1:timeout=9rrQNrRrFs rXtest_unixPathPositionalArgz,ClientStringTests.test_unixPathPositionalArgl s (++ =  fi&B&BC foow/ ~6 !, (()rZc*t|t}tj|d}ddlm}|j |j||j|j|ddf|j|jtddy ) z L{endpoints.clientFromString} looks up plugins of type L{IStreamClientEndpoint} and constructs endpoints from them. crfake:alpha:beta:cee=dee:num=1rfakeClientWithReactoralphabetadee1ceenumN) r#rrrBr$r[rpr%rrrr&)rWr'clientEndpointr[s rXr)z%ClientStringTests.test_typeFromPlugin| s~ dh "33 :  G n++-BC ,,{GV.LM ..C0HIrZc|jttjdd}|j t |dy)zq L{endpoints.clientFromString} raises C{ValueError} when given an unknown endpoint type. Nrr)rrrrBrrrs rXrz"ClientStringTests.test_unknownType rrZc t|t}tj|d}ddlm}|j |j|j|jf||ddftddfy ) z L{endpoints.clientFromString} will pass a reactor to plugins implementing the L{IStreamClientEndpointStringParserWithReactor} interface. rYrrZr\r]r^r_r`N) r#rrrBr$r[rr%rrr&)rWrrcr[s rXtest_stringParserWithReactorz.ClientStringTests.test_stringParserWithReactor su d("33 6  G   " "N$7$79N9N O%'6*C(  rZN)rlrmrnrorrHrKrMrOrrUrWr)rrfr]rZrXr>r> s@?"?" - -/* +* J E rZr>c.eZdZdZdZdZdZdZdZy)SSLClientStringTestszU Tests for L{twisted.internet.endpoints.clientFromString} which require SSL. c  t}tj|dtdtdt}|j |tj |j|j||j|jd|j|jd|j|jd|j|jd|j}|j |t|j|j t"|j%|j&t(z|j+}|j |t,|jt/|j0t2t5|j0}|j7t9|j:|j|t<t>jAdt>jAd fDcgc]R}|jCjEjGd r#t/jH|jKT}}g G fd d }|jLjO||jtQd DdtQ|dycc}w) When passed an SSL strports description, L{clientFromString} returns a L{SSL4ClientEndpoint} instance initialized with the values from the string. z*ssl:host=example.net:port=4321:privateKey=r+:bindAddress=10.0.0.3:timeout=3:caCertsDir= example.netrrz10.0.0.3r thing1.pem thing2.pemz.pemceZdZfdZy).SSLClientStringTests.test_ssl..ListCtxc*Gfdd}|S)NceZdZfdZy)LSSLClientStringTests.test_ssl..ListCtx.get_cert_store..Storec(j|yrdr)rWcert addedCertss rXadd_certzUSSLClientStringTests.test_ssl..ListCtx.get_cert_store..Store.add_cert s"))$/rZN)rlrmrnrxrwsrXStorert s0rZrzr])rWrzrws rXget_cert_storez=SSLClientStringTests.test_ssl..ListCtx.get_cert_store s00wrZN)rlrmrnr{rysrXListCtxrq s rZr|c32K|]}t|ywrd)rF).0xs rX z0SSLClientStringTests.test_ssl.. s4AQ4sc"|jSrdrrvs rXrz/SSLClientStringTests.test_ssl.. s t{{}rZ)keyc"|jSrdrrs rXrz/SSLClientStringTests.test_ssl.. s 4;;=rZN))rrrBrescapedCAsPathNamer<rrprrrCrrDrErrGrrBrrrDrrrFrtestCertificaterJ_setPrivateKeyrIrtestPrivateCertificaterrbasenamelowerendswithrr trustRoot_addCACertsToContextsorted) rWrr certOptionsr privateCertr expectedCertsr|rws @rXrzSSLClientStringTests.test_ssl s( (++ "#57I K  fi&B&BC foow/ }5 t, !, ,,o>//  k+=> ++Z8  ,,{:;$$& c;/ [%<%<=O()@)@A ""7;+A+A#BC &<=mmL17==3NO zz|!!#,,V4     /      2279=  44:T  =&@ A  ! sAK c t}tj|dtdtdt}|j |tj |j|j||j|jd|j|jd|j|jd|j|jdy) rjz ssl:example.net:4321:privateKey=rrkrlrrrmN)rrrBrrr<rrprrrCrrDrErFs rXtest_sslPositionalArgsz+SSLClientStringTests.test_sslPositionalArgs s (++ "#57I K  fi&B&BC foow/ }5 t, !, ,,o>rZct}tj|d}|j|tj|j |j ||j|jd|j|jd|j}|j|jt|j|j|j|jy)z When passed an SSL strports description without extra arguments, L{clientFromString} returns a L{SSL4ClientEndpoint} instance whose context factory is initialized with default values. zssl:example.net:4321rlrN)rrrBr<rrprrrCrrrrBrrr)rWrrrs rXrz)SSLClientStringTests.test_sslWithDefaults s (++G5KL fi&B&BC foow/ }5 t,//  ++Z8 +112 +001rZcvGddt}tjdj}||_|j t j|jDcgc] }t|c}tjtjdjgycc}w)z If a certificate in the directory is unreadable, L{endpoints._loadCAsFromDir} will ignore that certificate. ceZdZdZy)KSSLClientStringTests.test_unreadableCertificate..UnreadableFilePathctj|}|tjdjk(rt t |S)Nro)r;rrrOSErrorrrfs rXrzVSSLClientStringTests.test_unreadableCertificate..UnreadableFilePath.getContents=**407==6AACC!%.(KrZN)rlrmrnrr]rZrXUnreadableFilePathrs rZrrrnN) r;rrparent clonePathrr_loadCAsFromDir_caCertsrFrr)rWr casPathCloners rXtest_unreadableCertificatez/SSLClientStringTests.test_unreadableCertificates   }}Y/668 !3  %.%>%>|%L%U%U V[^ V  |! ++,$$& c;/rZN) rlrmrnrorrrrrr]rZrXrhrh s!2 h?(2" .0rZrhc:eZdZdZdZdZdZdZdZdZ dZ y ) AdoptedStreamServerEndpointTestszA Tests for adopted socket-based stream server endpoints. cTtj|||}d|_d|_|S)z Create an L{AdoptedStreamServerEndpoint} which may safely be used with an invalid file descriptor. This is convenient for a number of unit tests. cyrdr]rs rXrzPAdoptedStreamServerEndpointTests._createStubbedAdoptedEndpoint..FrrZcyrdr]rs rXrzPAdoptedStreamServerEndpointTests._createStubbedAdoptedEndpoint..GrrZ)rAdoptedStreamServerEndpoint_close_setNonBlocking)rWrfileno addressFamilyrs rX_createStubbedAdoptedEndpointz>AdoptedStreamServerEndpointTests._createStubbedAdoptedEndpoint=s.  1 1'6= Q#+rZcbd}t}|j|||}tddd}||||f|fS)a Create a new L{AdoptedStreamServerEndpoint} for use by a test. @return: A three-tuple: - The endpoint - A tuple of the arguments expected to be passed to the underlying reactor method - An IAddress object which will match the result of L{IListeningPort.getHost} on the port returned by the endpoint. rrqrrr)rrr)rWrrrrrvrs rXrGz5AdoptedStreamServerEndpointTests.createServerEndpointJsD 55gv}UeY56=':GDDrZc|jS)z @return: The ports which were actually adopted by C{reactor} via calls to its L{IReactorSocket.adoptStreamPort} implementation. ) adoptedPortsrs rXrPz0AdoptedStreamServerEndpointTests.expectedServers\s ###rZciS)zx @return: A C{dict} of additional keyword arguments to pass to the C{createServerEndpoint}. r]rVs rXr[z+AdoptedStreamServerEndpointTests.listenArgscs  rZctjdt}|jt j |jt t j}fd}|j||S)z L{AdoptedStreamServerEndpoint.listen} can only be used once. The file descriptor given is closed after the first use, and subsequent calls to C{listen} return a L{Deferred} that fails with L{AlreadyListened}. cPjdtjyr`)rr r)rrrWs rX listenFailedzEAdoptedStreamServerEndpointTests.test_singleUse..listenFailedus   QG$8$8 9 :rZ) r rrrOrrrAlreadyListenedr)rWrvrrrs` @rXtest_singleUsez/AdoptedStreamServerEndpointTests.test_singleUsejsi  /55gr7K!   xvx8%:O:O P ; l#rZct}j|dt}gfd}||_|j t }fd}|j ||S)zv L{AdoptedStreamServerEndpoint.listen} sets the file description given to it to non-blocking. rc,jd|fy)NsetNonBlockingr)reventss rXrzTAdoptedStreamServerEndpointTests.test_descriptionNonBlocking..setNonBlockings MM+V4 5rZc,jdgy)N)rrrTrrrWs rXlistenedzNAdoptedStreamServerEndpointTests.test_descriptionNonBlocking..listeneds   45v >rZ)r rrrrOrr)rWrrvrrrrs` @rXtest_descriptionNonBlockingz.closes! MM7FC0D0D,EF GrZc,jdgy)N)rrrarTrs rXrzHAdoptedStreamServerEndpointTests.test_descriptorClosed..listeneds   ./ 8rZ)r rrrrOrr)rWrvrrrrrs` @@rXtest_descriptorClosedz6AdoptedStreamServerEndpointTests.test_descriptorCloseds\  /55gr7K H  OOFH % 9 hrZN) rlrmrnrorrGrPr[rrrr]rZrXrr8s+ E$$",rZrceZdZdZej ZdZdZde de ddfdZ de de ddfd Z dd Z dd Zdd Zdd ZddZddZddZy)SystemdEndpointPluginTestsz Unit tests for the systemd stream server endpoint and endpoint string description parser. @see: U{systemd} ctttj}|D]}t ||j sy|j d|y)z L{endpoints._SystemdParser} is found as a plugin for L{interfaces.IStreamServerEndpointStringParser} interface. zDid not find systemd parser in Nr6r4r!IStreamServerEndpointStringParserr _parserClassrrWparsersrs rXtest_pluginDiscoveryz/SystemdEndpointPluginTests.test_pluginDiscoverysS z*"N"NOP EA!T../ E II7{C DrZcv|j}|jttj|y)zx L{endpoints._SystemdParser} instances provide L{interfaces.IStreamServerEndpointStringParser}. NrrrrrrWr%s rXrz)SystemdEndpointPluginTests.test_interface. ""$  EEv N rZraddressFamilyStringreturnNcVt}gd}gd}d}|j}t|||_|j ||t |}|j |j||j|j||j|j||y)a  Helper for tests for L{endpoints._SystemdParser.parseStreamServer} for different address families with a descriptor identified by index. Handling of the address family given will be verify. If there is a problem a test-failing exception will be raised. @param addressFamily: An address family constant, like L{socket.AF_INET}. @param addressFamilyString: A string which should be recognized by the parser as representing C{addressFamily}. rrrrQz5.socketz6.socketfooz8.socketz9.socketr)domainindexN) rrr= _sddaemonparseStreamServerrrprrrr) rWrrr descriptorsnamesrr%rs rX_parseIndexStreamServerTestz6SystemdEndpointPluginTests._parseIndexStreamServerTests (% G""$$[%8)) /s5z*  fnng. --}=  E(:;rZcbt}gd}gd}d}|j}t|||_|j |||}|j |j ||j|j||j|j||j|y)ze Like L{_parseIndexStreamServerTest} but for descriptors identified by name. rrr)rrN) rrr=rrrprrrrr) rWrrrrrrr%rs rX_parseNameStreamServerTestz5SystemdEndpointPluginTests._parseNameStreamServerTests(% G""$$[%8)) &*  fnng. --}=  EKK4E(FGrZc0|jtdyzC IPv4 can be specified using the string C{"INET"}. INETN)rrrVs rXtest_parseIndexStreamServerINETz:SystemdEndpointPluginTests.test_parseIndexStreamServerINETs ((&9rZc0|jtdyzD IPv6 can be specified using the string C{"INET6"}. INET6N)rrrVs rX test_parseIndexStreamServerINET6z;SystemdEndpointPluginTests.test_parseIndexStreamServerINET6s ((7;rZcz ddlm}|j|dy#t$rt j dwxYwzS A UNIX domain socket can be specified using the string C{"UNIX"}. r)AF_UNIXrzPlatform lacks AF_UNIX supportN)socketrr ImportErrorr@SkipTestrWrs rXtest_parseIndexStreamServerUNIXz:SystemdEndpointPluginTests.test_parseIndexStreamServerUNIX sA > &  , ,Wf = F##$DE E F:c0|jtdyr)rrrVs rXtest_parseNameStreamServerINETz9SystemdEndpointPluginTests.test_parseNameStreamServerINETs ''8rZc0|jtdyr)rrrVs rXtest_parseNameStreamServerINET6z:SystemdEndpointPluginTests.test_parseNameStreamServerINET6s ''':rZcz ddlm}|j|dy#t$rt j dwxYwr)rrrrr@rrs rXtest_parseNameStreamServerUNIXz9SystemdEndpointPluginTests.test_parseNameStreamServerUNIX#sA = &  + +GV < F##$DE E Frc|j}tgd|_|jt5|j t ddddddy#1swYyxYw)zQ The endpoint cannot be defined using both C{index} and C{name}. r]rrr)rrrN)rr=rrrrrrs rX"test_indexAndNameMutuallyExclusivez=SystemdEndpointPluginTests.test_indexAndNameMutuallyExclusive.s_""$$R,   z * R  $ $WV15 $ Q R R Rs AA#)rN)rlrmrnror_SystemdParserrrrrrrrrrrrrrrr]rZrXrrs++L E <*H*HADH H0: < >9 ; =RrZrc:eZdZdZej ZdZdZdZ y)TCP6ServerEndpointPluginTestsz[ Unit tests for the TCP IPv6 stream server endpoint string description parser. ctttj}|D]}t ||j sy|j d|y)z L{endpoints._TCP6ServerParser} is found as a plugin for L{interfaces.IStreamServerEndpointStringParser} interface. z*Did not find TCP6ServerEndpoint parser in Nrrs rXrz2TCP6ServerEndpointPluginTests.test_pluginDiscovery@S z*"N"NOP PA!T../ P IIB7+N OrZcv|j}|jttj|y)z{ L{endpoints._TCP6ServerParser} instances provide L{interfaces.IStreamServerEndpointStringParser}. Nrrs rXrz,TCP6ServerEndpointPluginTests.test_interfaceLrrZchtjtd}|j|tj|j|j t|j |jd|j |jd|j |jdy)z L{serverFromString} returns a L{TCP6ServerEndpoint} instance with a 'tcp6' endpoint string description. z$tcp6:8080:backlog=12:interface=\:\:1irrN) rrr r<rrrrrrrs rXtest_stringDescriptionz4TCP6ServerEndpointPluginTests.test_stringDescriptionVs  ' ' OD  b)">">? bkk=9 4( b) .rZN) rlrmrnror_TCP6ServerParserrrrrr]rZrXrr8s$ ..L P  /rZrc:eZdZdZej ZdZdZdZ y)StandardIOEndpointPluginTestszM Unit tests for the Standard I/O endpoint string description parser. ctttj}|D]}t ||j sy|j d|y)z L{endpoints._StandardIOParser} is found as a plugin for L{interfaces.IStreamServerEndpointStringParser} interface. z*Did not find StandardIOEndpoint parser in Nrrs rXrz2StandardIOEndpointPluginTests.test_pluginDiscoverylrrZcv|j}|jttj|y)z{ L{endpoints._StandardIOParser} instances provide L{interfaces.IStreamServerEndpointStringParser}. Nrrs rXrz,StandardIOEndpointPluginTests.test_interfacexrrZctjtd}|j|tj|j|j ty)z L{serverFromString} returns a L{StandardIOEndpoint} instance with a 'stdio' endpoint string description. zstdio:N)rrr r<rorrs rXrz4StandardIOEndpointPluginTests.test_stringDescriptionsB  ' '  B b)">">? bkk=9rZN) rlrmrnror_StandardIOParserrrrrr]rZrXrres$..L P :rZrceZdZdZdZdZy)ConnectProtocolTestsz' Tests for C{connectProtocol}. ct}tj|dd}t}tj|||j t |jd|jddj}|j|tj|j|jd|y)z C{endpoints.connectProtocol} calls the given endpoint's C{connect()} method with a factory that will build the given protocol. rkrrarN)r rryrconnectProtocolrr rQ_wrappedFactoryr<rr*rpr)rWrrv theProtocolrs rX"test_connectProtocolCreatesFactoryz7ConnectProtocolTests.test_connectProtocolCreatesFactorys  ///aHh !!(K8 W//0!4$$Q'*:: gx'7'78 g++D1;?rZctjGfdd}|}|jtj|t y)z~ C{endpoints.connectProtocol} returns the result of calling the given endpoint's C{connect()} method. ceZdZfdZy)OConnectProtocolTests.test_connectProtocolReturnsConnectResult..EndpointcS)zR Return a marker object for use in our assertion. r])rWrrs rXrzWConnectProtocolTests.test_connectProtocolReturnsConnectResult..Endpoint.connects  rZN)rlrmrnr)rsrXEndpointrs rZrN)rrrprrr)rWrrvrs @rX(test_connectProtocolReturnsConnectResultz=ConnectProtocolTests.test_connectProtocolReturnsConnectResultsA !  : fi77&(KLrZN)rlrmrnrorrr]rZrXr r s@$MrZr c2eZdZdZfdZfdZdZxZS)UppercaseWrapperProtocolzL A wrapper protocol which uppercases all strings passed through it. c@t||jy)z Uppercase a string passed in from the transport. @param data: The string to uppercase. @type data: L{bytes} N)rrgupperrWrSrs rXrgz%UppercaseWrapperProtocol.dataReceiveds TZZ\*rZc@t||jy)z Uppercase a string passed out to the transport. @param data: The string to uppercase. @type data: L{bytes} N)rrrrs rXrzUppercaseWrapperProtocol.writes  djjl#rZc4|D]}|j|y)zy Uppercase a series of strings passed out to the transport. @param seq: An iterable of strings. Nr)rWseqrSs rXrz&UppercaseWrapperProtocol.writeSequences  D JJt  rZ)rlrmrnrorgrrrrs@rXrrs+$rZrceZdZdZeZy)UppercaseWrapperFactoryzK A wrapper factory which uppercases all strings passed through it. N)rlrmrnrorrr]rZrXr"r"s(HrZr"ceZdZdZdZdZy)NetstringTrackerz A netstring receiver which keeps track of the strings received. @ivar strings: A L{list} of received strings, in order. cg|_yrd)stringsrVs rXrYzNetstringTracker.__init__s  rZc:|jj|y)z Receive a string and append it to C{self.strings}. @param string: The string to be appended to C{self.strings}. N)r&re)rWrs rXstringReceivedzNetstringTracker.stringReceiveds F#rZN)rlrmrnrorYr(r]rZrXr$r$s $rZr$ceZdZdZy) FakeErrorz An error which isn't really an error. This is raised in the L{wrapClientTLS} tests in place of a 'real' exception. Nr_r]rZrXr*r*srZr*c4eZdZdZdZdZdZdZdZdZ y) WrapperClientEndpointTestsz. Tests for L{_WrapperClientEndpoint}. ct\|_|_t|_t j |jt|_tjt|_ yrd) r>rv completerrcontextr_WrapperEndpointr"rr*rr$rrVs rXrwz WrapperClientEndpointTests.setUpsM(;(=% t~x  11 MM2  **+;< rZcH|jj|j}|jj }|j |}|j jjd|j|j|jdgy)z Any modifications performed by the underlying L{ProtocolWrapper} propagate through to the wrapped L{Protocol}. s5:hello,sHELLON) rrrr. succeedOncersrrrflushrr&rW connectingpumpr#s rXtest_wrappingBehaviorz0WrapperClientEndpointTests.test_wrappingBehaviorsu \\))$,,7 ~~))+$$Z0 ##K0   3rZc|jj|j}|jj }|j |}|j d|j|jjdy)z Methods defined on the wrapped L{Protocol} are accessible from the L{Protocol} returned from C{connect}'s L{Deferred}. sspams4:SPAM,N) rrrr.r2rs sendStringrclientIO getOutBufferr4s rXtest_methodsAvailablez0WrapperClientEndpointTests.test_methodsAvailablesi \\))$,,7 ~~))+$$Z0 ! 335zBrZc|jj|j}|j||jj t |j|t y)zS Connection failures propagate upward to C{connect}'s L{Deferred}. N)rrrassertNoResultr.failOncer*rrWrs rXtest_connectionFailurez1WrapperClientEndpointTests.test_connectionFailuresN LL  . A  , Q *rZc|jj|j}|j||j |j |t y)zM Cancellation propagates upward to C{connect}'s L{Deferred}. N)rrrr>r:rr#r@s rXtest_connectionCancellationz6WrapperClientEndpointTests.test_connectionCancellation'sD LL  . A   Q 89rZc|jj|j}|jj }|j |}|j |jj|jy)z| The transport of the wrapped L{Protocol}'s transport is the transport passed to C{makeConnection}. N) rrrr.r2rsrprr:r4s rX*test_transportOfTransportOfWrappedProtocolzEWrapperClientEndpointTests.test_transportOfTransportOfWrappedProtocol0sZ \\))$,,7 ~~))+$$Z0 eoo//?rZN) rlrmrnrorwr7r<rArCrEr]rZrXr,r,s'= 4 C+:@rZr,c8|jdjS)a, Given a L{MemoryReactor} and the result of calling L{wrapClientTLS}, extract the L{IOpenSSLClientConnectionCreator} associated with it. Implementation presently uses private attributes but could (and should) be refactored to just call C{.connect()} on the endpoint, when L{HostnameEndpoint} starts directing its C{getaddrinfo} call through the reactor it is passed somehow rather than via the global threadpool. @param memoryReactor: the reactor attached to the given endpoint. (Presently unused, but included so tests won't need to be modified to honor it.) @param tlsEndpoint: The result of calling L{wrapClientTLS}. @return: the client connection creator associated with the endpoint wrapper. @rtype: L{IOpenSSLClientConnectionCreator} N)_wrapperFactory_connectionCreator)r tlsEndpoints rXconnectionCreatorFromEndpointrJ;s(  & &t , ? ??rZc(eZdZdZdZdZdZdZy)WrapClientTLSParserTestsz0 Tests for L{_TLSClientEndpointParser}. ct}tj|td}|j}|j |j ||j|jd|j|jd|j|jd|j|jtdy)zm A L{HostnameEndpoint} is constructed from parameters passed to L{clientFromString}. z4tls:example.com:443:timeout=10:bindAddress=127.0.0.1rrdrbrkN) rrrBr8_wrappedEndpointrprrrLrrDrE)rWrrvhostnameEndpoints rX!test_hostnameEndpointConstructionz:WrapClientTLSParserTests.test_hostnameEndpointConstructionXs (--  O P $44 &//9 )44nE )//5 )22B7 )66 [8QRrZct}tj|d}|j|jj dt ||}|j|jdy)z The hostname passed to L{clientFromString} is treated as utf-8 bytes; it is then encoded as IDNA when it is passed along to L{HostnameEndpoint}, and passed as unicode to L{optionsForClientTLS}. stls:éxample.example.com:443sxn--xample-9ua.example.comuéxample.example.comN)rrrBrrNrLrJ _hostname)rWrrvconnectionCreators rXtest_utf8Encodingz*WrapClientTLSParserTests.test_utf8Encodingisj (-- :    % % 0 02O :'8L *446NOrZc t}tjt|dgdj t t tj tjjjd}|jtjt}|jj!\}}}}}|j#d|j%|Jt'j(tj+} t-| j.j0| j0t3j(t4j+j0g| } tt7| dtjfdj#dt9fd fd \} } } j:j=d |j?|}|j:j=d | jA|jCj:jD|jC|j:jD|jCj:jF|jC|j:jFt3jHj:}|jK|t3j(tj+y) z When passed a string endpoint description beginning with C{tls:}, L{clientFromString} returns a client endpoint initialized with the values from the string. rkz=tls:localhost:4321:privateKey={}:certificate={}:trustRoots={}asciiN)rrrrFcSrdr]) plainServersrXrz3WrapClientTLSParserTests.test_tls..s{rZ)isClientwrappedFactorycSrdr])serverProtocolsrXrz3WrapClientTLSParserTests.test_tls..NrZcSrdr])clientProtocolsrXrz3WrapClientTLSParserTests.test_tls..r]rZshello s hi you too )&r rrBrrrrpemPathrrencoderr*rr+rQpoprr>rJrrrGroriginalrF chainPathrLr?rrrsr3r disconnecting disconnectedpeerFromTransportr)rWrrvrrrLrrXrY serverCert serverOptionssProtocProtor6 plainClientpeerCertificater_rXr\s @@@rXtest_tlsz!WrapClientTLSParserTests.test_tlsys^$ / -- )'K= A K R R""--gnn.>.C.CD fWo     W00: ;4;4F4F4J4J4L1dGWk ..t4 A)))'//0B0B0DE *!,,55"++'// 0D0D0FGPPQ  j , "../BC  -   8 " "  ##L1**1- ##$56  ..<<= ..<<= ..;;< ..;;<%77 8M8MN +*=*=g>P>P>R*STrZct}tj|d}t||}|j |j d|j |j jdy)z When passed a C{tls:} strports description without extra arguments, L{clientFromString} returns a client endpoint whose context factory is initialized with default values. stls:example.com:443rrN)rrrBrJrrRrNrL)rWrrvcreators rXtest_tlsWithDefaultsz-WrapClientTLSParserTests.test_tlsWithDefaultss\ (--g7MN/B **M: 22==~NrZN)rlrmrnrorPrTrnrqr]rZrXrLrLRs S"P ?UB OrZrLc N |j}|j}|D] }||vst dj |i}|j||j|t||}|||j<|S#t$r|j}|j}YwxYw)a Create a copy of the given function with the given globals substituted. The globals must already exist in the function's existing global scope. @param function: any function object. @type function: L{types.FunctionType} @param newGlobals: each keyword argument should be a global to set in the new function's returned scope. @type newGlobals: L{dict} @return: a new function, like C{function}, but with new global scope. z$PTU -s>/BCrZN)rlrmrnrorr]rZrXrrs  DrZr)r]N)zfakeendpoint.py)roerrnorrrrrrrr typesr unicodedatar r@r zope.interfacer rrzope.interface.interfacerzope.interface.verifyrrtwistedrrrrrrrrrrtwisted.internet.abstractrtwisted.internet.addressrrrr r!twisted.internet.endpointsr"twisted.internet.errorr#twisted.internet.interfacesr$r%r&r'r(twisted.internet.protocolr)r*r+twisted.internet.stdior,twisted.internet.taskr-twisted.internet.testingr.r r/r0r1twisted.loggerr2r3twisted.pluginr4twisted.protocolsr5r6twisted.pythonr7twisted.python.compatr8twisted.python.componentsr9twisted.python.failurer:twisted.python.filepathr;twisted.python.modulesr<twisted.python.systemdr=twisted.test.iosimr>r? twisted.trialr8r9r`noTrailingNewlineKeyPemPathnoTrailingNewlineCertPemPathrlrrrdrrrr r rr OpenSSL.SSLrBrCrrDrEtwisted.internet.sslrFrGrHrIrJtwisted.protocols.tlsrLtwisted.test.test_sslverifyrMrrrrr*r+rrrrPrrqrr{rrrrTestCaserrrEr^rarhrmr}IProcessTransportrIReactorProcessrrrr'rHr}rrrSynchronousTestCaserrrrr$r*r?rGr\rlrrrrrrr#r>rhrrrrr ProtocolWrapperrWrappingFactoryr"NetstringReceiverr$rr*r,rJrLr~rr]rZrXrs WW!<<3;   4=;GF.' <%-.7*,,,L" N # , , 4 4\ B'7@@HH! )8AAII"  H  & & . .z : MM+ & 2Y227<<@)F)F)F$$*&+H)*G*G %%+'3Y227<<@4y44Y^^D:;)k))'*<*<*>?O7/778J8J8LMGM ,8,0 Z . ./ 00 Z / /04414" Z * *+*L*,*,--@>8,,@>FHAHAVM:M:`79T %g%$"&(">">E>PL(2C2CL:LC*ELC^1 '):):1 h1 '):):1 hE9$?ARARE9Ps9$?ARARs9lE; < <E;PC  < <C L/x'8'8/&>X->->>DM .0A0AM  M `n .0A0An b}P(##}P@^I))^IB%,g ))g TC08,,C0 C0Lm'BHDUDUm`MR!2!2MR`*/H$5$5*/Z$:H$5$5$:N&M8,,&MRx77B(h66($u..$& >@!2!2>@B@.qOx00qO qOh!HD**DuCGFMsA*\11] 6 ]]