HEX
Server: Apache
System: Linux scp1.abinfocom.com 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64
User: confeduphaar (1010)
PHP: 8.1.33
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //usr/lib/python3/dist-packages/twisted/internet/test/__pycache__/test_endpoints.cpython-38.pyc
U

��W[�D�@s\dZddlmZmZddlmZddlmZmZm	Z	m
Z
mZddlm
Z
ddlmZddlmZmZmZddlmZdd	lmZmZdd
lmZddlmZddlmZmZdd
lm Z ddl!m"Z"ddl#m$Z$m%Z%m&Z&m'Z'm(Z(ddl#m)Z)m*Z*m+Z+ddl,m-Z-m.Z.m/Z/ddl,m0Z0m1Z1ddl2m3Z3ddl4m5Z5m6Z6m7Z7ddl8m9Z9m:Z:m;Z;ddl<m=Z=ddl>m?Z?ddl@mAZAmBZBddlCmDZDddlEmFZFddlGmHZHddlImJZJddlKmLZLddlMmNZNddlOmPZPmQZQdd lRmSZSmTZTdd!lUmVZVdd"lWmXZXdd#l4mYZYdd$l4mZZZdd%l[m\Z\dd&l]m^Z^eLd'�j_�`d(�ZaeLd'�j_�`d)�ZbeLd'�j_�`d*�ZceLed�j_�`d+�Zeee�fd,�Zge'�heaji�Zje'�hebji�Zke'�hecji�Zle'�heeji�Zme'�hegji�Znzpdd-lompZpdd.lqmrZrmsZsmtZtmuZumvZvdd/lwmxZxdd0lymzZzm{Z{m|Z|m}Z}es�~ea���Z�er�~ea���Z�d1Z�Wne�k
�r4d2Z�YnXGd3d4�d4e:�Z�ee%j��Gd5d6�d6e���Z�ee%j��Gd7d8�d8e���Z�ee%j��Gd9d:�d:e���Z�Gd;d<�d<e9�Z�Gd=d>�d>e9�Z�Gd?d@�d@ej��Z�GdAdB�dBe��Z�GdCdD�dDe��Z�GdEdF�dFe�e��Z�GdGdH�dHe;�Z�GdIdJ�dJe��Z�GdKdL�dLej��Z�GdMdN�dNe(j:�Z�ee%j��GdOdP�dPe e���Z�ee%j5e��ee%j6e��ee%j�e��ee%j��GdQdR�dRe���Z�GdSdT�dTej��Z�GdUdV�dVej��Z�GdWdX�dXej��Z�GdYdZ�dZe�ej��Z�Gd[d\�d\e�ej��Z�Gd]d^�d^e�ej��Z�Gd_d`�d`ee?�Z�d�dcdd�Z�Gdedf�dfej��Z�Gdgdh�dhej��Z�Gdidj�dje��Z�Gdkdl�dle�ej��Z�Gdmdn�dne�ej��Z�Gdodp�dpe�ej��Z�Gdqdr�dre�ej��Z�Gdsdt�dtej��Z�Gdudv�dvej��Z�Gdwdx�dxej��Z�Gdydz�dzej��Z�Gd{d|�d|e�ej��Z�Gd}d~�d~e�ej��Z�Gdd��d�ej��Z�Gd�d��d�ej��Z�d�d�d��Z�Gd�d��d�ej��Z�Gd�d��d�ej��Z�Gd�d��d�e�ej��Z�Gd�d��d�ej��Z�Gd�d��d�ej��Z�Gd�d��d�ej��Z�Gd�d��d�ej��Z�Gd�d��d�eQj�e��Z�Gd�d��d�eQj�e��Z�Gd�d��d�ePj�e��Z�Gd�d��d�e��Z�Gd�d��d�ej��Z�d�d��Z�Gd�d��d�ej��Z�d�d��Z�Gd�d��d�ej��Z�dbS)�z�
Test the C{I...Endpoint} implementations that wrap the L{IReactorTCP},
L{IReactorSSL}, and L{IReactorUNIX} interfaces found in
L{twisted.internet.endpoints}.
�)�division�absolute_import)�EPERM)�AF_INET�AF_INET6�SOCK_STREAM�IPPROTO_TCP�gaierror)�	normalize)�FunctionType)�implementer�
providedBy�provider)�InterfaceClass)�verifyObject�verifyClass)�unittest)�MemoryReactorClock)�RaisingMemoryReactor�StringTransport)� StringTransportWithDisconnection)�plugins)�error�
interfaces�defer�	endpoints�protocol)�reactor�threads�stdio)�IPv4Address�IPv6Address�UNIXAddress)�_ProcessAddress�HostnameAddress)�StandardErrorBehavior)�	IConsumer�
IPushProducer�
ITransport)�
ClientFactory�Protocol�Factory)�PipeAddress)�Clock)�ILogObserver�globalLogPublisher)�
getPlugins)�log)�Failure)�FilePath)�	getModule)�	ListenFDs)�basic�policies)�connectedServerAndClient�connectableEndpoint)�ConnectingCancelledError)�nativeString)�IHostnameResolver)�IReactorPluggableNameResolver)�proxyForInterface)�
isIPv6Addressztwisted.testz
server.pemzkey.pem.no_trailing_newlinezcert.pem.no_trailing_newlineZfake_CAsz	chain.pem)�makeCertificate)�PrivateCertificate�Certificate�CertificateOptions�KeyPair�DiffieHellmanParameters��TLSMemoryBIOFactory)�ContextType�
SSLv23_METHOD�TLSv1_METHOD�OP_NO_SSLv3Fz.OpenSSL is required to construct SSL Endpointsc@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
�TestProtocolzx
    Protocol whose only function is to callback deferreds on the
    factory when it is connected or disconnected.
    cCsg|_g|_d|_dS�Nr)�data�connectionsLost�connectionMadeCalls��self�rS�F/usr/lib/python3/dist-packages/twisted/internet/test/test_endpoints.py�__init__\szTestProtocol.__init__cCsdS)N�A Test ProtocolrSrQrSrSrT�	logPrefixbszTestProtocol.logPrefixcCs|jd7_dS�N�)rPrQrSrSrT�connectionMadefszTestProtocol.connectionMadecCs|j�|�dS�N)rN�append�rRrNrSrSrT�dataReceivedjszTestProtocol.dataReceivedcCs|j�|�dSr[)rOr\�rR�reasonrSrSrT�connectionLostnszTestProtocol.connectionLostN)	�__name__�
__module__�__qualname__�__doc__rUrWrZr^rarSrSrSrTrLVsrLc@s(eZdZdZdd�Zdd�Zdd�ZdS)	�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.
    cCst�|�d|_d|_dS)NF)rLrU�readLost�	writeLostrQrSrSrTrU�s
z"TestHalfCloseableProtocol.__init__cCs
d|_dS�NT)rgrQrSrSrT�readConnectionLost�sz,TestHalfCloseableProtocol.readConnectionLostcCs
d|_dSri)rhrQrSrSrT�writeConnectionLost�sz-TestHalfCloseableProtocol.writeConnectionLostN)rbrcrdrerUrjrkrSrSrSrTrfssrfc@s eZdZdZdd�Zdd�ZdS)�"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.
    cCst�|�g|_dSr[)rLrZ�receivedDescriptorsrQrSrSrTrZ�s
z1TestFileDescriptorReceiverProtocol.connectionMadecCs|j�|�dSr[)rmr\)rRZ
descriptorrSrSrT�fileDescriptorReceived�sz9TestFileDescriptorReceiverProtocol.fileDescriptorReceivedN)rbrcrdrerZrnrSrSrSrTrl�srlc@s eZdZdZdd�Zdd�ZdS)�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}
    cCst�|�d|_dSrM)rLrU�handshakeCompletedCallsrQrSrSrTrU�s
zTestHandshakeListener.__init__cCs|jd7_dS)zk
        Called when a TLS handshake has completed.  Implemented per
        L{IHandshakeListener}
        rYN)rprQrSrSrT�handshakeCompleted�sz(TestHandshakeListener.handshakeCompletedN)rbrcrdrerUrqrSrSrSrTro�s	roc@seZdZdZeZdS)�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)rbrcrdrerLrrSrSrSrTrr�srrc@seZdZdZdd�ZdS)�NoneFactoryzC
    A one off factory whose C{buildProtocol} returns L{None}.
    cCsdSr[rS�rR�addrrSrSrT�
buildProtocol�szNoneFactory.buildProtocolN�rbrcrdrervrSrSrSrTrs�srsc@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,S)-�WrappingFactoryTestszS
    Test the behaviour of our ugly implementation detail C{_WrappingFactory}.
    cCs*t�}t�|�}|��|�d|j�dS)z�
        L{_WrappingFactory.doStart} passes through to the wrapped factory's
        C{doStart} method, allowing application-specific setup and logging.
        rYN)r)r�_WrappingFactoryZdoStart�assertEqual�numPorts�rR�factory�wfrSrSrT�test_doStart�s
z!WrappingFactoryTests.test_doStartcCs0t�}d|_t�|�}|��|�d|j�dS)z�
        L{_WrappingFactory.doStop} passes through to the wrapped factory's
        C{doStop} method, allowing application-specific cleanup and logging.
        ��N)r)r{rryZdoStoprzr|rSrSrT�test_doStop�s

z WrappingFactoryTests.test_doStopcsJGdd�dt�}t�|��}|�d���|jt�}|��fdd��|S)z�
        An exception raised in C{buildProtocol} of our wrappedFactory
        results in our C{onConnection} errback being fired.
        c@seZdZdZdd�ZdS)zCWrappingFactoryTests.test_failedBuildProtocol.<locals>.BogusFactoryzZ
            A one off factory whose C{buildProtocol} raises an C{Exception}.
            cSstd��dS)N�My protocol is poorly defined.)�
ValueErrorrtrSrSrTrv�szQWrappingFactoryTests.test_failedBuildProtocol.<locals>.BogusFactory.buildProtocolNrwrSrSrSrT�BogusFactory�sr�Ncs��|jd�S)N)r�)rz�args)�erQrSrT�<lambda>�s�z?WrappingFactoryTests.test_failedBuildProtocol.<locals>.<lambda>)r)rryrv�
assertFailure�
_onConnectionr��addCallback)rRr�r~�drSrQrT�test_failedBuildProtocol�s
z-WrappingFactoryTests.test_failedBuildProtocolcCs*t�t��}|�d�|�|jtj�dS)z�
        If the wrapped factory's C{buildProtocol} returns L{None} the
        C{onConnection} errback fires with L{error.NoProtocol}.
        N)rryrsrv�failureResultOfr�r�
