o
    b0r                     @   sL  d Z ddlmZ ddlmZ ddlmZmZ ddlm	Z	m
Z
 ddlmZmZ ddlmZ ddlmZmZmZmZ dd	lmZmZ dd
lmZmZmZ ddlmZ ddlmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 g dZ5G dd dej6Z7G dd de2j8Z9G dd dZ:ee,e"e%G dd dZ;G dd de;Z<G dd deZ=ee#G dd  d Z>ee!G d!d" d"Z?ee&e*e)e+e(e'G d#d$ d$Z@ee@D ]ZAeeAe@ qG d%d& d&e@e.ZBee*e)e+e(G d'd( d(ZCG d)d* d*ZDd+d, ZEee0G d-d. d.eZFd/S )0zJ
Assorted functionality which is commonly useful when writing unit tests.
    )Sequence)BytesIO)AF_INETAF_INET6)AnyCallable)implementedByimplementer)verifyClass)addresserrorprotocoltask)_dataMustBeBytesisIPv6Address)IPv4AddressIPv6AddressUNIXAddress)Deferred)UnsupportedAddressFamily)
IConnector	IConsumerIListeningPort	IProtocolIPushProducerIReactorCoreIReactorFDSetIReactorSocketIReactorSSLIReactorTCPIReactorUNIX
ITransport)Clock)ILogObserver)basic)failure)AccumulatingProtocolLineSendingProtocolFakeDatagramTransportStringTransport StringTransportWithDisconnectionStringIOWithoutClosing_FakeConnector	_FakePortMemoryReactorMemoryReactorClockRaisingMemoryReactorNonStreamingProducerwaitUntilAllDisconnectedEventLoggingObserverc                   @   s@   e Zd ZdZd ZZdZdZdZdZ	dd Z
dd Zd	d
 ZdS )r&   ad  
    L{AccumulatingProtocol} is an L{IProtocol} implementation which collects
    the data delivered to it and can fire a Deferred when it is connected or
    disconnected.

    @ivar made: A flag indicating whether C{connectionMade} has been called.
    @ivar data: Bytes giving all the data passed to C{dataReceived}.
    @ivar closed: A flag indicated whether C{connectionLost} has been called.
    @ivar closedReason: The value of the I{reason} parameter passed to
        C{connectionLost}.
    @ivar closedDeferred: If set to a L{Deferred}, this will be fired when
        C{connectionLost} is called.
    r   N    c                 C   sB   d| _ | jd ur| jjd ur| jj}d | j_||  d S d S d S N   )madefactoryprotocolConnectionMadecallbackselfd r>   :/usr/lib/python3/dist-packages/twisted/internet/testing.pyconnectionMadeT   s   z#AccumulatingProtocol.connectionMadec                 C   s   |  j |7  _ d S N)datar<   rB   r>   r>   r?   dataReceived[   s   z!AccumulatingProtocol.dataReceivedc                 C   s6   d| _ || _| jd ur| jd }| _|d  d S d S r5   )closedclosedReasonclosedDeferredr:   )r<   reasonr=   r>   r>   r?   connectionLost^   s   
z#AccumulatingProtocol.connectionLost)__name__
__module____qualname____doc__r7   rE   rF   rG   rB   r8   r@   rD   rI   r>   r>   r>   r?   r&   <   s    r&   c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )r'   FTc                 C   s   |d d  | _ g | _|| _d S rA   )linesresponsestart)r<   rN   rP   r>   r>   r?   __init__i   s   
zLineSendingProtocol.__init__c                 C   s$   | j r| jD ]	}| | qd S d S rA   )rP   rN   sendLiner<   liner>   r>   r?   r@   n   s
   
z"LineSendingProtocol.connectionMadec                 C   s2   | j s| jD ]}| | qg | _| j| d S rA   )rP   rN   rR   rO   appendrS   r>   r>   r?   lineReceiveds   s
   
z LineSendingProtocol.lineReceivedc                 C   
   d| _ d S NT)lostConn)r<   rH   r>   r>   r?   rI   z      
