
    hU              	      x   S r SSKJr  SSKrSSKJr  SSKJr  SSKJ	r	J
r
  SSKJr  SSKJrJrJrJrJrJrJrJrJr  SS	KJrJr  SS
KJr  SSKJrJr  SSKJrJrJ r J!r!  SSK"J#r#J$r$  SSK%J&r&J'r'J(r(  SSK)J*r*J+r+J,r,  SSK-J.r.  SSK/J0r0J1r1J2r2J3r3J4r4J5r5J6r6J7r7J8r8J9r9J:r:J;r;J<r<J=r=J>r>J?r?J@r@  SSKAJBrB  SSKCJDrDJErEJFrF  SSKGJHrH  SSKIJJrJ  SSKKJLrL  / SQrM\" S5      rN " S S\R                  5      rP " S S\ R                  5      rQ " S S\HR                  5      rS " S S 5      rT\" \@\2\75       " S! S"5      5       rU " S# S$\U5      rV " S% S&\5      rW\" \55       " S' S(5      5       rX\" \15       " S) S*5      5       rY\" \45      \ " S+ S,5      5       5       rZ\" \35       " S- S.5      5       r[\" \8\=\<\>\;\9\:5       " S/ S05      5       r\\" \\5       H  r]\" \]\\5        M      " S1 S2\\\B5      r^\" \=\<\>\;\:5       " S3 S45      5       r_ " S5 S65      r`S7 ra\" \D5       " S8 S9\\E   5      5       rb\" S:5      rc    S>S; jrdS?S< jreS= rfg)@zJ
Assorted functionality which is commonly useful when writing unit tests.
    )annotationsN)	dataclass)BytesIO)AF_INETAF_INET6)time)	AnyCallable	Coroutine	GeneratorIteratorSequenceTypeVarUnionoverload)implementedByimplementer)verifyClass)	ParamSpecSelf)addresserrorprotocoltask)_dataMustBeBytesisIPv6Address)IPv4AddressIPv6AddressUNIXAddress)DeferredensureDeferredsucceed)UnsupportedAddressFamily)IAddress
IConnector	IConsumerIHostnameResolverIHostResolutionIListeningPort	IProtocolIPushProducerIReactorCoreIReactorFDSetIReactorPluggableNameResolverIReactorSocketIReactorSSLIReactorTCPIReactorUNIXIResolutionReceiver
ITransport)Clock)ILogObserverLogEventLogPublisher)basic)failure)TestCase)AccumulatingProtocolLineSendingProtocolFakeDatagramTransportStringTransport StringTransportWithDisconnectionStringIOWithoutClosing_FakeConnector	_FakePortMemoryReactorMemoryReactorClockRaisingMemoryReactorNonStreamingProducerwaitUntilAllDisconnectedEventLoggingObserver_Pc                  $    \ rS rSr% SrS\S'   Srg)_ProtocolConnectionMadeHaverR   zX
Explicit stipulation of the implicit requirement of L{AccumulatingProtocol}'s factory.
z%Deferred[AccumulatingProtocol] | NoneprotocolConnectionMade N)__name__
__module____qualname____firstlineno____doc____annotations____static_attributes__rO       _/root/1688_scrapy/alibaba-scraper/venv/lib/python3.13/site-packages/twisted/internet/testing.pyrL   rL   R   s     BArW   rL   c                      \ rS rSr% SrS\S'   S\S'   S=rrSrS\S	'   Sr	S
\S'   Sr
S\S'   SrS\S'   SS jrSS jrSSS jjrSrg)r<   Z   a8  
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.
intmadeclosedr   Nfailure.Failure | NoneclosedReasonzDeferred[None] | NoneclosedDeferredrW   bytesdatazprotocol.Factory | Nonefactoryc                    SU l         U R                  nUb3  UR                  b%  UR                  nS Ul        UR                  U 5        g g g N   )r\   rc   rN   callback)selfrc   ds      rX   connectionMade#AccumulatingProtocol.connectionMader   sP    	LL 	 7#A#A#M..A-1G*JJt $NrW   c                .    U =R                   U-  sl         g N)rb   rh   rb   s     rX   dataReceived!AccumulatingProtocol.dataReceived|   s    		T	rW   c                    SU l         Xl        U R                  b%  U R                  S so l        UR                  S 5        g g re   )r]   r_   r`   rg   )rh   reasonri   s      rX   connectionLost#AccumulatingProtocol.connectionLost   s?    "*%)%8%8$"A"JJt +rW   )r]   r`   r_   r\   returnNone)rb   ra   rv   rw   rm   )rr   r^   rv   rw   )rP   rQ   rR   rS   rT   rU   r\   r]   r_   r`   rb   rc   rj   ro   rs   rV   rO   rW   rX   r<   r<   Z   s\     IKD6+/L(/,0N)0D%'+G$+ rW   r<   c                  4    \ rS rSrSrS	S jrS rS rS rSr	g)
r=      Fc                2    US S  U l         / U l        X l        g rm   )linesresponsestart)rh   r{   r}   s      rX   __init__LineSendingProtocol.__init__   s    1X