NoProtocol�rRZwrappingFactoryrSrSrT�test_buildNoneProtocols
z+WrappingFactoryTests.test_buildNoneProtocolcCs0t�t��}|j�dd��|�|�d��dS)z�
        If the wrapped factory's C{buildProtocol} returns L{None} then
        L{endpoints._WrappingFactory.buildProtocol} returns L{None}.
        cSsdSr[rS�r`rSrSrTr��zDWrappingFactoryTests.test_buildProtocolReturnsNone.<locals>.<lambda>N)rryrsr��
addErrback�assertIsNonervr�rSrSrT�test_buildProtocolReturnsNone
sz2WrappingFactoryTests.test_buildProtocolReturnsNonecCs*t�t��}|�d�}|�|��d�dS)z�
        If the wrapped protocol provides L{ILoggingContext}, whatever is
        returned from the wrapped C{logPrefix} method is returned from
        L{_WrappingProtocol.logPrefix}.
        NrV)rryrrrvrzrW)rRr~�wprSrSrT�test_logPrefixPassthroughs
z.WrappingFactoryTests.test_logPrefixPassthroughcCsDGdd�dt�}t�}||_t�|�}|�d�}|�|��d�dS)z�
        If the wrapped protocol does not provide L{ILoggingContext}, the
        wrapped protocol's class name is returned from
        L{_WrappingProtocol.logPrefix}.
        c@seZdZdS)z>WrappingFactoryTests.test_logPrefixDefault.<locals>.NoProtocolN�rbrcrdrSrSrSrTr�*sr�N)�objectrrrrryrvrzrW)rRr�r}r~r�rSrSrT�test_logPrefixDefault$s

z*WrappingFactoryTests.test_logPrefixDefaultcCs^t�t��}|�d�}|�d�|�d�|�|jjdg�|�d�|�|jjddg�dS)z�
        The wrapped C{Protocol}'s C{dataReceived} will get called when our
        C{_WrappingProtocol}'s C{dataReceived} gets called.
        Nsfoosbar)	rryrrrv�makeConnectionr^rz�_wrappedProtocolrN)rRr~�prSrSrT� test_wrappedProtocolDataReceived3s



z5WrappingFactoryTests.test_wrappedProtocolDataReceivedcCsHt�t��}|�d�}t�}|�|�|�|j|�|�|jj|�dS)zo
        Our transport is properly hooked up to the wrappedProtocol when a
        connection is made.
        N)	rryrrrvr�r�rz�	transportr�)rRr~r�ZdummyTransportrSrSrT�test_wrappedProtocolTransportCs

z2WrappingFactoryTests.test_wrappedProtocolTransportcCs:t�}t�|�}|�d�}|�d�|�|jjdg�dS)z�
        Our wrappedProtocol's connectionLost method is called when
        L{_WrappingProtocol.connectionLost} is called.
        N�fail)rrrryrvrarzr�rO)rRZtfr~r�rSrSrT�"test_wrappedProtocolConnectionLostTs



z7WrappingFactoryTests.test_wrappedProtocolConnectionLostcsVt�t��}ttjdd��}|�d|�g��fdd�}|j�|�|�	�|g�dS)z�
        Calls to L{_WrappingFactory.clientConnectionLost} should errback the
        L{_WrappingFactory._onConnection} L{Deferred}
        r���stringNcs��|�dSr[�r\��f��errorsrSrT�gotErrornszBWrappingFactoryTests.test_clientConnectionFailed.<locals>.gotError)
rryrrr2r�ConnectError�clientConnectionFailedr�r�rz)rRr~ZexpectedFailurer�rSr�rT�test_clientConnectionFailedbsz0WrappingFactoryTests.test_clientConnectionFailedcCs>d}t�}t�||�}|�tj�|��|�ttj|��dS)zv
        Our L{_WrappingProtocol} should be an L{IFileDescriptorReceiver} if the
        wrapped protocol is.
        N)rlr�_WrappingProtocol�
assertTruer�IFileDescriptorReceiverr
r)rRZconnectedDeferredZapplicationProtocol�wrapperrSrSrT�+test_wrappingProtocolFileDescriptorReceivervs�
�z@WrappingFactoryTests.test_wrappingProtocolFileDescriptorReceivercCs(t�}t�d|�}|�tj�|��dS)z~
        Our L{_WrappingProtocol} does not provide L{IHalfCloseableProtocol} if
        the wrapped protocol doesn't.
        N)rLrr��assertFalserr�r
�rR�tpr�rSrSrT�.test_wrappingProtocolNotFileDescriptorReceiver�szCWrappingFactoryTests.test_wrappingProtocolNotFileDescriptorReceivercCs@t�}t�t��|�}|�t��|�d�|�|j	dg�dS)z�
        L{_WrappingProtocol.fileDescriptorReceived} calls the wrapped
        protocol's C{fileDescriptorReceived} method.
        �*N)
rlrr�r�Deferredr�rrnrzrm)rRZwrappedProtocolr�rSrSrT�*test_wrappedProtocolFileDescriptorReceived�s�
z?WrappingFactoryTests.test_wrappedProtocolFileDescriptorReceivedcCs0t�}t�}t�||�}|�tj�|�d�dS)zw
        Our L{_WrappingProtocol} should be an L{IHalfCloseableProtocol} if the
        C{wrappedProtocol} is.
        TN)r�rfrr�rzr�IHalfCloseableProtocolr
)rRZcd�hcpr�rSrSrT�"test_wrappingProtocolHalfCloseable�s
�z7WrappingFactoryTests.test_wrappingProtocolHalfCloseablecCs*t�}t�d|�}|�tj�|�d�dS)z�
        Our L{_WrappingProtocol} should not provide L{IHalfCloseableProtocol}
        if the C{WrappedProtocol} doesn't.
        NF)rLrr�rzrr�r
r�rSrSrT�%test_wrappingProtocolNotHalfCloseable�s
�z:WrappingFactoryTests.test_wrappingProtocolNotHalfCloseablecCs(t�}t�d|�}|�tj�|��dS)zs
        Our L{_WrappingProtocol} should be an L{IHandshakeListener} if
        the C{wrappedProtocol} is.
        N)rorr�r�r�IHandshakeListenerr
)rRZhandshakeListener�wrappedrSrSrT�&test_wrappingProtocolHandshakeListener�sz;WrappingFactoryTests.test_wrappingProtocolHandshakeListenercCs(t�}t�d|�}|�tj�|��dS)z~
        Our L{_WrappingProtocol} should not provide L{IHandshakeListener}
        if the C{wrappedProtocol} doesn't.
        N)rLrr�r�rr�r
r�rSrSrT�)test_wrappingProtocolNotHandshakeListener�sz>WrappingFactoryTests.test_wrappingProtocolNotHandshakeListenercCs*t�}t�d|�}|��|�|j�dS)z~
        L{_WrappingProtocol.readConnectionLost} should proxy to the wrapped
        protocol's C{readConnectionLost}
        N)rfrr�rjr�rg�rRr�r�rSrSrT�&test_wrappedProtocolReadConnectionLost�sz;WrappingFactoryTests.test_wrappedProtocolReadConnectionLostcCs*t�}t�d|�}|��|�|j�dS)z�
        L{_WrappingProtocol.writeConnectionLost} should proxy to the wrapped
        protocol's C{writeConnectionLost}
        N)rfrr�rkr�rhr�rSrSrT�'test_wrappedProtocolWriteConnectionLost�sz<WrappingFactoryTests.test_wrappedProtocolWriteConnectionLostcCs,t�}t�d|�}|��|�|jd�dS)z~
        L{_WrappingProtocol.handshakeCompleted} should proxy to the
        wrapped protocol's C{handshakeCompleted}
        NrY)rorr�rqrzrp)rRZlistenerr�rSrSrT�&test_wrappedProtocolHandshakeCompleted�sz;WrappingFactoryTests.test_wrappedProtocolHandshakeCompletedN)rbrcrdrerr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rSrSrSrTrx�s,




rxc@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)�ClientEndpointTestCaseMixin�Q
    Generic test methods to be mixed into all client endpoint test classes.
    cCs0t�}|�t�|�\}}}|�ttj|��dS)zK
        The endpoint provides L{interfaces.IStreamClientEndpoint}
        N)r��createClientEndpoint�
MemoryReactorr�rrZIStreamClientEndpoint)rR�
clientFactory�ep�ignoredArgs�addressrSrSrT�test_interface�s�
z*ClientEndpointTestCaseMixin.test_interfacecCs|�|�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}
        rr���expectedClients�rRrrSrSrT�retrieveConnectedFactory�sz4ClientEndpointTestCaseMixin.retrieveConnectedFactorycs�t�}t�}t�}|�||�\}}}|�|�}g��fdd�}|�|�|�|�}	|	j�|�|��|g�|�	|�}
|�t
|
�d�|�|
d|�dS)z}
        A client endpoint can connect and returns a deferred who gets called
        back with a protocol instance.
        cs��|�dSr[r��r��ZreceivedProtosrSrT�
checkProtoszKClientEndpointTestCaseMixin.test_endpointConnectSuccess.<locals>.checkProtorYrN)r�r�r��connectr�r�r��callbackrzr��len�assertConnectArgs�rR�proto�mreactorr�r��expectedArgs�ignoredDestr�r�r}r�rSr�rT�test_endpointConnectSuccesss"�




z7ClientEndpointTestCaseMixin.test_endpointConnectSuccessc	sdtjdd�}t|d�}t�}|�||�\}}}|�|�}g��fdd�}|�|�|��|g�dS)�t
        If an endpoint tries to connect to a non-listening port it gets
        a C{ConnectError} failure.
        �Connection Failedr���connectExceptioncs��|j�dSr[�r\�valuer��ZreceivedExceptionsrSrT�checkFailure3szMClientEndpointTestCaseMixin.test_endpointConnectFailure.<locals>.checkFailureN)rr�rr�r�r�r�rz)	rR�
expectedErrorr�r�r�r�r�r�r�rSr�rT�test_endpointConnectFailure!s
�


z7ClientEndpointTestCaseMixin.test_endpointConnectFailurec
s�t�}t�}|�||�\}}}|�|�}g��fdd�}|�|�|��|�|�}|�dtt	�
���|�t��d��d}	|�
|	jt	j�|�|	jj|�dS)��
        Calling L{Deferred.cancel} on the L{Deferred} returned from
        L{IStreamClientEndpoint.connect} is errbacked with an expected
        L{ConnectingCancelledError} exception.
        cs��|�dSr[r�r��ZreceivedFailuresrSrTr�LszRClientEndpointTestCaseMixin.test_endpointConnectingCancelled.<locals>.checkFailureNrYr)r�r�r�r�r��cancelr�r�r2r�	UserErrorrzr��assertIsInstancer�r:r�)
rRr�r�r�r�r�r�r��attemptFactory�failurerSr�rT� test_endpointConnectingCancelled;s"�



z<ClientEndpointTestCaseMixin.test_endpointConnectingCancelledcCs^t�}t�}|j||f|���\}}}|�|�|�|�}|�t|�d�|�|d|�dS)zn
        The endpoint should pass it's connectArgs parameter to the reactor's
        listen methods.
        rYrN)	r�r�r��connectArgsr�r�rzr�r�)rRr}r�r�r��ignoredHostr�rSrSrT�"test_endpointConnectNonDefaultArgs`s��


z>ClientEndpointTestCaseMixin.test_endpointConnectNonDefaultArgsN)
rbrcrdrer�r�r�r�r�r�rSrSrSrTr��s
 %r�c@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�ServerEndpointTestCaseMixinr�cCs0t�}|�t�|�\}}}|�ttj|��dS)zL
        The endpoint provides L{interfaces.IStreamServerEndpoint}.
        N)r��createServerEndpointr�r�rrZIStreamServerEndpoint)rRr}r�r�r�rSrSrTr�zs�
z*ServerEndpointTestCaseMixin.test_interfacecsht�}t�}|�||�\}}}|�|�}g��fdd�}|�|�|��|g�|�|�|�|g�dS)zs
        An endpoint can listen and returns a deferred that gets called back
        with a port instance.
        cs��|���dSr[)r\�getHost)�port�Z
receivedHostsrSrT�checkPortAndServer�szRServerEndpointTestCaseMixin.test_endpointListenSuccess.<locals>.checkPortAndServerN)r�r�r��listenr�rz�expectedServers)rRr�r}r�r��expectedHostr�r�rSr�rT�test_endpointListenSuccess�s�


z6ServerEndpointTestCaseMixin.test_endpointListenSuccessc	sht�}t�dd|�}t|d�}|�||�\}}}|�t��}g��fdd�}|�|�|��|g�dS)z�
        When an endpoint tries to listen on an already listening port, a
        C{CannotListenError} failure is errbacked.
        ��P)�listenExceptioncs��|j�dSr[r�r�r�rSrTr��szLServerEndpointTestCaseMixin.test_endpointListenFailure.<locals>.checkFailureN)r�rZCannotListenErrorrr�r�r�rz)	rRr}�	exceptionr�r�r�r�r�r�rSr�rT�test_endpointListenFailure�s
�

z6ServerEndpointTestCaseMixin.test_endpointListenFailurecCsLt�}t�}|j||f|���\}}}|�|�|�|�}|�||g�dS)zm
        The endpoint should pass it's listenArgs parameter to the reactor's
        listen methods.
        N)r�r�r��
listenArgsr�r�rz)rRr}r�r�r�r�r�rSrSrT�!test_endpointListenNonDefaultArgs�s��


z=ServerEndpointTestCaseMixin.test_endpointListenNonDefaultArgsN)rbrcrdrer�r�rrrSrSrSrTr�vs

r�c@seZdZdZdS)�EndpointTestCaseMixinzJ
    Generic test methods to be mixed into all endpoint test classes.
    N�rbrcrdrerSrSrSrTr�src@s eZdZdZdd�Zdd�ZdS)�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.
    cCs
||_dSr[)�specificProtocol)rRr
rSrSrTrU�szSpecificFactory.__init__cCs"t|jd�rtd��||j_|jS)N�
passedAddresszspecificProtocol already used.)�hasattrr
r�rrtrSrSrTrv�szSpecificFactory.buildProtocolN)rbrcrdrerUrvrSrSrSrTr	�sr	c@seZdZdZddd�ZdS)�	FakeStdioz_
    A L{stdio.StandardIO} like object that simply captures its constructor
    arguments.
    NcCs||_||_dS)z�
        @param protocolInstance: like the first argument of L{stdio.StandardIO}

        @param reactor: like the reactor keyword argument of
            L{stdio.StandardIO}
        N)�protocolInstancer)rRrrrSrSrTrU�szFakeStdio.__init__)N�rbrcrdrerUrSrSrSrTr
�sr
c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�StandardIOEndpointsTestsz*
    Tests for Standard I/O Endpoints
    cCsNt�|_t�|j�}|�|jtj�t|_t	�|_
|�|�t
|j
���|_dS)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)r�rr�StandardIOEndpoint�assertIsZ_stdiorZ
StandardIOr
r*r
�successResultOfr�r	�	fakeStdio�rR�endpointrSrSrT�setUp�s�zStandardIOEndpointsTests.setUpcCs(|�|jj|j�|�|jjjt�dS)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)rrrr
r�rr,rQrSrSrT�test_protocolCreation
s
��z.StandardIOEndpointsTests.test_protocolCreationcCs|�|jj|j�dS)z�
        L{StandardIOEndpoint} passes its C{reactor} argument to the constructor
        of its L{stdio.StandardIO} like object.
        N)rrrrQrSrSrT�test_passedReactorsz+StandardIOEndpointsTests.test_passedReactorN)rbrcrdrerrrrSrSrSrTr�src@s eZdZdZdd�Zdd�ZdS)�StubApplicationProtocolz#
    An L{IProtocol} provider.
    cCs
||_dS)zY
        @param data: The data received by the protocol.
        @type data: str
        N)rNr]rSrSrTr^&sz$StubApplicationProtocol.dataReceivedcCs
||_dS)zA
        @type reason: L{twisted.python.failure.Failure}
        Nr�r_rSrSrTra.sz&StubApplicationProtocol.connectionLostN)rbrcrdrer^rarSrSrSrTr"srcsReZdZdZd�fdd�	Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
�ZS)�MemoryProcessTransportzC
    A fake L{IProcessTransport} provider to be used in tests.
    Ncs2tt|�jt�t�d�g|_t�|_t�|_dS)N)ZhostAddressZpeerAddress)	�superrrUr#�signals�set�closedChildFDsr*r�rRr��	__class__rSrTrU<s
�zMemoryProcessTransport.__init__cCs|dkr|�|�dSrM��write)rRZchildFDrNrSrSrT�writeToChildEsz#MemoryProcessTransport.writeToChildcCs|�d�dSrM��closeChildFDrQrSrSrT�
closeStdinJsz!MemoryProcessTransport.closeStdincCs|�d�dSrXr&rQrSrSrT�closeStdoutNsz"MemoryProcessTransport.closeStdoutcCs|�d�dS)Nr�r&rQrSrSrT�closeStderrRsz"MemoryProcessTransport.closeStderrcCs|j�|�dSr[)r�add)rR�fdrSrSrTr'Vsz#MemoryProcessTransport.closeChildFDcCs|j�|�dSr[)rr\)rR�signalrSrSrT�
signalProcessZsz$MemoryProcessTransport.signalProcess)N)rbrcrdrerUr%r(r)r*r'r.�
__classcell__rSrSr!rTr6s	rc@s(eZdZdZdidddddfdd�ZdS)�MemoryProcessReactorzA
    A fake L{IReactorProcess} provider to be used in tests.
    rSNrc

CsR||_||_||_||_||_||_||_||_|	|_t	�|_
|j�|j
�|j
S)z�
        @ivar processProtocol: Stores the protocol passed to the reactor.
        @return: An L{IProcessTransport} provider.
        )�processProtocol�
executabler��env�path�uid�gid�usePTY�childFDsr�processTransportr�)
rRr1r2r�r3r4r5r6r7r8rSrSrT�spawnProcessjsz!MemoryProcessReactor.spawnProcess)rbrcrdrer:rSrSrSrTr0es�r0c@sPeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�ZdS)�ProcessEndpointsTestsz,
    Tests for child process endpoints.
    cCs.t�|_t�|jd�|_t��|_t|j_dS�N�/bin/executable)	r0rr�ProcessEndpointr�rr+r}rrQrSrSrTr�s