z"LineSendingProtocol.connectionLostN)T)rJ   rK   rL   rY   rQ   r@   rV   rI   r>   r>   r>   r?   r'   f   s    
r'   c                   @   s&   e Zd Ze Zdd ZefddZdS )r(   c                 C   
   g | _ d S rA   )writtenr<   r>   r>   r?   rQ      rZ   zFakeDatagramTransport.__init__c                 C   s   | j ||f d S rA   )r\   rU   )r<   packetaddrr>   r>   r?   write   s   zFakeDatagramTransport.writeN)rJ   rK   rL   objectnoAddrrQ   r`   r>   r>   r>   r?   r(   ~   s    r(   c                   @   s   e Zd ZdZdZdZdZdZdZdZ	dZ
d#ddZdd Zd	d
 Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" ZdS )$r)   a  
    A transport implementation which buffers data in memory and keeps track of
    its other state without providing any behavior.

    L{StringTransport} has a number of attributes which are not part of any of
    the interfaces it claims to implement.  These attributes are provided for
    testing purposes.  Implementation code should not use any of these
    attributes; they are not provided by other transports.

    @ivar disconnecting: A C{bool} which is C{False} until L{loseConnection} is
        called, then C{True}.

    @ivar disconnected: A C{bool} which is C{False} until L{abortConnection} is
        called, then C{True}.

    @ivar producer: If a producer is currently registered, C{producer} is a
        reference to it.  Otherwise, L{None}.

    @ivar streaming: If a producer is currently registered, C{streaming} refers
        to the value of the second parameter passed to C{registerProducer}.

    @ivar hostAddr: L{None} or an object which will be returned as the host
        address of this transport.  If L{None}, a nasty tuple will be returned
        instead.

    @ivar peerAddr: L{None} or an object which will be returned as the peer
        address of this transport.  If L{None}, a nasty tuple will be returned
        instead.

    @ivar producerState: The state of this L{StringTransport} in its capacity
        as an L{IPushProducer}.  One of C{'producing'}, C{'paused'}, or
        C{'stopped'}.

    @ivar io: A L{io.BytesIO} which holds the data which has been written to
        this transport since the last call to L{clear}.  Use L{value} instead
        of accessing this directly.

    @ivar _lenient: By default L{StringTransport} enforces that
        L{resumeProducing} is not called after the connection is lost. This is
        to ensure that any code that does call L{resumeProducing} after the
        connection is lost is not blindly expecting L{resumeProducing} to have
        any impact.

        However, if your test case is calling L{resumeProducing} after
        connection close on purpose, and you know it won't block expecting
        further data to show up, this flag may safely be set to L{True}.

        Defaults to L{False}.
    @type lenient: L{bool}
    FN	producingc                 C   s4   |    |d ur|| _|d ur|| _d| _|| _d S rX   )clearhostAddrpeerAddr	connected_lenient)r<   hostAddresspeerAddresslenientr>   r>   r?   rQ      s   
zStringTransport.__init__c                 C   s   t  | _dS )z
        Discard all data written to this transport so far.

        This is not a transport method.  It is intended for tests.  Do not use
        it in implementation code.
        N)r   ior]   r>   r>   r?   rd      s   zStringTransport.clearc                 C   s
   | j  S )aN  
        Retrieve all data which has been buffered by this transport.

        This is not a transport method.  It is intended for tests.  Do not use
        it in implementation code.

        @return: A C{bytes} giving all data written to this transport since the
            last call to L{clear}.
        @rtype: C{bytes}
        )rl   getvaluer]   r>   r>   r?   value   s   
zStringTransport.valuec                 C   s   t | | j| d S rA   )r   rl   r`   rC   r>   r>   r?   r`      s   zStringTransport.writec                 C   s   | j d| d S )Nr4   )rl   r`   joinrC   r>   r>   r?   writeSequence   s   zStringTransport.writeSequencec                 C   
   d| _ dS )z~
        Close the connection. Does nothing besides toggle the C{disconnecting}
        instance variable to C{True}.
        TN)disconnectingr]   r>   r>   r?   loseConnection      
zStringTransport.loseConnectionc                 C      d| _ |   dS )z
        Abort the connection. Same as C{loseConnection}, but also toggles the
        C{aborted} instance variable to C{True}.
        TN)disconnectedrs   r]   r>   r>   r?   abortConnection   s   zStringTransport.abortConnectionc                 C      | j d u rtdddS | j S )NTCPz192.168.1.1i1  )rf   r   r   r]   r>   r>   r?   getPeer      