rW   c                p    U R                   (       a%  U R                   H  nU R                  U5        M     g g rm   )r}   r{   sendLinerh   lines     rX   rj   "LineSendingProtocol.connectionMade   s(    ::

d# # rW   c                    U R                   (       d+  U R                   H  nU R                  U5        M     / U l        U R                  R	                  U5        g rm   )r}   r{   r   r|   appendr   s     rX   lineReceived LineSendingProtocol.lineReceived   s<    zz

d# #DJT"rW   c                    SU l         g NT)lostConn)rh   rr   s     rX   rs   "LineSendingProtocol.connectionLost   s	    rW   )r{   r   r|   r}   N)T)
rP   rQ   rR   rS   r   r~   rj   r   rs   rV   rO   rW   rX   r=   r=      s    H
$
#rW   r=   c                  4    \ rS rSr\" 5       rS r\4S jrSrg)r>      c                    / U l         g rm   writtenrh   s    rX   r~   FakeDatagramTransport.__init__   s	    rW   c                <    U R                   R                  X45        g rm   )r   r   )rh   packetaddrs      rX   writeFakeDatagramTransport.write   s    VN+rW   r   N)	rP   rQ   rR   rS   objectnoAddrr~   r   rV   rO   rW   rX   r>   r>      s    XF "( ,rW   r>   c                      \ rS rSrSrSrSrSrSrSr	Sr
SrSS jrS rS rS	 rS
 rS rS rS rS rS rS rS rS rS rS rSrg)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                b    U R                  5         Ub  Xl        Ub  X l        SU l        X0l        g r   )clearhostAddrpeerAddr	connected_lenient)rh   hostAddresspeerAddresslenients       rX   r~   StringTransport.__init__   s-    

"'M"'MrW   c                "    [        5       U l        g)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   s    rX   r   StringTransport.clear   s     )rW   c                6    U R                   R                  5       $ )a  
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}
)r   getvaluer   s    rX   valueStringTransport.value   s     ww!!rW   c                P    [        U5        U R                  R                  U5        g rm   )r   r   r   rn   s     rX   r   StringTransport.write	  s    drW   c                X    U R                   R                  SR                  U5      5        g )NrW   )r   r   joinrn   s     rX   writeSequenceStringTransport.writeSequence  s    chhtn%rW   c                    SU l         g)zf
Close the connection. Does nothing besides toggle the C{disconnecting}
instance variable to C{True}.
TN)disconnectingr   s    rX   loseConnectionStringTransport.loseConnection  s    
 "rW   c                2    SU l         U R                  5         g)zp
Abort the connection. Same as C{loseConnection}, but also toggles the
C{aborted} instance variable to C{True}.
TN)disconnectedr   r   s    rX   abortConnectionStringTransport.abortConnection  s    
 !rW   c                d    U R                   c  [        R                  " SSS5      $ U R                   $ )NTCPz192.168.1.1i1  )r   r   r   r   s    rX   getPeerStringTransport.getPeer  s+    == &&umUCC}}rW   c                d    U R                   c  [        R                  " SSS5      $ U R                   $ )Nr   z10.0.0.1i90  )r   r   r   r   s    rX   getHostStringTransport.getHost$  s+    == &&uj%@@}}rW   c                L    U R                   b  [        S5      eXl         X l        g )NzCannot register two producersproducerRuntimeError	streaming)rh   r   r   s      rX   registerProducer StringTransport.registerProducer*  s"    ==$>?? "rW   c                P    U R                   c  [        S5      eS U l         S U l        g )Nz5Cannot unregister a producer unless one is registeredr   r   s    rX   unregisterProducer"StringTransport.unregisterProducer0  s&    == VWWrW   c                    U R                   (       a  U R                  (       d  [        S5      eU R                  S:X  a  [        S5      eg )Nz,Cannot resume producing after loseConnectionstoppedz Cannot resume a stopped producer)r   r   r   producerStater   s    rX   _checkStateStringTransport._checkState7  s<    dmmMNN*ABB +rW   c                2    U R                  5         SU l        g )Npausedr   r   r   s    rX   pauseProducingStringTransport.pauseProducing=  s    %rW   c                    SU l         g )Nr   )r   r   s    rX   stopProducingStringTransport.stopProducingA  s
    &rW   c                2    U R                  5         SU l        g )Nr   r   r   s    rX   resumeProducingStringTransport.resumeProducingD  s    (rW   )