zProcessEndpointsTests.setUpcCs�|�|jjt�|�|jjd�|�|jjd�|�|jji�|�|jj	�|�|jj
�|�|jj�|�|jjd�|�|jj
�|�|jjtj�dS)zU
        Default values are set for the optional parameters in the endpoint.
        r=rSrN)r�r��_reactorr0rz�_executable�_args�_envr��_path�_uid�_gid�_usePTY�	_childFDs�_errFlagr%ZLOGrQrSrSrT�test_constructorDefaults�sz.ProcessEndpointsTests.test_constructorDefaultscCs�ddi}t�t�ddgd|didddddd	d	d
�tj�
}|�|jt�|�|jd�|�|j	dg�|�|j
d|di�|�|jd�|�|jd�|�|j
d�|�|j�|�|jdd	d	d
��|�|jtj�dS)zI
        The parameters passed to the endpoint are stored in it.
        �HOMENr=�/runProcessHere/rYr�T�w�r�r���)rr>r0r%�DROPr�r?rzr@rArBrCrDrEr�rFrGrH)rR�environr�rSrSrT�test_constructorNonDefaults�s.

�z1ProcessEndpointsTests.test_constructorNonDefaultscCs2|j�|j�}|�|�|jj}|�|tj�dS)z�
        The wrapper function _WrapIProtocol gives an IProcessProtocol
        implementation that wraps over an IProtocol.
        N)	r�r�r}rrr1r�r�_WrapIProtocol�rRr�ZwpprSrSrT�test_wrappedProtocol�s
z*ProcessEndpointsTests.test_wrappedProtocolcCs�ddi}t�}t�|ddgd|didddddd	d	d
��	}|�|j�}|�|�|�|jtj�|�	|j
|j�|�	|j|j
�|�	|j|j�|�	|j|j�|�	|j|j�|�	|j|j�|�	|j|j�|�	|j|j�dS)z�
        The parameters for spawnProcess stored in the endpoint are passed when
        the endpoint's connect method is invoked.
        rJNr=rKrYr�TrLrMrN)r0rr>r�r}rr�r1rTrzr2r@r�rAr3rBr4rCr5rDr6rEr7rFr8rG)rRrR�
memoryReactorr�r�rSrSrT�test_spawnProcess�s4

�
�z'ProcessEndpointsTests.test_spawnProcesscCs@Gdd�dtj�}|�}|j�|�}|�|�|�|jt�dS)zz
        The address passed to the factory's buildProtocol in the endpoint is a
        _ProcessAddress instance.
        c@seZdZeZdZdd�ZdS)zBProcessEndpointsTests.test_processAddress.<locals>.TestAddrFactoryNcSs||_|��}||_|Sr[)r�rr})rRrur�rSrSrTrv�szPProcessEndpointsTests.test_processAddress.<locals>.TestAddrFactory.buildProtocol)rbrcrdrrr�rvrSrSrSrT�TestAddrFactory�srYN)rr+r�r�rr�r�r#)rRrYZ	myFactoryr�rSrSrT�test_processAddress�s


z)ProcessEndpointsTests.test_processAddresscCs$|�|j�|j��}|�|t�dS)zd
        L{ProcessEndpoint.connect} returns a Deferred with the connected
        protocol.
        N)rr�r�r}r�r)rRr�rSrSrT�test_connect�sz"ProcessEndpointsTests.test_connectcCs6dd�}||j_|j�|j�}|�|�}|�t�dS)zg
        In case of failure, L{ProcessEndpoint.connect} returns a Deferred that
        fails.
        c		Ss
t��dSr[)�	Exception)	Zppr2r�r3r4r5r6r7r8rSrSrT�testSpawnProcess�szCProcessEndpointsTests.test_connectFailure.<locals>.testSpawnProcessN)r�Z
_spawnProcessr�r}r�Ztrapr\)rRr]r�rrSrSrT�test_connectFailure�s

z)ProcessEndpointsTests.test_connectFailureN)rbrcrdrerrIrSrVrXrZr[r^rSrSrSrTr;�s	r;c@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"S)#�ProcessEndpointTransportTestsze
    Test the behaviour of the implementation detail
    L{endpoints._ProcessEndpointTransport}.
    cCsFt�|_t�|jd�|_|�|j�t�t	���}|jj
|_|j|_
dSr<)r0rrr>rrr�r+�forProtocolr*r9�processr��endpointTransportr rSrSrTrs��
z#ProcessEndpointTransportTests.setUpcCstt|j�dS)zE
        L{_ProcessEndpointTransport}s provide L{IConsumer}.
        N)rr&rbrQrSrSrT�test_verifyConsumersz1ProcessEndpointTransportTests.test_verifyConsumercCstt|j�dS)zI
        L{_ProcessEndpointTransport}s provide L{IPushProducer}.
        N)rr'rbrQrSrSrT�test_verifyProducer!sz1ProcessEndpointTransportTests.test_verifyProducercCstt|j�dS)zF
        L{_ProcessEndpointTransport}s provide L{ITransport}.
        N)rr(rbrQrSrSrT�test_verifyTransport(sz2ProcessEndpointTransportTests.test_verifyTransportcCs|�|jj|j�dS)zd
        The L{_ProcessEndpointTransport} instance stores the process passed to
        it.
        N)rrbZ_processrarQrSrSrT�test_constructor/sz.ProcessEndpointTransportTests.test_constructorcCs@tt�Gdd�dt��}|�}|j�|d�|�|jj|�dS)z�
        Registering a producer with the endpoint transport registers it with
        the underlying process transport.
        c@seZdZdS)zFProcessEndpointTransportTests.test_registerProducer.<locals>.AProducerNr�rSrSrSrT�	AProducer<srgFN)rr'r�rbZregisterProducerrra�producer)rRrgZ	aProducerrSrSrT�test_registerProducer7s
z3ProcessEndpointTransportTests.test_registerProducercCs|j��|�|jjd�dS)zY
        Pausing the endpoint transport pauses the underlying process transport.
        ZpausedN)rbZpauseProducingrzra�
producerStaterQrSrSrT�test_pauseProducingDs
z1ProcessEndpointTransportTests.test_pauseProducingcCs&|��|j��|�|jjd�dS)zc
        Resuming the endpoint transport resumes the underlying process
        transport.
        Z	producingN)rkrbZresumeProducingrzrarjrQrSrSrT�test_resumeProducingLs
z2ProcessEndpointTransportTests.test_resumeProducingcCs|j��|�|jjd�dS)zo
        Stopping the endpoint transport as a producer stops the underlying
        process transport.
        ZstoppedN)rbZ
stopProducingrzrarjrQrSrSrT�test_stopProducingVs
z0ProcessEndpointTransportTests.test_stopProducingcCs$|��|j��|�|jj�dS)z�
        Unregistring the endpoint transport's producer unregisters the
        underlying process transport's producer.
        N)rirbZunregisterProducerr�rarhrQrSrSrT�test_unregisterProducer_s
z5ProcessEndpointTransportTests.test_unregisterProducercCsg|j_|�tt|jd�dS)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)raro�assertRaises�AttributeError�getattrrbrQrSrSrT�test_extraneousAttributesis�z7ProcessEndpointTransportTests.test_extraneousAttributescCs*|j�dddg�|�|jj��d�dS)z�
        The writeSequence method of L{_ProcessEndpointTransport} writes a list
        of string passed to it to the transport's stdin.
        stest1stest2stest3stest1test2test3N)rb�
writeSequencerzra�io�getvaluerQrSrSrT�test_writeSequenceusz0ProcessEndpointTransportTests.test_writeSequencecCs$|j�d�|�|jj��d�dS)z�
        The write method of L{_ProcessEndpointTransport} writes a string of
        data passed to it to the child process's stdin.
        stestN)rbr$rzrarurvrQrSrSrT�
test_write~sz(ProcessEndpointTransportTests.test_writecCs|j��|�|jj�dS)z�
        A call to the loseConnection method of a L{_ProcessEndpointTransport}
        instance returns a call to the process transport's loseConnection.
        N)rbZloseConnectionr�raZ	connectedrQrSrSrT�test_loseConnection�s
z1ProcessEndpointTransportTests.test_loseConnectioncCs,|j��}|�|t�|�||j���dS)z�
        L{_ProcessEndpointTransport.getHost} returns a L{_ProcessAddress}
        instance matching the process C{getHost}.
        N)rbr�r�r#rra)rR�hostrSrSrT�test_getHost�s
z*ProcessEndpointTransportTests.test_getHostcCs,|j��}|�|t�|�||j���dS)z�
        L{_ProcessEndpointTransport.getPeer} returns a L{_ProcessAddress}
        instance matching the process C{getPeer}.
        N)rbZgetPeerr�r#rra)rRZpeerrSrSrT�test_getPeer�s
z*ProcessEndpointTransportTests.test_getPeerN)rbrcrdrerrcrdrerfrirkrlrmrnrsrwrxryr{r|rSrSrSrTr_	s"

	
			
r_c@sXeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�ZdS)�WrappedIProtocolTestszL
    Test the behaviour of the implementation detail C{_WrapIProtocol}.
    cCs4t�|_t�|jd�|_d|_t��|_t	|j_dSr<)
r0rrr>r��eventLogrr+r}rrQrSrSrTr�s

zWrappedIProtocolTests.setUpcCsD|j�|j�}|�|�|jj}|�|jt�|�	|j
|jj�dS)zQ
        Stores an L{IProtocol} provider and the flag to log/drop stderr
        N)r�r�r}rrr1r�rrrzZerrFlagrHrUrSrSrTrf�s

z&WrappedIProtocolTests.test_constructorcCs6|j�|j�}|�|�|jj}|�|jj|j�dS)zx
        Our process transport is properly hooked up to the wrappedIProtocol
        when a connection is made.
        N)	r�r�r}rrr1rzrr�rUrSrSrT�test_makeConnection�s
z)WrappedIProtocolTests.test_makeConnectioncCs
||_dS)z!
        A log observer.
        N)r~)rRZ	eventDictrSrSrT�_stdLog�szWrappedIProtocolTests._stdLogcCs�|j�|j�}|�|�|jj}t�|j�|�	tj
|j�|�dd�|�|j
d|j�|�|j
dd�|�|j
d|j�|�dt�|j
��dS)z�
        When the _errFlag is set to L{StandardErrorBehavior.LOG},
        L{endpoints._WrapIProtocol} logs stderr (in childDataReceived).
        r�sstderr1r2rNrzwrote stderr unhandled byN)r�r�r}rrr1r1�addObserverr��
addCleanup�removeObserver�childDataReceivedrzr~r2r�assertInZtextFromEventDictrUrSrSrT�test_logStderr�s

�z$WrappedIProtocolTests.test_logStderrcCsbtj|j_|j�|j�}|�|�|jj}t	�
|j�|�t	j
|j�|�dd�|�|j�dS)z�
        When the _errFlag is set to L{StandardErrorBehavior.DROP},
        L{endpoints._WrapIProtocol} ignores stderr.
        r�sstderr2N)r%rQr�rHr�r}rrr1r1r�r�r�r�r�r�r~rUrSrSrT�test_stderrSkip�s

z%WrappedIProtocolTests.test_stderrSkipcCs@|j�|j�}|�|�|jj}|�dd�|�|jj	d�dS)z�
        In childDataReceived of L{_WrappedIProtocol} instance, the protocol's
        dataReceived is called when stdout is generated.
        rYsstdoutN)
r�r�r}rrr1r�rzrrNrUrSrSrT�test_stdout�s

z!WrappedIProtocolTests.test_stdoutcCsR|j�|j�}|�|�|jj}|�tt�	d���|�
|jj�
tj�tj�dS)z�
        L{error.ProcessDone} with status=0 is turned into a clean disconnect
        type, i.e. L{error.ConnectionDone}.
        rN)r�r�r}rrr1�processEndedr2rZProcessDonerzrr`�checkZConnectionDonerUrSrSrT�test_processDone�s
�z&WrappedIProtocolTests.test_processDonecCsP|j�|j�}|�|�|jj}|�tt�	���|�
|jj�
tj�tj�dS)z{
        Exceptions other than L{error.ProcessDone} with status=0 are turned
        into L{error.ConnectionLost}.
        N)r�r�r}rrr1r�r2rZProcessTerminatedrzrr`r�ZConnectionLostrUrSrSrT�test_processEndeds
�z'WrappedIProtocolTests.test_processEndedN)
rbrcrdrerrfrr�r�r�r�r�r�rSrSrSrTr}�s
r}c@sHeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)�TCP4EndpointsTestsz'
    Tests for TCP IPv4 Endpoints.
    cCs|jS�zD
        @return: List of calls to L{IReactorTCP.listenTCP}
        �Z
tcpServersr�rSrSrTr�"sz"TCP4EndpointsTests.expectedServerscCs|jS�zE
        @return: List of calls to L{IReactorTCP.connectTCP}
        ��
tcpClientsr�rSrSrTr�)sz"TCP4EndpointsTests.expectedClientsc
CsP|\}}}}}|\}}	}
}}|�||�|�||	�|�||�|�||�dS�a]
        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}.
        N�rz�
rR�receivedArgsr�rzr��ignoredFactory�timeout�bindAddressr��expectedPort�_ignoredFactory�expectedTimeout�expectedBindAddressrSrSrTr�0s�z$TCP4EndpointsTests.assertConnectArgscCs
ddd�S��K
        @return: C{dict} of keyword arguments to pass to connect.
        �
��	localhosti���r�r�rSrQrSrSrTr�HszTCP4EndpointsTests.connectArgscCs
ddd�S��I
        @return: C{dict} of keyword arguments to pass to listen
        �d�	127.0.0.1��backlog�	interfacerSrQrSrSrTrOszTCP4EndpointsTests.listenArgscKsJtddd�}|dkri}tj||jf|�|j||�dd�|�dd�f|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}.
        �TCP�0.0.0.0rNr��2r�r)r r�TCP4ServerEndpointr��get�rRrr}rr�rSrSrTr�Vs��

��z'TCP4EndpointsTests.createServerEndpointc	KsFtddd�}tj||j|jf|�|j|j||�dd�|�dd�f|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}
        r�r�rr��r�N)r r�TCP4ClientEndpointrzr�r��rRrr�r�r�rSrSrTr�ps��


��z'TCP4EndpointsTests.createClientEndpointN�rbrcrdrer�r�r�r�rr�r�rSrSrSrTr�sr�c@sHeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)�TCP6EndpointsTestsz'
    Tests for TCP IPv6 Endpoints.
    cCs|jSr�r�r�rSrSrTr��sz"TCP6EndpointsTests.expectedServerscCs|jSr�r�r�rSrSrTr��sz"TCP6EndpointsTests.expectedClientsc
CsP|\}}}}}|\}}	}
}}|�||�|�||	�|�||�|�||�dSr�r�r�rSrSrTr��s�z$TCP6EndpointsTests.assertConnectArgscCs
ddd�Sr�rSrQrSrSrTr��szTCP6EndpointsTests.connectArgscCs
ddd�S)r�r��::1r�rSrQrSrSrTr�szTCP6EndpointsTests.listenArgscKsN|�dd�}td|d�}|dkr$i}tj||jf|�|j||�dd�|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}.
        r�z::r�rNr�r�)r�r!r�TCP6ServerEndpointr�)rRrr}rr�r�rSrSrTr��s��
��z'TCP6EndpointsTests.createServerEndpointc	KsFtddd�}tj||j|jf|�|j|j||�dd�|�dd�f|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}
        r�r�rr�r�r�N)r!r�TCP6ClientEndpointrzr�r�r�rSrSrTr��s��


��z'TCP6EndpointsTests.createClientEndpointNr�rSrSrSrTr��sr�c@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)�TCP6EndpointNameResolutionTestszl
    Tests for a TCP IPv6 Client Endpoint pointed at a hostname instead
    of an IPv6 address literal.
    c	s`tddd�}tj|d|jf|��_�fdd�}|�j_�j|j|j||�dd�|�d	d
�f|fS)r�r��::2r�ipv6.example.comcs>��d|�tttddftttddftttddfg}t�|�S)Nr�r)r�rrr)z::3rrr)z::4rrr)rzrrrr�succeed)rzrNrQrSrT�testNameResolutions�zPTCP6EndpointNameResolutionTests.createClientEndpoint.<locals>.testNameResolutionr�r�r�N)r!rr�r�r�Z_nameResolutionrzr�)rRrr�r�r�r�rSrQrTr��s"��


��z4TCP6EndpointNameResolutionTests.createClientEndpointcCs
ddd�Sr�rSrQrSrSrTr�sz+TCP6EndpointNameResolutionTests.connectArgscCs|jSr�r�r�rSrSrTr�#sz/TCP6EndpointNameResolutionTests.expectedClientsc
CsP|\}}}}}|\}}	}
}}|�||�|�||	�|�||�|�||�dSr�r�r�rSrSrTr�*s�z1TCP6EndpointNameResolutionTests.assertConnectArgscCs"t�ddd�}|�|jtj�dS)zg
        By default, L{TCP6ClientEndpoint._deferToThread} is
        L{threads.deferToThread}.
        Nzwww.example.com��)rr�rz�_deferToThreadrZ
deferToThread�rRr�rSrSrT�test_freeFunctionDeferToThreadBsz>TCP6EndpointNameResolutionTests.test_freeFunctionDeferToThreadcsZg��fdd�}t�tdd�}t�}||_||_|�t��|�|ddt	fifg��dS)zl
        While resolving hostnames, _nameResolution calls
        _deferToThread with _getaddrinfo.
        cs��|||f�t��Sr[)r\rr�)r�r��kwargs�ZcallsrSrT�fakeDeferToThreadRszNTCP6EndpointNameResolutionTests.test_nameResolution.<locals>.fakeDeferToThreadr�r�rN)
rr�rr��_getaddrinfor�r�rrrzr)rRr�r�fakegetaddrinforSr�rT�test_nameResolutionKs��z3TCP6EndpointNameResolutionTests.test_nameResolutionN)
rbrcrdrer�r�r�r�r�r�rSrSrSrTr��s 	r�c@seZdZdZddd�ZdS)�RaisingMemoryReactorWithClockzE
    An extension of L{RaisingMemoryReactor} with L{task.Clock}.
    NcCst�|�t�|||�dSr[)r-rUr)rRrr�rSrSrTrUes
z&RaisingMemoryReactorWithClock.__init__)NNrrSrSrSrTr�asr�rSNc
sh�dkri�����tt�G��fdd�dt���tt�G�fdd�dttdtt|������}||�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.
    Ncs eZdZed��fdd�	�ZdS)z9deterministicResolvingReactor.<locals>.SimpleNameResolverrNr�csT|�d���|��D]0}t|t�r<ttgt|�d||�}|�|�q|��dS)Nr�)	�resolutionBeganr��
isinstance�strr r!r?�addressResolved�resolutionComplete)ZresolutionReceiver�hostName�
portNumberZaddressTypesZtransportSemantics�expectedAddress��expectedAddresses�hostMaprSrT�resolveHostName�s

��zIdeterministicResolvingReactor.<locals>.SimpleNameResolver.resolveHostName)rNr�)rbrcrd�staticmethodr�rSr�rSrT�SimpleNameResolver�s
�r�cseZdZ��ZdS)z3deterministicResolvingReactor.<locals>.WithResolverN)rbrcrdZnameResolverrS)r�rSrT�WithResolver�sr��*)	�copyrr<r�r=r>r�tupler
)rr�r�r�rS)r�r�r�rT�deterministicResolvingReactorks�r�c@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
�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.
    csXg�_t���_t��j��_g�_g�_	d�_
ttj
�G�fdd�dt��}|�_dS)Nrcs<eZdZe�fdd��Ze�fdd��Ze�fdd��ZdS)z4SimpleHostnameResolverTests.setUp.<locals>._Receivercs�j�|�dSr[)�resolutionBeganCallsr\)ZresolutionInProgressrQrSrTr��szDSimpleHostnameResolverTests.setUp.<locals>._Receiver.resolutionBegancs�j�|�dSr[)�addressResolvedCallsr\)r�rQrSrTr��szDSimpleHostnameResolverTests.setUp.<locals>._Receiver.addressResolvedcs�jd7_dSrX)�resolutionCompleteCallCountrSrQrSrTr��szGSimpleHostnameResolverTests.setUp.<locals>._Receiver.resolutionCompleteN)rbrcrdr�r�r�r�rSrQrSrT�	_Receiver�sr�)�fakeResolverCallsrr��fakeResolverReturnsrZ_SimpleHostnameResolver�fakeResolver�resolverr�r�r�rrZIResolutionReceiverr��receiver)rRr�rSrQrTr�s
z!SimpleHostnameResolverTests.setUpcCs|j�||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}
        )r�r\r�)rRr�r�rSrSrTr��sz(SimpleHostnameResolverTests.fakeResolvercCs|�ttj|j��dS)zs
        A L{endpoints._SimpleHostnameResolver} instance provides
        L{interfaces.IHostnameResolver}.
        N)r�rrr<r�rQrSrSrTr��s
�z*SimpleHostnameResolverTests.test_interfacecs
g�tt��fdd���t���|��fdd��|j�|jd�}|�||j�|j	�
t��|�dt
���|�dt
|�t����\}|�|�d��|�|�dd��|�|�d	t|j���|�dt
|j��|�|jd
jd�|�|j�|�d|j�dS)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.
        cs��|�dSr[r�)�event)�logsrSrT�captureLogs�szHSimpleHostnameResolverTests.test_resolveNameFailure.<locals>.captureLogscs
t���Sr[)r/r�rS)r�rSrTr��r�zESimpleHostnameResolverTests.test_resolveNameFailure.<locals>.<lambda>�example.comrYZisError�name�callablerN)rr.r/r�r�r�r�r�rr�Zerrbackr\rzr��flushLoggedErrorsr�r��reprr�r�r�r�r�r�)rRr�r�rS)r�r�rT�test_resolveNameFailure�s$
z3SimpleHostnameResolverTests.test_resolveNameFailurec	Cs�d}d}d}|j�|jd�}|�||j�|j�tttd||fft	ttd||ffg�|�
dt|j��|�
|jdj
d�|�
|jtd||�td||�g�|�
|jd�d	S)
zs
        The resolution receiver begins, and resolved hostnames are
        delivered before it completes.
        r�1.2.3.4z
1::2::3::4r�rrYrr�N)r�r�r�rr�r�rrrrrzr�r�r�r�r r!r�)rRr�Zipv4HostZipv6Hostr�rSrSrT�test_resolveNameDeliverss �

�z4SimpleHostnameResolverTests.test_resolveNameDeliversN)	rbrcrdrerr�r�r�r�rSrSrSrTr��s	$r�c@seZdZdZdd�ZdS)�+HostnameEndpointFallbackNameResolutionTestszd
    L{HostnameEndpoint._fallbackNameResolution} defers a name
    resolution call to a thread.
    csJddlm}tj|ddd�}d\��|����}���fdd�}|�|�S)z�
        L{_fallbackNameResolution} returns a L{Deferred} that fires
        with the resoution of the the host and request port.
        r)r�ignored)rzr�)r�rYcsL��t|�d�|\\}}}}}��|t���|t���|��f�dSrX)rzr�rr)�result�family�socktype�_Zsockaddr�rzr�rRrSrT�assertHostPortFamilySockTypeEs
zmHostnameEndpointFallbackNameResolutionTests.test_fallbackNameResolution.<locals>.assertHostPortFamilySockType)�twisted.internetrr�HostnameEndpointZ_fallbackNameResolutionr�)rRrr�ZresolutionDeferredr�rSr�rT�test_fallbackNameResolution7s�zGHostnameEndpointFallbackNameResolutionTests.test_fallbackNameResolutionN)rbrcrdrer�rSrSrSrTr�1sr�c@sHeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)�#_HostnameEndpointMemoryReactorMixinz�
    Common methods for testing L{HostnameEndpoint} against
    L{MemoryReactor} instances that do not provide
    L{IReactorPluggableNameResolver}.
    cOs2z|||�}Wnt��YSXt�|�SdS)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.
        N)rr�r�)rRr�r�r�r�rSrSrT�synchronousDeferredToThreadWs
z?_HostnameEndpointMemoryReactorMixin.synchronousDeferredToThreadcCs|jS)z�
        Extract expected clients from the reactor.

        @param reactor: The L{MemoryReactor} under test.

        @return: List of calls to L{IReactorTCP.connectTCP}
        r�r�rSrSrTr�msz3_HostnameEndpointMemoryReactorMixin.expectedClientscCs
ddd�S)zL

        @return: C{dict} of keyword arguments to pass to connect.
        g$@r�r�rSrQrSrSrTr�xsz/_HostnameEndpointMemoryReactorMixin.connectArgsc
CsP|\}}}}}|\}}	}
}}|�||�|�||	�|�||�|�||�dSr�r�r�rSrSrTr��s�z5_HostnameEndpointMemoryReactorMixin.assertConnectArgscCsntjdd�}t|d�}t�}|�||�\}}}|�|�}|�tjj	�|�
|�|�j|�|�
g|�
��dS)z�
        When L{HostnameEndpoint.connect} cannot connect to its
        destination, the returned L{Deferred} will fail with
        C{ConnectError}.
        r�r�r�N�rr�r�r�r�r��advancerr��_DEFAULT_ATTEMPT_DELAYrzr�r��getDelayedCalls�rRr�r�r�r�r�r�r�rSrSrTr��s��

z?_HostnameEndpointMemoryReactorMixin.test_endpointConnectFailurecCs`t�}t�}|�||�|��}|�dt|��|�t|dd�|�|dd�	d��dS)z�
        Instantiating L{HostnameEndpoint} with a reactor that does not
        provide L{IReactorPluggableResolver} emits a deprecation warning.
        rYr�category�messagez�Passing HostnameEndpoint a reactor that does not provide IReactorPluggableNameResolver (twisted.test.proto_helpers.MemoryReactorClock) was deprecated in Twisted 17.5.0; please use a reactor that provides IReactorPluggableNameResolver insteadN)
r�r�r�Z
flushWarningsrzr�r�DeprecationWarningr��
startswith)rRr�r��warningsrSrSrT�test_deprecation�s�z4_HostnameEndpointMemoryReactorMixin.test_deprecationcCsft�}t�}|�||�\}}}dd�}||_|�|�}|�|�|�jtj	�|�
dt|�t
���dS)z8
        Hostname resolution errors are logged.
        c_stdd��dS)N���z#No address associated with hostname)r	)r�r�rSrSrT�getaddrinfoThatFails�szS_HostnameEndpointMemoryReactorMixin.test_errorsLogged.<locals>.getaddrinfoThatFailsrYN)r�r�r�r�r�r�r�r�r�DNSLookupErrorrzr�r�r	)rRr�r�r�r�r�rr�rSrSrT�test_errorsLogged�s�

�z5_HostnameEndpointMemoryReactorMixin.test_errorsLoggedN)rbrcrdrer�r�r�r�r�r	r
rSrSrSrTr�Psr�c@seZdZdZdd�ZdS)�&HostnameEndpointMemoryIPv4ReactorTestsz�
    IPv4 resolution tests for L{HostnameEndpoint} with
    L{MemoryReactor} subclasses that do not provide
    L{IReactorPluggableNameResolver}.
    c	sbd�tdd�}tj|d|jf|�}�fdd�}||_|j|_|�|j||�dd�|�dd	�f|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.comrcstttd�dffgS�Nrr)rrr�rzr�r�r��r�rSrTr��s�zTHostnameEndpointMemoryIPv4ReactorTests.createClientEndpoint.<locals>.fakegetaddrinfor�r�r�N�r$rr�r�r�r�r�r��rRrr�r�r�rr�rSrrTr��s$
��


��z;HostnameEndpointMemoryIPv4ReactorTests.createClientEndpointN�rbrcrdrer�rSrSrSrTr�src@seZdZdZdd�ZdS)�&HostnameEndpointMemoryIPv6ReactorTestsz�
    IPv6 resolution tests for L{HostnameEndpoint} with
    L{MemoryReactor} subclasses that do not provide
    L{IReactorPluggableNameResolver}.
    c	sbd�tdd�}tj|d|jf|�}�fdd�}||_|j|_|�|j||�dd�|�dd	�f|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:4�ipv6.example.comrcstttd�dffgSr)rrrrrrSrTr�)s��zTHostnameEndpointMemoryIPv6ReactorTests.createClientEndpoint.<locals>.fakegetaddrinfor�r�r�NrrrSrrTr�s$