zStringTransport.getPeerc                 C   rx   )Nry   z10.0.0.1i90  )re   r   r   r]   r>   r>   r?   getHost  r{   zStringTransport.getHostc                 C   s"   | j d ur	td|| _ || _d S )NzCannot register two producersproducerRuntimeError	streaming)r<   r~   r   r>   r>   r?   registerProducer	     

z StringTransport.registerProducerc                 C   s"   | j d u r	tdd | _ d | _d S )Nz5Cannot unregister a producer unless one is registeredr}   r]   r>   r>   r?   unregisterProducer  r   z"StringTransport.unregisterProducerc                 C   s*   | j r
| js
td| jdkrtdd S )Nz,Cannot resume producing after loseConnectionstoppedz Cannot resume a stopped producer)rr   rh   r   producerStater]   r>   r>   r?   _checkState  s
   
zStringTransport._checkStatec                 C      |    d| _d S )Npausedr   r   r]   r>   r>   r?   pauseProducing     
zStringTransport.pauseProducingc                 C   rW   )Nr   )r   r]   r>   r>   r?   stopProducing   rZ   zStringTransport.stopProducingc                 C   r   )Nrc   r   r]   r>   r>   r?   resumeProducing#  r   zStringTransport.resumeProducing)NNF)rJ   rK   rL   rM   rr   rv   r~   r   re   rf   r   rQ   rd   rn   r`   rp   rs   rw   rz   r|   r   r   r   r   r   r   r>   r>   r>   r?   r)      s0    3
		r)   c                   @   s"   e Zd ZU dZeed< dd ZdS )r*   zt
    A L{StringTransport} which on disconnection will trigger the connection
    lost on the attached protocol.
    r   c                 C   s,   | j rd| _ | jttd d S d S )NFzBye.)rg   r   rI   r%   Failurer   ConnectionDoner]   r>   r>   r?   rs   0  s   z/StringTransportWithDisconnection.loseConnectionN)rJ   rK   rL   rM   r   __annotations__rs   r>   r>   r>   r?   r*   (  s   
 r*   c                   @   s   e Zd ZdZdd ZdS )r+   z)
    A BytesIO that can't be closed.
    c                 C      dS )z
        Do nothing.
        Nr>   r]   r>   r>   r?   close;      zStringIOWithoutClosing.closeN)rJ   rK   rL   rM   r   r>   r>   r>   r?   r+   6  s    r+   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )r-   z
    A fake L{IListeningPort} to be used in tests.

    @ivar _hostAddress: The L{IAddress} this L{IListeningPort} is pretending
        to be listening on.
    c                 C   
   || _ dS )zz
        @param hostAddress: An L{IAddress} this L{IListeningPort} should
            pretend to be listening on.
        N_hostAddress)r<   ri   r>   r>   r?   rQ   J  rt   z_FakePort.__init__c                 C   r   )zQ
        Fake L{IListeningPort.startListening} that doesn't do anything.
        Nr>   r]   r>   r>   r?   startListeningQ  r   z_FakePort.startListeningc                 C   r   )zP
        Fake L{IListeningPort.stopListening} that doesn't do anything.
        Nr>   r]   r>   r>   r?   stopListeningV  r   z_FakePort.stopListeningc                 C      | j S )zN
        Fake L{IListeningPort.getHost} that returns our L{IAddress}.
        r   r]   r>   r>   r?   r|   [     z_FakePort.getHostN)rJ   rK   rL   rM   rQ   r   r   r|   r>   r>   r>   r?   r-   A  s    r-   c                   @   s@   e Zd ZdZdZdZdd Zdd Zdd Zd	d
 Z	dd Z
