
    \d1                     8   d Z ddlZddlZddlZddlmZ ddlmZmZm	Z	m
Z
mZ ddlmZmZ ddlmZ ddlmZ ddlmZ dd	lmZmZ d
Z eej                  Zej                            ej                  ed<    G d de	j                  Z  G d de          Z!dS )z
Tests for L{twisted.internet.stdio}.

@var properEnv: A copy of L{os.environ} which has L{bytes} keys/values on POSIX
    platforms and native L{str} keys/values on Windows.
    N)skipIf)defererrorprotocolreactorstdio)filepathlog)requireModule)platform)ConnectionLostNotifyingProtocol)SkipTestTestCases   xyz123abc Twisted is great!
PYTHONPATHc                   .    e Zd ZdZdZd Zd Zd Zd ZdS )StandardIOTestProcessProtocola  
    Test helper for collecting output from a child process and notifying
    something when it exits.

    @ivar onConnection: A L{defer.Deferred} which will be called back with
    L{None} when the connection to the child process is established.

    @ivar onCompletion: A L{defer.Deferred} which will be errbacked with the
    failure associated with the child process exiting when it exits.

    @ivar onDataReceived: A L{defer.Deferred} which will be called back with
    this instance whenever C{childDataReceived} is called, or L{None} to
    suppress these callbacks.

    @ivar data: A C{dict} mapping file descriptors to strings containing all
    bytes received from the child process on each file descriptor.
    Nc                 t    t          j                    | _        t          j                    | _        i | _        d S N)r   DeferredonConnectiononCompletiondataselfs    7lib/python3.11/site-packages/twisted/test/test_stdio.py__init__z&StandardIOTestProcessProtocol.__init__8   s-    !N,,!N,,			    c                 :    | j                             d            d S r   )r   callbackr   s    r   connectionMadez,StandardIOTestProcessProtocol.connectionMade=   s    ""4(((((r   c                     | j                             |d          |z   | j         |<   | j        &| j        dc}| _        |                    |            dS dS )z
        Record all bytes received from the child process in the C{data}
        dictionary.  Fire C{onDataReceived} if it is not L{None}.
        r   N)r   getonDataReceivedr   )r   namebytesds       r   childDataReceivedz/StandardIOTestProcessProtocol.childDataReceived@   s_    
 )--c22U:	$*%)%8$"At"JJt +*r   c                 :    | j                             |           d S r   )r   r   )r   reasons     r   processEndedz*StandardIOTestProcessProtocol.processEndedJ   s    ""6*****r   )	__name__
__module____qualname____doc__r#   r   r    r'   r*    r   r   r   r   #   sa         $ N  
) ) )  + + + + +r   r   c                       e Zd Z ej                    r ed          dZd Zd Zd Z	d Z
d Zd	 Zd
 Zd Zd Zd Zd Z e ej                    d          d             ZdS )StandardInputOutputTestswin32processNzIOn windows, spawnProcess is not available in the absence of win32process.c                     t           j        dd|z   t          j        j        gt          |          z   }t          j        |t           j        |fdt          i|S )a_  
        Launch a child Python process and communicate with it using the
        given ProcessProtocol.

        @param proto: A L{ProcessProtocol} instance which will be connected
        to the child process.

        @param sibling: The basename of a file containing the Python program
        to run in the child process.

        @param *args: strings which will be passed to the child process on
        the command line as C{argv[2:]}.

        @param **kw: additional arguments to pass to L{reactor.spawnProcess}.

        @return: The L{IProcessTransport} provider for the spawned process.
        s   -ms   twisted.test.env)sys