��


��z;HostnameEndpointMemoryIPv6ReactorTests.createClientEndpointNrrSrSrSrTrsrc@sZeZdZdZdd�Zdd�Zdd�Zdd	�Zddd�Zd
d�Z	dd�Z
dd�Zdd�Zd
S)�HostnameEndpointsOneIPv4Testsz^
    Tests for the hostname based endpoints when GAI returns only one
    (IPv4) address.
    c	KsPd}tdd�}tjt||g�d|jf|�}|||j||�dd�|�dd�f|fS)z{
        Creates a L{HostnameEndpoint} instance where the hostname is resolved
        into a single IPv4 address.
        r�rrr�r�r�N�r$rr�r�r�r�)rRrr�r�r�r�rrSrSrTr�?s

��


��z2HostnameEndpointsOneIPv4Tests.createClientEndpointcCs|jSr�r�r�rSrSrTr�Qsz-HostnameEndpointsOneIPv4Tests.expectedClientsc
CsP|\}}}}}|\}}	}
}}|�||�|�||	�|�||�|�||�dSr�r�r�rSrSrTr�Xs�z/HostnameEndpointsOneIPv4Tests.assertConnectArgscCs
ddd�Sr�rSrQrSrSrTr�psz)HostnameEndpointsOneIPv4Tests.connectArgsNc
Cs�t�}t��}tj|_|�||�\}}}|�|�}|dk	rD|�|�|��|�|�}|�	dt
t����|�
|�}	|�|	jtj�|�|	jj|�|�|jddjj�|�g|���dS)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�r�rr�r�r�r2rr�r�r�r�r:rzr�r�r��
_connector�stoppedConnectingr)
rRrr�r�r�r�r�r�r�r�rSrSrTr�ws$�




z>HostnameEndpointsOneIPv4Tests.test_endpointConnectingCancelledcCs$tjj}||d}|j|d�dS)a 
        Calling L{Deferred.cancel} on the L{Deferred} returned from
        L{IStreamClientEndpoint.connect} after enough time has passed that all
        connection attempts have been initiated will cause it to be errbacked
        with a L{ConnectingCancelledError} exception.
        g@)rN)rr�rr�)rRZ
oneBetweenrrSrSrT�7test_endpointConnectingCancelledAfterAllAttemptsStarted�szUHostnameEndpointsOneIPv4Tests.test_endpointConnectingCancelledAfterAllAttemptsStartedcCsntjdd�}t|d�}t�}|�||�\}}}|�|�}|�tjj	�|�
|�|�j|�|�
g|�
��dS)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�r�r�Nr�rrSrSrTr��s��

z9HostnameEndpointsOneIPv4Tests.test_endpointConnectFailurec
Cs�tjdd�}t�}t�}|�||�\}}}|�|�}|�d�|jd\}}	}
}}|
�|j	d|�|�
|�|�j|�|�
g|�
��dS)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�r��333333�?rN)rr�r�r�r�r�rr�r�Z
connectorsrzr�r�r)
rRr�r�r�r�r�r�r�rzr�r}r�r�rSrSrT�)test_endpointConnectFailureAfterIteration�s�


zGHostnameEndpointsOneIPv4Tests.test_endpointConnectFailureAfterIterationcs�t�}t�}t�}|�||�\}}}|�|�}g��fdd�}|�|�|�|�}	|�d�|	j�|�|�	�|g�|�
|�}
|�	t|
�d�|�|
d|�|�	g|�
��dS)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.
        cs��|�dSr[r�r�r�rSrTr��sz[HostnameEndpointsOneIPv4Tests.test_endpointConnectSuccessAfterIteration.<locals>.checkProtorrYrN)r�r�r�r�r�r�rr�r�rzr�r�r�rr�rSr�rT�)test_endpointConnectSuccessAfterIteration�s&	�





zGHostnameEndpointsOneIPv4Tests.test_endpointConnectSuccessAfterIteration)N)
rbrcrdrer�r�r�r�r�rr�rr rSrSrSrTr9s
 rc@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)�HostnameEndpointsOneIPv6Testsz^
    Tests for the hostname based endpoints when GAI returns only one
    (IPv6) address.
    c	KsLtdd�}tjt|dg�d|jf|�}|d|j||�dd�|�dd�f|fS)z{
        Creates a L{HostnameEndpoint} instance where the hostname is resolved
        into a single IPv6 address.
        rrrr�r�r�Nr)rRrr�r�r�rrSrSrTr�	s

��


��z2HostnameEndpointsOneIPv6Tests.createClientEndpointcCs|jSr�r�r�rSrSrTr�	sz-HostnameEndpointsOneIPv6Tests.expectedClientsc
CsP|\}}}}}|\}}	}
}}|�||�|�||	�|�||�|�||�dSr�r�r�rSrSrTr�	s�z/HostnameEndpointsOneIPv6Tests.assertConnectArgscCs
ddd�Sr�rSrQrSrSrTr�0	sz)HostnameEndpointsOneIPv6Tests.connectArgsc	Cs�t�}t��}tj|_|�t|dg�|�\}}}|�|�}|��|�|�}|�	dt
t����|�
|�}|�|jtj�|�|jj|�|�|jddjj�|�g|���dS)r�r�Nrr�)r�rr+r*r�r�r�r�r�r�r2rr�r�r�r�r:rzr�r�r�rrr)	rRr�r�r�r�r�r�r�r�rSrSrTr�7	s 
�



z>HostnameEndpointsOneIPv6Tests.test_endpointConnectingCancelledcCsjtjdd�}t|d�}t�}|�||�\}}}|�|�}|�d�|�|�|�j	|�|�g|�
��dS)r�r�r�r�rN)rr�r�r�r�r�rrzr�r�rrrSrSrTr�V	s
�


z9HostnameEndpointsOneIPv6Tests.test_endpointConnectFailureN)
rbrcrdrer�r�r�r�r�r�rSrSrSrTr!�sr!c@s8eZdZdZdZdZdd�Zdd�Zdd	�Zd
d�Z	dS)
�HostnameEndpointIDNATestszJ
    Tests for L{HostnameEndpoint}'s constructor's encoding behavior.
    �
bücher.chsxn--bcher-kva.chcCs>t�tt�dg�|jd�}|�|j|j�|�|j|j�dS)z�
        A L{HostnameEndpoint} constructed with text will contain an
        IDNA-encoded bytes representation of that text.
        r�rN�	rr�r�r��sampleIDNATextrz�
_hostBytes�sampleIDNABytes�	_hostTextrrSrSrT�test_idnaHostnameTextq	s�z/HostnameEndpointIDNATests.test_idnaHostnameTextcCs>t�tt�dg�|jd�}|�|j|j�|�|j|j�dS)z�
        A L{HostnameEndpoint} constructed with bytes will contain an
        IDNA-decoded textual representation of those bytes.
        r�rNr$rrSrSrT�test_idnaHostnameBytes~	s�z0HostnameEndpointIDNATests.test_idnaHostnameBytescCsDt�tt�dg�td|j�d�}|�|j|j�|�|j	|j�dS)z�
        A L{HostnameEndpoint} constructed with NFD-normalized text will store
        the NFC-normalized version of that text.
        r�ZNFDrN)
rr�r�r�r
r%rzr&r'r(rrSrSrT�test_nonNormalizedText�	s
�z0HostnameEndpointIDNATests.test_nonNormalizedTextcCs�t�tt�dg�dd�}|�t�t��}|�|t	�}|�
dt|��t�tt�dg�dd�}|�t��}|�|t	�}|�
dt|��dS)a&
        Since any client of L{IStreamClientEndpoint} needs to handle Deferred
        failures from C{connect}, L{HostnameEndpoint}'s constructor will not
        raise exceptions when given bad host names, instead deferring to
        returning a failing L{Deferred} from C{connect}.
        r���-garbage-�rz\xff-garbage-\xffu⿰-garbage-⿰z\u2ff0-garbage-\u2ff0N)rr�r�r�r�r+r`r*r�r�r�r�)rRrZdeferred�errrSrSrT�test_deferBadEncodingToConnect�	s ��z8HostnameEndpointIDNATests.test_deferBadEncodingToConnectN)
rbrcrdrer%r'r)r*r+r.rSrSrSrTr"i	s


r"c@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�HostnameEndpointReprTestsz@
    Tests for L{HostnameEndpoint}'s string representation.
    cCs>t�tt�g�dd�}t|�}|�d|�|�tt|��dS)z�
        The string representation of L{HostnameEndpoint} includes the host and
        port passed to the constructor.
        r�rz!<HostnameEndpoint example.com:80>N�	rr�r�r-r�rzrr��type�rRrZreprSrSrT�
test_allASCII�	s
�z'HostnameEndpointReprTests.test_allASCIIcCs>t�tt�g�dd�}t|�}|�d|�|�tt|��dS)z�
        When IDN is passed to the L{HostnameEndpoint} constructor the string
        representation includes the punycode version of the host.
        r#�z'<HostnameEndpoint xn--bcher-kva.ch:443>Nr0r2rSrSrT�test_idnaHostname�	s
�z+HostnameEndpointReprTests.test_idnaHostnamecCs>t�tt�g�dd�}t|�}|�d|�|�tt|��dS)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::1�z<HostnameEndpoint [::1]:22>Nr0r2rSrSrT�test_hostIPv6Address�	s
�z.HostnameEndpointReprTests.test_hostIPv6AddresscCs*t�tt�g�dd�}|�dt|��dS)z�
        When a bad hostname is passed to L{HostnameEndpoint}, the string
        representation displays invalid characters in backslash-escaped form.
        r,rz'<HostnameEndpoint \xff-garbage-\xff:80>N)rr�r�r-rzr�rrSrSrT�test_badEncoding�	s
��z*HostnameEndpointReprTests.test_badEncodingN)rbrcrdrer3r5r7r8rSrSrSrTr/�	s
r/c@seZdZdZdd�ZdS)� HostnameEndpointsGAIFailureTestszM
    Tests for the hostname based endpoints when GAI returns no address.
    cCsHt�tt�g�dd�}t�}|�|�}|�|tj�}|�	dt
|��dS)z�
        If no address is returned by GAI for a hostname, the connection attempt
        fails with L{error.DNSLookupError}.
        rrr�N)rr�r�r-r�r�r�rrr�r�)rRrr�ZdConnect�excrSrSrT�test_failure�	s
�
z-HostnameEndpointsGAIFailureTests.test_failureN)rbrcrdrer;rSrSrSrTr9�	sr9c@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
�&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.
    cCs(t�|_t�t|jddg�dd�|_dS)Nr�r�www.example.comr)r�r�rr�r�rrQrSrSrTr
s��z,HostnameEndpointsFasterConnectionTests.setUpcCs�t�|_t�t|jdt�dg�dd�|_d}|j�|�|j�d�|jj	d\}}}}}|�
t|jj	�d�|�
|d�|�
|d�dS)	z�
        If an address type other than L{IPv4Address} and L{IPv6Address} is
        returned by on address resolution, the endpoint ignores that address.
        r�rr=rNrrYr�)r�r�rr�r�r�rr�rr�rzr�)rRr�rzr�r}r�r�rSrSrT�test_ignoreUnknownAddressTypes
s��zEHostnameEndpointsFasterConnectionTests.test_ignoreUnknownAddressTypescCs�t��}tj|_|j�|�}g}|�|j�|jjd\}}}}}|�	|d�|�	|d�|�
||f�}	t�}
|�	|g�|	�|
�|�	t
|�d�|�	|dj|�|�	g|j���dS)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.
        rr�rrYN)rr+r*rr�r�r\r�r�rzrvr�r�r�r}r�rRr�r�Zresultsrzr�r}r�r�r�Z
fakeTransportrSrSrT�test_IPv4IsFaster.
s	
z8HostnameEndpointsFasterConnectionTests.test_IPv4IsFastercCs�t��}tj|_|j�|�}g}|�|j�|j�d�|jj	d\}}}}}|�
|d�|�
|d�|�||f�}	t�}
|�
|g�|	�
|
�|�
t|�d�|�
|dj|�|�
g|j���dS)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.
        rrYrrrN)rr+r*rr�r�r\r�rr�rzrvr�r�r�r}rr?rSrSrT�test_IPv6IsFasterN
s 	
z8HostnameEndpointsFasterConnectionTests.test_IPv6IsFastercCs�t��}tj|_|j�|�}g}|�|j�|j�d�|jj	d\}}}}}|�
||f�}	t�}
|	�|
�|�
d|jj	ddjj�|�
g|j���dS)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.
        rrYTrr�N)rr+r*rr�r�r\r�rr�rvr�r�rzrrrr?rSrSrT�test_otherConnectionsCancelledp
s
�zEHostnameEndpointsFasterConnectionTests.test_otherConnectionsCancelledN)	rbrcrdrerr>r@rArBrSrSrSrTr<
s "r<c@sXeZdZdZereZdd�Zdd�Zdd�Zdd	�Z	d
d�Z
dd
�Zdd�Zdd�Z
dS)�SSL4EndpointsTestsz"
    Tests for SSL Endpoints.
    cCs|jS)zD
        @return: List of calls to L{IReactorSSL.listenSSL}
        )Z
sslServersr�rSrSrTr��
sz"SSL4EndpointsTests.expectedServerscCs|jS)zE
        @return: List of calls to L{IReactorSSL.connectSSL}
        )Z
sslClientsr�rSrSrTr��
sz"SSL4EndpointsTests.expectedClientscCs`|\}}}}}}|\}	}
}}}
}|�||	�|�||
�|�||�|�||
�|�||�dS)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}.
        Nr�)rRr�r�rzr�r�ZcontextFactoryr�r�r�r�r�ZexpectedContextFactoryr�r�rSrSrTr��
s��
z$SSL4EndpointsTests.assertConnectArgscCs
ddd�Sr�rSrQrSrSrTr��
szSSL4EndpointsTests.connectArgscCs
ddd�Sr�rSrQrSrSrTr�
szSSL4EndpointsTests.listenArgscCsLtddd�\|_|_tddd�\|_|_t|j|jdd�|_tdd�|_d	S)
zF
        Set up client and server SSL contexts for use later.
        zServer Test Certificate�server)�OZCNzClient Test Certificate�clientF)�
privateKey�certificate�requireCertificate)rIN)r@ZsKeyZsCertZcKeyZcCertrC�serverSSLContext�clientSSLContextrQrSrSrTr�
s ����zSSL4EndpointsTests.setUpc	KsFtddd�}tj||j|jf|�|j||j|�dd�|�dd�f|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}.
        r�r�rr�r�r�r)r r�SSL4ServerEndpointr�rJr�r�rSrSrTr��
s��


��z'SSL4EndpointsTests.createServerEndpointc
KsZtddd�}|dkri}tj||j|j|jf|�|j|j||j|�dd�|�dd�f|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}
        r�r�rNr�r�r�)r r�SSL4ClientEndpointrzr�rKr�r�rSrSrTr��
s"��


��z'SSL4EndpointsTests.createClientEndpointN)rbrcrdre�skipSSL�skipr�r�r�r�rrr�r�rSrSrSrTrC�
srCc@sPeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�ZdS)�UNIXEndpointsTestsz)
    Tests for UnixSocket Endpoints.
    cCs|�|�ddS)z�
        Override L{EndpointTestCaseMixin.retrieveConnectedFactory} to account
        for different index of 'factory' in C{connectUNIX} args.
        rrYr�r�rSrSrTr�sz+UNIXEndpointsTests.retrieveConnectedFactorycCs|jS)zF
        @return: List of calls to L{IReactorUNIX.listenUNIX}
        )ZunixServersr�rSrSrTr�!sz"UNIXEndpointsTests.expectedServerscCs|jS)zG
        @return: List of calls to L{IReactorUNIX.connectUNIX}
        )ZunixClientsr�rSrSrTr�(sz"UNIXEndpointsTests.expectedClientscCs@|\}}}}|\}}}	}
|�||�|�||	�|�||
�dS)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}.
        Nr�)rRr�r�r4r�r��checkPIDZexpectedPathr�r�ZexpectedCheckPIDrSrSrTr�/s�z$UNIXEndpointsTests.assertConnectArgscCs
ddd�S)r�r�rY)r�rQrSrQrSrSrTr�EszUNIXEndpointsTests.connectArgscCsdddd�S)r�r�i�rY)r��mode�wantPIDrSrQrSrSrTrLszUNIXEndpointsTests.listenArgsc	KsHt|���}tj||jf|�|j||�dd�|�dd�|�dd�f|fS)a�
        Create an L{UNIXServerEndpoint} and return the tools to verify its
        behaviour.

        @param reactor: A fake L{IReactorUNIX} that L{UNIXServerEndpoint} can
            call L{IReactorUNIX.listenUNIX} 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{IReactorUNIX.listenUNIX}.
        r�r�rR�rSr)r"�mktempr�UNIXServerEndpointr�r�r�rSrSrTr�Ss�


��z'UNIXEndpointsTests.createServerEndpointcKs>t|���}tj||jf|�|j||�dd�|�dd�f|fS)a�
        Create an L{UNIXClientEndpoint} and return the values needed to verify
        its behaviour.

        @param reactor: A fake L{IReactorUNIX} that L{UNIXClientEndpoint} can
            call L{IReactorUNIX.connectUNIX} 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{IReactorUNIX.connectUNIX}
        r�r�rQr)r"rUr�UNIXClientEndpointr�r�r�rSrSrTr�js�

��z'UNIXEndpointsTests.createClientEndpointN)rbrcrdrer�r�r�r�r�rr�r�rSrSrSrTrPsrPc@sleZdZdZdZdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�ZdS)�ParserTestszK
    Tests for L{endpoints._parseServer}, the low-level parsing logic.
    r+cOstj||�S)zT
        Provide a hook for test_strports to substitute the deprecated API.
        )rZ_parseServer)rR�a�kwrSrSrT�parse�szParserTests.parsecCs,|�|�d|j�dd|jfddd�f�dS)zN
        Simple strings with a 'tcp:' prefix should be parsed as TCP.
        ztcp:80r�rrr��r�r�N�rzr[r�rQrSrSrT�test_simpleTCP�s�zParserTests.test_simpleTCPcCs,|�|�d|j�dd|jfddd�f�dS)zU
        TCP port descriptions parse their 'interface' argument as a string.
        ztcp:80:interface=127.0.0.1r�rr�r�r\Nr]rQrSrSrT�test_interfaceTCP�s�zParserTests.test_interfaceTCPcCs,|�|�d|j�dd|jfddd�f�dS)zU
        TCP port descriptions parse their 'backlog' argument as an integer.
        ztcp:80:backlog=6r�rr�r\Nr]rQrSrSrT�test_backlogTCP�s�zParserTests.test_backlogTCPc	Cs.|�|�d|j�dd|jfdddd�f�dS)	z�
        L{endpoints._parseServer} returns a C{'UNIX'} port description with
        defaults for C{'mode'}, C{'backlog'}, and C{'wantPID'} when passed a
        string with the C{'unix:'} prefix and no other parameter values.
        zunix:/var/run/finger�UNIX�/var/run/fingerrTr�T�rRr�rSNr]rQrSrSrT�test_simpleUNIX�s

��zParserTests.test_simpleUNIXc	Cs.|�|�d|j�dd|jfdddd�f�dS)	zK
        C{mode} can be set by including C{"mode=<some integer>"}.
        zunix:/var/run/finger:mode=0660rbrci�r�TrdNr]rQrSrSrT�
test_modeUNIX�s

��zParserTests.test_modeUNIXc	Cs.|�|�d|j�dd|jfdddd�f�dS)	zM
        C{wantPID} can be set to false by included C{"lockfile=0"}.
        zunix:/var/run/finger:lockfile=0rbrcrTr�FrdNr]rQrSrSrT�test_wantPIDUNIX�s

��zParserTests.test_wantPIDUNIXc	Cs.|�|�d|j�dd|jfdddd�f�dS)	zf
        Backslash can be used to escape colons and backslashes in port
        descriptions.
        zunix:foo\:bar\=baz\:qux\\rbzfoo:bar=baz:qux\rTr�TrdNr]rQrSrSrT�test_escape�s

��zParserTests.test_escapecCs|�t�d�d�dS)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)rzr�quoteStringArgumentrQrSrSrT�test_quoteStringArgument�s�z$ParserTests.test_quoteStringArgumentc	Cs.|�|�d|j�dd|jfdddd�f�dS)	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=barrbzfoo=barrTr�TrdNr]rQrSrSrT�test_impliedEscape�s

��zParserTests.test_impliedEscapecCs|�t|jd|j�dS)ze
        L{strports.parse} raises C{ValueError} when given an unknown endpoint
        type.
        zbogus-type:nothingN)rpr�r[r�rQrSrSrT�test_unknownType�szParserTests.test_unknownTypeN)rbrcrdrer�r[r^r_rarerfrgrhrjrkrlrSrSrSrTrX�s			


rXc@s�eZdZdZdd�Zdd�Zdd�ZdZd	d
�Zdd�Z	d
d�Z
dd�Zerpee_
e_
ee_
ee	_
ee
_
ee_
dd�Zdd�Zdd�ZdS)�ServerStringTestszC
    Tests for L{twisted.internet.endpoints.serverFromString}.
    cCs\t�}t�|d�}|�|tj�|�|j|�|�|jd�|�|j	d�|�|j
d�dS)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)r�r�serverFromStringr�r�rr?rz�_port�_backlog�
_interface)rRrrDrSrSrT�test_tcp�s�zServerStringTests.test_tcpcCs�t�}t�|dttf�}|�|tj�|�|j|�|�|j	d�|�|j
d�|�|jd�|�|jj
t�|j��}|�|t�dS)z�
        When passed an SSL strports description, L{endpoints.serverFromString}
        returns a L{SSL4ServerEndpoint} instance initialized with the values
        from the string.
        �Vssl:1234:backlog=12:privateKey=%s:certKey=%s:sslmethod=TLSv1_METHOD:interface=10.0.0.1r�rnroN)r�rrp�escapedPEMPathNamer�rLrr?rzrqrrrs�_sslContextFactory�methodrJ�
getContextrH�rRrrD�ctxrSrSrT�test_ssls��
zServerStringTests.test_sslcCs�t�}t�|dtf�}|�|tj�|�|j|�|�|j	d�|�|j
d�|�|jd�|�|jj
t�|�|jjt@�|j��}|�|t�dS)z�
        An SSL string endpoint description with minimal arguments returns
        a properly initialized L{SSL4ServerEndpoint} instance.
        zssl:4321:privateKey=%s��r�rN)r�rrprvr�rLrr?rzrqrrrsrwrxrIr��_optionsrKryrHrzrSrSrT�test_sslWithDefaultss �
�
z&ServerStringTests.test_sslWithDefaultsz(ssl:1234:privateKey=%s:extraCertChain=%scCstt�t�|jttf�}dd�dD�}|j}|�|jd�	d�|d�	d��|�|jd�	d�|d�	d��dS)zf
        Specifying a chain file loads the contained certificates in the right
        order.
        cSs&g|]}t�t�d|f�����qS)zthing%d.pem)rB�loadPEM�casPath�child�
getContent)�.0�nrSrSrT�
<listcomp>Es�z8ServerStringTests.test_sslChainLoads.<locals>.<listcomp>)rYr�rZsha1rYN)
rrpr��SSL_CHAIN_TEMPLATErv�escapedChainPathNamerwrz�extraCertChain�digest)rRrDZexpectedChainCerts�cfrSrSrT�test_sslChainLoads8s �����z$ServerStringTests.test_sslChainLoadsc	Cslt|���}|����|�t��&}t�t�|j	t
t�|j�f�W5QRX|�
t|j�d|jf�dS)zy
        If C{extraCertChain} is passed, it has to contain at least one valid
        certificate in PEM format.
        zOSpecified chain file '%s' doesn't contain any valid certificates in PEM format.N)r3rUZcreate�closerpr�rrpr�r�rvrir4rzr�r)rR�fpZcaughtrSrSrT� test_sslChainFileMustContainCertQs
��
��z2ServerStringTests.test_sslChainFileMustContainCertcCsLd}t�}t�|d�tt|��}|j}|�|jt�|�	t
|�|jj�dS)z�
        If C{dhParameters} are specified, they are passed as
        L{DiffieHellmanParameters} into L{CertificateOptions}.
        ZsomeFilez4ssl:4321:privateKey={0}:certKey={1}:dhParameters={2}N)r�rrp�formatrvrwr�ZdhParametersrErzr3Z_dhFile)rRZfileNamerrDr�rSrSrT�test_sslDHparametersks��z&ServerStringTests.test_sslDHparameterscCs�t�}t�|dttf�}|�|tj�|�|j|�|�	|j
d�|�	|jd�|�	|jd�|�	|j
jt�|j
��}|�|t�dS)zq
        Lack of a trailing newline in key and cert .pem files should not
        generate an exception.
        rur�rnroN)r�rrp�&escapedNoTrailingNewlineKeyPEMPathName�'escapedNoTrailingNewlineCertPEMPathNamer�rLrr?rzrqrrrsrwrxrJryrHrzrSrSrT�test_sslNoTrailingNewlinePem|s"���	
z.ServerStringTests.test_sslNoTrailingNewlinePemcCsht�}t�|d�}|�|tj�|�|j|�|�|jd�|�|j	d�|�|j
d�|�|j�dS)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/bar��SN)
r�rrpr�rVrr?rzZ_addressrr�_moder�Z_wantPID)rRrrrSrSrT�	test_unix�s�zServerStringTests.test_unixcCs&|�ttjdd�}|�t|�d�dS)zq
        L{endpoints.serverFromString} raises C{ValueError} when given an
        unknown endpoint type.
        N�ftl:andromeda/carcosa/hali/2387�Unknown endpoint type: 'ftl')rpr�rrprzr��rRr�rSrSrTrl�s��z"ServerStringTests.test_unknownTypecCsbt|�t�}t�|d�}ddlm}|�|j|�|�|j	|ddf�|�|j
tddd��d	S)
z�
        L{endpoints.serverFromString} looks up plugins of type
        L{IStreamServerEndpoint} and constructs endpoints from them.
        zfake:hello:world:yes=no:up=downr)�fakeZhelloZworldZnoZdown)ZyesZupN)�
addFakePluginr�rrp�twisted.plugins.fakeendpointr�r�parserrzr�r��dict)rR�notAReactorZfakeEndpointr�rSrSrT�test_typeFromPlugin�s�z%ServerStringTests.test_typeFromPluginN)rbrcrdrertr|rr�r�r�r�r�rNrOr�rlr�rSrSrSrTrm�s$rm�fakeendpoint.pycsxddl��j���ttj�����fdd�}|�|�t|���}|�	�t
t�j�
|��|�|��tj�|j�dS)z�
    For the duration of C{testCase}, add a fake plugin to twisted.plugins which
    contains some sample endpoint parsers.
    rNcs(�j���j����tjdd�<dSr[)�modules�clear�updater�__path__rS�ZsavedModulesZsavedPluginPath�sysrSrT�cleanup�s
zaddFakePlugin.<locals>.cleanup)r�r�r��listrr�r�r3rUZcreateDirectoryr4rb�filePath�siblingZcopyTor�r\r4)ZtestCaseZdropinSourcer�r�rSr�rTr��s


�r�c@sheZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZdS)�ClientStringTestszC
    Tests for L{twisted.internet.endpoints.clientFromString}.
    cCsjt�}t�|d�}|�|tj�|�|j|�|�|jd�|�|j	d�|�|j
d�|�|jd�dS)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.2r�r�r��z10.0.0.2rN�r�r�clientFromStringr�r�rr?rz�_hostrq�_timeout�_bindAddress�rRrrFrSrSrTrt�s�zClientStringTests.test_tcpcCsjt�}t�|d�}|�|tj�|�|j|�|�|jd�|�|j	d�|�|j
d�|�|jd�dS)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.2r�r�r�r�Nr�r�rSrSrT�test_tcpPositionalArgs�s�z(ClientStringTests.test_tcpPositionalArgscCs2t�}t�|d�}|�|jd�|�|jd�dS)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.2r�r�N�r�rr�rzr�rqr�rSrSrT�test_tcpHostPositionalArg
s�z+ClientStringTests.test_tcpHostPositionalArgcCs2t�}t�|d�}|�|jd�|�|jd�dS)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.2r�r�Nr�r�rSrSrT�test_tcpPortPositionalArg
s�z+ClientStringTests.test_tcpPortPositionalArgcCs0t�}t�|d�}|�|jd�|�|j�dS)z{
        A TCP strports description may omit I{timeout} or I{bindAddress} to
        allow the default to be used.
        ztcp:host=example.com:port=1234r�N)r�rr�rzr�r�r�r�rSrSrT�test_tcpDefaults-