dS )r,   a'  
    A fake L{IConnector} that allows us to inspect if it has been told to stop
    connecting.

    @ivar stoppedConnecting: has this connector's
        L{_FakeConnector.stopConnecting} method been invoked yet?

    @ivar _address: An L{IAddress} provider that represents our destination.
    Fc                 C   r   )zs
        @param address: An L{IAddress} provider that represents this
            connector's destination.
        N_address)r<   r   r>   r>   r?   rQ   q  rt   z_FakeConnector.__init__c                 C   rq   )zw
        Implement L{IConnector.stopConnecting} and set
        L{_FakeConnector.stoppedConnecting} to C{True}
        TN)stoppedConnectingr]   r>   r>   r?   stopConnectingx  rt   z_FakeConnector.stopConnectingc                 C   rq   )z@
        Implement L{IConnector.disconnect} as a no-op.
        TN)_disconnectedr]   r>   r>   r?   
disconnect     
z_FakeConnector.disconnectc                 C   r   )z=
        Implement L{IConnector.connect} as a no-op.
        Nr>   r]   r>   r>   r?   connect  r   z_FakeConnector.connectc                 C   r   )zp
        Implement L{IConnector.getDestination} to return the C{address} passed
        to C{__init__}.
        r   r]   r>   r>   r?   getDestination     z_FakeConnector.getDestinationN)rJ   rK   rL   rM   r   r   rQ   r   r   r   r   r>   r>   r>   r?   r,   b  s    
r,   c                   @   s   e Zd ZdZdd Zdd ZdDddZd	d
 Zdd Zdd Z	dEddZ
dd Zdedededef fddZdd Zdedef fddZdd Zd d! ZdFd#d$ZdGd'd(ZdHd+d,ZdGd-d.Z	*dHd/d0ZdId2d3ZdJd4d5Zd6d7 Zd8d9 Zd:d; Zd<d= Zd>d? Zd@dA Z dBdC Z!d*S )Kr.   a:  
    A fake reactor to be used in tests.  This reactor doesn't actually do
    much that's useful yet.  It accepts TCP connection setup attempts, but
    they will never succeed.

    @ivar hasInstalled: Keeps track of whether this reactor has been installed.
    @type hasInstalled: L{bool}

    @ivar running: Keeps track of whether this reactor is running.
    @type running: L{bool}

    @ivar hasStopped: Keeps track of whether this reactor has been stopped.
    @type hasStopped: L{bool}

    @ivar hasCrashed: Keeps track of whether this reactor has crashed.
    @type hasCrashed: L{bool}

    @ivar whenRunningHooks: Keeps track of hooks registered with
        C{callWhenRunning}.
    @type whenRunningHooks: L{list}

    @ivar triggers: Keeps track of hooks registered with
        C{addSystemEventTrigger}.
    @type triggers: L{dict}

    @ivar tcpClients: Keeps track of connection attempts (ie, calls to
        C{connectTCP}).
    @type tcpClients: L{list}

    @ivar tcpServers: Keeps track of server listen attempts (ie, calls to
        C{listenTCP}).
    @type tcpServers: L{list}

    @ivar sslClients: Keeps track of connection attempts (ie, calls to
        C{connectSSL}).
    @type sslClients: L{list}

    @ivar sslServers: Keeps track of server listen attempts (ie, calls to
        C{listenSSL}).
    @type sslServers: L{list}

    @ivar unixClients: Keeps track of connection attempts (ie, calls to
        C{connectUNIX}).
    @type unixClients: L{list}

    @ivar unixServers: Keeps track of server listen attempts (ie, calls to
        C{listenUNIX}).
    @type unixServers: L{list}

    @ivar adoptedPorts: Keeps track of server listen attempts (ie, calls to
        C{adoptStreamPort}).

    @ivar adoptedStreamConnections: Keeps track of stream-oriented
        connections added using C{adoptStreamConnection}.
    c                 C   st   d| _ d| _d| _d| _d| _g | _i | _g | _g | _g | _	g | _
g | _g | _g | _g | _g | _t | _t | _dS )z0
        Initialize the tracking lists.
        FTN)hasInstalledrunninghasRun