r   r   r   r   r   r   r   r   r   r   )NNF)rP   rQ   rR   rS   rT   r   r   r   r   r   r   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rV   rO   rW   rX   r?   r?      sy    1f MLHIHHM "&"
#C&')rW   r?   c                  *    \ rS rSr% SrS\S'   S rSrg)r@   iI  zh
A L{StringTransport} which on disconnection will trigger the connection
lost on the attached protocol.
r*   r   c                    U R                   (       aK  SU l         U R                  R                  [        R                  " [
        R                  " S5      5      5        g g )NFzBye.)r   r   rs   r:   Failurer   ConnectionDoner   s    rX   r   /StringTransportWithDisconnection.loseConnectionQ  s;    >>"DNMM((9M9Mf9U)VW rW   )r   N)rP   rQ   rR   rS   rT   rU   r   rV   rO   rW   rX   r@   r@   I  s    
 XrW   r@   c                      \ rS rSrSrS rSrg)rA   iW  z!
A BytesIO that can't be closed.
c                    g)z
Do nothing.
NrO   r   s    rX   closeStringIOWithoutClosing.close\      rW   rO   N)rP   rQ   rR   rS   rT   r   rV   rO   rW   rX   rA   rA   W  s    rW   rA   c                  0    \ rS rSrSrS rS rS rS rSr	g)	rC   ib  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                    Xl         g)zb
@param hostAddress: An L{IAddress} this L{IListeningPort} should
    pretend to be listening on.
N_hostAddress)rh   r   s     rX   r~   _FakePort.__init__k  s
    
 (rW   c                    g)zA
Fake L{IListeningPort.startListening} that doesn't do anything.
NrO   r   s    rX   startListening_FakePort.startListeningr  r   rW   c                    g)z@
Fake L{IListeningPort.stopListening} that doesn't do anything.
NrO   r   s    rX   stopListening_FakePort.stopListeningw  r   rW   c                    U R                   $ )z>
Fake L{IListeningPort.getHost} that returns our L{IAddress}.
r   r   s    rX   r   _FakePort.getHost|  s        rW   r   N)
rP   rQ   rR   rS   rT   r~   r   r   r   rV   rO   rW   rX   rC   rC   b  s    (

!rW   rC   c                  >    \ rS rSrSrSrSrS rS rS r	S r
S rS	rg
)rB   i  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                    Xl         g)z[
@param address: An L{IAddress} provider that represents this
    connector's destination.
N_address)rh   r   s     rX   r~   _FakeConnector.__init__  s	    
  rW   c                    SU l         g)z_
Implement L{IConnector.stopConnecting} and set
L{_FakeConnector.stoppedConnecting} to C{True}
TN)stoppedConnectingr   s    rX   stopConnecting_FakeConnector.stopConnecting  s    
 "&rW   c                    SU l         g)z0
Implement L{IConnector.disconnect} as a no-op.
TN)_disconnectedr   s    rX   
disconnect_FakeConnector.disconnect  s     "rW   c                    g)z-
Implement L{IConnector.connect} as a no-op.
NrO   r   s    rX   connect_FakeConnector.connect  r   rW   c                    U R                   $ )zX
Implement L{IConnector.getDestination} to return the C{address} passed
to C{__init__}.
r   r   s    rX   getDestination_FakeConnector.getDestination  s    
 }}rW   )r   r   r   N)rP   rQ   rR   rS   rT   r   r   r~   r   r   r  r  rV   rO   rW   rX   rB   rB     s-     M &"
rW   rB   c                  *    \ rS rSr% S\S'   SS jrSrg)_SynchronousResolutioni  strnamec                    [        S5      e)zs
Provided just for interface compliance; it should be impossible to
reach here, since it's resolved synchronously.
zalready resolved)	Exceptionr   s    rX   cancel_SynchronousResolution.cancel  s    
 *++rW   rO   Nru   )rP   rQ   rR   rS   rU   r  rV   rO   rW   rX   r	  r	    s     I,rW   r	  c                  B    \ rS rSrSr   S           SS jjrSrg)SynchronousResolveri  z