s�z"ClientStringTests.test_tcpDefaultscCsZt�}t�|d�}|�|tj�|�|j|�|�|jd�|�|j	d�|�
|j�dS)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�r�rr�r�rWrr?rzrCr�r��	_checkPIDr�rSrSrTr�:
s�zClientStringTests.test_unixcCs,t�t�d�}|�|jd�|�|j�dS)zz
        A UNIX strports description may omit I{lockfile} or I{timeout} to allow
        the defaults to be used.
        zunix:path=/var/foo/barr�N)rr�r�rzr�r�r�)rRrFrSrSrT�test_unixDefaultsK
s�z#ClientStringTests.test_unixDefaultscCsZt�}t�|d�}|�|tj�|�|j|�|�|jd�|�|j	d�|�
|j�dS)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=9r�r�Nr�r�rSrSrT�test_unixPathPositionalArgV
s�z,ClientStringTests.test_unixPathPositionalArgcCsbt|�t�}t�|d�}ddlm}|�|j|�|�|j	|ddf�|�|j
tddd��d	S)
z�
        L{endpoints.clientFromString} looks up plugins of type
        L{IStreamClientEndpoint} and constructs endpoints from them.
        �crfake:alpha:beta:cee=dee:num=1r��fakeClientWithReactor�alpha�beta�dee�1�ZceeZnumN)r�r�rr�r�r�rr�rzr�r�r�)rRr��clientEndpointr�rSrSrTr�g
s�z%ClientStringTests.test_typeFromPlugincCs&|�ttjdd�}|�t|�d�dS)zq
        L{endpoints.clientFromString} raises C{ValueError} when given an
        unknown endpoint type.
        Nr�r�)rpr�rr�rzr�r�rSrSrTrlv
s��z"ClientStringTests.test_unknownTypec	CsVt|�t�}t�|d�}ddlm}|�|j|j|j	f||ddft
ddd�f�d	S)
z�
        L{endpoints.clientFromString} will pass a reactor to plugins
        implementing the L{IStreamClientEndpointStringParserWithReactor}
        interface.
        r�rr�r�r�r�r�r�N)r�r�rr�r�r�rzr�r�r�r�)rRrr�r�rSrSrT�test_stringParserWithReactor�
s"��
��z.ClientStringTests.test_stringParserWithReactorN)rbrcrdrertr�r�r�r�r�r�r�r�rlr�rSrSrSrTr��s
r�c@s@eZdZdZereZdd�Zdd�Zdd�Zdd	�Z	d
d�Z
dS)
�SSLClientStringTestszU
    Tests for L{twisted.internet.endpoints.clientFromString} which require SSL.
    csbt�}t�|dtttf�}|�|tj�|�|j|�|�	|j
d�|�	|jd�|�	|jd�|�	|j
d�|j}|�|t�|�	|jt�|�|jt@�|��}|�|t�|�	t|j�t�t|j�}|�t|j��|�	|t�dd�t� d�t� d	�fD�}g�G�fd
d�dt�}|j!�"|��|�	t#dd
��D�dd�d�t#|dd�d��dS)��
        When passed an SSL strports description, L{clientFromString} returns a
        L{SSL4ClientEndpoint} instance initialized with the values from the
        string.
        zdssl:host=example.net:port=4321:privateKey=%s:certKey=%s:bindAddress=10.0.0.3:timeout=3:caCertsDir=%s�example.netr}r��z10.0.0.3rcSs,g|]$}|�����d�rt�|����qS)z.pem)�basename�lower�endswithrBr�r��r��xrSrSrTr��
s�z1SSLClientStringTests.test_ssl.<locals>.<listcomp>�
thing1.pem�
thing2.pemcseZdZ�fdd�ZdS)z.SSLClientStringTests.test_ssl.<locals>.ListCtxcsG�fdd�dt�}|�S)NcseZdZ�fdd�ZdS)zLSSLClientStringTests.test_ssl.<locals>.ListCtx.get_cert_store.<locals>.Storecs��|�dSr[r�)rR�cert�Z
addedCertsrSrT�add_cert�
szUSSLClientStringTests.test_ssl.<locals>.ListCtx.get_cert_store.<locals>.Store.add_certN)rbrcrdr�rSr�rSrT�Store�
sr�)r�)rRr�r�rSrT�get_cert_store�
sz=SSLClientStringTests.test_ssl.<locals>.ListCtx.get_cert_storeN)rbrcrdr�rSr�rSrT�ListCtx�
sr�css|]}t|�VqdSr[�rBr�rSrSrT�	<genexpr>�
sz0SSLClientStringTests.test_ssl.<locals>.<genexpr>cSs|��Sr[�r��r�rSrSrTr��
r�z/SSLClientStringTests.test_ssl.<locals>.<lambda>)�keycSs|��Sr[r�r�rSrSrTr��
r�N)$r�rr�rv�escapedCAsPathNamer�rMrr?rzr�rqr�r�rwrCrxrIr�r~rKryrHrBrH�testCertificaterAZ_setPrivateKeyrDrG�testPrivateCertificater�r��	trustRootZ_addCACertsToContext�sorted)rRrrF�certOptionsr{ZprivateCertZ
expectedCertsr�rSr�rTr|�
sJ��
����zSSLClientStringTests.test_sslcCstt�}t�|dtttf�}|�|tj�|�|j|�|�	|j
d�|�	|jd�|�	|jd�|�	|j
d�dS)r�zZssl:example.net:4321:privateKey=%s:certKey=%s:bindAddress=10.0.0.3:timeout=3:caCertsDir=%sr�r}r�r�N)r�rr�rvr�r�rMrr?rzr�rqr�r�r�rSrSrT�test_sslPositionalArgs�
s��z+SSLClientStringTests.test_sslPositionalArgscCszt�}t�|d�}|�|tj�|�|j|�|�|jd�|�|j	d�|j
}|�|jt�|�
|j�|�
|j�dS)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:4321r�r}N)r�rr�r�rMrr?rzr�rqrwrxrIr�rHrG)rRrrFr�rSrSrTr�
sz)SSLClientStringTests.test_sslWithDefaultscCsXGdd�dt�}t�d���}||_|�dd�t�|�jD�t	�
t�d����g�dS)z�
        If a certificate in the directory is unreadable,
        L{endpoints._loadCAsFromDir} will ignore that certificate.
        c@seZdZdd�ZdS)zKSSLClientStringTests.test_unreadableCertificate.<locals>.UnreadableFilePathcSs.t�|�}|t�d���kr&tt��n|SdS)Nr�)r3r�r�r��IOErrorrr]rSrSrTr��
s

zVSSLClientStringTests.test_unreadableCertificate.<locals>.UnreadableFilePath.getContentN)rbrcrdr�rSrSrSrT�UnreadableFilePath�
sr�r�cSsg|]}t|��qSrSr�r�rSrSrTr�	szCSSLClientStringTests.test_unreadableCertificate.<locals>.<listcomp>r�N)r3r�r��parentZ	clonePathrzrZ_loadCAsFromDirZ_caCertsrBr�r�)rRr�ZcasPathClonerSrSrT�test_unreadableCertificate�
s	
��z/SSLClientStringTests.test_unreadableCertificatecCsHt�}t�|d�}|j}|�|t�|�|j�|��}|�|t	�dS)z�
        When passed an SSL strports description without any extra parameters,
        L{clientFromString} returns a simple non-verifying endpoint that will
        speak SSL.
        z%ssl:host=simple.example.org:port=4321N)
r�rr�rwr�rCr�ZverifyryrH)rRrrFr�r{rSrSrT�test_sslSimples�z#SSLClientStringTests.test_sslSimpleN)rbrcrdrerNrOr|r�rr�r�rSrSrSrTr��
s1r�c@sHeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)� AdoptedStreamServerEndpointTestszA
    Tests for adopted socket-based stream server endpoints.
    cCs&t�|||�}dd�|_dd�|_|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.
        cSsdSr[rS�r,rSrSrTr�.r�zPAdoptedStreamServerEndpointTests._createStubbedAdoptedEndpoint.<locals>.<lambda>cSsdSr[rSr�rSrSrTr�/r�)rZAdoptedStreamServerEndpoint�_close�_setNonBlocking)rRr�fileno�
addressFamilyr�rSrSrT�_createStubbedAdoptedEndpoint$s�

z>AdoptedStreamServerEndpointTests._createStubbedAdoptedEndpointcCs2d}t}|�|||�}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.
        rnr�r�r�)rr�r )rRrr}r�r�rr�rSrSrTr�3s�z5AdoptedStreamServerEndpointTests.createServerEndpointcCs|jS)z�
        @return: The ports which were actually adopted by C{reactor} via calls
            to its L{IReactorSocket.adoptStreamPort} implementation.
        )�adoptedPortsr�rSrSrTr�Gsz0AdoptedStreamServerEndpointTests.expectedServerscCsiS)zx
        @return: A C{dict} of additional keyword arguments to pass to the
            C{createServerEndpoint}.
        rSrQrSrSrTrOsz+AdoptedStreamServerEndpointTests.listenArgscsRt�����dt�}|�t����|�t��tj�}��fdd�}|�|�|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}.
        �
cs��dt�j��dSrX)rzr�r��r��rrRrSrT�listenFailedcszEAdoptedStreamServerEndpointTests.test_singleUse.<locals>.listenFailed)	r�r�rr�r�r�rZAlreadyListenedr�)rRrr�r�rSr�rT�test_singleUseWs
�
z/AdoptedStreamServerEndpointTests.test_singleUsecsRt�}��|dt�}g��fdd�}||_|�t��}��fdd�}|�|�|S)zv
        L{AdoptedStreamServerEndpoint.listen} sets the file description given
        to it to non-blocking.
        r�cs��d|f�dS)N�setNonBlockingr��r�)�eventsrSrTr�sszTAdoptedStreamServerEndpointTests.test_descriptionNonBlocking.<locals>.setNonBlockingcs��dg��dS)N)r�r�r�r��r�rRrSrT�listenedzszNAdoptedStreamServerEndpointTests.test_descriptionNonBlocking.<locals>.listened)r�r�rr�r�r�r�)rRrrr�r�r�rSr�rT�test_descriptionNonBlockingjs
z<AdoptedStreamServerEndpointTests.test_descriptionNonBlockingcsTt�����dt�}g���fdd�}||_|�t��}��fdd�}|�|�|S)z�
        L{AdoptedStreamServerEndpoint.listen} closes its file descriptor after
        adding it to the reactor with L{IReactorSocket.adoptStreamPort}.
        r�cs��d|t�j�f�dS)Nr�)r\r�r�r�)r�rrSrTr��szEAdoptedStreamServerEndpointTests.test_descriptorClosed.<locals>.closecs��dg��dS)N)r�r�rYr�r�r�rSrTr��szHAdoptedStreamServerEndpointTests.test_descriptorClosed.<locals>.listened)r�r�rr�r�r�r�)rRrr�r�r�rS)r�rrRrT�test_descriptorClosed�s
z6AdoptedStreamServerEndpointTests.test_descriptorClosedN)rbrcrdrer�r�r�rr�r�rrSrSrSrTr�sr�c@sFeZdZdZejZdd�Zdd�Zdd�Z	dd	�Z
d
d�Zdd
�ZdS)�SystemdEndpointPluginTestsz�
    Unit tests for the systemd stream server endpoint and endpoint string
    description parser.

    @see: U{systemd<http://www.freedesktop.org/wiki/Software/systemd>}
    cCs<tttj��}|D]}t||j�rq8q|�d|f�dS)z�
        L{endpoints._SystemdParser} is found as a plugin for
        L{interfaces.IStreamServerEndpointStringParser} interface.
        z!Did not find systemd parser in %rN�r�r0r�!IStreamServerEndpointStringParserr��_parserClassr��rRZparsersr�rSrSrT�test_pluginDiscovery�s�z/SystemdEndpointPluginTests.test_pluginDiscoverycCs|��}|�ttj|��dS)zx
        L{endpoints._SystemdParser} instances provide
        L{interfaces.IStreamServerEndpointStringParser}.
        N�rr�rrr�rRr�rSrSrTr��s