hasStopped
hasCrashedwhenRunningHookstriggers
tcpClients
tcpServers
sslClients
sslServersunixClientsunixServersadoptedPortsadoptedStreamConnections
connectorssetreaderswritersr]   r>   r>   r?   rQ     s$   zMemoryReactor.__init__c                 C   rq   )zO
        Fake install callable to emulate reactor module installation.
        TN)r   r]   r>   r>   r?   install  r   zMemoryReactor.install
   c                 C      t  zA
        Not implemented; raises L{NotImplementedError}.
        NotImplementedError)r<   nametimeoutr>   r>   r?   resolve  r   zMemoryReactor.resolvec                 C   sF   | j du sJ d| _ d| _| jD ]\}}}||i | q|   dS )a  
        Fake L{IReactorCore.run}.
        Sets C{self.running} to L{True}, runs all of the hooks passed to
        C{self.callWhenRunning}, then calls C{self.stop} to simulate a request
        to stop the reactor.
        Sets C{self.hasRun} to L{True}.
        FTN)r   r   r   stop)r<   fargskwargsr>   r>   r?   run  s   zMemoryReactor.runc                 C   s   d| _ d| _dS )z
        Fake L{IReactorCore.run}.
        Sets C{self.running} to L{False}.
        Sets C{self.hasStopped} to L{True}.
        FTN)r   r   r]   r>   r>   r?   r        
zMemoryReactor.stopc                 C   s   d| _ d| _dS )z
        Fake L{IReactorCore.crash}.
        Sets C{self.running} to L{None}, because that feels crashy.
        Sets C{self.hasCrashed} to L{True}.
        NT)r   r   r]   r>   r>   r?   crash  r   zMemoryReactor.crashr   c                 C   r   r   r   )r<   delayr>   r>   r?   iterate  r   zMemoryReactor.iteratec                 C   r   r   r   )r<   	eventTyper>   r>   r?   fireSystemEvent  r   zMemoryReactor.fireSystemEventphaser   callable.c                 O   s.   | j |i }||g }||||f dS )z
        Fake L{IReactorCore.run}.
        Keep track of trigger by appending it to
        self.triggers[phase][eventType].
        N)r   
setdefaultrU   )r<   r   r   r   r   kwphaseTriggerseventTypeTriggersr>   r>   r?   addSystemEventTrigger%  s   z#MemoryReactor.addSystemEventTriggerc                 C   r   r   r   )r<   	triggerIDr>   r>   r?   removeSystemEventTrigger1  r   z&MemoryReactor.removeSystemEventTriggerc                 O      | j |||f dS )z
        Fake L{IReactorCore.callWhenRunning}.
        Keeps a list of invocations to make in C{self.whenRunningHooks}.
        N)r   rU   )r<   r   r   r   r>   r>   r?   callWhenRunning7  s   zMemoryReactor.callWhenRunningc                 C   sL   |t krtddd}n|tkrtddd}nt | j|||f t|S )zv
        Fake L{IReactorSocket.adoptStreamPort}, that logs the call and returns
        an L{IListeningPort}.
        ry   0.0.0.0  ::r   r   r   r   r   r   rU   r-   )r<   filenoaddressFamilyr8   r_   r>   r>   r?   adoptStreamPort>  s   zMemoryReactor.adoptStreamPortc                 C   r   )z
        Record the given stream connection in C{adoptedStreamConnections}.

        @see:
            L{twisted.internet.interfaces.IReactorSocket.adoptStreamConnection}
        N)r   rU   r<   fileDescriptorr   r8   r>   r>   r?   adoptStreamConnectionM  s   z#MemoryReactor.adoptStreamConnection    c                 C   sN   |t krtddd}n|tkrtddd}nt | j||||f t|S )z
        Fake L{IReactorSocket.adoptDatagramPort}, that logs the call and
        returns a fake L{IListeningPort}.

        @see: L{twisted.internet.interfaces.IReactorSocket.adoptDatagramPort}
        UDPr   r   r   r   )r<   r   r   r   maxPacketSizer_   r>   r>   r?   adoptDatagramPortV  s   zMemoryReactor.adoptDatagramPort2    c                 C   sD   | j ||||f t|rtd||}t|S tdd|}t|S )zm
        Fake L{IReactorTCP.listenTCP}, that logs the call and
        returns an L{IListeningPort}.
        ry   r   )r   rU   r   r   r   r-   )r<   portr8   backlog	interfacer   r>   r>   r?   	listenTCPg  s   zMemoryReactor.listenTCP   Nc                 C   sZ   | j |||||f t|rttd||}nttd||}|| | j| |S )zj
        Fake L{IReactorTCP.connectTCP}, that logs the call and
        returns an L{IConnector}.
        ry   )r   rU   r   r,   r   r   startedConnectingr   )r<   hostr   r8   r   bindAddressconnr>   r>   r?   