A very simple L{IHostnameResolver} that immediately, synchronously resolves
all host names to a single static address (TCPv4, 127.0.0.1) while
preserving any requested port number.
Nc                    [        U5      nUR                  U5        UR                  [        SSU5      5        UR	                  5         U$ )z|
Implement L{IHostnameResolver.resolveHostName} to synchronously resolve
the name and complete resolution before returning.
r   z	127.0.0.1)r	  resolutionBeganaddressResolvedr   resolutionComplete)rh   resolutionReceiverhostName
portNumberaddressTypestransportSemantics
resolutions          rX   resolveHostName#SynchronousResolver.resolveHostName  sE     ,H5
**:6**;uk:+VW--/rW   rO   )r   Nr   )r  r3   r  r
  r  r[   r  zSequence[type[IAddress]] | Noner  r
  rv   r(   )rP   rQ   rR   rS   rT   r  rV   rO   rW   rX   r  r    sV     8<"'/  	
 6   
 rW   r  c                  &   \ rS rSr% SrS\S'   S rS#S jrS rS$S jr	S	 r
S
 rS rS%S jrS r            S&S jrS r        S'S jrS rS rS(S jrS)S jrS*S jrS)S jr S*S jrS+S jrS,S jrS rS rS rS rS rS  r S! r!S"r"g)-rD   i  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}.
r'   nameResolverc                >   SU l         SU l        SU l        SU l        SU l        / U l        0 U l        / U l        / U l        / U l	        / U l
        / U l        / U l        / U l        / U l        / U l        [!        5       U l        [!        5       U l        ['        5       U l        g)z 
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   s    rX   r~   MemoryReactor.__init__  s     " "(*%uu/1rW   c                *    U R                   nXl         U$ z-
Implement L{IReactorPluggableNameResolver}.
r  )rh   resolveroldResolvers      rX   installNameResolver!MemoryReactor.installNameResolver;  s     ''$rW   c                    SU l         g)z?
Fake install callable to emulate reactor module installation.
TN)r!  r   s    rX   installMemoryReactor.installC  s     !rW   c                    [        5       ez1
Not implemented; raises L{NotImplementedError}.
NotImplementedError)rh   r  timeouts      rX   resolveMemoryReactor.resolveI       "##rW   c                    U R                   SL d   eSU l         SU l        U R                   H  u  pnU" U0 UD6  M     U R                  5         g)z
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)rh   fargskwargss       rX   runMemoryReactor.runO  sP     ||u$$$#44OAVtv  5 			rW   c                     SU l         SU l        g)za
Fake L{IReactorCore.run}.
Sets C{self.running} to L{False}.
Sets C{self.hasStopped} to L{True}.
FTN)r"  r$  r   s    rX   rH  MemoryReactor.stopa  s     rW   c                     SU l         SU l        g)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   s    rX   crashMemoryReactor.crashj  s     rW   c                    [        5       er@  rA  )rh   delays     rX   iterateMemoryReactor.iterates  rF  rW   c                    [        5       er@  rA  )rh   	eventTypes     rX   fireSystemEventMemoryReactor.fireSystemEventy  rF  rW   c                    U R                   R                  U0 5      nUR                  U/ 5      nUR                  X4U45        g)ze
Fake L{IReactorCore.run}.
Keep track of trigger by appending it to
self.triggers[phase][eventType].
N)r'  
setdefaultr   )rh   phaserX  callablerJ  kwphaseTriggerseventTypeTriggerss           rX   addSystemEventTrigger#MemoryReactor.addSystemEventTrigger  s@     00;)44YC  ("!56rW   c                    [        5       er@  rA  )rh   	triggerIDs     rX   removeSystemEventTrigger&MemoryReactor.removeSystemEventTrigger  rF  rW   c                >    U R                   R                  XU45        g)zh
Fake L{IReactorCore.callWhenRunning}.
Keeps a list of invocations to make in C{self.whenRunningHooks}.
N)r&  r   )rh   r^  rJ  r_  s       rX   callWhenRunningMemoryReactor.callWhenRunning  s     	$$hb%9:rW   c                    U[         :X  a  [        SSS5      nO"U[        :X  a  [        SSS5      nO
[	        5       eU R
                  R                  XU45        [        U5      $ )z^
Fake L{IReactorSocket.adoptStreamPort}, that logs the call and returns
an L{IListeningPort}.
r   0.0.0.0  ::r   r   r   r   r#   r.  r   rC   )rh   filenoaddressFamilyrc   r   s        rX   adoptStreamPortMemoryReactor.adoptStreamPort  s\    
 G#ui6Dh&udD1D*,,  &!ABrW   c                >    U R                   R                  XU45        g)z
Record the given stream connection in C{adoptedStreamConnections}.

@see:
    L{twisted.internet.interfaces.IReactorSocket.adoptStreamConnection}
N)r/  r   rh   fileDescriptorrq  rc   s       rX   adoptStreamConnection#MemoryReactor.adoptStreamConnection  s     	%%,,nW-UVrW   c                    U[         :X  a  [        SSS5      nO"U[        :X  a  [        SSS5      nO
[	        5       eU R
                  R                  XX445        [        U5      $ )z
Fake L{IReactorSocket.adoptDatagramPort}, that logs the call and
returns a fake L{IListeningPort}.

@see: L{twisted.internet.interfaces.IReactorSocket.adoptDatagramPort}
UDPrl  rm  rn  ro  )rh   rp  rq  r   maxPacketSizer   s         rX   adoptDatagramPortMemoryReactor.adoptDatagramPort  s\     G#ui6Dh&udD1D*,,  &!QRrW   c                    U R                   R                  XX445        [        U5      (       a  [        SXA5      nO[	        SSU5      n[        U5      $ )zU
Fake L{IReactorTCP.listenTCP}, that logs the call and
returns an L{IListeningPort}.
r   rl  )r)  r   r   r   r   rC   )rh   portrc   backlog	interfacer   s         rX   	listenTCPMemoryReactor.listenTCP  sK    
 	wBC##!%9G!%D9G!!rW   Nc                   U R                   R                  XX4U45        [        U5      (       a  [        [	        SX5      5      nO[        [        SX5      5      nUR                  U5        U R                  R                  U5        U$ )zR
