
    Vh8                       d Z ddlmZ ddlZddlZddlZddlmZm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mZ dd
l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jL                        Z'ejP                  jS                  ejT                        e'd<    G d dej*                        Z+ G d de#      Z,y)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.
    )annotationsN)AnyCallable)skipIf)defererrorprotocolreactorstdio)IProcessTransportIReactorProcess)ProcessProtocol)filepathlog)Failure)requireModule)platform)ConnectionLostNotifyingProtocol)SkipTestTestCases   xyz123abc Twisted is great!
PYTHONPATHc                  D    e Zd ZU dZdZded<   ded<   ddZd Zd	 Zd
 Z	y)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.
    Nzdefer.Deferred[None] | NoneonDataReceivedr   	transportc                v    t        j                         | _        t        j                         | _        i | _        y N)r   DeferredonConnectiononCompletiondataselfs    G/home/dcms/DCMS/lib/python3.12/site-packages/twisted/test/test_stdio.py__init__z&StandardIOTestProcessProtocol.__init__=   s'    27..2B27..2B&(	    c                :    | j                   j                  d        y r   )r   callbackr"   s    r$   connectionMadez,StandardIOTestProcessProtocol.connectionMadeB   s    ""4(r&   c                    | j                   j                  |d      |z   | j                   |<   | j                  &| j                  dc}| _        |j                  |        yy)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!   getr   r(   )r#   namebytesds       r$   childDataReceivedz/StandardIOTestProcessProtocol.childDataReceivedE   sW    
 ))--c2U:		$*%)%8%8$"At"JJt +r&   c                :    | j                   j                  |       y r   )r    r(   )r#   reasons     r$   processEndedz*StandardIOTestProcessProtocol.processEndedO   s    ""6*r&   )returnNone)
__name__
__module____qualname____doc__r   __annotations__r%   r)   r/   r2    r&   r$   r   r   '   s.    $ 37N/6  )
)+r&   r   c                     e Zd Z ej                         r
 ed      dZ	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZd Z		 d	 	 	 	 	 ddZ
ddZdd	Zdd
Zd Zd Zd Zd Zd Zd Zd Z e ej                         d      d        Zy)StandardInputOutputTestswin32processNzIOn windows, spawnProcess is not available in the absence of win32process.c                $   t        |t              r|j                         }t        j                  dd|z   t
        j                  j                  gt        |      z   } t        t
              j                  |t        j                  |fdt        i|S )ak  
        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.
        z-mztwisted.test.env)
isinstancer-   decodesys
executabler
   	__class__r6   listr   spawnProcess	properEnv)r#   protosiblingargskwprocargss         r$   _spawnProcessz&StandardInputOutputTests._spawnProcessZ   s    ( gu%nn&GNNg%((	

 J 5w'443>>8
1:
>@
 	
r&   c                >      fd}fd}|j                  ||      S )Nc                .    j                  d|        y )Nz%Process terminated with non-Failure: )fail)resultr#   s    r$   cbz4StandardInputOutputTests._requireFailure.<locals>.cb}   s    II=fZHIr&   c                     |       S r   r:   )errr(   s    r$   ebz4StandardInputOutputTests._requireFailure.<locals>.eb   s    C= r&   )addCallbacks)r#   r.   r(   rR   rU   s   ` `  r$   _requireFailurez(StandardInputOutputTests._requireFailurez   s!    	J	! ~~b"%%r&   c                      j                         t        j                  dz          t               j                  } j                  d        fd} j                  ||      S )z
        Verify that a protocol connected to L{StandardIO} can disconnect
        itself using C{transport.loseConnection}.
        zChild process logging to s   stdio_test_loseconnc                   t              5 }|D ](  }t        j                  d|j                         z          * 	 d d d        j	                  dj
                         | j                  t        j                         y # 1 sw Y   ExY w)NzChild logged:    )	openr   msgrstripfailIfInr!   trapr   ProcessDone)r1   flineerrorLogFilepr#   s      r$   r2   zBStandardInputOutputTests.test_loseConnection.<locals>.processEnded   so    l# >q >DGG,t{{}<=>> MM!QVV$KK))*> >s   .B  B	)mktempr   r\   r   r    rM   rW   )r#   r.   r2   rc   rd   s   `  @@r$   test_loseConnectionz,StandardInputOutputTests.test_loseConnection   s`    
 {{}+l:;)+NN14lC	+ ##A|44r&   c                   | j                         }t               t        j                         _        dfd}j                  j                  |       d }| j                  j                  |      }| j                  ||       |S )Nc                    j                   }rj                  j                          |S j                  j                          |S r   )r    r   closeStdout