connectTCPs  s   
zMemoryReactor.connectTCPc                 C   s&   | j |||||f ttdd|S )zm
        Fake L{IReactorSSL.listenSSL}, that logs the call and
        returns an L{IListeningPort}.
        ry   r   )r   rU   r-   r   r<   r   r8   contextFactoryr   r   r>   r>   r?   	listenSSL  s   zMemoryReactor.listenSSLc                 C   sB   | j ||||||f ttd||}|| | j| |S )zj
        Fake L{IReactorSSL.connectSSL}, that logs the call and returns an
        L{IConnector}.
        ry   )r   rU   r,   r   r   r   )r<   r   r   r8   r   r   r   r   r>   r>   r?   
connectSSL  s   
zMemoryReactor.connectSSL  c                 C   s"   | j |||||f tt|S )zo
        Fake L{IReactorUNIX.listenUNIX}, that logs the call and returns an
        L{IListeningPort}.
        )r   rU   r-   r   r<   r   r8   r   modewantPIDr>   r>   r?   
listenUNIX  s   zMemoryReactor.listenUNIXc                 C   s:   | j ||||f tt|}|| | j| |S )zl
        Fake L{IReactorUNIX.connectUNIX}, that logs the call and returns an
        L{IConnector}.
        )r   rU   r,   r   r   r   )r<   r   r8   r   checkPIDr   r>   r>   r?   connectUNIX  s
   
zMemoryReactor.connectUNIXc                 C      | j | dS )zW
        Fake L{IReactorFDSet.addReader} which adds the reader to a local set.
        N)r   addr<   readerr>   r>   r?   	addReader     zMemoryReactor.addReaderc                 C   r   )zg
        Fake L{IReactorFDSet.removeReader} which removes the reader from a
        local set.
        N)r   discardr   r>   r>   r?   removeReader     zMemoryReactor.removeReaderc                 C   r   )zW
        Fake L{IReactorFDSet.addWriter} which adds the writer to a local set.
        N)r   r   r<   writerr>   r>   r?   	addWriter  r  zMemoryReactor.addWriterc                 C   r   )zg
        Fake L{IReactorFDSet.removeWriter} which removes the writer from a
        local set.
        N)r   r  r  r>   r>   r?   removeWriter  r  zMemoryReactor.removeWriterc                 C   
   t | jS )zn
        Fake L{IReactorFDSet.getReaders} which returns a list of readers from
        the local set.
        )listr   r]   r>   r>   r?   
getReaders  rt   zMemoryReactor.getReadersc                 C   r	  )zn
        Fake L{IReactorFDSet.getWriters} which returns a list of writers from
        the local set.
        )r
  r   r]   r>   r>   r?   
getWriters  rt   zMemoryReactor.getWritersc                 C   s   | j   | j  dS )zt
        Fake L{IReactorFDSet.removeAll} which removed all readers and writers
        from the local sets.
        N)r   rd   r   r]   r>   r>   r?   	removeAll  s   
zMemoryReactor.removeAll)r   )r   )r   r   r   r   Nr   r   r   r   r   )"rJ   rK   rL   rM   rQ   r   r   r   r   r   r   r   strr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r>   r>   r>   r?   r.     sH    8
	
	


	


	


r.   c                   @   s   e Zd Zdd ZdS )r/   c                 C   s   t |  t|  d S rA   )r.   rQ   r"   r]   r>   r>   r?   rQ     s   
zMemoryReactorClock.__init__N)rJ   rK   rL   rQ   r>   r>   r>   r?   r/     s    r/   c                   @   sp   e Zd ZdZdddZdd Zdd	d
ZdddZdddZ	dddZ	dddZ
d ddZdd Zdd ZdS )!r0   z
    A fake reactor to be used in tests.  It accepts TCP connection setup
    attempts, but they will fail.

    @ivar _listenException: An instance of an L{Exception}
    @ivar _connectException: An instance of an L{Exception}
    Nc                 C   s   || _ || _dS )z
        @param listenException: An instance of an L{Exception} to raise
            when any C{listen} method is called.

        @param connectException: An instance of an L{Exception} to raise
            when any C{connect} method is called.
        N)_listenException_connectException)r<   listenExceptionconnectExceptionr>   r>   r?   rQ     s   