executabler   	__class__r,   listspawnProcess	properEnv)r   protosiblingargskws        r   _spawnProcessz&StandardInputOutputTests._spawnProcessV   s[    & Nw&(	

 JJ #E3>4UUYURTUUUr   c                 F      fd}fd}|                     ||          S )Nc                 8                         d|            d S )Nz%Process terminated with non-Failure: )fail)resultr   s    r   cbz4StandardInputOutputTests._requireFailure.<locals>.cbq   s$    IIHfHHIIIIIr   c                      |           S r   r/   )errr   s    r   ebz4StandardInputOutputTests._requireFailure.<locals>.ebt   s    8C== r   )addCallbacks)r   r&   r   rD   rG   s   ` `  r   _requireFailurez(StandardInputOutputTests._requireFailurep   sQ    	J 	J 	J 	J 	J	! 	! 	! 	! 	! ~~b"%%%r   c                                                        t          j        dz              t                      j        }                     d            fd}                     ||          S )z
        Verify that a protocol connected to L{StandardIO} can disconnect
        itself using C{transport.loseConnection}.
        Child process logging to s   stdio_test_loseconnc                 (   t                    5 }|D ]+}t          j        d|                                z              ,	 d d d            n# 1 swxY w Y                       dj                   |                     t          j                   d S )NzChild logged:    )	openr
   msgrstripfailIfInr   trapr   ProcessDone)r)   flineerrorLogFilepr   s      r   r*   zBStandardInputOutputTests.test_loseConnection.<locals>.processEnded   s    l## >q > >DG,t{{}}<====>> > > > > > > > > > > > > > > MM!QV$$$KK)*****s   /AAA)mktempr
   rO   r   r   r?   rI   )r   r&   r*   rV   rW   s   `  @@r   test_loseConnectionz,StandardInputOutputTests.test_loseConnectiony   s    
 {{}}+l:;;;)++N14lCCC	+ 	+ 	+ 	+ 	+ 	+ 	+ ##A|444r   c                 R   |                                  }t          j        d|z              t                      t	          j                    _        fd}j                            |           d }|                     j        |          }| 	                    d|           |S )z
        When stdin is closed and the protocol connected to it implements
        L{IHalfCloseableProtocol}, the protocol's C{readConnectionLost} method
        is called.
        rK   c                 H    j         }j                                         |S r   )r   	transport
closeStdin)ignoredr&   rW   s     r   cbByteszAStandardInputOutputTests.test_readConnectionLost.<locals>.cbBytes   s#    AK""$$$Hr   c                 D    |                      t          j                   d S r   )rR   r   rS   )r)   s    r   r*   zFStandardInputOutputTests.test_readConnectionLost.<locals>.processEnded   s    KK)*****r   s   stdio_test_halfclose)
rX   r
   rO   r   r   r   r#   addCallbackrI   r?   )r   rV   r_   r*   r&   rW   s        @r   test_readConnectionLostz0StandardInputOutputTests.test_readConnectionLost   s     {{}}+l:;;;)++ >++	 	 	 	 	
 	
$$W---	+ 	+ 	+   !1<@@15|DDDr   c                      t                      	                      dt          d           n.# t          $ r!}t	          t          |                    d}~ww xY w fd}                     j        |          S )z
        Verify that a write made directly to stdout using L{os.write}
        after StandardIO has finished is reliably received by the
        process reading that stdout.
        s   stdio_test_lastwriteT)usePTYNc                                          j        d                             t                    dj        d           |                     t
          j                   dS )z
            Asserts that the parent received the bytes written by the child
            immediately after the child starts.
            rM   z	Received z) from child, did not find expected bytes.N)
assertTruer   endswithUNIQUE_LAST_WRITE_STRINGrR   r   rS   r)   rW   r   s    r   r*   zEStandardInputOutputTests.test_lastWriteReceived.<locals>.processEnded   s`    
 OOq	""#;<<OAFOOO   KK)*****r   )r   r?   rh   