�z)SystemdEndpointPluginTests.test_interfacecCspt�}dddddg}d}|��}t|�|_|j||t|�d�}|�|j|�|�|j	|�|�|j
||�dS)	a�
        Helper for unit tests for L{endpoints._SystemdParser.parseStreamServer}
        for different address families.

        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}.
        rPr`r��r�r�)Zdomain�indexN)r�rr5Z	_sddaemonZparseStreamServerr�rrrzr�r�)rRr�ZaddressFamilyStringrZdescriptorsr
r�rDrSrSrT�_parseStreamServerTest�s
�z1SystemdEndpointPluginTests._parseStreamServerTestcCs|�td�dS)zC
        IPv4 can be specified using the string C{"INET"}.
        ZINETN)rrrQrSrSrT�test_parseStreamServerINET�sz5SystemdEndpointPluginTests.test_parseStreamServerINETcCs|�td�dS)zD
        IPv6 can be specified using the string C{"INET6"}.
        ZINET6N)rrrQrSrSrT�test_parseStreamServerINET6�sz6SystemdEndpointPluginTests.test_parseStreamServerINET6cCs@zddlm}Wntk
r.t�d��YnX|�|d�dS)zS
        A UNIX domain socket can be specified using the string C{"UNIX"}.
        r)�AF_UNIXzPlatform lacks AF_UNIX supportrbN)�socketr�ImportErrorrZSkipTestr)rRrrSrSrT�test_parseStreamServerUNIX�s
z5SystemdEndpointPluginTests.test_parseStreamServerUNIXN)
rbrcrdrerZ_SystemdParserrrr�rrr
rrSrSrSrTr�s
rc@s.eZdZdZejZdd�Zdd�Zdd�Z	dS)	�TCP6ServerEndpointPluginTestsz[
    Unit tests for the TCP IPv6 stream server endpoint string description
    parser.
    cCs<tttj��}|D]}t||j�rq8q|�d|f�dS)z�
        L{endpoints._TCP6ServerParser} is found as a plugin for
        L{interfaces.IStreamServerEndpointStringParser} interface.
        z,Did not find TCP6ServerEndpoint parser in %rNrrrSrSrTr�s��z2TCP6ServerEndpointPluginTests.test_pluginDiscoverycCs|��}|�ttj|��dS)z{
        L{endpoints._TCP6ServerParser} instances provide
        L{interfaces.IStreamServerEndpointStringParser}.
        NrrrSrSrTr�	s
�z,TCP6ServerEndpointPluginTests.test_interfacecCsXt�t�d�}|�|tj�|�|jt�|�|jd�|�|jd�|�|j	d�dS)z�
        L{serverFromString} returns a L{TCP6ServerEndpoint} instance with a
        'tcp6' endpoint string description.
        z$tcp6:8080:backlog=12:interface=\:\:1i�rnr�N)
rrpr�r�r�r?rzrqrrrsr�rSrSrT�test_stringDescriptions�z4TCP6ServerEndpointPluginTests.test_stringDescriptionN)
rbrcrdrerZ_TCP6ServerParserrrr�rrSrSrSrTr�s

rc@s.eZdZdZejZdd�Zdd�Zdd�Z	dS)	�StandardIOEndpointPluginTestszM
    Unit tests for the Standard I/O endpoint string description parser.
    cCs<tttj��}|D]}t||j�rq8q|�d|f�dS)z�
        L{endpoints._StandardIOParser} is found as a plugin for
        L{interfaces.IStreamServerEndpointStringParser} interface.
        z,Did not find StandardIOEndpoint parser in %rNrrrSrSrTr(s��z2StandardIOEndpointPluginTests.test_pluginDiscoverycCs|��}|�ttj|��dS)z{
        L{endpoints._StandardIOParser} instances provide
        L{interfaces.IStreamServerEndpointStringParser}.
        NrrrSrSrTr�7s
�z,StandardIOEndpointPluginTests.test_interfacecCs.t�t�d�}|�|tj�|�|jt�dS)z�
        L{serverFromString} returns a L{StandardIOEndpoint} instance with a
        'stdio' endpoint string description.
        zstdio:N)rrpr�r�rr?r�rSrSrTrAsz4StandardIOEndpointPluginTests.test_stringDescriptionN)
rbrcrdrerZ_StandardIOParserrrr�rrSrSrSrTr"s

rc@s eZdZdZdd�Zdd�ZdS)�ConnectProtocolTestsz'
    Tests for C{connectProtocol}.
    cCslt�}t�|dd�}t�}t�||�|�t|j�d�|jddj}|�	|t
j�|�|�
d�|�dS)z�
        C{endpoints.connectProtocol} calls the given endpoint's C{connect()}
        method with a factory that will build the given protocol.
        r�rrYr�N)r�rr�r��connectProtocolrzr�r�Z_wrappedFactoryr�rr+rrv)rRrrZtheProtocolr}rSrSrT�"test_connectProtocolCreatesFactoryPsz7ConnectProtocolTests.test_connectProtocolCreatesFactorycs:t���G�fdd�d�}|�}|��t�|t���dS)z~
        C{endpoints.connectProtocol} returns the result of calling the given
        endpoint's C{connect()} method.
        cseZdZ�fdd�ZdS)zOConnectProtocolTests.test_connectProtocolReturnsConnectResult.<locals>.Endpointcs�S)zR
                Return a marker object for use in our assertion.
                rS)rRr}�r�rSrTr�jszWConnectProtocolTests.test_connectProtocolReturnsConnectResult.<locals>.Endpoint.connectN)rbrcrdr�rSrrSrT�EndpointisrN)rr�rrrr�)rRrrrSrrT�(test_connectProtocolReturnsConnectResultcsz=ConnectProtocolTests.test_connectProtocolReturnsConnectResultN)rbrcrdrerrrSrSrSrTrLsrcs4eZdZdZ�fdd�Z�fdd�Zdd�Z�ZS)�UppercaseWrapperProtocolzL
    A wrapper protocol which uppercases all strings passed through it.
    cstt|��|���dS)z�
        Uppercase a string passed in from the transport.

        @param data: The string to uppercase.
        @type data: L{bytes}
        N)rrr^�upperr]r!rSrTr^zsz%UppercaseWrapperProtocol.dataReceivedcstt|��|���dS)z�
        Uppercase a string passed out to the transport.

        @param data: The string to uppercase.
        @type data: L{bytes}
        N)rrr$rr]r!rSrTr$�szUppercaseWrapperProtocol.writecCs|D]}|�|�qdS)zy
        Uppercase a series of strings passed out to the transport.

        @param seq: An iterable of strings.
        Nr#)rR�seqrNrSrSrTrt�sz&UppercaseWrapperProtocol.writeSequence)rbrcrdrer^r$rtr/rSrSr!rTrus

rc@seZdZdZeZdS)�UppercaseWrapperFactoryzK
    A wrapper factory which uppercases all strings passed through it.
    N)rbrcrdrerrrSrSrSrTr�src@s eZdZdZdd�Zdd�ZdS)�NetstringTrackerz�
    A netstring receiver which keeps track of the strings received.

    @ivar strings: A L{list} of received strings, in order.
    cCs
g|_dSr[)�stringsrQrSrSrTrU�szNetstringTracker.__init__cCs|j�|�dS)z�
        Receive a string and append it to C{self.strings}.

        @param string: The string to be appended to C{self.strings}.
        N)r r\)rRr�rSrSrT�stringReceived�szNetstringTracker.stringReceivedN)rbrcrdrerUr!rSrSrSrTr�src@seZdZdZdS)�	FakeErrorz�
    An error which isn't really an error.

    This is raised in the L{wrapClientTLS} tests in place of a
    'real' exception.
    NrrSrSrSrTr"�sr"c@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)�WrapperClientEndpointTestsz.
    Tests for L{_WrapperClientEndpoint}.
    cCs6t�\|_|_t�|_t�|jt�|_t	�
t�|_dSr[)
r9r�	completerr��contextrZ_WrapperEndpointrr�r+r`rr}rQrSrSrTr�s�z WrapperClientEndpointTests.setUpcCsL|j�|j�}|j��}|�|�}|jj�d�|�	�|�
|jdg�dS)z�
        Any modifications performed by the underlying L{ProtocolWrapper}
        propagate through to the wrapped L{Protocol}.
        s5:hello,sHELLON)r�r�r}r$�succeedOncerrDr�r$�flushrzr �rRZ
connecting�pumpr�rSrSrT�test_wrappingBehavior�s

z0WrapperClientEndpointTests.test_wrappingBehaviorcCsB|j�|j�}|j��}|�|�}|�d�|�|j�	�d�dS)z�
        Methods defined on the wrapped L{Protocol} are accessible from the
        L{Protocol} returned from C{connect}'s L{Deferred}.
        sspams4:SPAM,N)
r�r�r}r$r&rZ
sendStringrz�clientIOZgetOutBufferr(rSrSrT�test_methodsAvailable�s



z0WrapperClientEndpointTests.test_methodsAvailablecCs6|j�|j�}|�|�|j�t��|�|t�dS)zS
        Connection failures propagate upward to C{connect}'s L{Deferred}.
        N)r�r�r}�assertNoResultr$ZfailOncer"r��rRr�rSrSrT�test_connectionFailure�s
z1WrapperClientEndpointTests.test_connectionFailurecCs0|j�|j�}|�|�|��|�|t�dS)zM
        Cancellation propagates upward to C{connect}'s L{Deferred}.
        N)r�r�r}r-r�r�r:r.rSrSrT�test_connectionCancellation�s
z6WrapperClientEndpointTests.test_connectionCancellationcCs8|j�|j�}|j��}|�|�}|�|jj|j�dS)z|
        The transport of the wrapped L{Protocol}'s transport is the transport
        passed to C{makeConnection}.
        N)	r�r�r}r$r&rrr�r+r(rSrSrT�*test_transportOfTransportOfWrappedProtocol�s

�zEWrapperClientEndpointTests.test_transportOfTransportOfWrappedProtocolN)
rbrcrdrerr*r,r/r0r1rSrSrSrTr#�s


r#cCs|�d�jS)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)Z_wrapperFactoryZ_connectionCreator)rWZtlsEndpointrSrSrT�connectionCreatorFromEndpointsr2c@s8eZdZdZereZdd�Zdd�Zdd�Zdd	�Z	d
S)�WrapClientTLSParserTestsz0
    Tests for L{_TLSClientEndpointParser}.
    cCsjt�}t�|td��}|j}|�|j|�|�|jd�|�|j	d�|�|j
d�|�|jtd��dS)zm
        A L{HostnameEndpoint} is constructed from parameters passed to
        L{clientFromString}.
        z4tls:example.com:443:timeout=10:bindAddress=127.0.0.1rr4r�r�N)r�rr�r;�_wrappedEndpointrr?rzr&rqr�r�)rRrrZhostnameEndpointrSrSrT�!test_hostnameEndpointConstruction's���z:WrapClientTLSParserTests.test_hostnameEndpointConstructioncCs>t�}t�|d�}|�|jjd�t||�}|�|jd�dS)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)r�rr�rzr4r&r2�	_hostname)rRrrZconnectionCreatorrSrSrT�test_utf8Encoding:s ����z*WrapClientTLSParserTests.test_utf8Encodingcs|t�}t�t|dg�d�ttt�t��j	���
d��}|�t�
t��}|j��\}}}}}|�d��|�|��dk	szt�t�t���}	t|	jj|	jt�t���jg|	d�}
t��t|
dt�
�fdd��d	��d��t�fd
d��fdd��\}}}
�j�d�|� |�}|j�d
�|
�!�|�"�jj#�|�"|jj#�|�"�jj$�|�"|jj$�t�%�j�}|�&|t�t����dS)z�
        When passed a string endpoint description beginning with C{tls:},
        L{clientFromString} returns a client endpoint initialized with the
        values from the string.
        r�z=tls:localhost:4321:privateKey={}:certificate={}:trustRoots={}�asciiN)rGrHr�r�Fcs�Sr[rSrS)�plainServerrSrTr�}r�z3WrapClientTLSParserTests.test_tls.<locals>.<lambda>)ZisClientZwrappedFactorycs�Sr[rSrS)�serverProtocolrSrTr��r�cs�Sr[rSrS)�clientProtocolrSrTr��r�shello
shi you too
)'r�rr�r�r�rvri�pemPathr�r4�encoder�r+r`r*r��poprvr-�AssertionErrorrAr�r�rCrGZoriginalrB�	chainPathrGr8r�r$rr'r�Z
disconnectingZdisconnectedZpeerFromTransportrz)rRrrr�rzr�r}r�r�Z
serverCertZ
serverOptionsZsProtoZcProtor)ZplainClientZpeerCertificaterS)r;r9r:rT�test_tlsNs`
���

����

�

�z!WrapClientTLSParserTests.test_tlscCs>t�}t�|d�}t||�}|�|jd�|�|jjd�dS)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:443r�rN)r�rr�r2rzr6r4r&)rRrrZcreatorrSrSrT�test_tlsWithDefaults�s

z-WrapClientTLSParserTests.test_tlsWithDefaultsN)
rbrcrdrerNrOr5r7rArBrSrSrSrTr3sCr3cKs�z|j}|j}Wn tk
r0|j}|j}YnX|D]}||kr6td�|���q6i}|�|�|�|�t||�}|||j	<|S)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<Name bound by replacingGlobals but not present in module: {})
Z	func_codeZfunc_globalsrq�__code__�__globals__�	TypeErrorr�r�rrb)ZfunctionZ
newGlobalsZ
codeObjectZfuncGlobalsr�Z
mergedGlobalsZnewFunctionrSrSrT�replacingGlobals�s&
��



rFc@seZdZdZdd�ZdS)�WrapClientTLSTestszj
    Tests for the error-reporting behavior of L{wrapClientTLS} when
    C{pyOpenSSL} is unavailable.
    cCs2ttjdd�}|�t|dd�}|�dt|��dS)z�
        If SSL is not supported, L{TLSMemoryBIOFactory} will be L{None}, which
        causes C{_wrapper} to also be L{None}.  If C{_wrapper} is L{None}, then
        an exception is raised.
        NrFzOpenSSL not available)rFrZ
wrapClientTLSrp�NotImplementedErrorr�r�)rRZreplacedZnotImplementedrSrSrT�test_noOpenSSL�s��z!WrapClientTLSTests.test_noOpenSSLN)rbrcrdrerIrSrSrSrTrG�srG)rSN)r�)�reZ
__future__rr�errnorrrrrrr	�unicodedatar
�typesrZzope.interfacerr
rZzope.interface.interfacerZzope.interface.verifyrrZ
twisted.trialrZtwisted.test.proto_helpersrr�rrrZtwistedrr�rrrrrrrrZtwisted.internet.addressr r!r"r#r$Ztwisted.internet.endpointsr%Ztwisted.internet.interfacesr&r'r(Ztwisted.internet.protocolr)r*r+Ztwisted.internet.stdior,Ztwisted.internet.taskr-Ztwisted.loggerr.r/Ztwisted.pluginr0Ztwisted.pythonr1Ztwisted.python.failurer2Ztwisted.python.filepathr3Ztwisted.python.modulesr4Ztwisted.python.systemdr5Ztwisted.protocolsr6r7Ztwisted.test.iosimr8r9Ztwisted.internet.errorr:Ztwisted.python.compatr;r<r=Ztwisted.python.componentsr>Ztwisted.internet.abstractr?r�r�r<ZnoTrailingNewlineKeyPemPathZnoTrailingNewlineCertPemPathrbr�r�r@rir4rvr�r�r�r�Ztwisted.test.test_sslverifyr@Ztwisted.internet.sslrArBrCrDrEZtwisted.protocols.tlsrGZOpenSSL.SSLrHrIrJrKr�r�r�r�rNrrLr�rfr�rlr�rorrrsZTestCaserxr�r�r�rr	r
rrZIProcessTransportrZIReactorProcessr0r;r_r}r�r�r�r�r�ZSynchronousTestCaser�r�r�rrrr!r"r/r9r<rCrPrXrmr�r�r�r�rrrrZProtocolWrapperrZWrappingFactoryrZNetstringReceiverrr\r"r#r2r3rFrGrSrSrSrT�<module>sJ
�
�
��

	T�,(
xlm�k
�
8
�-
�.�C�nGG��mr^
3�zZ/*)$
G$