zRaisingMemoryReactor.__init__c                 C      | j )zb
        Fake L{IReactorSocket.adoptStreamPort}, that raises
        L{_listenException}.
        r  )r<   r   r   r8   r>   r>   r?   r     r   z$RaisingMemoryReactor.adoptStreamPortr   r   c                 C   r  )zQ
        Fake L{IReactorTCP.listenTCP}, that raises L{_listenException}.
        r  )r<   r   r8   r   r   r>   r>   r?   r     r   zRaisingMemoryReactor.listenTCPr   c                 C   r  )zS
        Fake L{IReactorTCP.connectTCP}, that raises L{_connectException}.
        r  )r<   r   r   r8   r   r   r>   r>   r?   r     r   zRaisingMemoryReactor.connectTCPc                 C   r  )zQ
        Fake L{IReactorSSL.listenSSL}, that raises L{_listenException}.
        r  r   r>   r>   r?   r     r   zRaisingMemoryReactor.listenSSLc                 C   r  )zS
        Fake L{IReactorSSL.connectSSL}, that raises L{_connectException}.
        r  )r<   r   r   r8   r   r   r   r>   r>   r?   r     s   zRaisingMemoryReactor.connectSSLr   r   c                 C   r  )zS
        Fake L{IReactorUNIX.listenUNIX}, that raises L{_listenException}.
        r  r   r>   r>   r?   r     r   zRaisingMemoryReactor.listenUNIXc                 C   r  )zU
        Fake L{IReactorUNIX.connectUNIX}, that raises L{_connectException}.
        r  )r<   r   r8   r   r   r>   r>   r?   r   "  r   z RaisingMemoryReactor.connectUNIXc                 C   r  )ze
        Fake L{IReactorSocket.adoptDatagramPort}, that raises
        L{_connectException}.
        r  )r<   r   r   r   r   r>   r>   r?   r   (  r   z&RaisingMemoryReactor.adoptDatagramPortc                 C   r  )zi
        Fake L{IReactorSocket.adoptStreamConnection}, that raises
        L{_connectException}.
        r  r   r>   r>   r?   r   /  r   z*RaisingMemoryReactor.adoptStreamConnection)NNr  r  r  r  )rJ   rK   rL   rM   rQ   r   r   r   r   r   r   r   r   r   r>   r>   r>   r?   r0     s    






r0   c                   @   s@   e Zd ZdZdZdZdd Zdd Zdd	 Zd
d Z	dd Z
dS )r1   z5
    A pull producer which writes 10 times only.
    r   Fc                 C   s   || _ t | _d S rA   )consumerr   result)r<   r  r>   r>   r?   rQ   ?  s   zNonStreamingProducer.__init__c                 C   sb   | j du s
| jdkrtd| j d| jf  |  jd7  _| jdkr/| j   |   dS dS )z/
        Write the counter value once.
        Nr   z"BUG: resume after unregister/stop.s   %dr6   )r  counterr   r`   r   _doner]   r>   r>   r?   r   C  s   