Fake L{IReactorTCP.connectTCP}, that logs the call and
returns an L{IConnector}.
r   )r(  r   r   rB   r   r   startedConnectingr0  )rh   hostr  rc   rC  bindAddressconns          rX   
connectTCPMemoryReactor.connectTCP  so    
 	GkJK!+eT"@AD!+eT"@AD!!$'t$rW   c                j    U R                   R                  XX4U45        [        [        SSU5      5      $ )zU
Fake L{IReactorSSL.listenSSL}, that logs the call and
returns an L{IListeningPort}.
r   rl  )r+  r   rC   r   rh   r  rc   contextFactoryr  r  s         rX   	listenSSLMemoryReactor.listenSSL  s1    
 	~	RSUIt<==rW   c                    U R                   R                  XX4XV45        [        [        SX5      5      nUR	                  U5        U R
                  R                  U5        U$ )zR
Fake L{IReactorSSL.connectSSL}, that logs the call and returns an
L{IConnector}.
r   )r*  r   rB   r   r  r0  )rh   r  r  rc   r  rC  r  r  s           rX   
connectSSLMemoryReactor.connectSSL  sX     	'G	
 k%<=!!$'t$rW   c                f    U R                   R                  XX4U45        [        [        U5      5      $ )zW
Fake L{IReactorUNIX.listenUNIX}, that logs the call and returns an
L{IListeningPort}.
)r-  r   rC   r   rh   r   rc   r  modewantPIDs         rX   
listenUNIXMemoryReactor.listenUNIX  s/    
 	7' JKW-..rW   c                    U R                   R                  XX445        [        [        U5      5      nUR	                  U5        U R
                  R                  U5        U$ )zT
Fake L{IReactorUNIX.connectUNIX}, that logs the call and returns an
L{IConnector}.
)r,  r   rB   r   r  r0  )rh   r   rc   rC  checkPIDr  s         rX   connectUNIXMemoryReactor.connectUNIX  sQ    
 	7 EFk'23!!$'t$rW   c                :    U R                   R                  U5        g)zG
Fake L{IReactorFDSet.addReader} which adds the reader to a local set.
N)r2  addrh   readers     rX   	addReaderMemoryReactor.addReader       	 rW   c                :    U R                   R                  U5        g)zO
Fake L{IReactorFDSet.removeReader} which removes the reader from a
local set.
N)r2  discardr  s     rX   removeReaderMemoryReactor.removeReader      
 	V$rW   c                :    U R                   R                  U5        g)zG