ValueErrorr   strrI   r   )r   er*   rW   s   `  @r   test_lastWriteReceivedz/StandardInputOutputTests.test_lastWriteReceived   s     *++	#*,DT       	# 	# 	#3q66"""	#		+ 		+ 		+ 		+ 		+ 		+ ##ANLAAAs   1 
AAAc                      t                      j        }                     d            fd}                     ||          S )z
        Verify that the transport of a protocol connected to L{StandardIO}
        has C{getHost} and C{getPeer} methods.
        s   stdio_test_hostpeerc                     j         d                                         \  }}                    |                               |           |                     t          j                   d S )NrM   )r   
splitlinesrf   rR   r   rS   )r)   hostpeerrW   r   s      r   r*   z?StandardInputOutputTests.test_hostAndPeer.<locals>.processEnded   s]    --//JD$OOD!!!OOD!!!KK)*****r   r   r   r?   rI   r   r&   r*   rW   s   `  @r   test_hostAndPeerz)StandardInputOutputTests.test_hostAndPeer   se    
 *++N14555	+ 	+ 	+ 	+ 	+ 	+ ##A|444r   c                      t                      j        }                     d            fd}                     ||          S )z
        Verify that the C{write} method of the transport of a protocol
        connected to L{StandardIO} sends bytes to standard out.
        s   stdio_test_writec                                          j        d         d           |                     t          j                   d S NrM   s   ok!assertEqualr   rR   r   rS   ri   s    r   r*   z9StandardInputOutputTests.test_write.<locals>.processEnded   :    QVAY///KK)*****r   rs   rt   s   `  @r   