closeStdin)ignoredr.   outrd   s     r$   cbByteszGStandardInputOutputTests.exampleOutputsAndZeroExitCode.<locals>.cbBytes   s=    A'') H &&(Hr&   c                B    | j                  t        j                         y r   )r_   r   r`   )r1   s    r$   r2   zLStandardInputOutputTests.exampleOutputsAndZeroExitCode.<locals>.processEnded   s    KK))*r&   )rk   r4   r3   defer.Deferred[None])re   r   r   r   r   addCallbackrW   rM   )r#   examplerl   rc   rm   r2   r.   rd   s     `    @r$   exampleOutputsAndZeroExitCodez6StandardInputOutputTests.exampleOutputsAndZeroExitCode   sx     {{})+ >>+	 	
$$W-	+   !1!1<@1g|4r&   c                $    | 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.
        stdio_test_halfcloserr   r"   s    r$   test_readConnectionLostz0StandardInputOutputTests.test_readConnectionLost   s     112HIIr&   c                $    | j                  d      S )
        When stdin is closed and the protocol connnected to it implements
        L{IHalfCloseableProtocol} but its C{readConnectionLost} method raises
        an exception its regular C{connectionLost} method will be called.
        stdio_test_halfclose_buggyru   r"   s    r$   test_buggyReadConnectionLostz5StandardInputOutputTests.test_buggyReadConnectionLost   s     112NOOr&   c                (    | j                  dd      S )rx    stdio_test_halfclose_buggy_writeT)rl   ru   r"   s    r$   test_buggyWriteConnectionLostz6StandardInputOutputTests.test_buggyWriteConnectionLost   s!     11.D 2 
 	
r&   c                     t               	  j                  dt        d        fd} j                  j                  |      S # t        $ r}t	        t        |            d}~ww xY w)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                  j                  d   j                  t              dj                  d       | j	                  t
        j                         y)z
            Asserts that the parent received the bytes written by the child
            immediately after the child starts.
            rZ   z	Received z) from child, did not find expected bytes.N)
assertTruer!   endswithUNIQUE_LAST_WRITE_STRINGr_   r   r`   r1   rd   r#   s    r$   r2   zEStandardInputOutputTests.test_lastWriteReceived.<locals>.processEnded   sM    
 OOq	""#;<AFF:%NO KK))*r&   )r   rM   r   
ValueErrorr   strrW   r    )r#   er2   rd   s   `  @r$   test_lastWriteReceivedz/StandardInputOutputTests.test_lastWriteReceived   so     *+	#*,DT  		+ ##ANNLAA  	#3q6""	#s   A	 		A+A&&A+c                     t               j                  } j                  d        fd} j                  ||      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   j                         \  }}j                  |       j                  |       | j                  t        j
                         y )NrZ   )r!   
splitlinesr   r_   r   r`   )r1   hostpeerrd   r#   s      r$   r2   z?StandardInputOutputTests.test_hostAndPeer.<locals>.processEnded   sG    --/JD$OOD!OOD!KK))*r&   r   r    rM   rW   r#   r.   r2   rd   s   `  @r$   test_hostAndPeerz)StandardInputOutputTests.test_hostAndPeer   sA    
 *+NN145	+ ##A|44r&   c                     t               j                  } j                  d        fd} j                  ||      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                  j                  d   d       | j                  t        j                         y NrZ   s   ok!assertEqualr!   r_   r   r`   r   s    r$   r2   z9StandardInputOutputTests.test_write.<locals>.processEnded  -    QVVAY/KK))*r&   r   r   s   `  @r$   
test_writez#StandardInputOutputTests.test_write  sA    
 *+NN112	+ ##A|44r&   c                     t               j                  } j                  d        fd} j                  ||      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                  j                  d   d       | j                  t        j                         y r   r   r   s    r$   r2   zAStandardInputOutputTests.test_writeSequence.<locals>.processEnded   r   r&   r   r   s   `  @r$   test_writeSequencez+StandardInputOutputTests.test_writeSequence  sA    
 *+NN145	+ ##A|44r&   c                    | j                         }t        |d      5 }t        d      D ]  }|j                  d|fz          	 d d d        |S # 1 sw Y   |S xY w)Nwbi      %d
)re   r[   rangewrite)r#   junkPathjunkFileis       r$   	_junkPathz"StandardInputOutputTests._junkPath&  s\    ;;=(D! 	/X4[ /w!~./	/ 	/ s   &AAc                    t               j                  }g t        t        d            fd j	                  d      j
                  j                          fd} j                  ||      S )z
        Verify that the transport of a protocol connected to L{StandardIO}
        is a working L{IProducer} provider.
        d   c                    rOj                  dj                         fz         j                  d          t        j                  dd        y y )Nr   g{Gz?)appendpopr   r
   	callLater)ignr)   proctoWritewrittens    r$   r)   z>StandardInputOutputTests.test_producer.<locals>.connectionMade8  sG    w'++-)99:

72;'!!$= r&   s   stdio_test_producerc                    j                  j                  d   dj                               j                  dt	              fz         | j                  t        j                         y )NrZ   r&   z*Connection lost with %d writes left to go.)r   r!   joinassertFalselenr_   r   r`   )r1   rd   r#   r   r   s    r$   r2   z<StandardInputOutputTests.test_producer.<locals>.processEndedB  sW    QVVAY(9:EWW KK))*r&   )r   r    rE   r   rM   r   rp   rW   )r#   r.   r2   r)   rd   r   r   r   s   `  @@@@@r$   test_producerz&StandardInputOutputTests.test_producer-  so    
 *+NNuSz"	> !!!%;<	"">2	+ ##A|44r&   c                     t               j                  } j                          j                  d        fd} j	                  ||      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                  j                  d   |j                                d d d        | j	                  t
        j                         y # 1 sw Y   )xY w)NrbrZ   )r[   r   r!   readr_   r   r`   )r1   ra   r   rd   r#   s     r$   r2   z<StandardInputOutputTests.test_consumer.<locals>.processEndedW  sT    h% 6  AFFH56KK))*6 6s   .A$$A-)r   r    r   rM   rW   )r#   r.   r2   r   rd   s   `  @@r$   test_consumerz&StandardInputOutputTests.test_consumerK  sO    
 *+NN>>#14h?	+
 ##A|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                   j                               j                  d      x _        } j                  |j                         t        |j                               }t        j                         s\t        j                         \  }} j                  t        j                  |        j                  t        j                  |       ||d<   t!        j"                  |fi |d
t%        j&                         		
fdt)        j*                  d       	
 fd}|j-                  |       |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 ]/  } | k(  rj                           y j                  d| fz          n t        j                  d       y )N   %dr   )loseConnectionr   r
   r   )value
connectioncounthowManyspins    r$   r   zAStandardInputOutputTests.test_normalFileStandardOut.<locals>.spin  sS     G#--/  %!12 a&r&   r   c           	         j                  t              dz          j                  j                         dj                  d t	              D                     y )NrZ   r&   c              3  (   K   | ]
  }d |fz    yw)r   Nr:   ).0r   s     r$   	<genexpr>zVStandardInputOutputTests.test_normalFileStandardOut.<locals>.cbLost.<locals>.<genexpr>  s     +QQEQDL+Qs   )r   next
getContentr   r   )r1   r   r   pathr#   s    r$   cbLostzCStandardInputOutputTests.test_normalFileStandardOut.<locals>.cbLost  sH    T%['A+6!388+Q%.+Q#Qr&   )r   r   r   r   FilePathre   r[   normal
addCleanupclosedictfilenor   	isWindowsospiper   
StandardIO	itertoolsr   r
   r   rp   )r#   
onConnLostrH   r   kwargsrwr   r   r   r   r   r   s   `       @@@@@r$   test_normalFileStandardOutz3StandardInputOutputTests.test_normalFileStandardOut^  s	    ^^%
/
;  /#yy.f%V]]_-!!# 779DAqOOBHHa(OOBHHa(F7O%%e6v6
 !	' 	!T"	 	v&r&   )
rH   r   rI   zstr | bytesrJ   r   rK   r   r3   r   )r.   ro   r(   zCallable[[Failure], object]r3   ro   )F)rq   r   rl   boolr3   ro   )r3   ro   )r5   r6   r7   r   r   r   skiprM   rW   rf   rr   rv   rz   r}   r   r   r   r   r   r   r   r   r   r:   r&   r$   r<   r<   S   s    xn = E' 	

$
/:
CF
NQ
	
@	&%	&1L	&		&5. ).!%	2JP
%BN5"5 5 5<5& 	=
3
3r&   r<   )-r8   
__future__r   r   r   rB   typingr   r   unittestr   twisted.internetr   r   r	   r
   r   twisted.internet.interfacesr   r   twisted.internet.protocolr   twisted.pythonr   r   twisted.python.failurer   twisted.python.reflectr   twisted.python.runtimer   twisted.test.test_tcpr   twisted.trial.unittestr   r   r   r   environrG   pathsepr   r   r   r<   r:   r&   r$   <module>r      s    #  	 
    C C J 5 ( * 0 + A 5 : 	**//#((3	, )+H$<$< )+XCx Cr&   