Fake L{IReactorFDSet.addWriter} which adds the writer to a local set.
N)r3  r  rh   writers     rX   	addWriterMemoryReactor.addWriter  r  rW   c                :    U R                   R                  U5        g)zO
Fake L{IReactorFDSet.removeWriter} which removes the writer from a
local set.
N)r3  r  r  s     rX   removeWriterMemoryReactor.removeWriter  r  rW   c                ,    [        U R                  5      $ )zV
Fake L{IReactorFDSet.getReaders} which returns a list of readers from
the local set.
)listr2  r   s    rX   
getReadersMemoryReactor.getReaders&      
 DLL!!rW   c                ,    [        U R                  5      $ )zV
Fake L{IReactorFDSet.getWriters} which returns a list of writers from
the local set.
)r  r3  r   s    rX   
getWritersMemoryReactor.getWriters-  r  rW   c                l    U R                   R                  5         U R                  R                  5         g)z\
Fake L{IReactorFDSet.removeAll} which removed all readers and writers
from the local sets.
N)r2  r   r3  r   s    rX   	removeAllMemoryReactor.removeAll4  s$    
 	rW   )r.  r/  r0  r%  r!  r#  r$  r  r2  r"  r*  r+  r(  r)  r'  r,  r-  r&  r3  )r8  r'   rv   r'   )
   )r   )r]  r
  rX  r
  r^  Callable[_P, object]rJ  _P.argsr_  	_P.kwargsrv   rw   )r^  r  rJ  r  r_  r  rv   rw   )i    2       Nr  i  r   r  r   )#rP   rQ   rR   rS   rT   rU   r~   r:  r=  rD  rL  rH  rQ  rU  rY  rb  rf  ri  rr  rw  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  rV   rO   rW   rX   rD   rD     s    6p $#28!$$$$77 7 '	7
 7 7 
7"$;,;5<;DM;	;W"
"> LP/	!%!%""rW   rD   c                      \ rS rSrS rSrg)rE   iA  c                Z    [         R                  U 5        [        R                  " U 5        g rm   )rD   r~   r5   r   s    rX   r~   MemoryReactorClock.__init__B  s    t$trW   rO   N)rP   rQ   rR   rS   r~   rV   rO   rW   rX   rE   rE   A  s    rW   rE   c                      \ rS rSrSr  S     SS jjrSS jrS rSS jrSS jr	SS	 jr
 SS
 jrSS jrSS jrS rS rSrg)rF   iG  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                :    Xl         X l        [        5       U l        g)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_connectExceptionr  r  )rh   listenExceptionconnectExceptions      rX   r~   RaisingMemoryReactor.__init__W  s     !0!1/B/DrW   c                ,    U R                   Uso l         U$ r6  r7  )rh   r  previouss      rX   r:  (RaisingMemoryReactor.installNameResolverg  s     '+&7&7##rW   c                    U R                   e)zJ
Fake L{IReactorSocket.adoptStreamPort}, that raises
L{_listenException}.
r  )rh   rp  rq  rc   s       rX   rr  $RaisingMemoryReactor.adoptStreamPortn  s    
 ###rW   c                    U R                   e)zA
Fake L{IReactorTCP.listenTCP}, that raises L{_listenException}.
r  )rh   r  rc   r  r  s        rX   r  RaisingMemoryReactor.listenTCPu       ###rW   c                    U R                   e)zC
Fake L{IReactorTCP.connectTCP}, that raises L{_connectException}.
r  )rh   r  r  rc   rC  r  s         rX   r  RaisingMemoryReactor.connectTCP{       $$$rW   c                    U R                   e)zA
Fake L{IReactorSSL.listenSSL}, that raises L{_listenException}.
r  r  s         rX   r  RaisingMemoryReactor.listenSSL  r  rW   c                    U R                   e)zC
Fake L{IReactorSSL.connectSSL}, that raises L{_connectException}.
r  )rh   r  r  rc   r  rC  r  s          rX   r  RaisingMemoryReactor.connectSSL  s     $$$rW   c                    U R                   e)zC
Fake L{IReactorUNIX.listenUNIX}, that raises L{_listenException}.
r  r  s         rX   r  RaisingMemoryReactor.listenUNIX  r  rW   c                    U R                   e)zE
Fake L{IReactorUNIX.connectUNIX}, that raises L{_connectException}.
r  )rh   r   rc   rC  r  s        rX   r   RaisingMemoryReactor.connectUNIX  r  rW   c                    U R                   e)zM
Fake L{IReactorSocket.adoptDatagramPort}, that raises
L{_connectException}.
r  )rh   rv  rq  r   r{  s        rX   r|  &RaisingMemoryReactor.adoptDatagramPort      
 $$$rW   c                    U R                   e)zQ
