Ϫfͦ dZddlZddlZddlZddlZddlZddlmZddlm Z m Z m Z m Z m Z mZmZddlmZddlmZmZddlmZmZddlZddlmZmZdd lmZmZmZm Z m!Z!m"Z"dd l#m$Z$m%Z%dd l&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/dd l0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;dd lZ>m?Z?ddl@mAZAmBZBmCZCmDZDmEZEmFZFmGZGddlHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQddlRmSZSmTZTmUZUddlVmWZWmXZXddlYmZZZddl[m\Z\ddl]m^Z^ddl_m`Z`ddlambZbmcZcmdZdmeZeddlfmgZgmhZhmiZi ddljmkZkddllmmZmdZndZp ej ejejZpepjddZtdZuepepje`jrddlzm{Z{e{jZ}dZ~n dd lzmZejZ}dZ~d"Zd#ZGd$d%ZGd&d'eiZGd(d)e>Zee6Gd*d+Zee6eGd,d-eiZGd.d/eiZGd0d1eLZGd2d3eZee:Gd4d5ZGd6d7eSeKeOZGd8d9eZeeteuGd:d;eZGd<d=eSZGd>d?eZeeteuGd@dAeZdBZGdCdDeZeeejdEGdFdGZee~dHGdIdJehZdKZee~dHGdLdMehZGdNdOeMZGdPdQZGdRdSeZGdTdUeZGdVdWZGdXdYeSeeeZGdZd[eSeeeZGd\d]e>Zd^Zd_Zd`ZGdadbeSZGdcddZGdedfZGdgdheeeSZGdidjeeeSZejSejUejSejUejSejUejSejUejSejUejSejUejSejUejSejUejSejUGdkdleJZGdmdneJZGdodpeJZGdqdreZGdsdteJZGdudveJZGdwdxeJZGdydzeZGd{d|eZGd}d~eZGddeZGddeJZGddeJZGddeZGddeZGddeZGddeZGddZGddeSeZejSejUeeteuGddeiZGddehZee~dHGddehZGddehZy#eo$rdZnYwxYw#ev$rZwdZtdewZuYdZw[wdZw[wwwxYw#eo$rd!Z}YwxYw)zU Tests for implementations of L{IReactorTCP} and the TCP parts of L{IReactorSocket}. Nwraps)CallableClassVarListMappingOptionalSequenceType)skipIf) Interface implementer) verifyClass verifyObject) IPv4Address IPv6Address)Deferred DeferredListfail gatherResults maybeDeferredsucceed)TCP4ClientEndpointTCP4ServerEndpoint) ConnectBindErrorConnectionAbortedConnectionClosedConnectionDoneConnectionLostConnectionRefusedErrorDNSLookupError NoProtocol UserError) IConnectorIHalfCloseableProtocolILoggingContext IPullProducer IPushProducer IReactorFDSetIReactorSocket IReactorTCP IReactorTimeIResolverSimple ITLSTransport) ClientFactoryProtocol ServerFactory) ConnectionServer _BuffersLogs_FileDescriptorReservation_IFileDescriptorReservation_NullFileDescriptorReservation _resolveIPv6) BrokenContextFactoryConnectableProtocolConnectionTestsMixinEndpointCreatorLogObserverMixinStopStreamClientTestsMixin findFreePortrunProtocolsWithReactor)ReactorBuilderneedsRunningReactor stopOnError) MemoryReactorStringTransport)Logger)log)Failure)platform)ClientStartStopFactoryClosingFactoryMyClientFactoryMyServerFactory)SkipTestSynchronousTestCaseTestCase)SSL)ClientContextFactoryTF)::1rzIPv6 not available. ) _win32ifaces) _posixifacescgSNrZ@/usr/lib/python3/dist-packages/twisted/internet/test/test_tcp.pyr]sBr[c:t}|r|dStd)al Find and return a configured link local IPv6 address including a scope identifier using the % separation syntax. If the system has no link local IPv6 addresses, raise L{SkipTest} instead. @raise SkipTest: if no link local address can be found or if the C{netifaces} module is not available. @return: a C{str} giving the address rz#Link local IPv6 address unavailable)getLinkLocalIPv6AddressesrO) addressess r\getLinkLocalIPv6Addressras%*+I| 8 99r[c|\}}d|vsd|vrtj||dd}n||f}|j|y)a7 Connect a socket to the given destination. @param client: A C{socket.socket}. @param destination: A tuple of (host, port). The host is a C{str}, the port a C{int}. If the C{host} is an IPv6 IP, the address is resolved using C{getaddrinfo} and the first version found is used. %:rN)socket getaddrinfoconnect)client destinationhostportaddresss r\rhrhsKLT4 d{cTk$$T403A6, NN7r[c@eZdZdZdZdZdZdZdZdZ dZ d Z y ) FakeSocketz A fake for L{socket.socket} objects. @ivar data: A C{str} giving the data which will be returned from L{FakeSocket.recv}. @ivar sendBuffer: A C{list} of the objects passed to L{FakeSocket.send}. c ||_g|_yrY)data sendBufferselfrqs r\__init__zFakeSocket.__init__s r[c||_yrY)blocking)rtrws r\ setblockingzFakeSocket.setblockings   r[c|jSrY)rq)rtsizes r\recvzFakeSocket.recvs yyr[cN|jj|t|S)z I{Send} all of C{bytes} by accumulating it into C{self.sendBuffer}. @return: The length of C{bytes}, indicating all the data has been accepted. )rrappendlenrtbytess r\sendzFakeSocket.sends  u%5zr[cy)z Shutdown is not implemented. The method is provided since real sockets have it and some code expects it. No behavior of L{FakeSocket} is affected by a call to it. NrZ)rthows r\shutdownzFakeSocket.shutdownr[cy)z Close is not implemented. The method is provided since real sockets have it and some code expects it. No behavior of L{FakeSocket} is affected by a call to it. NrZrts r\closezFakeSocket.closerr[cy)z Setsockopt is not implemented. The method is provided since real sockets have it and some code expects it. No behavior of L{FakeSocket} is affected by a call to it. NrZ)rtargss r\ setsockoptzFakeSocket.setsockoptrr[cy)z Return a fake file descriptor. If actually used, this will have no connection to this L{FakeSocket} and will probably cause surprising results. rZrs r\filenozFakeSocket.filenos r[N) __name__ __module__ __qualname____doc__rurxr{rrrrrrZr[r\roros/!   r[roc"eZdZdZdZdZdZy)FakeSocketTestszT Test that the FakeSocket can be used by the doRead method of L{Connection} cttd}|jd|j|jdy)NsomeDatar)rorx assertEqualrwrtskts r\ test_blockingzFakeSocketTests.test_blockings,%  q)r[c\td}|j|jddy)Nr )rorr{rs r\ test_recvzFakeSocketTests.test_recvs$% "{3r[ctd}|jd}|j|d|j|jdgy)z L{FakeSocket.send} accepts the entire string passed to it, adds it to its send buffer, and returns its length. r[sfooN)rorrrr)rtrcounts r\ test_sendzFakeSocketTests.test_sendsA o  " &2r[N)rrrrrrrrZr[r\rrs* 43r[rceZdZdZdZy) FakeProtocolzL An L{IProtocol} that returns a value from its dataReceived method. cy)zq Return something other than L{None} to trigger a deprecation warning for that behavior. rZrZrss r\ dataReceivedzFakeProtocol.dataReceiveds r[NrrrrrrZr[r\rrs r[rc@eZdZdZdZdZdZdZdZdZ dZ d Z y ) _FakeFDSetReactora An in-memory implementation of L{IReactorFDSet}, which records the current sets of active L{IReadDescriptor} and L{IWriteDescriptor}s. @ivar _readers: The set of L{IReadDescriptor}s active on this L{_FakeFDSetReactor} @type _readers: L{set} @ivar _writers: The set of L{IWriteDescriptor}s active on this L{_FakeFDSetReactor} @ivar _writers: L{set} c@t|_t|_yrY)set_readers_writersrs r\ruz_FakeFDSetReactor.__init__s  r[c:|jj|yrY)raddrtreaders r\ addReaderz_FakeFDSetReactor.addReader! &!r[cX||jvr|jj|yyrY)rremovers r\ removeReaderz_FakeFDSetReactor.removeReader$% T]] " MM  ( #r[c:|jj|yrY)rrrtwriters r\ addWriterz_FakeFDSetReactor.addWriter(rr[cX||jvr|jj|yyrY)rrrs r\ removeWriterz_FakeFDSetReactor.removeWriter+rr[ch|j|jz}|j|SrY) getReaders getWritersrurtresults r\ removeAllz_FakeFDSetReactor.removeAll/s("T__%66  r[c,t|jSrY)listrrs r\rz_FakeFDSetReactor.getReaders4DMM""r[c,t|jSrY)rrrs r\rz_FakeFDSetReactor.getWriters7rr[N) rrrrrurrrrrrrrZr[r\rrs/ ")") ##r[rc.eZdZdZdZdZdZdZdZy)TCPServerTestsz< Whitebox tests for L{twisted.internet.tcp.Server}. ct|_Gdd}td|_t |_t |j|j d|d|j|_y)NceZdZdZy)&TCPServerTests.setUp..FakePortrN)rrr_realPortNumberrZr[r\FakePortrFsOr[rr[)rUr)rreactorrorr0protocolr3server)rtrs r\setUpzTCPServerTests.setUpCsS(*   c?   HHdmmWhj$   r[c|jjttd|jj d|j |j jgy)zq L{Server.write} discards bytes passed to it if called after it has lost its connection. Simulated lost connection hello worldN)rconnectionLostrI Exceptionwriterrrrrs r\test_writeAfterDisconnectz(TCPServerTests.test_writeAfterDisconnectOsM ""795P+Q#RS .) ,,b1r[cFd|j_|jy)z L{Server.write} discards bytes passed to it if called after it has lost its connection when the connection had started TLS. TN)rTLSrrs r\!test_writeAfterDisconnectAfterTLSz0TCPServerTests.test_writeAfterDisconnectAfterTLSXs   &&(r[c|jjttd|jj dg|j |j jgy)zy L{Server.writeSequence} discards bytes passed to it if called after it has lost its connection. rrN)rrrIr writeSequencerrrrrs r\!test_writeSequenceAfterDisconnectz0TCPServerTests.test_writeSequenceAfterDisconnect`sP ""795P+Q#RS !!>"23 ,,b1r[cFd|j_|jy)z L{Server.writeSequence} discards bytes passed to it if called after it has lost its connection when the connection had started TLS. TN)rrrrs r\)test_writeSequenceAfterDisconnectAfterTLSz8TCPServerTests.test_writeSequenceAfterDisconnectAfterTLSis   ..0r[N) rrrrrrrrrrZr[r\rr>s   2)21r[rc<eZdZdZdZdZee ddZy)TCPConnectionTestsz@ Whitebox tests for L{twisted.internet.tcp.Connection}. cDtd}t}t||}|j|j tj g}|j |ddt|j |ddd|j t|dy)z When an L{IProtocol} implementation that returns a value from its C{dataReceived} method, a deprecated warning is emitted. rrcategorymessagezReturning a value other than None from twisted.internet.test.test_tcp.FakeProtocol.dataReceived is deprecated since Twisted 11.0.0.rN) rorr2doRead flushWarningsrrDeprecationWarningr~)rtrrconnwarningss r\test_doReadWarningIsRaisedz-TCPConnectionTests.test_doReadWarningIsRaisedws %>#x( %%|'@'@&AB !Z02DE  QK " 2 X*r[c|td}t}t||}|j|jy)z The C{TLS} attribute of a L{Connection} instance is C{False} before L{Connection.startTLS} is called. r[N)rorr2 assertFalserrtrrrs r\test_noTLSBeforeStartTLSz+TCPConnectionTests.test_noTLSBeforeStartTLSs2 o>#x( "r[zNo SSL support availablectd}t}t||t}d|_|j t d|j|jy)z} The C{TLS} attribute of a L{Connection} instance is C{True} after L{Connection.startTLS} is called. r[rTN) rorr2r_tlsClientDefaultstartTLSrS assertTruerrs r\test_tlsAfterStartTLSz(TCPConnectionTests.test_tlsAfterStartTLSsP o>#x1B1DE!% *,d3 !r[N) rrrrrrr useSSLrrZr[r\rrrs/+&# J23 "4 "r[rc eZdZdZdZdZdZy) TCPCreatorzO Create IPv4 TCP endpoints for L{runProtocolsWithReactor}-based tests. 127.0.0.1c2t|d|jS)z4 Create a server-side TCP endpoint. r interface)rr)rtrs r\rzTCPCreator.servers"'1GGr[cDt||j|jS)z Create a client end point that will connect to the given address. @type serverAddress: L{IPv4Address} )rrrl)rtr serverAddresss r\rizTCPCreator.clients "'4>>=;M;MNNr[N)rrrrrrrirZr[r\rrsIH Or[rceZdZdZdZy) TCP6CreatoraV Create IPv6 TCP endpoints for C{ReactorBuilder.runProtocolsWithReactor}-based tests. The endpoint types in question here are still the TCP4 variety, since these simply pass through IPv6 address literals to the reactor, and we are only testing address literals, not name resolution (as name resolution has not yet been implemented). See http://twistedmatrix.com/trac/ticket/4470 for more specific information about new endpoint classes. The naming is slightly misleading, but presumably if you're passing an IPv6 literal, you know what you're asking for. c"t|_yrYrarrs r\ruzTCP6Creator.__init__ 02r[N)rrrrrurZr[r\rrs  3r[rcBeZdZdZdeeeffdZd dedeeddfdZ y ) FakeResolverzR A resolver implementation based on a C{dict} mapping names to addresses. namesc||_yrY)r)rtrs r\ruzFakeResolver.__init__s  r[nametimeoutreturnz Deferred[str]c t|j|S#t$rtt d|zcYSwxYw)z Return the address mapped to C{name} if it exists, or raise a C{DNSLookupError}. @param name: The name to resolve. @param timeout: The lookup timeout, ignore here. zFakeResolver couldn't find )rrKeyErrorrr!)rtrr s r\ getHostByNamezFakeResolver.getHostByNamesC N4::d+, , N'Dt'KLM M Ns  ==N)rZ) rrrrrstrrur intr rZr[r\rrs>gc3h/ N# N N Nr[rcXeZdZdZefZdZedZedZ dZ dZ dZ dZ d Zy) TCPClientTestsBasea Base class for builders defining tests related to L{IReactorTCP.connectTCP}. Classes which uses this in must provide all of the documented instance variables in order to specify how the test works. These are documented as instance variables rather than declared as methods due to some peculiar inheritance ordering concerns, but they are effectively abstract methods. @ivar endpoints: A client/server endpoint creator appropriate to the address family being tested. @type endpoints: L{twisted.internet.test.connectionmixins.EndpointCreator} @ivar interface: An IP address literal to locally bind a socket to as well as to connect to. This can be any valid interface for the local host. @type interface: C{str} @ivar port: An unused local listening port to listen on and connect to. This will be used in conjunction with the C{interface}. (Depending on what they're testing, some tests will locate their own port with L{findFreePort} instead.) @type port: C{int} @ivar family: an address family constant, such as L{socket.AF_INET}, L{socket.AF_INET6}, or L{socket.AF_UNIX}, which indicates the address family of the transport type under test. @type family: C{int} @ivar addressClass: the L{twisted.internet.interfaces.IAddress} implementor associated with the transport type under test. Must also be a 3-argument callable which produces an instance of same. @type addressClass: C{type} @ivar fakeDomainName: A fake domain name to use, to simulate hostname resolution and to distinguish between hostnames and IP addresses where necessary. @type fakeDomainName: C{str} Nc|j$|jjjSt|j|j dS)z Return the port number to connect to, using C{self._port} set up by C{listen} if available. @return: The port number to connect to. @rtype: C{int} r)_portgetHostrlr@rfamilyrs r\rlzTCPClientTestsBase.port sA :: !::%%',, ,DNNDKK8;;r[c.|jjS)zK Return the interface attribute from the endpoints object. ) endpointsrrs r\rzTCPClientTestsBase.interfaces ~~'''r[c`|jd||j|_|jS)z Start a TCP server with the given C{factory}. @param reactor: The reactor to create the TCP port in. @param factory: The server factory. @return: A TCP port instance. rr) listenTCPrrrtrfactorys r\listenzTCPClientTestsBase.listen!s+&&q'T^^&L zzr[cP|j|j|j|S)z Start a TCP client with the given C{factory}. @param reactor: The reactor to create the connection in. @param factory: The client factory. @return: A TCP connector instance. ) connectTCPrrlrs r\rhzTCPClientTestsBase.connect.s!!!$..$))WEEr[c t j t} |_t Gddt  j j j|} fd}|j|}fd}d}|j|| fd}|j|}|jtj fd} |j| j y) zr When the factory's C{buildProtocol} returns L{None} the connection is gracefully closed. ceZdZdZy)ETCPClientTestsBase.test_buildProtocolReturnsNone..NoneFactorycyrYrZ)rtrms r\ buildProtocolzSTCPClientTestsBase.test_buildProtocolReturnsNone..NoneFactory.buildProtocolHsr[Nrrrr#rZr[r\ NoneFactoryr!Gs r[r%c}jj|j}|j|SrY)rrirrh)rl clientFactoryendpointr%rrts r\listenedzBTCPClientTestsBase.test_buildProtocolReturnsNone..listenedMs7'MM~~,,WdllnEH##M2 2r[c0jd|dy)Nz.Stream client endpoint connect succeeded with z%, should have failed with NoProtocol.)r)rrts r\connectSucceededzJTCPClientTestsBase.test_buildProtocolReturnsNone..connectSucceededTs II9AD r[c.|jtyrY)trapr")reasons r\ connectFailedzGTCPClientTestsBase.test_buildProtocolReturnsNone..connectFailedZs KK #r[cSrYrZ)ignoredrs r\ connectedzCTCPClientTestsBase.test_buildProtocolReturnsNone..connected_s " !r[c&jyrYstop)r1rs r\ disconnectedzFTCPClientTestsBase.test_buildProtocolReturnsNone..disconnectedjs LLNr[N)r buildReactorrNprotocolConnectionLostrDr1rrr addCallback addCallbacks addErrbackrHerr runReactor) rt serverFactory listeningr) connectingr+r/r2 disconnectingr6r%rrs ` @@@r\test_buildProtocolReturnsNonez0TCPClientTestsBase.test_buildProtocolReturnsNone:s "##%') /= , D'" - NN))'299-H  3 **84    $  0-@ " #..y9    )  !!,/  r[c tjjdd\}}j j j t ji jdtjt| j}dddd G fddt}t  | _ fd}t |j  j r)j# j j%d j' d j( d j*t- d }|gt/t1j2j j4dd d dz}|gt/t1j2j|j6dd d dz}j9 d j:dg|j9 dj:dg|j9t= d |y)a A client's transport's C{getHost} and C{getPeer} return L{IPv4Address} instances which have the dotted-quad string form of the resolved address of the local and remote endpoints of the connection respectively as their C{host} attribute, not the hostname originally passed in to L{connectTCP}, if a hostname was used. Nrr)rkpeerinstanceceZdZfdZy)7TCPClientTestsBase.test_addresses..CheckAddressc||jd<|jd<|d<jy)NrkrErF)rgetPeerr5)rt transportr transportDatas r\makeConnectionzFTCPClientTestsBase.test_addresses..CheckAddress.makeConnections<(1(9(9(; f%(1(9(9(; f%,5 j) r[NrrrrM)rrLsr\ CheckAddressrHs r[rOc( tjj}j|df}tjd| j j j||d_y#t$rYwxYw)Nrz!Connect attempt with bindAddress ) bindAddress) r@rrrHmsgrrrl boundPortr)rlrQr' fakeDomainrrtrs r\ connectMez4TCPClientTestsBase.test_addresses..connectMes#DNNDKK@#~~tAw7 ;K=IJ &&"(--%$/ '/31gM+ (s -B BBz<{} to {} at {:x}>rFrrkTCPrE)r@rrr7fakeDomainNameinstallResolverrrr1 forProtocolr0rr>rrCr= failReasonr getTracebackformat __class__addridrrfrgrSrlr addressClassrepr)rtrkr1rrOrU transportReprrS serverPortr'rTrrrLs` @@@@@r\test_addressesz!TCPClientTestsBase.test_addressesus$%T^^T[[A"1E g##%((  j$..-I JK"" }((2d# ( !%tF  8 W !-   $ GY/   # # IIm..;;= >,33 * % / / * % * * }Z( ) FT   t~~}/F/F G J2 Nqr R  Vd   t~~}/A/A B1 Eb I!" M   v.0A0A0A%0T)0TU v.0A0A0A%0U*0UV mJ78-Hr[c j tg tjt} j d|j }jj |j}t}t|_ |j| fd fd fd}t |j jt! dd t# dt$r dj' ddk(r t)d jtj*t- dy ) z If the context factory passed to L{ITCPTransport.startTLS} raises an exception from its C{getContext} method, that exception is raised by L{ITCPTransport.startTLS}. rrctj|jsjdyjj t |jj y)Nskip)r. providedByrKr} assertRaises ValueErrorr)r brokenFactoryresultsrts r\r2z5TCPClientTestsBase.test_badContext..connectedsP ++H,>,>?v&%%"H$6$6$?$?r[c(j|yrYr})failurerms r\r/z9TCPClientTestsBase.test_badContext..connectFaileds NN7 #r[crjjjfdy)Nc$jSrYr4ignrs r\r]zETCPClientTestsBase.test_badContext..whenRun..s  r[)r9r;addBoth)connectDeferredr/r2rsr\whenRunz3TCPClientTestsBase.test_badContext..whenRuns.  ' ' 2  & &} 5  # #$> ?r[rzmore than one callback result: rhz&Reactor does not support ITLSTransportN)r7r9r1rZr0rrrrirr/rrhrCr=rr~ isinstancerIraiseExceptionrOrr) rtr>rlr(r'rwrlrvr/r2rrms ` @@@@@@r\test_badContextz"TCPClientTestsBase.test_badContexts! ##%,. %11(;   MT^^ L>>(($,,.A% !) "**=9  $ @ GW-   Wq,KG9*UV gaj' * AJ % % ' 1: CD D -55s71:Gr[)rrrrr+requiredInterfacesrpropertyrlrrrhrBrerzrZr[r\rrs\$L& E  < <((  F9!vHIT0Hr[rc>eZdZdZdZej ZeZ e Z y)TCP4ClientTestsBuilderze Builder configured with IPv4 parameters for tests related to L{IReactorTCP.connectTCP}. zsome-fake.domain.example.comN) rrrrrXrfAF_INETrrrarrrZr[r\r~r~s# 4N ^^FL Ir[r~c2eZdZdZej ZeZdZ y)TCP6ClientTestsBuilderze Builder configured with IPv6 parameters for tests related to L{IReactorTCP.connectTCP}. cXt|_|jj|_yrY)rrrrXrs r\rzTCP6ClientTestsBuilder.setUp s!%#nn66r[N) rrrrrfAF_INET6rrrarrZr[r\rrs __FL 7r[rc(eZdZdZefZdZdZdZy)TCPConnectorTestsBuilderzU Tests for the L{IConnector} provider returned by L{IReactorTCP.connectTCP}. c$ t}|jjd||j}||_|j j}gg t } fd|_j|_ j|j||}|jtj||j}|j|j d|j|j"|j|j|j||j$j'fd|j) dj+t,|j||gy)aU L{IReactorTCP.connectTCP} returns an object which provides L{IConnector}. The destination of the connector is the address which was passed to C{connectTCP}. The same connector object is passed to the factory's C{startedConnecting} method as to the factory's C{clientConnectionLost} method. rrcHj|j|fSrYro) connectorr.seenConnectors seenFailuress r\r]zATCPConnectorTestsBuilder.test_connectorIdentity../s'  ! !) ,    'H r[rWc$jSrYr4_rs r\r]zATCPConnectorTestsBuilder.test_connectorIdentity..< GLLNr[N)rLr7rrrlrrKclientConnectionLostr}startedConnectingrrr$rigetDestinationrtyperk whenStoppedrur=r-r) rtr>tcpPort portNumberr'rdestrrrs @@@r\test_connectorIdentityz/TCPConnectorTestsBuilder.test_connectorIdentitysA'( ##%##A}#O$ __&++  .0 . *+9*?*? '&&t~~z=Q   --i89'') E* DNN3 J/!!))*BC  Q^, )Y)?@r[c.t}jjd|j}|j j gfd}t |_jjfdjfdjr"jdjjjt j#j$dy)z Calling L{IConnector.stopConnecting} in C{Factory.startedConnecting} results in C{Factory.clientConnectionFailed} being called with L{error.UserError} as the reason. rrc |jy#t$r,jtj YywxYwrY)stopConnectingrr}rIr5)r fatalErrorsrs r\rzATCPConnectorTestsBuilder.test_userFail..startedConnectingPs< ((* ""79-  s2A A c$jSrYr4rs r\r]z8TCPConnectorTestsBuilder.test_userFail..Zrr[c>jjSrY)rr)r'rrrtsr\r]z8TCPConnectorTestsBuilder.test_userFail..]sG&&t~~z=Qr[rN)rNr7rrrrlrKrrrucallWhenRunningr=rr\r.r-r#rfailed)rtr>rrr'rrrs` @@@@r\ test_userFailz&TCPConnectorTestsBuilder.test_userFailCs () ##%##A}#O__&++   /0 *; '!!))*BC Q    IIk!n113 4!!), --q1r[ct}|jjd||j}||_|j j}t d}|_j|j|gfd}jj||jjjt|jdgy)z Calling L{IConnector.connect} in C{Factory.clientConnectionLost} causes a new connection attempt to be made. rrc$|jyrY)rh)rr.s r\rzETCPConnectorTestsBuilder.test_reconnect..clientConnectionLostts    r[cj}j|j|jfj yrY)rr}madeclosedr5)r1pr'protocolMadeAndClosedrs r\reconnectFailedz@TCPConnectorTestsBuilder.test_reconnect..reconnectFailed|s2&&A ! ( (!&&!((); < LLNr[)rrN)rLr7rrrlrrMrr failDeferredr9r=r.r-r r) rtr>rrrrr'rrs @@@r\test_reconnectz'TCPConnectorTestsBuilder.test_reconnectgs '( ##%##A}#O$ __&++ ')  .B *4>>:}E "  ""..?  !!"89 .9r[N) rrrrr+r{rrrrZr[r\rrs#&$AL"2H:r[rc,eZdZdZej ZeZy)TCP4ConnectorTestsBuilderrN) rrrrrfrrrrarZr[r\rrsI ^^FLr[rc.eZdZejZeZdZy)TCP6ConnectorTestsBuilderc"t|_yrYrrs r\rzTCP6ConnectorTestsBuilder.setUprr[N) rrrrfrrrrarrZr[r\rrs __FL3r[rchtj||}|j|j|S)z Create a socket for the duration of the given test. @param test: the test to add cleanup to. @param addressFamily: an C{AF_*} constant @param socketType: a C{SOCK_*} constant. @return: a socket object. )rf addCleanupr)test addressFamily socketTypers r\createTestSocketrs) -- z 2COOCII Jr[c"eZdZdZdZdZdZy)_IExhaustsFileDescriptorsz% A way to trigger C{EMFILE}. cy)z Open file descriptors until C{EMFILE} is reached. This can raise any exception except an L{OSError} whose C{errno} is C{EMFILE}. Any exception raised to the caller implies L{release}. NrZrZr[r\exhaustz!_IExhaustsFileDescriptors.exhaustrr[cyzD Release all file descriptors opened by L{exhaust}. NrZrZr[r\releasez!_IExhaustsFileDescriptors.releaserr[cy) Return the number of opened file descriptors. @return: The number of opened file descriptors; this will be zero if this instance has not opened any. @rtype: L{int} NrZrZr[r\rz_IExhaustsFileDescriptors.countrr[NrrrrrrrrZr[r\rrs   r[r) auto_attribsc,eZdZUdZeZeeed<ejddZ e ge fed<eje jdZe e gdfed<ejej edd Zee ed <d Zd Zd Zy)_ExhaustsFileDescriptorsa_ A class that triggers C{EMFILE} by creating as many file descriptors as necessary. @ivar fileDescriptorFactory: A factory that creates a new file descriptor. @type fileDescriptorFactory: A L{callable} that accepts no arguments and returns an integral file descriptor, suitable for passing to L{os.close}. _logc,tjdSNr)osduprZr[r\r]z!_ExhaustsFileDescriptors.sq r[F)defaultrb_fileDescriptorFactoryN_close)rinitrb_fileDescriptorsctj |j}|jj |-#t $r(}|j t jk(rYd}~n d}~wwxYw |jjd|jy#t$r|jwxYw)zC Open file descriptors until C{EMFILE} is reached. NzCEMFILE reached by opening {openedFileDescriptors} file descriptors.)openedFileDescriptors) gccollectrrr}OSErrorerrnoEMFILErinforrrrtfdes r\rz _ExhaustsFileDescriptors.exhausts  5446B ))004ww%,,. IINN=&*jjl     LLN  s9B%AB% A5 A0*B%/A00A55B%%Cc|jr:|jj} |j||jr9yy#t$r(}|jtj k(rYd}~rd}~wwxYwr)rpoprrrEBADFrs r\rz _ExhaustsFileDescriptors.releasesd##&&**,B  B## 77ekk) sA A9A43A44A9c,t|jS)r)r~rrs r\rz_ExhaustsFileDescriptors.counts4(())r[)rrrrrGrr__annotations__attribrrrrrrFactoryrrrrrrrZr[r\rrs $XD(6 %07!1HRW-%,DGGBHH5$IFHcUD[ !I")$'' T"U#d3i4 *r[r9Reserved EMFILE file descriptor not supported on Windows.cLeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z y ) ExhaustsFileDescriptorsTestsz0 Tests for L{_ExhaustsFileDescriptors}. clt|_|j|jjyrY)r exhausterrrrs r\rz"ExhaustsFileDescriptorsTests.setUps$13 ../r[cRttjjy)z` Attempt to open a file; if successful, the file is immediately closed. N)openrdevnullrrs r\ openAFilez&ExhaustsFileDescriptorsTests.openAFiles RZZ r[c8tt|jy)ze L{_ExhaustsFileDescriptors} instances provide L{_IExhaustsFileDescriptors}. N)rrrrs r\test_providesInterfacez3ExhaustsFileDescriptorsTests.test_providesInterface"s .?r[ch|j|jjd|jj|j |jjd|jj |j|jjdy)zh L{_ExhaustsFileDescriptors.count} returns the number of open file descriptors. rN)rrrr assertGreaterrrs r\ test_countz'ExhaustsFileDescriptorsTests.test_count)s{ --/3   4>>//115   --/3r[c|j|jj|jj|j t |j }|j|jtjy)z{ L{_ExhaustsFileDescriptors.exhaust} causes the process to exhaust its available file descriptors. N) rrrrrjIOErrorrrrr)rt exceptions r\test_exhaustTriggersEMFILEz7ExhaustsFileDescriptorsTests.test_exhaustTriggersEMFILE4sX ../  %%gt~~>  %,,7r[c`d}t|}|jt|jy)z An L{OSError} raised within L{_ExhaustsFileDescriptors.exhaust} with an C{errno} other than C{EMFILE} is reraised to the caller. c<ttjdzd)Nrz Not EMFILE)rrrrZr[r\ raiseOSErrorzLExhaustsFileDescriptorsTests.test_exhaustRaisesOSError..raiseOSErrorEs%,,*L9 9r[N)rrjrr)rtrrs r\test_exhaustRaisesOSErrorz6ExhaustsFileDescriptorsTests.test_exhaustRaisesOSError>s) :-\:  '9#4#45r[c|jj|jj|jy)zc L{_ExhaustsFileDescriptors.release} releases all opened file descriptors. N)rrrrrs r\ test_releasez)ExhaustsFileDescriptorsTests.test_releaseKs.     r[cgfd}t|}|j|j|jt|j |j td|j |jdD]Q}|jttj|}|j |jtjSy)z L{_ExhaustsFileDescriptors.exhaust} closes any opened file descriptors if an exception occurs during its exhaustion loop. ctdk(r tdtjd}j ||S)Nrz9test_fileDescriptorsReleasedOnFailure fake open exceptionr)r~rkrrr}rfileDescriptorss r\failsAfterThreez[ExhaustsFileDescriptorsTests.test_fileDescriptorsReleasedOnFailure..failsAfterThree\sB?#q( RVVAY&&r* r[rrN)rrrrjrkrrr~rrrfstatrr)rtrrrrrs @r\%test_fileDescriptorsReleasedOnFailurezBExhaustsFileDescriptorsTests.test_fileDescriptorsReleasedOnFailureUs  -_=   ))* *i&7&78 _-q1 *A.! ;B))'288R@I   Y__ekk : ;r[cPgfd}t|}|j|j|j|j |j dt jd|j|j|j dy)z L{_ExhaustsFileDescriptors.release} continues to close opened file descriptors even when closing one fails with C{EBADF}. cTtjd}j||Sr)rrr}rs r\recordFileDescriptorszTExhaustsFileDescriptorsTests.test_releaseIgnoresEBADF..recordFileDescriptorsxs#B  " "2 &Ir[rN) rrrrrrrrr)rtrrrs @r\test_releaseIgnoresEBADFz5ExhaustsFileDescriptorsTests.test_releaseIgnoresEBADFqs   --BC   ))* 9??,a0 #$ *A.r[cgfd}d}t||}|j|jd|j|j |jd|j t |jy)z An L{OSError} raised within L{_ExhaustsFileDescriptors.release} with an C{errno} other than C{EBADF} is reraised to the caller. ctdk(rttjdj ddS)NrzToo many filesrV)r~rrrr})fakeFileDescriptorssr\ opensThreezJExhaustsFileDescriptorsTests.test_releaseRaisesOSError..opensThrees<&'1,ell,<==  & &r *&r* *r[ctdd)N z&test_releaseRaisesOSError fake OSError)r)rs r\ failingClosezLExhaustsFileDescriptorsTests.test_releaseRaisesOSError..failingCloses"FG Gr[)rrN)rrrrrrjrr)rtrr rrs @r\test_releaseRaisesOSErrorz6ExhaustsFileDescriptorsTests.test_releaseRaisesOSErrorst ! +  H-Z|L  *A. 9??,a0 '9#4#45r[N)rrrrrrrrrrrrrr rZr[r\rrs:0 !@ 48 6;8/.6r[rcd |jjtt}|_dgfd}|j |t tjr) fd}jdjd|n>} | j} | jjfd} jj|  jj| |g} |j| j |j#| d|j% j|j' j|j)t* j,j.y)a# Assert that an L{IListeningPort} immediately closes an accepted peer socket when the number of open file descriptors exceeds the soft resource limit. @param testCase: The test case under which to run this assertion. @type testCase: L{trial.unittest.SynchronousTestCase} @param exhauster: The file descriptor exhauster. @type exhauster: L{_ExhaustsFileDescriptors} @param reactor: The reactor under test. @param runReactor: A callable that will synchronously run the provided reactor. @param listen: A callback to bind to a port. @type listen: A L{callable} that accepts two arguments: the provided C{reactor}; and a L{ServerFactory}. It must return an L{IListeningPort} provider. @param connect: A callback to connect a client to the listening port. @type connect: A L{callable} that accepts three arguments: the provided C{reactor}; the address returned by L{IListeningPort.getHost}; and a L{ClientFactory}. Its return value is ignored. Fc0jdd<y)NTrr4)rrserverConnectionCompleteds r\stopReactorIfServerAcceptedz=assertPeerClosedOnEMFILE..stopReactorIfServerAccepteds '+!!$r[cl}|j}|jyrY)rr)rl listeningHostr'rhrrrr>s r\innerz'assertPeerClosedOnEMFILE..inners2'=1D LLNM G]M :    r[rcHjj|SrY)rr5)rrrs r\"stopReactorAndCloseFileDescriptorszDassertPeerClosedOnEMFILE..stopReactorAndCloseFileDescriptorss  r[z1Server accepted connection; EMFILE not triggered.N)rrrNrprotocolConnectionMader9rMr,ri callLaterrrrdeferredrurr}rassertNoResultsuccessResultOfrjr lostReasonry)testCaserrr=rrhserverConnectionMaderrrlrrnoResultr'r r>s `` `` @@@r\assertPeerClosedOnEMFILErsnH  ))*#%M#:+?M(!&,$$%@A#%Mw'   !W..59g}-   6 1 12 ""#EF&&'IJwH  1 #VW M667 ]334   //r[cLeZdZdZeeGddZdZdZdZ y)AssertPeerClosedOnEMFILETestsz0 Tests for L{assertPeerClosedOnEMFILE}. c"eZdZdZdZdZdZy)+AssertPeerClosedOnEMFILETests.NullExhausterz1 An exhauster that does nothing. cy)zB See L{_IExhaustsFileDescriptors.exhaust} NrZrs r\rz3AssertPeerClosedOnEMFILETests.NullExhauster.exhaust rr[cy)zB See L{_IExhaustsFileDescriptors.release} NrZrs r\rz3AssertPeerClosedOnEMFILETests.NullExhauster.releaserr[cy)z@ See L{_IExhaustsFileDescriptors.count} NrZrs r\rz1AssertPeerClosedOnEMFILETests.NullExhauster.countrr[NrrZr[r\ NullExhausterr!s      r[r%c@t|_t|_yrY)rErrPrrs r\rz#AssertPeerClosedOnEMFILETests.setUps$ +- r[c@tt|jy)zZ L{NullExhauster} instances provide L{_IExhaustsFileDescriptors}. N)rrr%rs r\#test_nullExhausterProvidesInterfacezAAssertPeerClosedOnEMFILETests.test_nullExhausterProvidesInterfaces .0B0B0DEr[c P|j}dgfd}fd}d}|j|jjt|j||j |||}|j dt||j|j jy)z If the exhauster fails to trigger C{EMFILE} and a connection reaches the server, the reactor is stopped and the test fails. Nc|jdjtddd}|jt y)NrrWri)runr#rrMrF)rprotor>s r\r=z[AssertPeerClosedOnEMFILETests.test_reactorStoppedOnSuccessfulConnection..runReactor+s@ KKM!!$22E;5E  !2 3r[cX|jdd|}|j|d<|S)Nrir)rdoStart)rrrlr>s r\rzWAssertPeerClosedOnEMFILETests.test_reactorStoppedOnSuccessfulConnection..listen2s0$$[$@D OO &M! Kr[c*|jdd|y)Nrr)r)rrmrs r\rhzXAssertPeerClosedOnEMFILETests.test_reactorStoppedOnSuccessfulConnection..connect8s   {Aw 7r[rrrr=rrhr) r%rjrfailureExceptionrrassertInrrrunning)rtrr=rrhrr>s @r\)test_reactorStoppedOnSuccessfulConnectionzGAssertPeerClosedOnEMFILETests.test_reactorStoppedOnSuccessfulConnection#s &&(   4   8%% MM * * $]]LL!&   hI/ --.r[N) rrrrrrr%rr(r4rZr[r\rrs6*+,(.F$/r[rc:eZdZdZdZdZeeddZy)StreamTransportTestsMixinzR Mixin defining tests which apply to any port/connection based transport. c|j}|j}ttGddt}|}|j ||}|j |d}|j|f|ddy)zt When a port starts, a message including a description of the associated factory is logged. ceZdZdZy)NStreamTransportTestsMixin.test_startedListeningLogMessage..SomeFactorycy)N Crazy FactoryrZrs r\ logPrefixzXStreamTransportTestsMixin.test_startedListeningLogMessage..SomeFactory.logPrefixYs&r[N)rrrr<rZr[r\ SomeFactoryr9Ws 'r[r=r;rrN)observer7rr&r1getListeningPort#getExpectedStartListeningLogMessager)rtloggedMessagesrr=rrexpectedMessages r\test_startedListeningLogMessagez9StreamTransportTestsMixin.test_startedListeningLogMessageOs ##% _ % '- ' & '-  ! !'7 3BB1oV /+^A->y-IJr[c<gfd|j|jt|j}t j fdfd}j |j|j|y)z When a connection is lost, an informative message should be logged (see L{getExpectedConnectionLostLogMsg}): an address identifying the port and the fact that it was closed. cNjtj|yrY)r}rHtextFromEventDict) eventDictrAs r\logConnectionLostMsgzQStreamTransportTestsMixin.test_connectionLostLogMsg..logConnectionLostMsgjs  ! !#"7"7 "B Cr[cPtjjyrY)rHremoveObserverr5)r1rHrs r\ stopReactorzHStreamTransportTestsMixin.test_connectionLostLogMsg..stopReactorrs   3 4 LLNr[cxtjtjj yrY)rH addObserverr stopListeningr9)rHrrKsr\doStopListeningzLStreamTransportTestsMixin.test_connectionLostLogMsg..doStopListeningvs' OO0 1 !// * 6 6{ Cr[N) r7r?r1getExpectedConnectionLostLogMsgrHrMrr+r2)rtrBrOrHrArrrKs @@@@@r\test_connectionLostLogMsgz3StreamTransportTestsMixin.test_connectionLostLogMsgas D##%  ! !'=? ;>>qA ,-  D 0  o~6r[rct|t|j|j|j|j y)z2 See L{assertPeerClosedOnEMFILE}. r0N)rrr7r=r?connectToListenerrs r\test_closePeerOnEMFILEz0StreamTransportTestsMixin.test_closePeerOnEMFILEs: !.0%%'((**  r[N) rrrrrCrQr SKIP_EMFILErTrZr[r\r6r6Js/K$7< KTU  V  r[r6ceZdZdZdZdZy)ConnectToTCPListenerMixina^ Provides L{connectToListener} for TCP transports. @ivar LISTENER_HOST: The host on which the port is expected to be listening. This is specific to avoid compatibility issues with Windows, which cannot connect to the wildcard host. @type LISTENER_HOST: L{str} @see: U{http://twistedmatrix.com/trac/ticket/1472} rcP|j|j|j|S)a Connect to the given listening TCP port. @param reactor: The reactor under test. @type reactor: L{IReactorTCP} @param address: The listening port's address. Only the C{port} component is used; see L{LISTENER_HOST}. @type address: L{IPv4Address} or L{IPv6Address} @param factory: The client factory. @type factory: L{ClientFactory} @return: The connector )r LISTENER_HOSTrl)rtrrmrs r\rSz+ConnectToTCPListenerMixin.connectToListeners# !!$"4"4gllGLLr[N)rrrrrYrSrZr[r\rWrWs  MMr[rWceZdZdZddZy)ListenTCPMixinzT Mixin which uses L{IReactorTCP.listenTCP} to hand out listening TCP ports. c*|j|||S)z0 Get a TCP port from a reactor. r)r)rtrrrlrs r\r?zListenTCPMixin.getListeningPorts  w) DDr[NrrUrrrrr?rZr[r\r[r[s Er[r[ceZdZdZddZy)SocketTCPMixinza Mixin which uses L{IReactorSocket.adoptStreamPort} to hand out listening TCP ports. c>tj|rd|vr-tj}tj||dd}ntj }||f}tj|}|j ||jd|jd |j|j|j||j|jStd#|j|jwxYw)zi Get a TCP port from a reactor, wrapping an already-initialized file descriptor. rdrrerFz'Reactor does not provide IReactorSocket)r*rirfrrgrbindrrxadoptStreamPortrrrrO)rtrrrlrdomainrmportSocks r\r?zSocketTCPMixin.getListeningPorts  $ $W -i ,,Y=a@C$d+}}V,H MM' " OOA    ' !..OO%x ! DE E ! s $*C::"DNr]r^rZr[r\r`r`s  Fr[r`cTeZdZUdZefZeeee e d<dZ dZ dZ eeedZeeedZdZd Zeeed Zeeed Zd Zd ZeeedZeeedZdZeeedZeeedZy)TCPPortTestsMixinz, Tests for L{IReactorTCP.listenTCP} r{c@d||jjfzS)zY Get the message expected to be logged when a TCP port starts listening. z%s starting on %drrl)rtrlrs r\r@z5TCPPortTestsMixin.getExpectedStartListeningLogMessages #gt||~/B/B%CCCr[c>d|jjdS)zJ Get the expected connection lost message for a TCP port. z (TCP Port z Closed)ri)rtrls r\rPz1TCPPortTestsMixin.getExpectedConnectionLostLogMsgs DLLN//099r[c|j}|j|t}|j}|j |t y)z When no interface is passed to L{IReactorTCP.listenTCP}, the returned listening port listens on an IPv4 address. N)r7r?r1rassertIsInstancer)rtrrlrms r\test_portGetHostOnIPv4z(TCPPortTestsMixin.test_portGetHostOnIPv4sA ##%$$Wmo>,,. g{3r[cZ|j}ttjddd\}}|j |t ||}|j }|j|t|jd|j|j||jy)z When listening on an IPv6 address, L{IListeningPort.getHost} returns an L{IPv6Address} with C{host} and C{port} attributes reflecting the address the port is bound to. rT)rrNrD) r7r@rfrr?r1rrlrrrkrl)rtrrkrrlrms r\test_portGetHostOnIPv6z(TCPPortTestsMixin.test_portGetHostOnIPv6s##%'v%PQSRSTj$$Wmoz4P,,. g{3  - W\\2r[ct}|j}|j|td|}|j }|j |t |j||jy)a( When a link-local IPv6 address including a scope identifier is passed as the C{interface} argument to L{IReactorTCP.listenTCP}, the resulting L{IListeningPort} reports its address as an L{IPv6Address} with a host value that includes the scope identifier. rN) rar7r?r1rrlrrrk)rt linkLocalrrlrms r\test_portGetHostOnIPv6ScopeIDz/TCPPortTestsMixin.test_portGetHostOnIPv6ScopeID sa,- ##%$$Wmoq)L,,. g{3 GLL1r[cGfddt}|}|j|j|d|}|jd t ||j j |j jf|j|jS#t$rD}|j|jtjtjfYd}~ed}~wwxYw)a Connect C{client} to a server listening on C{interface} started with L{IReactorTCP.listenTCP} and return the address passed to the factory's C{buildProtocol} method. @param client: A C{SOCK_STREAM} L{socket.socket} created with an address family such that it will be able to connect to a server listening on C{interface}. @param interface: A C{str} giving an address for a server to listen on. This should almost certainly be the loopback address for some address family supported by L{IReactorTCP.listenTCP}. @return: Whatever object, probably an L{IAddress} provider, is passed to a server factory's C{buildProtocol} method when C{client} establishes a connection. ceZdZfdZy)CTCPPortTestsMixin._buildProtocolAddressTest..ObserveAddresscFj||_tSrY)r5observedAddressr0)rtrmrs r\r#zQTCPPortTestsMixin._buildProtocolAddressTest..ObserveAddress.buildProtocol/s '.$z!r[Nr$rsr\ObserveAddressru.s "r[rxrFN)r1r7r?rxrhrrkrlrr2r EINPROGRESS EWOULDBLOCKr=rw)rtrirrxrrlrrs @r\_buildProtocolAddressTestz+TCPPortTestsMixin._buildProtocolAddressTests& "] " !"##%$$Wgq)D5! K FT\\^00$,,.2E2EF G  &&&  K MM!''E$5$5u7H7H#I J J Ks>B++ C84:C33C8cd}t|tjtj}|j ||}|j t dg|j|y)z When a connection is accepted over IPv4, an L{IPv4Address} is passed to the factory's C{buildProtocol} method giving the peer's address. rrWN)rrfr SOCK_STREAMr{rr getsockname)rtrrirws r\test_buildProtocolIPv4Addressz/TCPPortTestsMixin.test_buildProtocolIPv4AddressAsV  !$8J8JK88K UBV-?-?-ABOTr[c,d}t|tjtj}|j ||}|j }tj |tjd}|jtd||d|y)z When a connection is accepted to an IPv6 address, an L{IPv6Address} is passed to the factory's C{buildProtocol} method giving the peer's address. rTrrWrN) rrfrr}r{r~ getnameinfoNI_NUMERICHOSTrrrtrrirwrEhostnames r\test_buildProtocolIPv6Addressz/TCPPortTestsMixin.test_buildProtocolIPv6AddressKs{ !$9K9KL88K!!#%%dF,A,AB1E UHd1g>Pr[c<t}t|tjtj}|j ||}|j }tj|tjd}|jtd|g|dd|y)z When a connection is accepted to a link-local IPv6 address, an L{IPv6Address} is passed to the factory's C{buildProtocol} method giving the peer's address, including a scope identifier. rrWrN) rarrfrr}r{r~rrrrrs r\$test_buildProtocolIPv6AddressScopeIDz6TCPPortTestsMixin.test_buildProtocolIPv6AddressScopeID[s,- !$9K9KL88K!!#%%dF,A,AB1E UH@tABx@/Rr[cGfddt}|jt}||_|j |d|}|j d t ||jj|jjf|j|j S#t$rD}|j|jtjtjfYd}~ed}~wwxYw)a Connect C{client} to a server listening on C{interface} started with L{IReactorTCP.listenTCP} and return the address returned by one of the server transport's address lookup methods, C{getHost} or C{getPeer}. @param client: A C{SOCK_STREAM} L{socket.socket} created with an address family such that it will be able to connect to a server listening on C{interface}. @param interface: A C{str} giving an address for a server to listen on. This should almost certainly be the loopback address for some address family supported by L{IReactorTCP.listenTCP}. @param which: A C{str} equal to either C{"getHost"} or C{"getPeer"} determining which address will be returned. @return: Whatever object, probably an L{IAddress} provider, is returned from the method indicated by C{which}. ceZdZfdZy)ITCPPortTestsMixin._serverGetConnectionAddressTest..ObserveAddresscfjt||j_yrY)r5getattrrrm)rtrKrwhichs r\rMzXTCPPortTestsMixin._serverGetConnectionAddressTest..ObserveAddress.makeConnections$ '@wy%'@'B $r[NrN)rrsr\rxrs  Cr[rxrFN)r0r7r1rr?rxrhrrkrlrr2rryrzr=rm) rtrirrrxrrlrrs ` @r\_serverGetConnectionAddressTestz1TCPPortTestsMixin._serverGetConnectionAddressTestks* CX C ##%/)$$Wgq)D5! K FT\\^00$,,.2E2EF G   K MM!''E$5$5u7H7H#I J J Ks>B77 D:C??Dcd}t|tjtj}|j ||d}|j t dg|j|y)z When a connection is accepted over IPv4, the server L{ITransport.getHost} method returns an L{IPv4Address} giving the address on which the server accepted the connection. rrrWN)rrfrr}rrr getpeername)rtrri hostAddresss r\test_serverGetHostOnIPv4z*TCPPortTestsMixin.test_serverGetHostOnIPv4X  !$8J8JK::69iX  UBV-?-?-ABKPr[c.d}t|tjtj}|j ||d}|j }tj |tjd}|jtd|g|dd|y)z When a connection is accepted over IPv6, the server L{ITransport.getHost} method returns an L{IPv6Address} giving the address on which the server accepted the connection. rTrrrWrN) rrfrr}rrrrrrrtrrirrErs r\test_serverGetHostOnIPv6z*TCPPortTestsMixin.test_serverGetHostOnIPv6 !$9K9KL::69iX !!#%%dF,A,AB1E UH@tABx@+Nr[c>t}t|tjtj}|j ||d}|j }tj|tjd}|jtd|g|dd|y)z When a connection is accepted over IPv6, the server L{ITransport.getHost} method returns an L{IPv6Address} giving the address on which the server accepted the connection, including the scope identifier. rrrWrN) rarrfrr}rrrrrrrs r\test_serverGetHostOnIPv6ScopeIDz1TCPPortTestsMixin.test_serverGetHostOnIPv6ScopeID,- !$9K9KL::69iX !!#%%dF,A,AB1E UH@tABx@+Nr[cd}t|tjtj}|j ||d}|j t dg|j|y)z When a connection is accepted over IPv4, the server L{ITransport.getPeer} method returns an L{IPv4Address} giving the address of the remote end of the connection. rrJrWN)rrfrr}rrrr~)rtrri peerAddresss r\test_serverGetPeerOnIPv4z*TCPPortTestsMixin.test_serverGetPeerOnIPv4rr[c.d}t|tjtj}|j ||d}|j }tj |tjd}|jtd|g|dd|y)z When a connection is accepted over IPv6, the server L{ITransport.getPeer} method returns an L{IPv6Address} giving the address on the remote end of the connection. rTrJrrWrN) rrfrr}rr~rrrrrtrrirrErs r\test_serverGetPeerOnIPv6z*TCPPortTestsMixin.test_serverGetPeerOnIPv6rr[c>t}t|tjtj}|j ||d}|j }tj|tjd}|jtd|g|dd|y)z When a connection is accepted over IPv6, the server L{ITransport.getPeer} method returns an L{IPv6Address} giving the address on the remote end of the connection, including the scope identifier. rJrrWrN) rarrfrr}rr~rrrrrs r\test_serverGetPeerOnIPv6ScopeIDz1TCPPortTestsMixin.test_serverGetPeerOnIPv6ScopeIDrr[N)rrrrr+r{r r r r rr@rPrmr ipv6Skipipv6SkipReasonrorrr{rrrrrrrrrrrZr[r\rgrgs8@Kn$y/!:;LD : 4 Hn% 3& 3 Hn% 2& 2$'LU Hn% Q& Q Hn% S& S$L Q Hn% O& O Hn%O&O Q Hn% O& O Hn%O&Or[rgc eZdZy)TCPPortTestsBuilderNrrrrZr[r\rr  r[rc eZdZy)TCPFDPortTestsBuilderNrrZr[r\rrrr[rc"eZdZdZdZdZdZy)StopStartReadingProtocolzD Protocol that pauses and resumes the transport a few times c4d|_|jdy)Nr[r)rqpauseResumeProducingrs r\connectionMadez'StopStartReadingProtocol.connectionMades  !!!$r[cd|jj|jj|r5|jjj d|j |dz y|jjj d|jjj|y)z? Toggle transport read state, then count down. rrN) rKpauseProducingresumeProducingrrrrreadycallback)rtcounters r\rz-StopStartReadingProtocol.pauseResumeProducingsz %%' &&(  LL * *1d.G.GST U LL * *1dll.@.@.I.I4 Pr[ctjdt||xj|z c_t|jdk(r0|jj j |jyy)Nzgot datai@)rHrRr~rqrr5rrss r\rz%StopStartReadingProtocol.dataReceivedsS  CI& T tyy>X % LL   & &tyy 1 &r[N)rrrrrrrrZr[r\rrs% Q2r[rc.tfd}|S)aG Decorate a L{ReactorBuilder} test function which tests one reactor and one connected transport. Run that test method in the context of C{connectionMade}, and immediately drop the connection (and end the test) when that completes. @param testMethod: A unit test method on a L{ReactorBuilder} test suite; taking two additional parameters; a C{reactor} as built by the L{ReactorBuilder}, and an L{ITCPTransport} provider. @type testMethod: 3-argument C{function} @return: a no-argument test method. @rtype: 1-argument C{function} c~tGfddt}|}t|ty)NceZdZfdZy)BoneTransportTest..actualTestMethod..ServerProtocolc |j|j|j|jjjjjyy#|j|jjjjjwwxYwrY)rrKloseConnection)rtbuilderother testMethods r\rzQoneTransportTest..actualTestMethod..ServerProtocol.connectionMade,s9w dnnE~~155726683~~155726683s A//AB>Nrrrr)rrrsr\ServerProtocolr+s 9r[r)r:rAr)rrserverProtocolrrs` @r\actualTestMethodz*oneTransportTest..actualTestMethod's7#% 9 90 9() Mr[r)rrs` r\oneTransportTestrs&  :NN r[ctj|r!|j||jy|j||j|j |j y)a^ Use the given test to assert that the given transport is actively reading in the given reactor. @note: Maintainers; for more information on why this is a function rather than a method on a test case, see U{this document on how we structure test tools } @param testCase: a test case to perform the assertion upon. @type testCase: L{TestCase} @param reactor: A reactor, possibly one providing L{IReactorFDSet}, or an IOCP reactor. @param transport: An L{ITCPTransport} N)r)rir2rhandlesrreadingrrrKs r\ assertReadingr;sU$()W%7%7%9: )W__5I--.r[ctj|r!|j||jy|j |j y)ae Use the given test to assert that the given transport is I{not} actively reading in the given reactor. @note: Maintainers; for more information on why this is a function rather than a method on a test case, see U{this document on how we structure test tools } @param testCase: a test case to perform the assertion upon. @type testCase: L{TestCase} @param reactor: A reactor, possibly one providing L{IReactorFDSet}, or an IOCP reactor. @param transport: An L{ITCPTransport} N)r)ri assertNotInrrrrs r\assertNotReadingrUsA$(Y(:(:(<= Y../r[cXeZdZdZefZdZedZedZ edZ dZ dZ y) TCPConnectionTestsBuilderzP Builder defining tests relating to L{twisted.internet.tcp.Connection}. c t jx _ddg} jj}||vrt j r tdt _ t _ t _ jd }|jj} fd}fd t! d|}t#}t$|_ t'|j)| jgj+||}|j-t.j0j3 y) zt This test verifies transport socket read state after multiple pause/resumeProducing calls. Glib2Reactor Gtk2Reactorz.This test is broken on gtk/glib under Windows.rc j|dj|d|dd|ddf}|djjddzddzzjj ||j fdS)zL Send several IOCPReactor's buffers' worth of data. rrx yc$jSrYr4rss r\r]zRTCPConnectionTestsBuilder.test_stopStartReading..proceed..s GLLNr[)rrKrr5r9)protosrlcleanuprrtsfs r\proceedz@TCPConnectionTestsBuilder.test_stopStartReading..proceeds OOF1I & OOF1I &AYq\6!9Q</F 1I   % %dh&7$(:K&K L77&&w=II* r[cj|ddzddzzdtt|djjt|djjt|j gS)z Make sure IOCPReactor didn't start several WSARecv operations that clobbered each other's results. rrrzdid not get the right datarr)rrrrKrrN)rqrrlrts r\rz@TCPConnectionTestsBuilder.test_stopStartReading..cleanups}   !DH$55,   !&)"5"5"D"DE!&)"5"5"D"DE!$"4"45 r[rN)r1r7rr^rrJ isWindowsrOrrrrr5rrrlrr/r0rrhr9r;rHr<r=) rtskippedReactorsreactorClassNamerrlrcccfdrrrs ` @@@r\test_stopStartReadingz/TCPConnectionTestsBuilder.test_stopStartReadingus _#0022"*)=9",,55  .83E3E3GKL L. :*   a $yy{  $ d ; _ "**R."((3 4 @ @! L SWW  r[cx|jt||||jt|||y)zz When a L{Server} is connected, its C{resumeProducing} method adds it as a reader to the reactor. N)rrrrrtrrs r\test_resumeProducingz.TCPConnectionTestsBuilder.test_resumeProducings4 w/ dGV,r[c^|j|jt|||y)z When a L{Server} has already started disconnecting via C{loseConnection}, its C{resumeProducing} method does not add it as a reader to its reactor. N)rrrrs r\&test_resumeProducingWhileDisconnectingz@TCPConnectionTestsBuilder.test_resumeProducingWhileDisconnectings(  w/r[c|jttdt||||j t|||y)z When a L{Server} has already lost its connection, its C{resumeProducing} method does not add it as a reader to its reactor. dummyN)rrIrrrrs r\%test_resumeProducingWhileDisconnectedz?TCPConnectionTestsBuilder.test_resumeProducingWhileDisconnecteds@ gi&89:w/ w/r[cGddt}Gddt}|}t|||t|j|jgdy)a Alice connects to Bob. Alice writes some bytes and then shuts down the connection. Bob receives the bytes from the connection and then pauses the transport object. Shortly afterwards Bob resumes the transport object. At that point, Bob is notified that the connection has been closed. This is no problem for most reactors. The underlying event notification API will probably just remind them that the connection has been closed. It is a little tricky for win32eventreactor (MsgWaitForMultipleObjects). MsgWaitForMultipleObjects will only deliver the close notification once. The reactor needs to remember that notification until Bob resumes the transport. c$eZdZdZdZdZdZy)QTCPConnectionTestsBuilder.test_connectionLostAfterPausedTransport..Pausercg|_yrY)eventsrs r\ruzZTCPConnectionTestsBuilder.test_connectionLostAfterPausedTransport..Pauser.__init__s   r[c|jjd|jj|jj d|j y)Npausedr)rr}rKrrrresumers r\rz^TCPConnectionTestsBuilder.test_connectionLostAfterPausedTransport..Pauser.dataReceiveds< ""8,--/ &&q$++6r[cn|jjd|jjy)Nresumed)rr}rKrrs r\rzXTCPConnectionTestsBuilder.test_connectionLostAfterPausedTransport..Pauser.resumes$ ""9-..0r[cf|jjdtj||y)Nlost)rr}r:rrtr.s r\rz`TCPConnectionTestsBuilder.test_connectionLostAfterPausedTransport..Pauser.connectionLosts$ ""6*#224@r[N)rrrrurrrrZr[r\Pauserrs ! 7  1 Ar[rceZdZdZy)QTCPConnectionTestsBuilder.test_connectionLostAfterPausedTransport..Clientcn|jjd|jjy)Nssome bytes for you)rKrrrs r\rz`TCPConnectionTestsBuilder.test_connectionLostAfterPausedTransport..Client.connectionMades%$$%:;--/r[NrrZr[r\Clientrs 0r[r)rrrN)r:rArrr)rtrrpausers r\'test_connectionLostAfterPausedTransportzATCPConnectionTestsBuilder.test_connectionLostAfterPausedTransportsN  A( A$ 0( 0 ffh E (EFr[cttGddt}Gddt}t|||t y)a- If one side half-closes its connection, and then the other side of the connection calls C{loseWriteConnection}, and then C{loseConnection} in {writeConnectionLost}, the connection is closed correctly. This rather obscure case used to fail (see ticket #3037). ceZdZdZdZy)HTCPConnectionTestsBuilder.test_doubleHalfClose..ListenerProtocolc8|jjyrY)rKloseWriteConnectionrs r\readConnectionLostz[TCPConnectionTestsBuilder.test_doubleHalfClose..ListenerProtocol.readConnectionLosts224r[c8|jjyrYrKrrs r\writeConnectionLostz\TCPConnectionTestsBuilder.test_doubleHalfClose..ListenerProtocol.writeConnectionLost--/r[N)rrrrrrZr[r\ListenerProtocolrs  5 0r[r ceZdZdZy)>TCPConnectionTestsBuilder.test_doubleHalfClose..Clientc8|jjyrYrrs r\rzMTCPConnectionTestsBuilder.test_doubleHalfClose..Client.connectionMade rr[NrrZr[r\rr  s 0r[rN)rr%r:rAr)rtr rs r\test_doubleHalfClosez.TCPConnectionTestsBuilder.test_doubleHalfClosesI + , 02 0 - 0 0( 0 &6&8&(JLQr[N) rrrrr+r{rrrrrrr rZr[r\rrns`&6!p--0000)GVRr[rcReZdZUdZefZeeee e d<dZ dZ dZ dZdZy) WriteSequenceTestsMixinzM Test for L{twisted.internet.abstract.FileDescriptor.writeSequence}. r{c<t|dd||_y||_y)z Set the write buffer size for the given transport, mananing possible differences (ie, IOCP). Bug #4322 should remove the need of that hack. writeBufferSizeN)rr bufferSize)rtrKvalues r\setWriteBufferSizez*WriteSequenceTestsMixin.setWriteBufferSizes$ 9/ 6 B(-I %#(I r[cfd}j}j|dtj}|j ||j t jj|y)zV C{writeSequence} sends the data even if C{write} hasn't been called. ch|\}}fd}||_jjgdy)Nctjd|zj|djj y)Nzdata received: %rsSome sequence splitted)rHrRrrKr)rqrirts r\rz^WriteSequenceTestsMixin.test_writeSequeceWithoutWrite..connected..dataReceived+s8+d23  '@A  //1r[)sSome s sequence ssplitted)rrKr) protocolsrrlrrirts @r\r2zHWriteSequenceTestsMixin.test_writeSequeceWithoutWrite..connected(s3#, FFD 2 #/F     * *+P Qr[rN r7getConnectedClientAndServerrfrr9r;rHr<r=rtr2rrs` r\test_writeSequeceWithoutWritez5WriteSequenceTestsMixin.test_writeSequeceWithoutWrite#sY R##%  , ,Wk6>> R i  SWW  r[cfd}j}j|dtj}|j ||j t jj|y)zo C{writeSequence} with an element in the sequence of type unicode raises C{TypeError}. c|\}}}jt|jjdg}j t |d|jj y)NzUnicode is not kosherzData must be bytes)rj TypeErrorrKrrrr)rrirrlexcrts r\r2zWWriteSequenceTestsMixin.test_writeSequenceWithUnicodeRaisesException..connected@s_#, FFD##6++99> R i  SWW  r[czttGdd}|fd}j}j|dtj }|j ||jtjj|jjddgy)z{ C{writeSequence} pauses its streaming producer if too much data is buffered, and then resumes it. c,eZdZdZdZdZdZdZdZy)JWriteSequenceTestsMixin.test_streamingProducer..SaveActionProducerNcg|_yrYactionsrs r\ruzSWriteSequenceTestsMixin.test_streamingProducer..SaveActionProducer.__init__\ ! r[c:|jjdy)Npauser'r}rs r\rzYWriteSequenceTestsMixin.test_streamingProducer..SaveActionProducer.pauseProducing_s ##G,r[c|jjd|jjj |j jj y)Nr)r'r}rirKunregisterProducerrrrs r\rzZWriteSequenceTestsMixin.test_streamingProducer..SaveActionProducer.resumeProducingbsB ##H- %%88:  %%446r[c:|jjdyNr5r+rs r\ stopProducingzXWriteSequenceTestsMixin.test_streamingProducer..SaveActionProducer.stopProducingl ##F+r[) rrrrirrurrr0rZr[r\SaveActionProducerr$Ws FF " - 7 ,r[r2cR|dd\}}|_|_|jjdj j gj |jd|jjdgdzj j dgy)NrDT2xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxr*)rirrKregisterProducerrr'rr)rrirproducerrts r\r2zAWriteSequenceTestsMixin.test_streamingProducer..connectedqs&r]NFF$HO$HO    - -h =   X--r 2  # #F$4$4c :    * *I;+; <   X--y 9r[rr*rN) rr(r7rrfrr9r;rHr<r=rr')rtr2r2rrr8s` @r\test_streamingProducerz.WriteSequenceTestsMixin.test_streamingProducerQs ] # , , $ ,.&' :##%  , ,Wk6>> R i  SWW   ))GX+>?r[cttGfdd}|fd}j}j|dtj }|j ||jtjj|jjddgy)z C{writeSequence} pauses its producer if too much data is buffered only if this is a streaming producer. c(eZdZdZdZfdZdZy)MWriteSequenceTestsMixin.test_nonStreamingProducer..SaveActionProducerNcg|_yrYr&rs r\ruzVWriteSequenceTestsMixin.test_nonStreamingProducer..SaveActionProducer.__init__r(r[c`|jjd|jjddk(r%|jjj yj |jjd|jjjdgdzy)NrrDr4r5r6)r'r}rrirK stopConsumingrr)rtrs r\rz]WriteSequenceTestsMixin.test_nonStreamingProducer..SaveActionProducer.resumeProducings{ ##H-<<%%h/14KK))779++DKK,A,A3GKK))77 b8HIr[c:|jjdyr/r+rs r\r0z[WriteSequenceTestsMixin.test_nonStreamingProducer..SaveActionProducer.stopProducingr1r[)rrrrirurr0)rsr\r2r<sF " J ,r[r2c|d}|_|jjdjjdgy)NrFr)rirKr7rr')rrir8rts r\r2zDWriteSequenceTestsMixin.test_nonStreamingProducer..connectedsCq\F$HO    - -h >   X--z :r[rrN) rr'r7rrfrr9r;rHr<r=rr')rtr2r2rrr8rs` @@r\test_nonStreamingProducerz1WriteSequenceTestsMixin.test_nonStreamingProducers  ] # , , $ ,"&' ;##%  , ,Wk6>> R i  SWW   ))Hh+?@r[N)rrrrr+r{r r r r rrrr!r9rBrZr[r\rrsB@Kn$y/!:;L)!.!.3@j*Ar[rc@eZdZdZdZdZdZeee dZ y)"TCPTransportServerAddressTestMixinzE Test mixing for TCP server address building and log prefix. ct)z Helper method returnine a L{Deferred} firing with a tuple of a client protocol, a server protocol, and a running TCP port. )NotImplementedError)rtrrrs r\rz>TCPTransportServerAddressTestMixin.getConnectedClientAndServers "##r[cfd}j}j||}|j||jtj j |y)zT Helper method to test TCP server addresses on either IPv4 or IPv6. cz|\}}} jd|jjd|jjdt |jjd|jjd|jj |jj\}j|jd|jj|j|jjy#|jjwxYw)NzzAccumulatingProtocol,,rW) rrK sessionnorrlrlogstrr peerAddressesrlrrkr)rrirrlr adressClassrrts r\r2zHTCPTransportServerAddressTestMixin._testServerAddress..connecteds#, FFD 2  ''114<<>3F3FH(()   ''119>$$++ !' < < %%k;?   (8(89  K,<,<=  //1  //1s C:DD:N)r7rr9r;rHr<r=)rtrrrNr2rrs`` ` r\_testServerAddressz5TCPTransportServerAddressTestMixin._testServerAddresssT  2.##%  , ,Wi O i  SWW  r[cL|jdtjtS)z L{Server} instances have a string representation indicating on which port they're running, and the connected address is stored on the C{peerAddresses} attribute of the factory. r)rOrfrrrs r\test_serverAddressTCP4z9TCPTransportServerAddressTestMixin.test_serverAddressTCP4s &&{FNNKPPr[c\|jttjtS)z IPv6 L{Server} instances have a string representation indicating on which port they're running, and the connected address is stored on the C{peerAddresses} attribute of the factory. )rOrarfrrrs r\test_serverAddressTCP6z9TCPTransportServerAddressTestMixin.test_serverAddressTCP6s%&& # %v   r[N) rrrrrrOrQr rrrSrZr[r\rDrDs3$ !DQ Hn% & r[rDceZdZdZdZy)TCPTransportTestsBuilderzT Test standard L{ITCPTransport}s built with C{listenTCP} and C{connectTCP}. c t}t|_t|_t }t|_t|_j d|| t |j|jg}fd}|j|t |j|jg}t fd} |j| j| jj| S)z Return a L{Deferred} firing with a L{MyClientFactory} and L{MyServerFactory} connected pair, and the listening C{Port}. rrc(j|SrYr4rrs r\r5zBTCPTransportTestsBuilder.getConnectedClientAndServer..stop s LLNMr[c|\}}tjd|ztjd|zj||fyNzclient connected %szserver connected %srHrRrrrirrrls r\startzCTCPTransportTestsBuilder.getConnectedClientAndServer..start E&NFF GG)F2 3 GG)F2 3   vvt4 5r[) rNrrr8rMrrrur9rrrl) rtrrrrri lostDeferredr5 startDeferredr]rrls ` @@r\rz4TCPTransportTestsBuilder.getConnectedClientAndServers !"(0 %(0 % "(0 %(0 %  Fi @$  * *F,I,I J   T"%  * *F,I,I J : 6 !!%(9dlln&9&96Br[N)rrrrrrZr[r\rUrUs )r[rUceZdZdZeefZdZy)!AdoptStreamConnectionTestsBuilderzF Test server transports built using C{adoptStreamConnection}. c t}t|_t t _t _t }t|_t|_j d||  fd}|jj |t|j jg}fd}|j|t j|t|j jg} fd} | j | j| jj| S)a0 Return a L{Deferred} firing with a L{MyClientFactory} and L{MyServerFactory} connected pair, and the listening C{Port}. The particularity is that the server protocol has been obtained after doing a C{adoptStreamConnection} against the original server connection. rrcj|jj|jj|jj yrY)rrKradoptStreamConnectionr)r,rrrs r\firtServerConnectedzZAdoptStreamConnectionTestsBuilder.getConnectedClientAndServer..firtServerConnectedE sI   1   1  ) )&&(- r[c@jrj|SrY)r3r5rXs r\r5zKAdoptStreamConnectionTestsBuilder.getConnectedClientAndServer..stopR s Mr[c|\}}tjd|ztjd|zj||fyrZr[r\s r\r]zLAdoptStreamConnectionTestsBuilder.getConnectedClientAndServer..start` r^r[) rNrrr8rMrr9rrur;rrrl)rtrrr firstServerrirfr_r5r`r]rrlrs ` ` @@@r\rz=AdoptStreamConnectionTestsBuilder.getConnectedClientAndServer1 s &' -5Z * "(0 %(0 % "(0 %(0 %  K9 E  **667JK$  * *F,I,I J   T":D!%  * *F,I,I J  6 !!%(9dlln&9&96Br[N)rrrrr)r*r{rrZr[r\rbrb( s(88r[rbceZdZdZdZy)ServerAbortsTwicez' Call abortConnection() twice. cl|jj|jjyrY)rKabortConnectionrss r\rzServerAbortsTwice.dataReceived| s" &&( &&(r[NrrZr[r\rkrkw )r[rkceZdZdZdZy)ServerAbortsThenLosesz> Call abortConnection() followed by loseConnection(). cl|jj|jjyrY)rKrmrrss r\rz"ServerAbortsThenLoses.dataReceived s" &&( %%'r[NrrZr[r\rprp (r[rpceZdZdZdZy)AbortServerWritingProtocolz4 Protocol that writes data upon connection. c:|jjdy)zW Tell the client that the connection is set up and it's time to abort. sreadyNrKrrs r\rz)AbortServerWritingProtocol.connectionMade s X&r[NrrrrrrZr[r\rtrt s 'r[rtceZdZdZdZy)ReadAbortServerProtocolz Server that should never receive any data, except 'X's which are written by the other side of the connection before abortConnection, and so might possibly arrive. c>|jddr tdy)NXr[zUnexpectedly received data.)replacerrss r\rz$ReadAbortServerProtocol.dataReceived s! <<c "9: : #r[NrrZr[r\ryry s  ;r[ryceZdZdZdZy) NoReadServerz Stop reading immediately on connection. This simulates a lost connection that will cause the other side to time out, and therefore call abortConnection(). c8|jjyrY)rK stopReadingrs r\rzNoReadServer.connectionMade s ""$r[NrwrZr[r\r~r~ s %r[r~c0eZdZdZdZdZdZdZdZdZ y)EventualNoReadServerz Like NoReadServer, except we Wait until some bytes have been delivered before stopping reading. This means TLS handshake has finished, where applicable. Fc|js?d|_|jj|d|jjdyy)NTFhello)gotDatarKr7rrss r\rz!EventualNoReadServer.dataReceived s;||DL NN + +D% 8 NN  *r[c`|jryd|_|jjyNT)stoppedReadingrKrrs r\rz$EventualNoReadServer.resumeProducing s&    " ""$r[cyrYrZrs r\rz#EventualNoReadServer.pauseProducing  r[cyrYrZrs r\r0z"EventualNoReadServer.stopProducing rr[N) rrrrrrrrrr0rZr[r\rr s' GN+ %  r[rceZdZdZdZdZy)BaseAbortingClientz/ Base class for abort-testing clients. Fc^|jr tdtj||y)Nz,BUG: connectionLost was called re-entrantly!)inReactorMethod RuntimeErrorr:rrs r\rz!BaseAbortingClient.connectionLost s'   MN N**48r[N)rrrrrrrZr[r\rr sO9r[rceZdZdZdZy)WritingButNotAbortingClientz& Write data, but don't abort. c:|jjdy)Nrrvrs r\rz*WritingButNotAbortingClient.connectionMade s X&r[NrwrZr[r\rr s 'r[rceZdZdZdZdZy)AbortingClientz9 Call abortConnection() after writing some data. c@d|_|jd|_y)zF Some data was received, so the connection is set up. TFN)r writeAndAbortrss r\rzAbortingClient.dataReceived s  $ $r[c|jjddz|jj|jjddzy)Nr{i'Y)rKrrmrs r\rzAbortingClient.writeAndAbort s@ TE\* &&( TE\*r[N)rrrrrrrZr[r\rr s%+r[rceZdZdZdZy)AbortingTwiceClientz@ Call abortConnection() twice, after writing some data. cbtj||jjyrY)rrrKrmrs r\rz!AbortingTwiceClient.writeAndAbort s $$T* &&(r[NrrrrrrZr[r\rr rnr[rceZdZdZdZy)AbortingThenLosingClientz; Call abortConnection() and then loseConnection(). cbtj||jjyrY)rrrKrrs r\rz&AbortingThenLosingClient.writeAndAbort s $$T* %%'r[NrrZr[r\rr rrr[rc6eZdZdZdZdZdZdZdZdZ dZ y ) ProducerAbortingClientzA Call abortConnection from doWrite, via resumeProducing. TFc|jjddzd|_|jj|dd|_y)NslalalaiTF)rKrinRegisterProducerr7rs r\rzProducerAbortingClient.write s= Y/0"& ''e4"'r[c$|jyrYrrs r\rz%ProducerAbortingClient.connectionMade  r[cld|_|js|jjd|_y)NTF)rrrKrmrs r\rz&ProducerAbortingClient.resumeProducing s+#&& NN * * ,$r[cd|_yr)producerStoppedrs r\r0z$ProducerAbortingClient.stopProducing$ s #r[c|js td|jr tdtj||y)Nz&BUG: stopProducing() was never called.z(BUG: connectionLost called re-entrantly!)rrrr:rrs r\rz%ProducerAbortingClient.connectionLost' s<##GH H   IJ J**48r[N) rrrrrrrrrr0rrZr[r\rr s,OO( % $9r[rcFeZdZdZdZdZdZdZdZdZ dZ dZ d Z d Z y ) StreamingProducerClienta Call abortConnection() when the other side has stopped reading. In particular, we want to call abortConnection() only once our local socket hits a state where it is no longer writeable. This helps emulate the most common use case for abortConnection(), closing a connection after a timeout, with write buffers being full. Since it's very difficult to know when this actually happens, we just write a lot of data, and assume at that point no more writes will happen. Frc$|jyrYrrs r\rz&StreamingProducerClient.connectionMade@ rr[c|jj|dtdD] }|jjddz"y)zh Write large amount to transport, then wait for a while for buffers to fill up. Tds 1234567890i}N)rKr7ranger)rtis r\rzStreamingProducerClient.writeC sB ''d3s 8A NN !6 7 8r[cd|_y)NF)rrs r\rz'StreamingProducerClient.resumeProducingL s  r[cyrYrZrs r\r0z%StreamingProducerClient.stopProducingO rr[cx|jryd|_|jjd|jy)a& Called when local buffer fills up. The goal is to hit the point where the local file descriptor is not writeable (or the moral equivalent). The fact that pauseProducing has been called is not sufficient, since that can happen when Twisted's buffers fill up but OS hasn't gotten any writes yet. We want to be as close as possible to every buffer (including OS buffers) being full. So, we wait a bit more after this for Twisted to write out a few chunks, then abortConnection. NTg{Gz?)rrrdoAbortrs r\rz&StreamingProducerClient.pauseProducingR s/ ;;   tT\\2r[c|jstjtdd|_|j j d|_y)Nz&BUG: We should be paused a this point.TF)rrHr<rrrKrmrs r\rzStreamingProducerClient.doAbortg s;{{ GGL!IJ K# &&($r[cx|jjjtj||yrY) otherProtocolrK startReadingr:rrs r\rz&StreamingProducerClient.connectionLostn s* $$113**48r[N)rrrrr extraWritesrrrrr0rrrrZr[r\rr/ s; FKO8 3*%9r[rceZdZdZdZdZy)StreamingProducerClientLaterzX Call abortConnection() from dataReceived, after bytes have been exchanged. cH|jjdd|_y)NrF)rKrrrs r\rz+StreamingProducerClientLater.connectionMadez s X& r[cL|jsd|_|jyyr)rrrss r\rz)StreamingProducerClientLater.dataReceived~ s||DL JJLr[NrrrrrrrZr[r\rrt s r[rceZdZdZdZdZy)ProducerAbortingClientLaterz Call abortConnection from doWrite, via resumeProducing. Try to do so after some bytes have already been exchanged, so we don't interrupt SSL handshake. cyrYrZrs r\rz*ProducerAbortingClientLater.connectionMade s r[c$|jyrYrrss r\rz(ProducerAbortingClientLater.dataReceived rr[NrrZr[r\rr s r[rceZdZdZdZy)DataReceivedRaisingClientzN Call abortConnection(), and then throw exception, from dataReceived. cL|jjtd)NONO)rKrmZeroDivisionErrorrss r\rz&DataReceivedRaisingClient.dataReceived s &&(&&r[NrrZr[r\rr s 'r[rceZdZdZdZdZy)ResumeThrowsClientzL Call abortConnection() and throw exception from resumeProducing(). cf|js%|jjtdy)Nzono!)rrKrmrrs r\rz"ResumeThrowsClient.resumeProducing s+&& NN * * ,#F+ +'r[c0tj||yrY)r:rrs r\rz!ResumeThrowsClient.connectionLost s **48r[N)rrrrrrrZr[r\rr s, 9r[rceZdZUdZdZeeed<ddZdZ dZ dZ dZ d Z eej j#d d j%d k(xrej(d dZeej j#d d j%d k(xrej(d dZdZdZdZdZy)AbortConnectionMixinz7 Unit tests for L{ITransport.abortConnection}. Nrcjttf}ttf}tr(|tj fz}|tj fz}|}|}||_||_t||||j}|j|jg|j|jg|+|j|jj|f|zn&|j|jj||j|jj|y)z A test runner utility function, which hooks up a matched pair of client and server protocols. We then run the reactor until both sides have disconnected, and then verify that the right exception resulted. N)rrrrrRErrorrrArrrgetDelayedCallsrldisconnectReasonr) rt clientClass serverClassclientConnectionLostReasonclientExpectedExceptionsserverExpectedExceptionsrirrs r\ runAbortTestz!AbortConnectionMixin.runAbortTest s%6~#F $2N#C  '?399,'N $'?399,'N $%%)$O **,b1 002B7 % 1  ! !''--+-0HH   ! !''--/G  f55;;=UVr[c6|jttS)z abortConnection() is called in dataReceived. The protocol should be disconnected, but connectionLost should not be called re-entrantly. )rrryrs r\test_dataReceivedAbortz+AbortConnectionMixin.test_dataReceivedAbort s   1HIIr[c6|jttS)z abortConnection() is called twice by client. No exception should be thrown, and the connection will be closed. )rrryrs r\ test_clientAbortsConnectionTwicez5AbortConnectionMixin.test_clientAbortsConnectionTwice s   !46MNNr[c6|jttS)z Client calls abortConnection(), followed by loseConnection(). No exception should be thrown, and the connection will be closed. )rrryrs r\.test_clientAbortsConnectionThenLosesConnectionzCAbortConnectionMixin.test_clientAbortsConnectionThenLosesConnection s   !9;RSSr[cB|jtttS)z abortConnection() is called twice by server. No exception should be thrown, and the connection will be closed. r)rrrkrrs r\ test_serverAbortsConnectionTwicez5AbortConnectionMixin.test_serverAbortsConnectionTwice s%   ' '5!  r[cB|jtttS)z Server calls abortConnection(), followed by loseConnection(). No exception should be thrown, and the connection will be closed. r)rrrprrs r\.test_serverAbortsConnectionThenLosesConnectionzCAbortConnectionMixin.test_serverAbortsConnectionThenLosesConnection s%   ' !'5!  r[CIrUtruezFlaky on macOS on Azure.c8|jtty)z abortConnection() is called in resumeProducing, before any bytes have been exchanged. The protocol should be disconnected, but connectionLost should not be called re-entrantly. N)rrr:rs r\test_resumeProducingAbortz.AbortConnectionMixin.test_resumeProducingAbort s 02EFr[c6|jttS)z abortConnection() is called in resumeProducing, after some bytes have been exchanged. The protocol should be disconnected. )rrrtrs r\test_resumeProducingAbortLaterz3AbortConnectionMixin.test_resumeProducingAbortLater s  ')C  r[c8|jtty)a{ abortConnection() triggered by the write buffer being full. In particular, the server side stops reading. This is supposed to simulate a realistic timeout scenario where the client notices the server is no longer accepting data. The protocol should be disconnected, but connectionLost should not be called re-entrantly. N)rrr~rs r\test_fullWriteBufferz)AbortConnectionMixin.test_fullWriteBuffer( s 1<@r[c6|jttS)z abortConnection() is triggered by a write buffer being full. However, this buffer is filled after some bytes have been exchanged, allowing a TLS handshake if we're testing TLS. The connection will then be lost. )rrrrs r\%test_fullWriteBufferAfterByteExchangez:AbortConnectionMixin.test_fullWriteBufferAfterByteExchange5 s  !=?STTr[c|jttt|j t}|j t |dy)aJ dataReceived calls abortConnection(), and then raises an exception. The connection will be lost, with the thrown exception (C{ZeroDivisionError}) as the reason on the client. The idea here is that bugs should not be masked by abortConnection, in particular unexpected exceptions. rrN)rrrtrflushLoggedErrorsrr~rterrorss r\test_dataReceivedThrowsz,AbortConnectionMixin.test_dataReceivedThrows? sG  % &'8  ''(9: Va(r[c|jttt|j t}|j t |dy)aM resumeProducing calls abortConnection(), and then raises an exception. The connection will be lost, with the thrown exception (C{ZeroDivisionError}) as the reason on the client. The idea here is that bugs should not be masked by abortConnection, in particular unexpected exceptions. rrN)rrr:rrrr~rs r\test_resumeProducingThrowsz/AbortConnectionMixin.test_resumeProducingThrowsP sG   '8  ''(9: Va(r[rY)rrrrrr r<rrrrrrrr renvirongetlowerrJisMacOSXrrrrrrrZr[r\rr s ,0Ix(/#WJJOT      tR &&(F2J7Hx7H7H7J"G G  tR &&(F2J7Hx7H7H7J"   AU)")r[rc$eZdZdZefZeZy)AbortConnectionTestsz5 TCP-specific L{AbortConnectionMixin} tests. N)rrrrr+r{rrrZr[r\rrb s& Ir[rcXeZdZdZdZeejddZdZ y)SimpleUtilityTestszJ Simple, direct tests for helpers within L{twisted.internet.tcp}. c|jtjtdd}|j |j dtj y)a L{_resolveIPv6} raises a L{socket.gaierror} (L{socket.EAI_NONAME}) when invoked with a non-numeric host. (In other words, it is passing L{socket.AI_NUMERICHOST} to L{socket.getaddrinfo} and will not accidentally block if it receives bad input.) localhostrrNrjrfgaierrorr8rr EAI_NONAMErtr<s r\test_resolveNumericHostz*SimpleUtilityTests.test_resolveNumericHostu s<{AN !f&7&78r[z@The AI_NUMERICSERV flag is not supported by Microsoft providers.c|jtjtdd}|j |j dtj y)a L{_resolveIPv6} raises a L{socket.gaierror} (L{socket.EAI_NONAME}) when invoked with a non-numeric port. (In other words, it is passing L{socket.AI_NUMERICSERV} to L{socket.getaddrinfo} and will not accidentally block if it receives bad input.) rThttprNrrs r\test_resolveNumericServicez-SimpleUtilityTests.test_resolveNumericService s<ufM !f&7&78r[ctdd}|jt|d|j|dt|j|dt|j|dddy)zb L{_resolveIPv6} discovers the flow info and scope ID of an IPv6 address. rTrDrerN)rTrD)r8rr~rlrrs r\test_resolveIPv6z#SimpleUtilityTests.test_resolveIPv6 sf eQ' Va( fQi- fQi- Z0r[N) rrrrrr rJrrr rZr[r\rro s;9 J 9  91r[rc(eZdZdZdZdZdZdZy)BuffersLogsTestsz$ Tests for L{_BuffersLogs}. c~d|_g|_t|j|jj|_y)Nz name.space) namespacerr4r} logBufferrs r\rzBuffersLogsTests.setUp s,% %dnndkk6H6HIr[c|j5}|jd|j|jdddy#1swYyxYw)zj The context manager's logger does not log to provided observer inside the block. An eventN)rrrr)rtloggers r\test_buffersInBlockz$BuffersLogsTests.test_buffersInBlock s@ ^^ *v KK #   T[[ ) * * *s -AA cl|j5}|jd|j|jddd|j dt |j|j\}|j |dd|j |d|j y#1swYqxYw)zw The context manager flushes its buffered logs when the block terminates without an exception. rNr log_format log_namespace)rrrrrr~r )rtrevents r\test_flushesOnExitz#BuffersLogsTests.test_flushesOnExit s ^^ *v KK #   T[[ ) * C ,-++ |,j9 /@  * *s -B**B3cGddt}|j|5|j5}|jd|j |j |#1swYnxYw dddn #1swYnxYw|j dt|j |j \}|j |dd|j |d|jy)zz The context manager flushes its buffered logs when the block terminates because of an exception. ceZdZdZy)GBuffersLogsTests.test_flushesOnExitWithException..TestExceptionz@ An exception only raised by this test. NrrrrrZr[r\ TestExceptionr  r[rrNrrr) rrjrrrrrr~r )rtrrrs r\test_flushesOnExitWithExceptionz0BuffersLogsTests.test_flushesOnExitWithException s  I    } - & &6 J'  -#o% & & & & & & C ,-++ |,j9 /@s A84A""A+ 'A88BN)rrrrrrrrrZr[r\r r  sJ * AAr[r cLeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z y ) FileDescriptorReservationTestsz2 Tests for L{_FileDescriptorReservation}. chg_j_fd}t|_y)NcjjtjdjdS)NwrV)reservedFileObjectsr}rtempfilersr\fakeFileFactoryz=FileDescriptorReservationTests.setUp..fakeFileFactory s3  $ $ + +D,D E++B/ /r[)r$mktempr%r5 reservedFD)rtr&s` r\rz$FileDescriptorReservationTests.setUp s+#%    05_Er[c8tt|jy)zi L{_FileDescriptorReservation} instances provide L{_IFileDescriptorReservation}. N)rr6r(rs r\rz5FileDescriptorReservationTests.test_providesInterface s 0$//Br[c<|jt|jdtdD]i}|jj |jt|jd|j |jdjky)zh Multiple acquisitions without releases open the reservation file exactly once. rrrN)rr~r$rr(reserverr)rtrs r\test_reserveOpensFileOncez8FileDescriptorReservationTests.test_reserveOpensFileOnce s~ T556:r AA OO # # %   S!9!9:A >   T55a8?? @ Ar[ct}|j|j|j|j |j j |j j|j |j j |jtt}|jt|d|j|djjtjy)z If reserving the file descriptor fails because of C{EMFILE}, the exception is suppressed but logged and the reservation remains unavailable. rrN)rrrrrr( availabler+rrrrr~rrr)rtrrs r\test_reserveEMFILELoggedz7FileDescriptorReservationTests.test_reserveEMFILELogged s -.   ))* 2245 ! 2245''9 Va( .. =r[ctttfD].}|fd}t|}|j ||j 0y)z Any exception raised while opening the reserve file that is not an L{OSError} or L{IOError} whose errno is C{EMFILE} is allowed through to the caller. c6|tjdzd)Nrr)rr) errorClasss r\ failsWithzWFileDescriptorReservationTests.test_reserveRaisesNonEMFILEExceptions..failsWith s !19==r[N)rrrkr5rjr+)rtr2r3 reserveFDs r\%test_reserveRaisesNonEMFILEExceptionszDFileDescriptorReservationTests.test_reserveRaisesNonEMFILEExceptions sF #GZ8 =J&0 >39=I   j)*;*; < =r[c|j|jj|jj|j |jjy)z] The reservation is available after the file descriptor is reserved. N)rr(r.r+rrs r\test_availablez-FileDescriptorReservationTests.test_available sH 2245 ! 1134r[c|jt5|j5 ddddddy#1swYxYw#1swYyxYw)zp A reservation without an open file used as a context manager raises a L{RuntimeError}. N)rjrr(rs r\test_enterFailsWithoutFilez9FileDescriptorReservationTests.test_enterFailsWithoutFile$ sK   | , = =< = = = = = = =s A6A? AA cp|jj|j|jj|j5|j |jjddd|j|jjy#1swY3xYw)zq Entering a reservation closes its file for the duration of the context manager's block. N)r(r+rr.rrs r\!test_enterClosesFileExitOpensFilez@FileDescriptorReservationTests.test_enterClosesFileExitOpensFile- s} ! 1134 __ :   T__668 9 : 1134 : :s *B,,B5cGddt}|jj|j|5|j5|#1swYnxYw dddy#1swYyxYw)z An exception raised within a reservation context manager's block does not prevent the file from being reopened. ceZdZdZy)SFileDescriptorReservationTests.test_exitOpensFileOnException..TestExceptionz> An exception only used by this test. NrrZr[r\rr>> rr[rN)rr(r+rj)rtrs r\test_exitOpensFileOnExceptionz.AllowedExceptionzA The exception allowed out of the block. NrrZr[r\AllowedExceptionrBO rr[rCceZdZdZy)cFileDescriptorReservationTests.test_exitSuppressesReservationException..SuppressedExceptionzM An exception raised by the file descriptor factory. NrrZr[r\SuppressedExceptionrET rr[rFFcNdrdd<tjS)NrT)ioBytesIO)rFcalledsr\+failsWithSuppressedExceptionAfterSecondOpenz{FileDescriptorReservationTests.test_exitSuppressesReservationException..failsWithSuppressedExceptionAfterSecondOpen[ s(ay)++ q zz|#r[Nr) rr5r+rr.rjrrr~)rtrCrKr(rrFrJs @@r\'test_exitSuppressesReservationExceptionzFFileDescriptorReservationTests.test_exitSuppressesReservationExceptionH s y   )   $0 7    ,,./   / 0 ) )&(( ) ) ) ) ) )''(;< Va(s5B8BB BBN)rrrrrrr,r/r5r7r9r;r?rLrZr[r\r r  s<FC A>$ =5= 5& &)r[r c(eZdZdZdZdZdZdZy)"NullFileDescriptorReservationTestsz6 Tests for L{_NullFileDescriptorReservation}. c"t|_yrY)r7nullReservedFDrs r\rz(NullFileDescriptorReservationTests.setUpv s <>r[c8tt|jy)zd L{_NullFileDescriptorReservation} provides L{_IFileDescriptorReservation}. N)rr6rPrs r\rz9NullFileDescriptorReservationTests.test_providesInterfacey s 0$2E2EFr[cV|j|jjy)zG The null reserved file descriptor is never available. NrrPr.rs r\r7z1NullFileDescriptorReservationTests.test_available s! ,,6689r[c<|j|jj|j5|j|jjddd|j|jjy#1swY3xYw)zN The null reserved file descriptor is a null context manager. NrSrs r\test_contextManagerz6NullFileDescriptorReservationTests.test_contextManager sy ,,6689   >   T00::< = > ,,6689 > >s *BBN)rrrrrrr7rUrZr[r\rNrNq s?G: :r[rN)rrrrHrrf functoolsrtypingrrrrr r r unittestr zope.interfacer rzope.interface.verifyrrrtwisted.internet.addressrrtwisted.internet.deferrrrrrrtwisted.internet.endpointsrrtwisted.internet.errorrrrrrr r!r"r#twisted.internet.interfacesr$r%r&r'r(r)r*r+r,r-r.twisted.internet.protocolr/r0r1twisted.internet.tcpr2r3r4r5r6r7r8&twisted.internet.test.connectionmixinsr9r:r;r<r=r>r?r@rA#twisted.internet.test.reactormixinsrBrCrDtwisted.internet.testingrErFtwisted.loggerrGtwisted.pythonrHtwisted.python.failurerItwisted.python.runtimerJtwisted.test.test_tcprKrLrMrNtwisted.trial.unittestrOrPrQOpenSSLrRtwisted.internet.sslrSr ImportErrorsrr}rbrrrrrrtwisted.internet.testrVwin32GetLinkLocalIPv6Addressesr_rUrWposixGetLinkLocalIPv6Addressesrarhrorrrrrrrrrr~rrrrrrrrrrr6rWr[r`rgrrrrrrrrrDrUrbglobalsupdatemakeTestCaseClassesrkrprtryr~rrrrrrrrrrrrrrrr r rNrZr[r\rus  NNN1; =N       ML    D!*+ KJ: F foov'9'9:AFF: HN=GGI82 , K KKP6%1$O$O!K:"$99x3h32 8  ])#)#)#X M,-11X11h-"-"`OO,3*3$ _NNN.MH)=?UMH` / .!7/7"7,p:~p:f 8 .!3 83"3"  : &'TD*D*(D*N PQN6#6N6RN6bYx PQI/$7I/RI/XA 0A HMMB E. E"F."FJGOGOT      2x26!H/402aRaRH^A^AB? ? D0&(?0fA&(?AH ';;=> ';;=> $88:; &::<= *>>@A *>>@A *>>@A )==?@ 2FFHI)+)(/( '!4 ' ;8 ; %& % . < 9, 9'"4'+'+,).)(~(909DB91B9J #:  "8  ''9/9"p)p)f>+? %99;<.!-1-1"-1`4A*4An PQV)%8V)RV)r:)<:]` F0H+A3/N0& /$.!/s< X"8X0Y "X-,X-0Y5YY YY