z$NonStreamingProducer.resumeProducingc                 C   s   t d)z
        An implementation of C{IPushProducer.pauseProducing}. This should never
        be called on a pull producer, so this just raises an error.
        z"BUG: pause should never be called.)r   r]   r>   r>   r?   r   P  s   z#NonStreamingProducer.pauseProducingc                 C   s   d| _ | j}| `|d dS )zQ
        Fire a L{Deferred} so that users can wait for this to complete.
        N)r  r  r:   r;   r>   r>   r?   r  W  s   zNonStreamingProducer._donec                 C   ru   )z&
        Stop all production.
        TN)r   r  r]   r>   r>   r?   r   `  s   z"NonStreamingProducer.stopProducingN)rJ   rK   rL   rM   r  r   rQ   r   r   r  r   r>   r>   r>   r?   r1   7  s    	r1   c                    s0   d  fdd}t | |  _ jdddS )a  
    Take a list of disconnecting protocols, callback a L{Deferred} when they're
    all done.

    This is a hack to make some older tests less flaky, as
    L{ITransport.loseConnection} is not atomic on all reactors (for example,
    the CoreFoundation, which sometimes takes a reactor turn for CFSocket to
    realise). New tests should either not use real sockets in testing, or take
    the advice in
    I{https://jml.io/pages/how-to-disconnect-in-twisted-really.html} to heart.

    @param reactor: The reactor to schedule the checks on.
    @type reactor: L{IReactorTime}

    @param protocols: The protocols to wait for disconnecting.
    @type protocols: A L{list} of L{IProtocol}s.
    Nc                      s"   ddd D vr    d S d S )NTc                 S   s   g | ]}|j jqS r>   )	transportrg   ).0xr>   r>   r?   
<listcomp>}  s    z<waitUntilAllDisconnected.<locals>._check.<locals>.<listcomp>)r   r>   lc	protocolsr>   r?   _check|  s   z(waitUntilAllDisconnected.<locals>._checkg{Gz?T)now)r   LoopingCallclockrP   )reactorr$  r%  r>   r"  r?   r2   h  s
   
r2   c                   @   sD   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Ze	dd Z
dS )r3   a  
    L{ILogObserver} That stores its events in a list for later inspection.
    This class is similar to L{LimitedHistoryLogObserver} save that the
    internal buffer is public and intended for external inspection.  The
    observer implements the sequence protocol to ease iteration of the events.

    @ivar _events: The events captured by this observer
    @type _events: L{list}
    c                 C   r[   rA   _eventsr]   r>   r>   r?   rQ     rZ   zEventLoggingObserver.__init__c                 C   r	  rA   )lenr+  r]   r>   r>   r?   __len__  rZ   zEventLoggingObserver.__len__c                 C   s
   | j | S rA   r*  )r<   indexr>   r>   r?   __getitem__  rZ   z EventLoggingObserver.__getitem__c                 C   r	  rA   )iterr+  r]   r>   r>   r?   __iter__  rZ   zEventLoggingObserver.__iter__c                 C   r   )z'
        @see: L{ILogObserver}
        N)r+  rU   )r<   eventr>   r>   r?   __call__  r  zEventLoggingObserver.__call__c                    s(   |      | fdd  S )a-  
        Create an L{EventLoggingObserver} instance that observes the provided
        publisher and will be cleaned up with addCleanup().

        @param testInstance: Test instance in which this logger is used.
        @type testInstance: L{twisted.trial.unittest.TestCase}

        @param publisher: Log publisher to observe.
        @type publisher: twisted.logger.LogPublisher

        @return: An EventLoggingObserver configured to observe the provided
            publisher.
        @rtype: L{twisted.test.proto_helpers.EventLoggingObserver}
        c                      s
     S rA   )removeObserverr>   obs	publisherr>   r?   <lambda>  s   
 z8EventLoggingObserver.createWithCleanup.<locals>.<lambda>)addObserver
addCleanup)clstestInstancer7  r>   r5  r?   createWithCleanup  s   
z&EventLoggingObserver.createWithCleanupN)rJ   rK   rL   rM   rQ   r-  r/  r1  r3  classmethodr=  r>   r>   r>   r?   r3     s    
r3   N)GrM   collections.abcr   rl   r   socketr   r   typingr   r   zope.interfacer   r	   zope.interface.verifyr
   twisted.internetr   r   r   r   twisted.internet.abstractr   r   twisted.internet.addressr   r   r   twisted.internet.deferr   twisted.internet.errorr   twisted.internet.interfacesr   r   r   r   r   r   r   r   r   r   r    r!   twisted.internet.taskr"   twisted.loggerr#   twisted.protocolsr$   twisted.pythonr%   __all__Protocolr&   LineReceiverr'   r(   r)   r*   r+   r-   r,   r.   ifacer/   r0   r1   r2   r3   r>   r>   r>   r?   <module>   sZ   8*

   /  IP1