Fake L{IReactorSocket.adoptStreamConnection}, that raises
L{_connectException}.
r  ru  s       rX   rw  *RaisingMemoryReactor.adoptStreamConnection  r  rW   )r  r  r  )NN)r  Exception | Noner  r  rv   rw   )r  r'   rv   r'   r  r  r  r  )rP   rQ   rR   rS   rT   r~   r:  rr  r  r  r  r  r  r  r|  rw  rV   rO   rW   rX   rF   rF   G  sm     -1-1E)E +E 
	E $$%$ LP%$%%%rW   rF   c                  >    \ rS rSrSrSrSrS rS rS r	S r
S	 rS
rg)rG   i  z-
A pull producer which writes 10 times only.
r   Fc                .    Xl         [        5       U l        g rm   )consumerr    result)rh   r  s     rX   r~   NonStreamingProducer.__init__  s     jrW   c                F   U R                   b  U R                  S:  a  [        S5      eU R                   R                  SU R                  4-  5        U =R                  S-  sl        U R                  S:X  a+  U R                   R	                  5         U R                  5         gg)z
Write the counter value once.
Nr  z"BUG: resume after unregister/stop.s   %drf   )r  counterr   r   r   _doner   s    rX   r   $NonStreamingProducer.resumeProducing  sz     == DLLB$6CDDMM 78LLAL||r!002

 "rW   c                    [        S5      e)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   s    rX   r   #NonStreamingProducer.pauseProducing  s    
 ?@@rW   c                P    SU l         U R                  nU ?UR                  S5        g)zA
Fire a L{Deferred} so that users can wait for this to complete.
N)r  r  rg   )rh   ri   s     rX   r  NonStreamingProducer._done  s%     KKK	

4rW   c                2    SU l         U R                  5         g)z
Stop all production.
TN)r   r  r   s    rX   r   "NonStreamingProducer.stopProducing  s     

rW   )r  r  r   N)rP   rQ   rR   rS   rT   r  r   r~   r   r   r  r   rV   rO   rW   rX   rG   rG     s-     GG!ArW   rG   c                r   ^^ SmUU4S jn[         R                  " U5      mU Tl        TR                  SSS9$ )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T V s/ s H  o R                   R                  PM     sn ;  a  TR                  5         g g s  sn f r   )	transportr   rH  )xlc	protocolss    rX   _check(waitUntilAllDisconnected.<locals>._check  s4    yAy!--yAAGGI BAs   >g{Gz?T)now)r   LoopingCallclockr}   )reactorr   r  r  s    ` @rX   rH   rH     s;    $ 
B 
		&	!BBH88Dd8##rW   c                      \ rS rSrSrSS jrSS jr\SS j5       r\SS j5       rSS jrSS jr	SS	 jr
\SS
 j5       rSrg)rI   i  ah  
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                    / U l         g rm   _eventsr   s    rX   r~   EventLoggingObserver.__init__  s	    ')rW   c                ,    [        U R                  5      $ rm   )lenr
  r   s    rX   __len__EventLoggingObserver.__len__  s    4<<  rW   c                    g rm   rO   rh   indexs     rX   __getitem__ EventLoggingObserver.__getitem__
      rW   c                    g rm   rO   r  s     rX   r  r    r  rW   c                     U R                   U   $ rm   r	  r  s     rX   r  r    s    ||E""rW   c                ,    [        U R                  5      $ rm   )iterr
  r   s    rX   __iter__EventLoggingObserver.__iter__  s    DLL!!rW   c                :    U R                   R                  U5        g)z
@see: L{ILogObserver}
N)r
  r   )rh   events     rX   __call__EventLoggingObserver.__call__  s     	E"rW   c                f   ^^ U " 5       mTR                  T5        UR                  UU4S j5        T$ )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                 &   > TR                  T 5      $ rm   )removeObserver)obs	publishers   rX   <lambda>8EventLoggingObserver.createWithCleanup.<locals>.<lambda>0  s    	(@(@(ErW   )addObserver
addCleanup)clstestInstancer$  r#  s     `@rX   createWithCleanup&EventLoggingObserver.createWithCleanup  s.      ec" EF
rW   r	  Nru   )rv   r[   )r  r[   rv   r7   )r  slicerv   zSequence[LogEvent])r  zint | slicerv   zLogEvent | Sequence[LogEvent])rv   zIterator[LogEvent])r  r7   rv   rw   )r*  r;   r$  r8   rv   r   )rP   rQ   rR   rS   rT   r~   r  r   r  r  r  classmethodr+  rV   rO   rW   rX   rI   rI     s\    *!    #"#  rW   rI   _Tc                &   ^ ^ U 4S jmSU4S jjnU$ )z
Decorator for running a benchmark tests that loops the reactor.