test_writez#StandardInputOutputTests.test_write   se    
 *++N11222	+ 	+ 	+ 	+ 	+ 	+ ##A|444r   c                      t                      j        }                     d            fd}                     ||          S )z
        Verify that the C{writeSequence} method of the transport of a
        protocol connected to L{StandardIO} sends bytes to standard out.
        s   stdio_test_writeseqc                                          j        d         d           |                     t          j                   d S rx   ry   ri   s    r   r*   zAStandardInputOutputTests.test_writeSequence.<locals>.processEnded   r{   r   rs   rt   s   `  @r   test_writeSequencez+StandardInputOutputTests.test_writeSequence   se    
 *++N14555	+ 	+ 	+ 	+ 	+ 	+ ##A|444r   c                     |                                  }t          |d          5 }t          d          D ]}|                    d|fz             	 d d d            n# 1 swxY w Y   |S )Nwbi      %d
)rX   rN   rangewrite)r   junkPathjunkFileis       r   	_junkPathz"StandardInputOutputTests._junkPath  s    ;;==(D!! 	/X4[[ / /w!~..../	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ s   ,AA"%A"c                      t                      j        }g t          t          d                    fd                     d          j                                        fd}                     ||          S )z
        Verify that the transport of a protocol connected to L{StandardIO}
        is a working L{IProducer} provider.
        d   c                     r^                     d                                fz                                 d                    t          j        dd            d S d S )Nr   g{Gz?)appendpopr   r   	callLater)ignr    proctoWritewrittens    r   r    z>StandardInputOutputTests.test_producer.<locals>.connectionMade  sh     >w'++--)99:::

72;'''!$=====> >r   s   stdio_test_producerc                                          j        d         d                                                             dt	                    fz             |                     t          j                   d S )NrM   r   z*Connection lost with %d writes left to go.)rz   r   joinassertFalselenrR   r   rS   )r)   rW   r   r   r   s    r   r*   z<StandardInputOutputTests.test_producer.<locals>.processEnded  ss    QVAY(9(9:::EWW   KK)*****r   )r   r   r8   r   r?   r   ra   rI   )r   r&   r*   r    rW   r   r   r   s   `  @@@@@r   test_producerz&StandardInputOutputTests.test_producer  s    
 *++NuSzz""	> 	> 	> 	> 	> 	> 	> 	> !!!%;<<	"">222	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ ##A|444r   c                      t                      j        }                                                      d            fd}                     ||          S )z
        Verify that the transport of a protocol connected to L{StandardIO}
        is a working L{IConsumer} provider.
        s   stdio_test_consumerc                     t          d          5 }                    j        d         |                                           d d d            n# 1 swxY w Y   |                     t
          j                   d S )NrbrM   )rN   rz   r   readrR   r   rS   )r)   rT   r   rW   r   s     r   r*   z<StandardInputOutputTests.test_consumer.<locals>.processEnded2  s    h%% 6  AFFHH5556 6 6 6 6 6 6 6 6 6 6 6 6 6 6KK)*****s   4AAA)r   r   r   r?   rI   )r   r&   r*   r   rW   s   `  @@r   test_consumerz&StandardInputOutputTests.test_consumer&  s|    
 *++N>>##14h???	+ 	+ 	+ 	+ 	+ 	+ 	+
 ##A|444r   zpStandardIO does not accept stdout as an argument to Windows.  Testing redirection to a file is therefore harder.c                    	
 t          j                    }t          |          }t          j                                                                       d          x _        }                     |j	                   t          |                                          }t          j                    s[t          j                    \  }}                     t          j	        |                                t          j	        |           ||d<   t!          j        |fi |d
t%          j                    		
fdt)          j        d           	
 fd}|                    |           |S )aE  
        If L{StandardIO} is created with a file descriptor which refers to a
        normal file (ie, a file from the filesystem), L{StandardIO.write}
        writes bytes to that file.  In particular, it does not immediately
        consider the file closed or call its protocol's C{connectionLost}
        method.
        r   )stdoutstdin   c                      D ]8} | k    r                                   d S                     d| fz              t          j        d           d S )N   %dr   )loseConnectionr   r   r   )value
connectioncounthowManyspins    r   r   zAStandardInputOutputTests.test_normalFileStandardOut.<locals>.spin]  sm      G##--///FF  %!1222a&&&&&r   r   c           	                               t                    dz                                                                   d                    d t	                    D                                  d S )NrM   r   c              3   "   K   | ]
}d |fz  V  dS )r   Nr/   ).0r   s     r   	<genexpr>zVStandardInputOutputTests.test_normalFileStandardOut.<locals>.cbLost.<locals>.<genexpr>m  s(      +Q+QQEQDL+Q+Q+Q+Q+Q+Qr   )rz   next
getContentr   r   )r)   r   r   pathr   s    r   cbLostzCStandardInputOutputTests.test_normalFileStandardOut.<locals>.cbLostj  su    T%[['A+666!!388+Q+Q%..+Q+Q+Q#Q#Q    r   )r   r   r   r	   FilePathrX   rN   normal
addCleanupclosedictfilenor   	isWindowsospiper   
StandardIO	itertoolsr   r   r   ra   )r   
onConnLostr;   r   kwargsrwr   r   r   r   r   r   s   `       @@@@@r   test_normalFileStandardOutz3StandardInputOutputTests.test_normalFileStandardOut9  s    ^%%
/
;; //#yy.f%%%V]]__---!## 	  799DAqOOBHa(((OOBHa(((F7O%e66v66
 !!	' 	' 	' 	' 	' 	' 	' 	' 	!T"""	 	 	 	 	 	 	 	 	v&&&r   )r+   r,   r-   r   r   r   skipr?   rI   rY   rb   rm   ru   r|   r   r   r   r   r   r   r/   r   r   r1   r1   N   s)       x 
n = = E' 	
V V V4& & &5 5 5,  4%B %B %BN5 5 5"5 5 5 5 5 5   5 5 5<5 5 5& V	= 
3 3 
3 3 3r   r1   )"r.   r   r   r5   unittestr   twisted.internetr   r   r   r   r   twisted.pythonr	   r
   twisted.python.reflectr   twisted.python.runtimer   twisted.test.test_tcpr   twisted.trial.unittestr   r   rh   r   environr:   pathsepr   r   ProcessProtocolr   r1   r/   r   r   <module>r      sp        				 



       C C C C C C C C C C C C C C ( ( ( ( ( ( ( ( 0 0 0 0 0 0 + + + + + + A A A A A A 5 5 5 5 5 5 5 5 : D	*//#(33	, (+ (+ (+ (+ (+H$< (+ (+ (+Vc c c c cx c c c c cr   