This is designed to decorate test method executed using pytest and
pytest-benchmark.
c                 $   > [        T " 5       5      $ rm   )r!   )test_targets   rX   deferredWrapper._benchmarkWithReactor.<locals>.deferredWrapperH  s    km,,rW   c                   > [        5       n[        S 5        [        5       U-
  n[        5       n[        T5        [        5       U-
  nX2-  S:  a  [        S5      eU " [        T5        g )Nc                     [        S 5      $ rm   )r"   rO   rW   rX   r%  ?_benchmarkWithReactor.<locals>.benchmark_test.<locals>.<lambda>Q  s    GDMrW      zThe function you are benchmarking is fast enough that its run time is being swamped by the startup/shutdown of the reactor. Consider adding a for loop to the benchmark function so it does the work a number of times.)r   _runReactorr   )	benchmarkr}   justReactorElapsedbenchmarkElapsedr3  s       rX   benchmark_test-_benchmarkWithReactor.<locals>.benchmark_testK  sf    
 )*!Ve^O$6E>014B  	+/rW   )r:  r	   rv   rw   rO   )r2  r=  r3  s   ` @rX   _benchmarkWithReactorr?  7  s    "-0. rW   c                   ^ SSK Jm  / nU " 5       nUR                  UR                  5        UR	                  U4S j5        TR                  SS9  U(       a  US   R                  5         gg)z>
(re)Start a reactor that might have been previously started.
r   r  c                2   > TR                  S[        T5      $ )Nr   )	callLater_stopReactor)_r  s    rX   r%  _runReactor.<locals>.<lambda>r  s    w00L'JrW   F)installSignalHandlersN)twisted.internetr  
addErrbackr   addBothrL  raiseException)rg   errorsdeferredr  s      @rX   r9  r9  e  s[     )$&FzH&JKKKeK,q	  " rW   c                N   U R                  5         U R                  5         [        U S5      (       d   e[        U S5      (       d   e[        U S5      (       d   e[        U S5      (       d   eSU l        SU l        SU l        SU l        U R                  SSU R                  5        g)	z7
Stop the reactor and allow it to be re-started later.
_startedBefore_started_justStoppedr"  FduringstartupN)	rH  rU  hasattrrO  rP  rQ  r"  rb  _reallyStartRunningrA  s    rX   rD  rD  z  s     LLNOO 7,----7J''''7N++++7I&&&&"GG GGO !!(Iw7R7RSrW   )r2  zgCallable[[], Union[Coroutine[Deferred[Any], Any, _T], Generator[Deferred[Any], Any, _T], Deferred[_T]]]rv   zCallable[[Any], None])rg   zCallable[[], Deferred[_T]]rv   rw   )grT   
__future__r   typingdataclassesr   r   r   socketr   r   r   r	   r
   r   r   r   r   r   r   r   zope.interfacer   r   zope.interface.verifyr   typing_extensionsr   r   rH  r   r   r   r   twisted.internet.abstractr   r   twisted.internet.addressr   r   r   twisted.internet.deferr    r!   r"   twisted.internet.errorr#   twisted.internet.interfacesr$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   twisted.internet.taskr5   twisted.loggerr6   r7   r8   twisted.protocolsr9   twisted.pythonr:   twisted.trial.unittestr;   __all__rJ   ProtocolrL   r<   LineReceiverr=   r>   r?   r@   rA   rC   rB   r	  r  rD   ifacerE   rF   rG   rH   rI   r/  r?  r9  rD  rO   rW   rX   <module>rk     s  
 #  !  $ 
 
 
 6 - - ; ; E J J D D ;    & ( ? ? # " +" t_B6?? B*8,, *Z%,, 0, , ZM2\) \) 3\)~X XW  ^! ! !@ Z, , ,^ _
, ,  ,    4 !V VVr
 =)E}% *  !Y% Y%Y%x. .b$: \88H- 8 8v T]++ +\#*TrW   