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

��W[hP�@svdZddlmZmZmZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZzddl
Z
Wnek
r�dZ
ZYnXddlmZddlmZddlmZddlmZddlmZmZmZmZmZdd	lmZdd
lmZm Z ddl!m"Z"m#Z#m$Z$m%Z%ddl&m'Z'e'ej(��)�Z*d
Z+ej,�-��sPe%�Z.ej/�0ej1��2e�3��e.d<ne4ej5�Z.ej/�0ej1�e.d<Gdd�dej6�Z7Gdd�dej8�Z9Gdd�dej6�Z:Gdd�dej6�Z;Gdd�dej6�Z<Gdd�dej6�Z=Gdd�de;�Z>Gdd�dej6�Z?Gd d!�d!e?�Z@Gd"d#�d#e?�ZAGd$d%�d%ej8�ZBGd&d'�d'ej6�ZCGd(d)�d)�ZDGd*d+�d+eDej8�ZEGd,d-�d-eDej8�ZFGd.d/�d/ej6�ZGGd0d1�d1ej8�ZHGd2d3�d3ej6�ZIGd4d5�d5eJ�ZKGd6d7�d7eJ�ZLGd8d9�d9eJ�ZMedk	�rGd:d;�d;ejN�ZOGd<d=�d=ejP�ZQGd>d?�d?ejR�ZSGd@dA�dAej8�ZTGdBdC�dCej8eK�ZUGdDdE�dEej8eK�ZVGdFdG�dGe=�ZWGdHdI�dIej8�ZXGdJdK�dKej8�ZYGdLdM�dMej8�ZZGdNdO�dOej8�Z[GdPdQ�dQej8�Z\GdRdS�dSej6�Z]GdTdU�dUej8�Z^dVZ_ej,�`�dWk�se�aed��se_eU_be_eV_be_eF_be_eH_bej,�`�dXk�s:e�aed��sXe_eX_be_eE_be_eZ_be_e[_be_eY_be�aed��sre_eB_be_e^_bdS)Ya�
Test running processes.

@var CONCURRENT_PROCESS_TEST_COUNT: The number of concurrent processes to use
    to stress-test the spawnProcess API.  This value is tuned to a number of
    processes which has been determined to stay below various
    experimentally-determined limitations of our supported platforms.
    Particularly, Windows XP seems to have some undocumented limitations which
    cause spurious failures if this value is pushed too high.  U{Please see
    this ticket for a discussion of how we arrived at its current value.
    <http://twistedmatrix.com/trac/ticket/3404>}

@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.
�)�division�absolute_import�print_functionN)�process)�verifyObject)�BytesIO��msg)�reactor�protocol�error�
interfaces�defer)�unittest)�runtime�	procutils)�_PY3�
networkString�range�bytesEnviron)�FilePath��
PYTHONPATH�
PYTHONPATHc@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
�StubProcessProtocolz�
    ProcessProtocol counter-implementation: all methods on this class raise an
    exception, so instances of this may be used to verify that only certain
    methods are called.
    cCs
t��dS�N��NotImplementedError��self�data�r!�;/usr/lib/python3/dist-packages/twisted/test/test_process.py�outReceivedFszStubProcessProtocol.outReceivedcCs
t��dSrrrr!r!r"�errReceivedJszStubProcessProtocol.errReceivedcCs
t��dSrr�rr!r!r"�inConnectionLostNsz$StubProcessProtocol.inConnectionLostcCs
t��dSrrr%r!r!r"�outConnectionLostRsz%StubProcessProtocol.outConnectionLostcCs
t��dSrrr%r!r!r"�errConnectionLostVsz%StubProcessProtocol.errConnectionLostN)	�__name__�
__module__�__qualname__�__doc__r#r$r&r'r(r!r!r!r"r@src@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)�ProcessProtocolTestszj
    Tests for behavior provided by the process protocol base class,
    L{protocol.ProcessProtocol}.
    cCsttjt���dS)zD
        L{ProcessProtocol} implements L{IProcessProtocol}.
        N)rr
ZIProcessProtocolr�ProcessProtocolr%r!r!r"�test_interface`sz#ProcessProtocolTests.test_interfacecs@g�G�fdd�dt�}d}|�}|�d|�|��|g�dS)z�
        Verify that when stdout is delivered to
        L{ProcessProtocol.childDataReceived}, it is forwarded to
        L{ProcessProtocol.outReceived}.
        cseZdZ�fdd�ZdS)z:ProcessProtocolTests.test_outReceived.<locals>.OutProtocolcs��|�dSr��appendr�Zreceivedr!r"r#oszFProcessProtocolTests.test_outReceived.<locals>.OutProtocol.outReceivedN)r)r*r+r#r!r2r!r"�OutProtocolnsr3�bytes�N�r�childDataReceived�assertEqual)rr3�bytesToSend�pr!r2r"�test_outReceivedgsz%ProcessProtocolTests.test_outReceivedcs@g�G�fdd�dt�}d}|�}|�d|�|��|g�dS)zA
        Similar to L{test_outReceived}, but for stderr.
        cseZdZ�fdd�ZdS)z:ProcessProtocolTests.test_errReceived.<locals>.ErrProtocolcs��|�dSrr0rr2r!r"r$~szFProcessProtocolTests.test_errReceived.<locals>.ErrProtocol.errReceivedN)r)r*r+r$r!r2r!r"�ErrProtocol}sr<r4�Nr6)rr<r9r:r!r2r"�test_errReceivedxsz%ProcessProtocolTests.test_errReceivedcs:g�G�fdd�dt�}|�}|�d�|��dg�dS)z�
        Verify that when stdin close notification is delivered to
        L{ProcessProtocol.childConnectionLost}, it is forwarded to
        L{ProcessProtocol.inConnectionLost}.
        cseZdZ�fdd�ZdS)zBProcessProtocolTests.test_inConnectionLost.<locals>.InLostProtocolcs��d�dSrr0r%�Zlostr!r"r&�szSProcessProtocolTests.test_inConnectionLost.<locals>.InLostProtocol.inConnectionLostN)r)r*r+r&r!r?r!r"�InLostProtocol�sr@rN�r�childConnectionLostr8)rr@r:r!r?r"�test_inConnectionLost�s

z*ProcessProtocolTests.test_inConnectionLostcs:g�G�fdd�dt�}|�}|�d�|��dg�dS)zF
        Similar to L{test_inConnectionLost}, but for stdout.
        cseZdZ�fdd�ZdS)zDProcessProtocolTests.test_outConnectionLost.<locals>.OutLostProtocolcs��d�dSrr0r%r?r!r"r'�szVProcessProtocolTests.test_outConnectionLost.<locals>.OutLostProtocol.outConnectionLostN)r)r*r+r'r!r?r!r"�OutLostProtocol�srDr5NrA)rrDr:r!r?r"�test_outConnectionLost�s

z+ProcessProtocolTests.test_outConnectionLostcs:g�G�fdd�dt�}|�}|�d�|��dg�dS)zF
        Similar to L{test_inConnectionLost}, but for stderr.
        cseZdZ�fdd�ZdS)zDProcessProtocolTests.test_errConnectionLost.<locals>.ErrLostProtocolcs��d�dSrr0r%r?r!r"r(�szVProcessProtocolTests.test_errConnectionLost.<locals>.ErrLostProtocol.errConnectionLostN)r)r*r+r(r!r?r!r"�ErrLostProtocol�srFr=NrA)rrFr:r!r?r"�test_errConnectionLost�s

z+ProcessProtocolTests.test_errConnectionLostN)
r)r*r+r,r/r;r>rCrErGr!r!r!r"r-[sr-c@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�TrivialProcessProtocolz�
    Simple process protocol for tests purpose.

    @ivar outData: data received from stdin
    @ivar errData: data received from stderr
    cCs||_g|_g|_dS)zl
        Create the deferred that will be fired at the end, and initialize
        data structures.
        N)�deferred�outData�errData�r�dr!r!r"�__init__�szTrivialProcessProtocol.__init__cCs||_|j�d�dSr��reasonrI�callback�rrPr!r!r"�processEnded�sz#TrivialProcessProtocol.processEndedcCs|j�|�dSr)rJr1rr!r!r"r#�sz"TrivialProcessProtocol.outReceivedcCs|j�|�dSr)rKr1rr!r!r"r$�sz"TrivialProcessProtocol.errReceivedN)r)r*r+r,rNrSr#r$r!r!r!r"rH�s

rHc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�TestProcessProtocolcCs$dg|_d|_d|_|j�d�dS)Nr5��abcd)�stagesr �err�	transport�writer%r!r!r"�connectionMade�sz"TestProcessProtocol.connectionMadecCs2|dkr|j|7_n|dkr.|j|7_dS)z�
        Override and disable the dispatch provided by the base class to ensure
        that it is really this method which is being called, and the transport
        is not going directly to L{outReceived} or L{errReceived}.
        r5r=N)r rX�r�childFDr r!r!r"r7�sz%TestProcessProtocol.childDataReceivedcCs�|dkr<|j�d�|jdkr.td|jf��|j�d�n\|dkr�|j�d�|jdkrjtd|jf��|j�d�|j�d�n|d	kr�|j�d
�dS)z�
        Similarly to L{childDataReceived}, disable the automatic dispatch
        provided by the base implementation to verify that the transport is
        calling this method directly.
        r5r=rVzData was %r instead of 'abcd's1234�zErr was %r instead of '1234'�r�N)rWr1r �RuntimeErrorrYrZrX�rr]r!r!r"rB�s"

�

�z'TestProcessProtocol.childConnectionLostcCs||_|j�d�dSrrOrRr!r!r"rSsz TestProcessProtocol.processEndedN)r)r*r+r[r7rBrSr!r!r!r"rT�srTc@s@eZdZddZdZdZdZdd�Zdd	�Zd
d�Z	dd
�Z
dS)�EchoProtocols1234567i��
rNcCs||_d|_dS�Nr)�onEnded�count)rrfr!r!r"rNszEchoProtocol.__init__cCsV|jdkst�t|jd�D]}|j�|j�q|j�|j|jg�|j|j|_dS)Nr=)�n�AssertionErrorrrYrZ�sZ
writeSequence�buffer)r�ir!r!r"r[s
zEchoProtocol.connectionMadecCsh|j|j|jt|��|kr8d||jf|_|j��n,|jt|�7_|jt|j�krd|j��dS)Nzwrong bytes received)rkrg�len�failurerY�
closeStdinrr!r!r"r#szEchoProtocol.outReceivedcCs0d|_|�tj�s dt|�|_|j�|�dS)Nr5z#process didn't terminate normally: )�finished�checkr�ProcessDone�strrnrfrQrRr!r!r"rS&szEchoProtocol.processEnded)r)r*r+rjrhrprnrNr[r#rSr!r!r!r"rcs	
rcc@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�SignalProtocola�
    A process protocol that sends a signal when data is first received.

    @ivar deferred: deferred firing on C{processEnded}.
    @type deferred: L{defer.Deferred}

    @ivar signal: the signal to send to the process.
    @type signal: C{str}

    @ivar signaled: A flag tracking whether the signal has been sent to the
        child or not yet.  C{False} until it is sent, then C{True}.
    @type signaled: C{bool}
    cCs||_||_d|_dS)NF)rI�signal�signaled)rrI�sigr!r!r"rN=szSignalProtocol.__init__cCs,td|f�|js(d|_|j�|j�dS)z�
        Handle the first output from the child process (which indicates it
        is set up and ready to receive the signal) by sending the signal to
        it.  Also log all output to help with debugging.
        zReceived %r from child stdoutTN)r	rvrY�
signalProcessrurr!r!r"r#CszSignalProtocol.outReceivedcCstd|f�dS)z_
        Log all data received from the child's stderr to help with
        debugging.
        zReceived %r from child stderrNrrr!r!r"r$OszSignalProtocol.errReceivedcCs�td|��f�|�tj�s4|j�td|f��S|j}t	|j
t�rXtt
d|j
�}n|j
}|j
dk	r�|j�td|j
|j
f��S|j
|kr�|j�td|j
|j
|f��St�|j�|kr�|j�td|j
t�|j�f��S|j�d�dS)aL
        Callback C{self.deferred} with L{None} if C{reason} is a
        L{error.ProcessTerminated} failure with C{exitCode} set to L{None},
        C{signal} set to C{self.signal}, and C{status} holding the status code
        of the exited process. Otherwise, errback with a C{ValueError}
        describing the problem.
        zChild exited: %r�wrong termination: %sZSIGNzSIG%s: exitCode is %s, not Nonez SIG%s: .signal was %s, wanted %sz	SIG%s: %s)r	ZgetTracebackrqr�ProcessTerminatedrI�errback�
ValueError�value�
isinstancerurs�getattr�exitCode�os�WTERMSIG�statusrQ)rrP�vZsignalValuer!r!r"rSWs4�

��
���zSignalProtocol.processEndedN)r)r*r+r,rNr#r$rSr!r!r!r"rt.s
rtc@seZdZdd�Zdd�ZdS)�TestManyProcessProtocolcCst��|_dSr�r�DeferredrIr%r!r!r"rNxsz TestManyProcessProtocol.__init__cCs0||_|�tj�r |j�d�n|j�|�dSr)rPrqrrrrIrQr{rRr!r!r"rS|sz$TestManyProcessProtocol.processEndedN)r)r*r+rNrSr!r!r!r"r�wsr�c@sPeZdZdZdZedd��Zdd�Zdd�Zd	d
�Z	dd�Z
d
d�Zdd�ZdS)�UtilityProcessProtocolz�
    Helper class for launching a Python process and getting a result from it.

    @ivar programName: The name of the program to run.
    NcCs*|�}|j|ttdd|jg||d�|S)a9
        Run a Python process connected to a new instance of this protocol
        class.  Return the protocol instance.

        The Python process is given C{self.program} on the command line to
        execute, in addition to anything specified by C{argv}.  C{env} is
        the complete environment.
        �-u�-m��env)�spawnProcess�pyExe�programName)�clsr
�argvr�rr!r!r"�run�s
�zUtilityProcessProtocol.runcCsg|_g|_dSr)�bytes�requestsr%r!r!r"rN�szUtilityProcessProtocol.__init__cCs
t��dS)zR
        Called with all bytes received on stdout when the process exits.
        Nr�rr�r!r!r"�parseChunks�sz"UtilityProcessProtocol.parseChunkscCst��}|j�|�|S)z{
        Return a Deferred which will fire with the result of L{parseChunks}
        when the child process exits.
        )rr�r�r1rLr!r!r"�	getResult�sz UtilityProcessProtocol.getResultcCs$|j}d|_|D]}|�|�qdS)zt
        Callback all Deferreds returned up until now by L{getResult}
        with the given result object.
        N)r�rQ)r�resultr�rMr!r!r"�_fireResultDeferreds�sz+UtilityProcessProtocol._fireResultDeferredscCs|j�|�dS)zE
        Accumulate output from the child process in a list.
        N)r�r1r�r!r!r"r#�sz"UtilityProcessProtocol.outReceivedcCs|�|�|j��dS)zu
        Handle process termination by parsing all received output and firing
        any waiting Deferreds.
        N)r�r�r�rRr!r!r"rS�sz#UtilityProcessProtocol.processEnded)
r)r*r+r,r��classmethodr�rNr�r�r�r#rSr!r!r!r"r��s

r�c@seZdZdZdZdd�ZdS)�GetArgumentVectorzl
    Protocol which will read a serialized argv from a process and
    expose it to interested parties.
    stwisted.test.process_getargvcCsd�|��d�S)z�
        Parse the output from the process to which this protocol was
        connected, which is a single unterminated line of \0-separated
        strings giving the argv of that process.  Return this as a list of
        str objects.
        rU�)�join�split)r�chunksr!r!r"r��szGetArgumentVector.parseChunksN�r)r*r+r,r�r�r!r!r!r"r��sr�c@seZdZdZdZdd�ZdS)�GetEnvironmentDictionaryzx
    Protocol which will read a serialized environment dict from a process
    and expose it to interested parties.
    stwisted.test.process_getenvcCs`d�|�}|siSt|�d��}i}zt|�}Wntk
rHYq\Yq$Xt|�}|||<q$|S)a
        Parse the output from the process to which this protocol was
        connected, which is a single unterminated line of \0-separated
        strings giving key value pairs of the environment from that process.
        Return this as a dictionary.
        rUr�)r��iterr��next�
StopIteration)rr�Z
environString�environrM�kr�r!r!r"r��s


z$GetEnvironmentDictionary.parseChunksNr�r!r!r!r"r��sr�c@sLeZdZdZdZdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�ZdS)�ProcessTestsz!
    Test running a process.
    Fcs~d}t��t��}�_tj�ttdd|gtd�jd��j	�
d��j	�
d��j	�
d��j	����fd	d
�}|�|�S)z1
        L{twisted.internet.stdio} test.
        stwisted.test.process_twistedr�r�N�r��path�usePTY�hello, worldsabcs123cs,���j��dd�j���j��f�dS)Nshello, worldabc123zBOutput follows:
%s
Error message from process_twisted follows:
%s
)r8�outF�getvalue�errF��ign�r:rr!r"rSs
��z-ProcessTests.test_stdio.<locals>.processEnded)
�Accumulatorrr��
endedDeferredr
r�r��	properEnvr�rYrZro�addCallback�r�
scriptPathrMrSr!r�r"�
test_stdios�
zProcessTests.test_stdiocs\t��}t|�}d}tj|ttdd|gtd�����j���fdd�}|j	�
�|�|�S)z�
        Test if pid is None/non-None before/after process termination.  This
        reuses process_echoer.py to get a process that blocks on stdin.
        �twisted.test.process_echoerr�r�r�cs���j�dSr��assertIsNone�pid��ignored�Z	procTransrr!r"�afterProcessEnd+sz3ProcessTests.test_unsetPid.<locals>.afterProcessEnd)rr�rHr
r�r�r��
assertTruer�rYror�)rrpr:r�r�r!r�r"�
test_unsetPids
�
zProcessTests.test_unsetPidcsNd}t��}t��|�_tj�ttdd|gtd���fdd�}|�|�|S)zp
        Test running a process: check its output, it exitCode, some property of
        signalProcess.
        �twisted.test.process_testerr�r�r�cs����jdddddg��j}|�tj���|jjd���tj	�j
jd�z0ddl}ddl
}|�
|j�D]}t�|�qlWnYnXdS)	Nr5r=r^r_r`��INTr)r8rWrP�traprrzr}r��assertRaises�ProcessExitedAlreadyrYrx�process_tester�globZtest_file_matchr��remove)r��fr�r�r�r!r"rq=s�z(ProcessTests.test_process.<locals>.check)	rr�rTrIr
r�r�r�r�)rr�rMrqr!r�r"�test_process2s�
zProcessTests.test_processc	s~�fdd�}d}tdd|g}g}g}tt�D]2}t�}|�|�tj|t|td�|�|j�q,t	j
|dd�}|�||�|S)	Nc	s^|D]T}��|jdddddgdt|j�t|j�f�|j}|�tj���|j	j
d�qdS)Nr5r=r^r_r`z[%d] stages = %sr�)r8rW�idrYrsrPr�rrzr}r�)Zresults�	protocolsr:r�r%r!r"�_checkRs
��z/ProcessTests.test_manyProcesses.<locals>._checkr�r�r�r�T)Z
consumeErrors)r�r�CONCURRENT_PROCESS_TEST_COUNTr�r1r
r�r�rIrZDeferredListr�)	rr�r��argsr�Z	deferredsrlr:ZdeferredListr!r%r"�test_manyProcessesPs

zProcessTests.test_manyProcessescsXt��}t|��d}tj�ttdd|gtd���fdd�}�fdd�}|�|��|�S)	z�
        A spawning a subprocess which echoes its stdin to its stdout via
        L{IReactorProcess.spawnProcess} will result in that echoed output being
        delivered to outReceived.
        r�r�r�r�csB���j�j���t�d����t�j�t�j�j��dS)Nrk)	�assertFalsernr��hasattrr8rmrkrjrhr�r�r!r"�assertsysz'ProcessTests.test_echo.<locals>.assertscs�j��|Sr)rYro)rX)r:r!r"�takedownProcess~s
z/ProcessTests.test_echo.<locals>.takedownProcess)	rr�rcr
r�r�r�r�Z
addErrback)rrpr�r�r�r!r�r"�	test_echols�zProcessTests.test_echoc	shddddddddd	g	�d
}t��t��}�_tj�ttdd|g�tdd
����fdd�}|�|�S)Nsa\"b sa\b s a\\"bs a\\bs"foo bar" "s	abs"\sa"bsa'bstwisted.test.process_cmdliner�r��r�r�cs0���j��d��j����}��|��dS�NrU)r8r�r�r��
splitlines)r�Z	recvdArgs�r�r:rr!r"rS�sz3ProcessTests.test_commandLine.<locals>.processEnded�	r�rr�r�r
r�r�r�r�r�r!r�r"�test_commandLine�s 
��zProcessTests.test_commandLinec	Cs�t��}ddiddiddiddig}tdgdtdgg}d	}z|�t���Wn>tk
r�|�|d
i�|�d|i�|�t|g�YnX|D]"}|jt	t
j|ttdd
g|d�q�|D]}|jt	t
j|t|dd�q�dS)z�
        Test invalid arguments to spawnProcess: arguments and environment
        must only contains string or unicode, and not null bytes.
        sfoor=seggar^sbarsbarfoosspamsfoobaru☃zvalue for bad unicode keyzkey for bad unicode value�-crUr�N)rr.r��encode�sys�getfilesystemencoding�UnicodeEncodeErrorr1r��	TypeErrorr
r�)rr:ZbadEnvsZbadArgsZ
badUnicoder�r�r!r!r"�test_wrongArguments�sF��	��z ProcessTests.test_wrongArgumentsN)r)r*r+r,r�r�r�r�r�r�r�r�r!r!r!r"r�sr�c@s,eZdZdZdZdd�Zdd�Zdd�Zd	S)
�TwoProcessProtocol���rcCst��|_dSrr�r%r!r!r"rN�szTwoProcessProtocol.__init__cCsdSrr!rr!r!r"r#�szTwoProcessProtocol.outReceivedcCsd|_|j�d�dS�Nr5)rprIrQrRr!r!r"rS�szTwoProcessProtocol.processEndedN)r)r*r+�numrprNr#rSr!r!r!r"r��s
r�c@s6eZdZdd�Zd
dd�Zdd�Zdd	�Zd
d�ZdS)�TestTwoProcessesBasecCs$ddg|_ddg|_d|_d|_dSre)�	processes�ppZdone�verboser%r!r!r"�setUp�s

zTestTwoProcessesBase.setUprcCsVd}dD]H}t�|j|<||j|_tj|j|ttdd|gt|d�}||j|<qdS)Nstwisted.test.process_reader)rr5r�r��r�r�)r�r�r�r
r�r�r�r�)rr�r�r�r:r!r!r"�createProcesses�s
�z$TestTwoProcessesBase.createProcessescCs`|jrtd|�|j|}|j|}|�|jd�|��|jr\t|jdj|jdj�dS)Nzclosing stdin [%d]�Process finished too earlyrr5)r��printr�r�r�rp�loseConnection�rr�r:r�r!r!r"�close�s

zTestTwoProcessesBase.closecCst�dd�|jD��S)NcSsg|]
}|j�qSr!�rI)�.0r:r!r!r"�
<listcomp>�sz1TestTwoProcessesBase._onClose.<locals>.<listcomp>)r�
gatherResultsr�r%r!r!r"�_onClose�szTestTwoProcessesBase._onClosecCs>|jrtd�|��t�d|jd�t�d|jd�|��S)N�starting processesr5rr=�r�r�r�r
�	callLaterr�r�r%r!r!r"�
test_close�szTestTwoProcessesBase.test_closeN)r)r)r*r+r�r�r�r�r�r!r!r!r"r��s

	r�c@seZdZdS)�TwoProcessesNonPosixTestsN)r)r*r+r!r!r!r"r�sr�c@s4eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZdS)�TwoProcessesPosixTestsc	CsPt|j|j�D]8\}}|jszt�|jtj�Wqt	k
rDYqXq|�
�Sr)�zipr�r�rpr��killr�ru�SIGTERM�OSErrorr�)rr��prr!r!r"�tearDownszTwoProcessesPosixTests.tearDowncCsh|jrtd|�|j|}|j|}|�|jd�t�|jt	j
�|jrdt|jdj|jdj�dS)Nzkill [%d] with SIGTERMr�rr5)r�r�r�r�r�rpr�rr�rurr�r!r!r"rs

zTwoProcessesPosixTests.killcCsB|jrtd�|jdd�t�d|jd�t�d|jd�|��S)Nr�r�r�r5r=�r�r�r�r
r�rr�r%r!r!r"�	test_killsz TwoProcessesPosixTests.test_killcCsB|jrtd�|jdd�t�d|jd�t�d|jd�|��S�Nr�r5rrr=r�r%r!r!r"�
test_closePty%sz$TwoProcessesPosixTests.test_closePtycCsB|jrtd�|jdd�t�d|jd�t�d|jd�|��Sr
rr%r!r!r"�test_killPty-sz#TwoProcessesPosixTests.test_killPtyN)r)r*r+rrr	rrr!r!r!r"rs
	rc@sHeZdZdZdZdZdd�Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�ZdS)�	FDCheckerrrUNcCs
||_dSrr�rLr!r!r"rN;szFDChecker.__init__cCs||_|j�d�dSr)�failedrIrQ)rZwhyr!r!r"�fail?szFDChecker.failcCs|j�dd�d|_dS)NrrVr5)rY�writeToChild�stater%r!r!r"r[DszFDChecker.connectionMadecCs8|jdkr�|dkr(|�d||f�dS|j|7_t|j�dkr�|jdkrb|�d|j�dSd|_d|_|j�dd	�dS|jdkr�|�d
||f�dS|jdk�r|dkr�|�d||f�dS|j|7_t|j�dk�r|jdk�r|�d
|j�dSd|_dS|jdk�r4|�d||f�dSdS)Nr5z)read '%s' on fd %d (not 1) during state 1�srightoz"got '%s' on fd1, expected 'righto'rUr=r^sefghz!read '%s' on fd %s during state 2z)read '%s' on fd %s (not 1) during state 3sclosedz"got '%s' on fd1, expected 'closed'r_z!read '%s' on fd %s during state 4)rrr rmrYrr\r!r!r"r7IsL
�
�
��zFDChecker.childDataReceivedcCsZ|jdkr|�d|�dS|jdkrV|dkr@|�d|�dSd|_|j�d�dSdS)Nr5z%got connectionLost(%d) during state 1r=r_z-got connectionLost(%d) (not 4) during state 2r^r`)rrrYZcloseChildFDrbr!r!r"rBps

�zFDChecker.childConnectionLostcCsp|jj}|jdkr$|�d|�dS|jjdkrF|�d|jj�dS|dkr`|�d|�dS|j�d�dS)Nr_zprocessEnded early, rc %dzprocessEnded with signal %srzprocessEnded with rc %d)r}r�rrrurIrQ)rr�Zrcr!r!r"rS~s
zFDChecker.processEnded)r)r*r+rr rrNrr[r7rBrSr!r!r!r"r
6s'r
c@seZdZdd�Zdd�ZdS)�FDTestscsVd}t��}t|��tj�ttdd|gtddddddd�d�|���fd	d
��|S)Nstwisted.test.process_fdsr�r��w�rr=)rr5r=r^r_r`�r��childFDscs���j�j�Sr)r�r��xr�r!r"�<lambda>�rUz!FDTests.test_FD.<locals>.<lambda>)rr�r
r
r�r�r�r�)rr�rMr!r�r"�test_FD�s��zFDTests.test_FDcsRd}t��t��}�_tj�ttdd|gtddd�d���fdd	�}|�|�S)
Nstwisted.test.process_lingerr�r�rr=)r5r=rcs���j��d�dS)Nshere is some text
goodbye
)r8r�r�r�r�r!r"rS�s�z)FDTests.test_linger.<locals>.processEndedr�r�r!r�r"�test_linger�s�zFDTests.test_lingerN)r)r*r+rrr!r!r!r"r�src@sHeZdZdZdZdZdd�Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�ZdS)r�zAccumulate data from a process.rNcCst�|_t�|_dSr)rr�r�r%r!r!r"r[�szAccumulator.connectionMadecCs|j�|�dSr)r�rZrLr!r!r"r#�szAccumulator.outReceivedcCs|j�|�dSr)r�rZrLr!r!r"r$�szAccumulator.errReceivedcCsdSrr!r%r!r!r"r'�szAccumulator.outConnectionLostcCsdSrr!r%r!r!r"r(�szAccumulator.errConnectionLostcCs,d|_|jdk	r(|jd}|_|�d�dSr�)�closedr�rQ)rrPrMr!r!r"rS�s
zAccumulator.processEnded)r)r*r+r,rr�r[r#r$r'r(rSr!r!r!r"r��sr�c@s|eZdZdZdZdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zej��rpde_dd�ZdS)�PosixProcessBasez!
    Test running processes.
    FcCsNtd��|�}td��|�}|��r,|��S|��r<|��Std|f��dS)zq
        Return the path of the shell command named C{commandName}, looking at
        common locations.
        z/binz/usr/binz %s not found in /bin or /usr/binN)r�child�exists�_asBytesPathra)rZcommandNameZbinLocZ	usrbinLocr!r!r"�
getCommand�s�zPosixProcessBase.getCommandcsN��d�}t��}t|��tj�|dgd�jd���fdd�}|�|�|S)N�truestruer�cs4�j�tj����jjjd����jjj�dSre)	rPr�rrrr8r}r�r�rur�r�r!r"rq�sz6PosixProcessBase.test_normalTermination.<locals>.check)r"rr�rHr
r�r�r�)r�cmdrMrqr!r�r"�test_normalTermination�s
�
z'PosixProcessBase.test_normalTerminationcsHt��}t|��tj�ttddgd�jd���fdd�}|�|�|S)z�
        When a process terminates with a system exit code set to 1,
        C{processEnded} is called with a L{error.ProcessTerminated} error,
        the C{exitCode} attribute reflecting the system exit code.
        r�simport sys; sys.exit(1)Nr�cs4�j�tj����jjjd����jjj�dSr�)	rPr�rrzr8r}r�r�rur�r�r!r"rqsz8PosixProcessBase.test_abnormalTermination.<locals>.check)rr�rHr
r�r�r�r�)rrMrqr!r�r"�test_abnormalTermination�s�
z)PosixProcessBase.test_abnormalTerminationcCs8d}t��}t||�}tj|ttdd|gt|jd�|S)N�twisted.test.process_signalr��-mr�)rr�rtr
r�r�r�r��rrwr�rMr:r!r!r"�_testSignal
s
�zPosixProcessBase._testSignalcCs
|�d�S)ai
        Sending the SIGHUP signal to a running process interrupts it, and
        C{processEnded} is called with a L{error.ProcessTerminated} instance
        with the C{exitCode} set to L{None} and the C{signal} attribute set to
        C{signal.SIGHUP}. C{os.WTERMSIG} can also be used on the C{status}
        attribute to extract the signal value.
        �HUP�r*r%r!r!r"�test_signalHUPszPosixProcessBase.test_signalHUPcCs
|�d�S)ai
        Sending the SIGINT signal to a running process interrupts it, and
        C{processEnded} is called with a L{error.ProcessTerminated} instance
        with the C{exitCode} set to L{None} and the C{signal} attribute set to
        C{signal.SIGINT}. C{os.WTERMSIG} can also be used on the C{status}
        attribute to extract the signal value.
        r�r,r%r!r!r"�test_signalINTszPosixProcessBase.test_signalINTcCs
|�d�S)ak
        Sending the SIGKILL signal to a running process interrupts it, and
        C{processEnded} is called with a L{error.ProcessTerminated} instance
        with the C{exitCode} set to L{None} and the C{signal} attribute set to
        C{signal.SIGKILL}. C{os.WTERMSIG} can also be used on the C{status}
        attribute to extract the signal value.
        �KILLr,r%r!r!r"�test_signalKILL)sz PosixProcessBase.test_signalKILLcCs
|�d�S)ak
        Sending the SIGTERM signal to a running process interrupts it, and
        C{processEnded} is called with a L{error.ProcessTerminated} instance
        with the C{exitCode} set to L{None} and the C{signal} attribute set to
        C{signal.SIGTERM}. C{os.WTERMSIG} can also be used on the C{status}
        attribute to extract the signal value.
        �TERMr,r%r!r!r"�test_signalTERM4sz PosixProcessBase.test_signalTERMcCs2tj}t�|tj�}|�tjtj|�|�tj�S)z�
        The disposition of signals which are ignored in the parent
        process is reset to the default behavior for the child
        process.
        )ru�SIGUSR1�SIG_IGN�
addCleanupr*)r�whichZhandlerr!r!r"�test_childSignalHandling?sz)PosixProcessBase.test_childSignalHandlingcsp��d�}t��}t|��dd�}tj}|t_z4tj�|dgd�jd���fdd�}|�	|�W5|t_X|S)	zJ
        Raise an error during execvpe to check error management.
        ZfalsecSstd��dS)NZOuch)ra)�commandr�Zenvironmentr!r!r"�buggyexecvpebsz:PosixProcessBase.test_executionError.<locals>.buggyexecvpesfalseNr�cs.d��j�j�}��d|���d|�dS)NrUsUpon execvpesOuch)r�rKrJ�assertIn)r�rKr�r!r"rqjsz3PosixProcessBase.test_executionError.<locals>.check)
r"rr�rHr��execvper
r�r�r�)rr$rMr9Z
oldexecvperqr!r�r"�test_executionErrorZs
�z$PosixProcessBase.test_executionErrorz+Test is flaky from a Darwin bug. See #8840.cs�t���t���d}G��fdd�dtj�}tj|�ttdd|gtdd�g���fdd	�}��|���fd
d�}��|��S)z�
        The handler which reaps a process is removed when the process is
        reaped, even if the protocol's C{processEnded} method raises an
        exception.
        r�cs(eZdZdZ�fdd�Z�fdd�ZdS)zFPosixProcessBase.test_errorInProcessEnded.<locals>.ErrorInProcessEndedzM
            A protocol that raises an error in C{processEnded}.
            cs��|�dSr�rQ�rrY��	connectedr!r"�makeConnection�szUPosixProcessBase.test_errorInProcessEnded.<locals>.ErrorInProcessEnded.makeConnectioncst�d�jd�td��dS)NrzDeliberate error)r
r�rQrarR��endedr!r"rS�szSPosixProcessBase.test_errorInProcessEnded.<locals>.ErrorInProcessEnded.processEndedN�r)r*r+r,rArSr!�r@rCr!r"�ErrorInProcessEnded�srFr�r�Nr�cs(��|j���|jtj�|��dSr)r1r�r:r�reapProcessHandlersr��rY�r�rr!r"�cbConnected�sz>PosixProcessBase.test_errorInProcessEnded.<locals>.cbConnectedcs0��t�}��t|�d����dtj�dS)Nr5r)�flushLoggedErrorsrar8rmZassertNotInrrG)r�ZexcsrIr!r"�checkTerminated�s
zBPosixProcessBase.test_errorInProcessEnded.<locals>.checkTerminated)	rr�rr.r
r�r�r�r�)rr�rFrJrLr!)r@rCr�rr"�test_errorInProcessEndedxs"

�

z)PosixProcessBase.test_errorInProcessEndedN)r)r*r+r,r�r"r%r&r*r-r.r0r2r7r<r�platformZisMacOSX�skiprMr!r!r!r"r�s 	
�rc@s eZdZdZdd�Zdd�ZdS)�
MockSignalzF
    Neuter L{signal.signal}, but pass other attributes unscathed
    cCs
t�|�Sr)ru�	getsignal)rrw�actionr!r!r"ru�szMockSignal.signalcCs
tt|�Sr)rru)r�attrr!r!r"�__getattr__�szMockSignal.__getattr__N)r)r*r+r,rurTr!r!r!r"rP�srPc@sxeZdZdZdZdZdZdZdZdZ	dZ
dZdZdZ
dZdZdd�Zd	d
�Zdd�Zd
d�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Z d)d*�Z!d+d,�Z"d-d.�Z#d/d0�Z$d1d2�Z%d3d4�Z&d5d6�Z'd7d8�Z(d9d:�Z)d;d<�Z*d=d>�Z+d?d@�Z,dAdB�Z-dCdD�Z.dEdF�Z/dGdH�Z0dIdJ�Z1dKdL�Z2dMdN�Z3dOdP�Z4dQdR�Z5dSdT�Z6dS)U�MockOSaF
    The mock OS: overwrite L{os}, L{fcntl} and {sys} functions with fake ones.

    @ivar exited: set to True when C{_exit} is called.
    @type exited: C{bool}

    @ivar O_RDWR: dumb value faking C{os.O_RDWR}.
    @type O_RDWR: C{int}

    @ivar O_NOCTTY: dumb value faking C{os.O_NOCTTY}.
    @type O_NOCTTY: C{int}

    @ivar WNOHANG: dumb value faking C{os.WNOHANG}.
    @type WNOHANG: C{int}

    @ivar raiseFork: if not L{None}, subsequent calls to fork will raise this
        object.
    @type raiseFork: L{None} or C{Exception}

    @ivar raiseExec: if set, subsequent calls to execvpe will raise an error.
    @type raiseExec: C{bool}

    @ivar fdio: fake file object returned by calls to fdopen.
    @type fdio: C{BytesIO} or C{BytesIO}

    @ivar actions: hold names of some actions executed by the object, in order
        of execution.

    @type actions: C{list} of C{str}

    @ivar closed: keep track of the file descriptor closed.
    @type closed: C{list} of C{int}

    @ivar child: whether fork return for the child or the parent.
    @type child: C{bool}

    @ivar pipeCount: count the number of time that C{os.pipe} has been called.
    @type pipeCount: C{int}

    @ivar raiseWaitPid: if set, subsequent calls to waitpid will raise
        the error specified.
    @type raiseWaitPid: L{None} or a class

    @ivar waitChild: if set, subsequent calls to waitpid will return it.
    @type waitChild: L{None} or a tuple

    @ivar euid: the uid returned by the fake C{os.geteuid}
    @type euid: C{int}

    @ivar egid: the gid returned by the fake C{os.getegid}
    @type egid: C{int}

    @ivar seteuidCalls: stored results of C{os.seteuid} calls.
    @type seteuidCalls: C{list}

    @ivar setegidCalls: stored results of C{os.setegid} calls.
    @type setegidCalls: C{list}

    @ivar path: the path returned by C{os.path.expanduser}.
    @type path: C{str}

    @ivar raiseKill: if set, subsequent call to kill will raise the error
        specified.
    @type raiseKill: L{None} or an exception instance.

    @ivar readData: data returned by C{os.read}.
    @type readData: C{str}
    FNTrrUcCsHg|_g|_d|_d|_d|_d|_dd�|_dd�|_g|_g|_	dS)	z-
        Initialize data structures.
        rr�������cSsdSrer!rr!r!r"rrUz!MockOS.__init__.<locals>.<lambda>cSsdSr�r!rr!r!r"rrUN)
�actionsr�	pipeCount�O_RDWR�O_NOCTTY�WNOHANG�WEXITSTATUS�	WIFEXITED�seteuidCalls�setegidCallsr%r!r!r"rNs

zMockOS.__init__cCsdS)ze
        Fake C{os.open}. Return a non fd number to be sure it's not used
        elsewhere.
        ���r!)rZdev�flagsr!r!r"�openszMockOS.opencCs
t�d�S)zT
        Fake C{os.fstat}.  Return a C{os.stat_result} filled with garbage.
        )
rrrrrrrrrr)r��stat_result�r�fdr!r!r"�fstat#szMockOS.fstatcCs |dkrt�|_ndst�|jS)zz
        Fake C{os.fdopen}. Return a file-like object whose content can
        be tested later via C{self.fdio}.
        �wbF)r�fdiori)rrf�flagr!r!r"�fdopen*s
z
MockOS.fdopencCs|j�d�dS)z1
        Fake C{os.setsid}. Save action.
        �setsidN�rXr1r%r!r!r"rl6sz
MockOS.setsidcCs8|j�dt��f�|jdk	r&|j�n|jr0dSdSdS)z�
        Fake C{os.fork}. Save the action in C{self.actions}, and return 0 if
        C{self.child} is set, or a dumb number.
        �forkNr�)rXr1�gc�	isenabled�	raiseForkrr%r!r!r"rn=s
zMockOS.forkcCs|j�|�dS)zK
        Fake C{os.close}, saving the closed fd in C{self.closed}.
        N)rr1rer!r!r"r�LszMockOS.closecCsdS)z.
        Fake C{os.dup2}. Do nothing.
        Nr!)rZfd1Zfd2r!r!r"�dup2SszMockOS.dup2cCs|j�d||f�dS)z0
        Fake C{os.write}. Save action.
        rZNrm)rrfr r!r!r"rZYszMockOS.writecCs|j�d||f�|jS)z�
        Fake C{os.read}: save action, and return C{readData} content.

        @param fd: The file descriptor to read.

        @param size: The maximum number of bytes to read.

        @return: A fixed C{bytes} buffer.
        �read)rXr1�readData)rrf�sizer!r!r"rt`s
zMockOS.readcCs|j�d�|jrtd��dS)zn
        Fake C{os.execvpe}. Save the action, and raise an error if
        C{self.raiseExec} is set.
        �execZBarN)rXr1�	raiseExecra)rr8r�r�r!r!r"r;nszMockOS.execvpecCs&|jd7_d|jdd|jfS)z�
        Fake C{os.pipe}. Return non fd numbers to be sure it's not used
        elsewhere, and increment C{self.pipeCount}. This is used to uniquify
        the result.
        r5rV)rYr%r!r!r"�pipexszMockOS.pipecCsdS)z;
        Fake C{os.ttyname}. Return a dumb string.
        �foor!rer!r!r"�ttyname�szMockOS.ttynamecCs |j�d|f�d|_t��dS)zs
        Fake C{os._exit}. Save the action, set the C{self.exited} flag, and
        raise C{SystemError}.
        �exitTN)rXr1�exited�SystemError)r�coder!r!r"�_exit�szMockOS._exitcCsdS)z6
        Override C{fcntl.ioctl}. Do nothing.
        Nr!)rrfrb�argr!r!r"�ioctl�szMockOS.ioctlcCsdS)z?
        Override C{fdesc.setNonBlocking}. Do nothing.
        Nr!rer!r!r"�setNonBlocking�szMockOS.setNonBlockingcCs0|j�d�|jdk	r|j�|jdk	r,|jSdS)z�
        Override C{os.waitpid}. Return values meaning that the child process
        has exited, save executed action.
        �waitpidN)r5r)rXr1�raiseWaitPid�	waitChild)rr�Zoptionsr!r!r"r��s

zMockOS.waitpidcCsdS)zD
        Override C{sys.settrace} to keep coverage working.
        Nr!)rr�r!r!r"�settrace�szMockOS.settracecCsdS)z>
        Override C{os.getgid}. Return a dumb number.
        i�r!r%r!r!r"�getgid�sz
MockOS.getgidcCsdS)z>
        Override C{os.getuid}. Return a dumb number.
        i�r!r%r!r!r"�getuid�sz
MockOS.getuidcCs|j�d|f�dS)z4
        Override C{os.setuid}. Do nothing.
        �setuidNrm�r�valr!r!r"r��sz
MockOS.setuidcCs|j�d|f�dS)z4
        Override C{os.setgid}. Do nothing.
        �setgidNrmr�r!r!r"r��sz
MockOS.setgidcCs|j�d||f�dS)z6
        Override C{os.setregid}. Do nothing.
        �setregidNrm�rZval1Zval2r!r!r"r��szMockOS.setregidcCs|j�d||f�dS)z<
        Override C{os.setreuid}.  Save the action.
        �setreuidNrmr�r!r!r"r��szMockOS.setreuidcCs|j�d||f�dS)z>
        Override L{util.switchUID}. Save the action.
        �	switchuidNrm)r�uid�gidr!r!r"�	switchUID�szMockOS.switchUIDcCsdS)zK
        Override C{pty.openpty}, returning fake file descriptors.
        )����r!r%r!r!r"�openpty�szMockOS.openptycCs|j�d|f�dS)z{
        Override C{os.chdir}. Save the action.

        @param path: The path to change the current directory to.
        �chdirNrm�rr�r!r!r"r��szMockOS.chdircCs|jS)zE
        Mock C{os.geteuid}, returning C{self.euid} instead.
        )�euidr%r!r!r"�geteuid�szMockOS.geteuidcCs|jS)zE
        Mock C{os.getegid}, returning C{self.egid} instead.
        )�egidr%r!r!r"�getegid�szMockOS.getegidcCs|j�|�dS)z3
        Mock C{os.seteuid}, store result.
        N)r_r1�rr�r!r!r"�seteuidszMockOS.seteuidcCs|j�|�dS)z3
        Mock C{os.setegid}, store result.
        N)r`r1r�r!r!r"�setegid
szMockOS.setegidcCs|jS)z-
        Mock C{os.path.expanduser}.
        )r�r�r!r!r"�
expanduserszMockOS.expandusercCsdS)z'
        Mock C{pwd.getpwnam}.
        )rrr5r=r!)r�userr!r!r"�getpwnamszMockOS.getpwnamcCsdS)zN
        Override C{os.listdir}, returning fake contents of '/dev/fd'
        )z-1z-2r!r�r!r!r"�listdirszMockOS.listdircCs&|j�d||f�|jdk	r"|j�dS)zh
        Override C{os.kill}: save the action and raise C{self.raiseKill} if
        specified.
        rN)rXr1�	raiseKill)rr�ZsignalIDr!r!r"r&s
zMockOS.killcCs|j�d|f�dS)zl
        Override C{os.unlink}. Save the action.

        @param filename: The file name to remove.
        �unlinkNrm)r�filenamer!r!r"r�0sz
MockOS.unlinkcCs|j�d|f�dS)zo
        Override C{os.umask}. Save the action.

        @param mask: The new file mode creation mask.
        �umaskNrm)r�maskr!r!r"r�9szMockOS.umaskcCsdS)zL
        Return a fixed PID value.

        @return: A fixed value.
        i�r!r%r!r!r"�getpidBsz
MockOS.getpidcCsdS)z`
        Return a fixed filesystem encoding.

        @return: A fixed value of "utf8".
        �utf8r!r%r!r!r"r�KszMockOS.getfilesystemencoding)7r)r*r+r,r}rxrirr�rrr�r�r�r�r�rurNrcrgrkrlrnr�rsrZrtr;ryr{r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rr�r�r�r�r!r!r!r"rU�shD


	
			rUc@seZdZdZdd�ZdS)�DumbProcessWriterzA
        A fake L{process.ProcessWriter} used for tests.
        cCsdS�zD
            Here's the faking: don't do anything here.
            Nr!r%r!r!r"�startReadingZszDumbProcessWriter.startReadingN�r)r*r+r,r�r!r!r!r"r�Usr�c@seZdZdZdd�ZdS)�DumbProcessReaderzA
        A fake L{process.ProcessReader} used for tests.
        cCsdSr�r!r%r!r!r"r�dszDumbProcessReader.startReadingNr�r!r!r!r"r�_sr�c@seZdZdZdd�ZdS)�DumbPTYProcessz>
        A fake L{process.PTYProcess} used for tests.
        cCsdSr�r!r%r!r!r"r�nszDumbPTYProcess.startReadingNr�r!r!r!r"r�isr�c@s�eZdZdZedkrdZdd�Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�ZdS)8�MockProcessTestsz?
    Mock a process runner to test forked child code path.
    Nz1twisted.internet.process is never used on WindowscCs�t��r|�tj�n|�tj�t�|_d|j_d|j_|�	t
d|j�|�	t
d|j�|�	t
d|j�|�	t
d|jj�|�	t
d|j�|�	t
jdt
�|�	t
jd	t�|�	t
d
|j�t�|_|�	t
d|j�dS)
z|
        Replace L{process} os, fcntl, sys, switchUID, fdesc and pty modules
        with the mock class L{MockOS}.
        i���r��fcntlr�r�ZfdescZprocessReaderFactoryZprocessWriterFactoryZptyruN)rprqr5�enable�disablerU�mockosr�r��patchrr��Processr�r�rPZmocksigr%r!r!r"r�}s zMockProcessTests.setUpcCs
it_dS)z6
        Reset processes registered for reap.
        N)rrGr%r!r!r"r�szMockProcessTests.tearDownc	Cs�t��d}t��}t|�}ztj||dgddd�Wn8tk
rn|�|j	j
�|�|j	jdddg�YnX|�
d	�|�t���dS)
zk
        Test a classic spawnProcess. Check the path of the client code:
        fork, exec, exit.
        �
/mock/ouch�ouchNFr��rnFrw�r|r5�Should not be here)rpr�rr�rHr
r�r~r�r�r}r8rXrr�rq�rr$rMr:r!r!r"�
test_mockFork�s �
�

zMockProcessTests.test_mockForkcCshd|j_d}t��}t|�}tj||dgddd�|�t|jj	�tdddg��|�|jj
d	d
g�dS)z�
        Assert that in the main process, spawnProcess disables the garbage
        collector, calls fork, closes the pipe file descriptors it created for
        the child process, and calls waitpid.
        Fr�r�Nr�r�rW���r�r�)r�rrr�rHr
r�r8�setrrXr�r!r!r"�_mockForkInParentTest�s�z&MockProcessTests._mockForkInParentTestcCs"t��|��|�t���dS)z�
        The garbage collector should be enabled when L{reactor.spawnProcess}
        returns if it was initially enabled.

        @see L{_mockForkInParentTest}
        N)rpr�r�r�rqr%r!r!r"�,test_mockForkInParentGarbageCollectorEnabled�sz=MockProcessTests.test_mockForkInParentGarbageCollectorEnabledcCs"t��|��|�t���dS)z�
        The garbage collector should be disabled when L{reactor.spawnProcess}
        returns if it was initially disabled.

        @see L{_mockForkInParentTest}
        N)rpr�r�r�rqr%r!r!r"�-test_mockForkInParentGarbageCollectorDisabled�sz>MockProcessTests.test_mockForkInParentGarbageCollectorDisabledc	CsZd}t��}t|�}|jttj||dgddd�|�|jj	�|�
|jjdddd	g�dS)
zg
        Test a TTY spawnProcess: check the path of the client code:
        fork, exec, exit.
        r�r�NTr�r�rlrwr�)rr�rHr�r~r
r�r�r�r}r8rXr�r!r!r"�test_mockForkTTY�s�
�z!MockProcessTests.test_mockForkTTYcCs@ttjd�|j_td�}|�ttj|d�|�	|jj
dg�dS)z�
        Assert that if the fork call fails, no other process setup calls are
        made and that spawnProcess raises the exception fork raised.
        Nr�)r�errno�EAGAINr�rrrHr�r
r�r8rX�rrr!r!r"�_mockWithForkError�sz#MockProcessTests._mockWithForkErrorcCs"t��|��|�t���dS)z�
        The garbage collector should be enabled when L{reactor.spawnProcess}
        raises because L{os.fork} raised, if it was initially enabled.
        N)rpr�r�r�rqr%r!r!r"�-test_mockWithForkErrorGarbageCollectorEnabled�sz>MockProcessTests.test_mockWithForkErrorGarbageCollectorEnabledcCs"t��|��|�t���dS)z�
        The garbage collector should be disabled when
        L{reactor.spawnProcess} raises because L{os.fork} raised, if it was
        initially disabled.
        N)rpr�r�r�rqr%r!r!r"�.test_mockWithForkErrorGarbageCollectorDisabledsz?MockProcessTests.test_mockWithForkErrorGarbageCollectorDisabledc
Cs0|��|�t|jj�tddddddg��dS)z}
        When C{os.fork} raises an exception, the file descriptors created
        before are closed and don't leak.
        r�rWr�rVra���N)r�r8r�r�rr%r!r!r"�test_mockForkErrorCloseFDss�z+MockProcessTests.test_mockForkErrorCloseFDsc	Cs�ttjd�|j_td�}|jttj|ddddd�d�|�	|jj
dg�|�	|jjg�|jttj|ddddd�d�|�	t|jj�td	d
g��dS)z�
        When C{os.forks} raises an exception and that file descriptors have
        been specified with the C{childFDs} arguments of
        L{reactor.spawnProcess}, they are not closed.
        Ni����i����r�)rr5r=�rr�rr�rV)
rr�r�r�rrrHr�r
r�r8rXrr�r�r!r!r"�test_mockForkErrorGivenFDss
�
�z+MockProcessTests.test_mockForkErrorGivenFDscCs`ttjd�|j_td�}|jttj|ddd�|�	|jj
dg�|�	t|jj�tddg��dS)z�
        When C{os.fork} raises an exception, the file descriptors created by
        C{pty.openpty} are closed and don't leak, when C{usePTY} is set to
        C{True}.
        NTrr�r�r�)
rr�r�r�rrrHr�r
r�r8rXr�rr�r!r!r"�test_mockForkErrorClosePTY.s�z+MockProcessTests.test_mockForkErrorClosePTYcCsTttjd�|j_td�}|jttj|ddd�|�	|jj
dg�|�	|jjg�dS)z�
        If a tuple is passed to C{usePTY} to specify slave and master file
        descriptors and that C{os.fork} raises an exception, these file
        descriptors aren't closed.
        N)i��i��rzrr�)rr�r�r�rrrHr�r
r�r8rXrr�r!r!r"�test_mockForkErrorPTYGivenFDs<s�z.MockProcessTests.test_mockForkErrorPTYGivenFDsc	Cs�d}t��}t|�}d|j_ztj||dgddd�Wn|tk
r�|�|jj	�|�
|jjddd	g�|�d
|jj
�|�d|jj
�|�d|jj
�|�d
|jj���YnX|�d�dS)z�
        Spawn a process but simulate an error during execution in the client
        path: C{os.execvpe} raises an error. It should close all the standard
        fds, try to print the error encountered, and exit cleanly.
        r�Tr�NFr�r�rwr�rr5r=sRuntimeError: Barr�)rr�rHr�rxr
r�r~r�r}r8rXr:rrir�rr�r!r!r"�test_mockWithExecErrorJs&�
�z'MockProcessTests.test_mockWithExecErrorcCs~d}t��}t|�}ztj||dgdddd�Wn>tk
rn|�|jj�|�	|jj
ddd	d
ddg�YnX|�d
�dS)z�
        Try creating a process with setting its uid: it's almost the same path
        as the standard path, but with a C{switchUID} call before the exec.
        r�r�NF��r�r�r�r��r�r�r�r)r�r�r�rwr�r��rr�rHr
r�r~r�r�r}r8rXrr�r!r!r"�test_mockSetUidfs&�
��
z MockProcessTests.test_mockSetUidcCsLd|j_d}t��}t|�}tj||dgdddd�|�|jjddg�dS)	z�
        When spawning a child process with a UID different from the UID of the
        current process, the current process does not have its UID changed.
        Fr�r�Nr�r�r�r�)	r�rrr�rHr
r�r8rXr�r!r!r"�test_mockSetUidInParent|s�z(MockProcessTests.test_mockSetUidInParentc
Cs�d}t��}t|�}ztj||dgdddd�Wn@tk
rp|�|jj�|�	|jj
ddd	d
ddd
g�YnX|�d�dS)z�
        Try creating a PTY process with setting its uid: it's almost the same
        path as the standard path, but with a C{switchUID} call before the
        exec.
        r�r�NT�r�r�rlr�r�)r�r�r�rwr�r�r�r�r!r!r"�test_mockPTYSetUid�s&�
��
z#MockProcessTests.test_mockPTYSetUidcCsfd|j_d}t��}t|�}tj}z"tt_tj	||dgdddd�W5|t_X|�
|jjdd	g�dS)
z�
        When spawning a child process with PTY and a UID different from the UID
        of the current process, the current process does not have its UID
        changed.
        Fr�r�NTr�r�r�r�)r�rrr�rHr�
PTYProcessr�r
r�r8rX)rr$rMr:Z
oldPTYProcessr!r!r"�test_mockPTYSetUidInParent�s�
z+MockProcessTests.test_mockPTYSetUidInParentcCs�d|j_d}d|j_t��}t|�}tj||dgddd�}|�|jj	ddg�t
�|j_|��|�
�}|�t|�d	�|d
�t
�dS)z;
        Test that reapProcess logs errors raised.
        Fr��rrr�Nr�r�r�r5r)r�rr�rr�rHr
r�r8rXrr��reapProcessrKrmr�)rr$rMr:�proc�errorsr!r!r"�test_mockWithWaitError�s�
z'MockProcessTests.test_mockWithWaitErrorcCspd|j_d}d|j_t��}t|�}tj||dgddd�}|�|jj	ddg�t
�|j_tj
|jj_|��dS)	z{
        Test that reapProcess doesn't log anything when waitpid raises a
        C{OSError} with errno C{ECHILD}.
        Fr�r�r�Nr�r�r�)r�rr�rr�rHr
r�r8rXrr�r�ZECHILDr�)rr$rMr:r�r!r!r"�!test_mockErrorECHILDInReapProcess�s�
z2MockProcessTests.test_mockErrorECHILDInReapProcesscsnddddg��fdd�}||j_td�}|�ttj|d�|�|jjg�|�t	|jj
�t	ddddg��dS)z�
        If C{os.pipe} raises an exception after some pipes where created, the
        created pipes are closed and don't leak.
        r�rVrarWcs6z��d���d�fWStk
r0t��YnXdSre)�pop�
IndexErrorrr!�Zpipesr!r"ry�sz3MockProcessTests.test_mockErrorInPipe.<locals>.pipeN)r�ryrHr�rr
r�r8rXr�r)rryrr!r�r"�test_mockErrorInPipe�sz%MockProcessTests.test_mockErrorInPipecCs^d|j_d|j_d}td�}tj||dgddd�}|�d�|�|jjdd	d
dt	j
fg�dS)z{
        L{process.Process.signalProcess} calls C{os.kill} translating the given
        signal string to the PID.
        Fr�r�Nr�r�r/r�r�rro)r�rr�rHr
r�rxr8rXru�SIGKILL�rr$r:r�r!r!r"r	�s

�zMockProcessTests.test_killcCs@d|j_d}td�}tj||dgddd�}|�tj|jd�dS)zz
        L{process.Process.signalProcess} raises L{error.ProcessExitedAlready}
        if the process has exited.
        Fr�Nr�r�r/)	r�rrHr
r�r�rr�rxr�r!r!r"�test_killExiteds�z MockProcessTests.test_killExitedcCsXd|j_d|j_d}td�}tj||dgddd�}ttjd�|j_	|�
tj|j
d�dS)	a*
        L{process.Process.signalProcess} raises L{error.ProcessExitedAlready}
        if the process has exited but that twisted hasn't seen it (for example,
        if the process has been waited outside of twisted): C{os.kill} then
        raise C{OSError} with C{errno.ESRCH} as errno.
        Fr�r�Nr�r�z	Not foundr/)r�rr�rHr
r�rr�ZESRCHr�r�rr�rxr�r!r!r"�test_killExitedButNotDetecteds�z.MockProcessTests.test_killExitedButNotDetectedcCsfd|j_d|j_d}td�}tj||dgddd�}ttjd�|j_	|�
t|jd�}|�|jtj�dS)	z�
        L{process.Process.signalProcess} doesn't mask C{OSError} exceptions if
        the errno is different from C{errno.ESRCH}.
        Fr�r�Nr�r�zInvalid signalr/)
r�rr�rHr
r�rr�ZEINVALr�r�rxr8)rr$r:r�rXr!r!r"�test_killErrorInKill"s�z%MockProcessTests.test_killErrorInKill) r)r*r+r,rrOr�rr�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!r!r"r�us:

r�c@seZdZdd�Zdd�ZdS)�PosixProcessTestsc	sXd}t��t��}�_tj�ttdtd�|��gdd�j	d���fdd�}|�
|�S)	z�
        Bytes written to stderr by the spawned process are passed to the
        C{errReceived} callback on the C{ProcessProtocol} passed to
        C{spawnProcess}.
        Z42r�z#import sys; sys.stderr.write('{0}')N�/tmpr�cs��d�j���dS)Ns42)r8r�r�r�r�r!r"rSGsz3PosixProcessTests.test_stderr.<locals>.processEnded)r�rr�r�r
r�r�r�formatr�r�)rr}rMrSr!r�r"�test_stderr6s���zPosixProcessTests.test_stderrcsn��d�}d�t��t��}�_tj�||dgdd�jd��j�	���j�
����fdd�}|�|�S)N�gzipsTthere's no place like home!
there's no place like home!
there's no place like home!
r�r�r�c	s>�j}|�dd�tj|d��}��|����W5QRXdS)Nr)Zfileobj)r��seekr�ZGzipFiler8rt)r�r�Zgf�r:rjrr!r"rSVsz4PosixProcessTests.test_process.<locals>.processEnded)r"r�rr�r�r
r�r�rYrZror�)rr$rMrSr!r�r"r�Ls
�
zPosixProcessTests.test_processN)r)r*r+r�r�r!r!r!r"r�3sr�c@s$eZdZdZdZdd�Zdd�ZdS)�PosixProcessPTYTestszE
    Just like PosixProcessTests, but use ptys instead of pipes.
    TcsZd}t��t��}�_tj�ttdd|gt�jd��j	�
d���fdd�}|�|�S)Nstwisted.test.process_ttyr�r�r�s
hello world!
cs8��tj�jjd����j��dd�j��f�dS)Nr+shello world!
hello world!
z-Error message from process_tty follows:

%s

)r�rr�rYrxr8r�r�r�r�r!r"rSss�
��z:PosixProcessPTYTests.test_openingTTY.<locals>.processEnded)r�rr�r�r
r�r�r�r�rYrZr�r�r!r�r"�test_openingTTYks�z$PosixProcessPTYTests.test_openingTTYc	Cs4tdddg}t�}|jttj|t|dddid�dS)Nr�r��print('hello')r5�r)r�r�r�r�r�r|r
r��r�pyArgsr:r!r!r"�test_badArgs~s�z!PosixProcessPTYTests.test_badArgsN)r)r*r+r,r�r�r�r!r!r!r"r�_sr�c@seZdZdZdd�ZdS)�Win32SignalProtocolz�
    A win32-specific process protocol that handles C{processEnded}
    differently: processes should exit with exit code 1.
    cCsZ|�tj�s"|j�td|f��S|j}|jdkrJ|j�td|jf��S|j�d�dS)z�
        Callback C{self.deferred} with L{None} if C{reason} is a
        L{error.ProcessTerminated} failure with C{exitCode} set to 1.
        Otherwise, errback with a C{ValueError} describing the problem.
        ryr5zWrong exit code: %sN)	rqrrzrIr{r|r}r�rQ)rrPr�r!r!r"rS�s�
�z Win32SignalProtocol.processEndedN)r)r*r+r,rSr!r!r!r"r��sr�c@sXeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�ZdS)�Win32ProcessTestsz?
    Test process programs that are packaged with twisted.
    csTt��t��}�_t��||||��j�d��j����fdd�}|�	|�S)zH
        Spawn a process, write to stdin, and check the output.
        r�cs(���j��d����j��d�dS)Nserr
err
sout
hello, world
out
)r8r�r�r�r�r�r!r"rS�sz9Win32ProcessTests._test_stdinReader.<locals>.processEnded)
r�rr�r�r
r�rYrZror�)rr�r�r�r�rMrSr!r�r"�_test_stdinReader�s
z#Win32ProcessTests._test_stdinReadercCsnddl}ttj���}|dddg}t�}tj�tj	��
t���|d<|��}|�
t���}|�
||||�}|S)z=
        Pass L{bytes} args to L{_test_stdinReader}.
        rNr�r�s twisted.test.process_stdinreaderr)�win32apirr��
executabler!rr��pathsepr�r�r�r��GetTempPathr�)rrr�r�r�r�rMr!r!r"�test_stdinReader_bytesArgs�s�z,Win32ProcessTests.test_stdinReader_bytesArgscCs�ddl}ttj���}|dddg}t}tj�tj	�}t
|t�rL|�t�
��}||d<|��}t
|t�rt|�t�
��}|�||||�}|S)z?
        Pass L{unicode} args to L{_test_stdinReader}.
        rNz-ur(z twisted.test.process_stdinreaderr)rrr�rZ_asTextPathr�r�rr�r�r~r��decoder�rr�)rrr�r�r�Z
pythonPathr�rMr!r!r"�test_stdinReader_unicodeArgs�s

z.Win32ProcessTests.test_stdinReader_unicodeArgscCsztdddg}t�}|jttj|t|dd�|jttj|t|dd�|jttj|t|dd�|jttj|t|ddid	�dS)
Nr�r�r�r5)r�)r�rrr�r�r�r!r!r"r��s<����zWin32ProcessTests.test_badArgscCs4d}t��}t||�}tj|ttdd|gtd�|S)Nr'r�r�r�)rr�r�r
r�r�r�r)r!r!r"r*�s
�zWin32ProcessTests._testSignalcCs
|�d�S)z�
        Sending the SIGTERM signal terminates a created process, and
        C{processEnded} is called with a L{error.ProcessTerminated} instance
        with the C{exitCode} attribute set to 1.
        r1r,r%r!r!r"r2�sz!Win32ProcessTests.test_signalTERMcCs
|�d�S)z�
        Sending the SIGINT signal terminates a created process, and
        C{processEnded} is called with a L{error.ProcessTerminated} instance
        with the C{exitCode} attribute set to 1.
        r�r,r%r!r!r"r.�sz Win32ProcessTests.test_signalINTcCs
|�d�S)z�
        Sending the SIGKILL signal terminates a created process, and
        C{processEnded} is called with a L{error.ProcessTerminated} instance
        with the C{exitCode} attribute set to 1.
        r/r,r%r!r!r"r0�sz!Win32ProcessTests.test_signalKILLcs�ddl�t���t���G��fdd�dtj�}|�}tdddg}t�|t|�����fdd	�}��|����fd
d�}��|�t�	��g�S)zU
        The win32 handles should be properly closed when the process exits.
        rNcs(eZdZdZ�fdd�Z�fdd�ZdS)z;Win32ProcessTests.test_closeHandles.<locals>.SimpleProtocolzZ
            A protocol that fires deferreds when connected and disconnected.
            cs��|�dSrr=r>r?r!r"rA	szJWin32ProcessTests.test_closeHandles.<locals>.SimpleProtocol.makeConnectioncs��d�dSrr=rRrBr!r"rS	szHWin32ProcessTests.test_closeHandles.<locals>.SimpleProtocol.processEndedNrDr!rEr!r"�SimpleProtocol	srr�r�r�cs8��|�����j����j��j�_�j�_dSr)ZassertIs�GetHandleInformation�hProcess�hThreadrH�r�rrr!r"rJ	s
z8Win32ProcessTests.test_closeHandles.<locals>.cbConnectedcsP���j����j����j����j�j�j����j�j�j�dSr)r�r�r	r
r�rrr�rr!r"rL)	s��z<Win32ProcessTests.test_closeHandles.<locals>.checkTerminated)
rrr�rr.r�r
r�r�r�)rrr:r�rJrLr!)r@rCr�rrr"�test_closeHandles	s



z#Win32ProcessTests.test_closeHandlesN)
r)r*r+r,r�rrr�r*r2r.r0rr!r!r!r"r��s
				r�c@s eZdZdZdZdZdd�ZdS)�Win32UnicodeEnvironmentTestsz2
    Tests for Unicode environment on Windows
    �UNICODEcsJ�jtj�j<��tjtj�j�t�t	gt
�}�fdd�}|���|�S)a
        Test C{os.environ} (inherited by every subprocess on Windows) that
        contains an ascii-encodable Unicode string. This is different from
        passing Unicode environment explicitly to spawnProcess (which is not
        supported on Python 2).
        cs$��|�j�d��j�d��dS)N�ascii)r8�goodKeyr��	goodValue)r�r%r!r"�gotEnvironmentK	s
�zUWin32UnicodeEnvironmentTests.test_encodableUnicodeEnvironment.<locals>.gotEnvironment)
rr�r�rr5�operator�delitemr�r�r
r�r�r�)rr:rr!r%r"� test_encodableUnicodeEnvironment@	s
z=Win32UnicodeEnvironmentTests.test_encodableUnicodeEnvironmentN)r)r*r+r,rrrr!r!r!r"r
9	sr
c@s eZdZdZdd�Zdd�ZdS)�DumbWin32ProcTestsz3
    L{twisted.internet._dumbwin32proc} tests.
    c
s�ddlm}ddlm}��|d|�tt��d�j}tt	j
���j}t�
�}t|�}d}|d||g}|�t|d|id����d	�j���d
t�����fdd�}	|�|	�S)
z�
        Simple test for the pid attribute of Process on win32.
        Launch process with mock win32process. The only mock aspect of this
        module is that the pid of the process created will always be 42.
        r��_dumbwin32proc)�mock_win32process�win32process�process_cmdline.pyzcmd.exe�/cN�*z<Process pid=42>cs���j�dSrr�)r�r�r!r"�
pidCompleteCbm	sz2DumbWin32ProcTests.test_pid.<locals>.pidCompleteCb)�twisted.internetrZtwisted.testrr�r�__file__�siblingr�r�rZ
asTextModerr�rHr�r
r8r��reprr�)
rrrr�r�rM�processProto�comspecr$rr!r�r"�test_pidW	s*�zDumbWin32ProcTests.test_pidcCs8ddlm}td�}|�d�||j�}|�|d�dS)zP
        Look for the string after the shebang C{#!}
        in a file.
        r)�_findShebangsexample.cgis#!/usr/bin/pythonz/usr/bin/pythonN)Ztwisted.internet._dumbwin32procr&rZ
setContentr�r8)rr&Z	cgiScriptZprogramr!r!r"�test_findShebangr	s


z#DumbWin32ProcTests.test_findShebangN)r)r*r+r,r%r'r!r!r!r"rS	src@seZdZdZejdd��ZdS)�Win32CreateProcessFlagsTestsz2
    Check the flags passed to CreateProcess.
    c	#s�ddlm}g�|jj���fdd�}|�|jd|�tj}tt��	d�}t
��}t|�}t
tjd�}|d||jg}|�t|d	|id	�|V|��|jjg�d	S)
a�
        Verify that the flags passed to win32process.CreateProcess() prevent a
        new console window from being created. Use the following script
        to test this interactively::

            # Add the following lines to a script named
            #   should_not_open_console.pyw
            from twisted.internet import reactor, utils

            def write_result(result):
            open("output.log", "w").write(repr(result))
            reactor.stop()

            PING_EXE = r"c:\windows\system32\ping.exe"
            d = utils.getProcessOutput(PING_EXE, ["slashdot.org"])
            d.addCallbacks(write_result)
            reactor.run()

        To test this, run::

            pythonw.exe should_not_open_console.pyw
        rrc		
s"��|��|||||||||�	S)a�
            See the Windows API documentation for I{CreateProcess} for further details.

            @param appName: The name of the module to be executed
            @param commandLine: The command line to be executed.
            @param processAttributes: Pointer to SECURITY_ATTRIBUTES structure or None.
            @param threadAttributes: Pointer to SECURITY_ATTRIBUTES structure or  None
            @param bInheritHandles: boolean to determine if inheritable handles from this
                                    process are inherited in the new process
            @param creationFlags: flags that control priority flags and creation of process.
            @param newEnvironment: pointer to new environment block for new process, or None.
            @param currentDirectory: full path to current directory of new process.
            @param startupinfo: Pointer to STARTUPINFO or STARTUPINFOEX structure
            @return: True on success, False on failure
            @rtype: L{bool}
            r0)	ZappNameZcommandLineZprocessAttributesZthreadAttributesZbInheritHandlesZ
creationFlagsZnewEnvironmentZcurrentDirectoryZstartupinfo�rbZrealCreateProcessr!r"�fakeCreateprocess�	s
�zBWin32CreateProcessFlagsTests.test_flags.<locals>.fakeCreateprocess�
CreateProcessrZCOMSPECrN)rrrr+r�r�rrr r!rr�rHrsr�r�r�r�r
r8ZCREATE_NO_WINDOW)	rrr*�exer�rMr#r$r$r!r)r"�
test_flags�	s$
��z'Win32CreateProcessFlagsTests.test_flagsN)r)r*r+r,rZinlineCallbacksr-r!r!r!r"r(	sr(c@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
�	UtilTestsz\
    Tests for process-related helper functions (currently only
    L{procutils.which}.
    cCs(tjj}|��}||d�|_||d�|_||jd�|_||jd�|_||jd�|_||jd�|_	|j|j|j|j	fD]}t�
|�qt||jd�df||jd�df||jd�df||jd�df||j	d�dffD]"\}}t|d���t�
||�q�tj�d	d
�|_tj�|j|j|j|j	f�tjd	<d
S)z�
        Create several directories and files, some of which are executable
        and some of which are not.  Save the current PATH setting.
        rz�bazZbarri��executable.binrrh�PATHN)r�r�r�Zmktemprzr/Zfoobar�foobaz�bazfoo�bazbar�makedirsrcr��chmodr��get�oldPathr)r�j�baserM�name�moder!r!r"r��	s2��zUtilTests.setUpcCsXt�tj�|jd�tj�|jdkrHztjd=WqTt	k
rDYqTXn|jtjd<dS)z�
        Restore the saved PATH setting, and set all created files readable
        again so that they can be deleted easily.
        rNr1)
r�r6r�r�r4�stat�S_IWUSRr8r��KeyErrorr%r!r!r"r�	s
zUtilTests.tearDowncCstjd=|�t�d�g�dS)z}
        Test that if C{os.environ} does not have a C{'PATH'} key,
        L{procutils.which} returns an empty list.
        r1rN)r�r�r8rr6r%r!r!r"�test_whichWithoutPATH�	szUtilTests.test_whichWithoutPATHcCsVtjj}t�d�}||jd�||jd�g}tj�	�rF|�
||jd��|�||�dS)Nr)
r�r�r�rr6r2r3rrN�	isWindowsr1r4r8)rr9�paths�
expectedPathsr!r!r"�
test_which
s


�
zUtilTests.test_whichc	Cs�tjj}tj�dd�}tj�d�tjd<zt�d�}W5|dkrJtjd=n
|tjd<X||jd�||j	d�||j	d�g}t
j��r�|�
||jd��|�||�dS)NZPATHEXT)z.binz.exez.shrr0)r�r�r�r�r7rrr6r2r3rrNrAr1r4r8)rr9�oldrBrCr!r!r"�test_whichPathExt
s



�
zUtilTests.test_whichPathExtN)	r)r*r+r,r�rr@rDrFr!r!r!r"r.�	s 	
r.c@s4eZdZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�ClosingPipesProcessProtocolrUcCst��|_||_dSr)rr�rI�outOrErr)rrHr!r!r"rN(
s
z$ClosingPipesProcessProtocol.__init__cCs|j�|�dSr)rIrQrRr!r!r"rS-
sz(ClosingPipesProcessProtocol.processEndedcCs|j|7_dSr)�outputrr!r!r"r#1
sz'ClosingPipesProcessProtocol.outReceivedcCs|j|7_dSr��errputrr!r!r"r$5
sz'ClosingPipesProcessProtocol.errReceivedN)	r)r*r+rIrKrNrSr#r$r!r!r!r"rG$
srGc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�ClosingPipesTestsc	Cs�td�}|�|jtj�|j�|j|�tj|t	t	ddt
d|f�gdd�|dkr`|j��n|dkrt|j�
�nt�|j�d	�|j��|jS)
a
        Create a child process and close one of its output descriptors using
        L{IProcessTransport.closeStdout} or L{IProcessTransport.closeStderr}.
        Return a L{Deferred} which fires after verifying that the descriptor was
        really closed.
        Tr�r�z�try: input = raw_input
except NameError: pass
input()
import sys, os, time
for i in range(1000):
    os.write(%d, b"foo\n")
    time.sleep(0.01)
sys.exit(42)
Nr�r5r=sgo
)rGZ
assertFailurerIrrzr��_endProcessr
r�r�rrYZcloseStdoutZcloseStderrrarZro)rrfr:r!r!r"�doit<
s.���
zClosingPipesTests.doitcCs(|�|jdd|�|�|jd�|jS)zo
        Check that a failed write prevented the process from getting to its
        custom exit code.
        rzprocess reason was %rrU)ZassertNotEqualr�r8rIrK)rrPr:r!r!r"rMg
s�zClosingPipesTests._endProcesscs$��d�}�fdd�}|�|�|S)zQ
        ProcessProtocol.transport.closeStdout actually closes the pipe.
        r5cs`tr6tj��r(��d|���d|�qB��d|�n��d|�tj��dkr\��d|�dS)NsOSErrors22sBrokenPipeError�win32sBroken pipe)rrrNrAr:�getTyperJr%r!r"r�x
s
z-ClosingPipesTests.test_stdout.<locals>._check�rNr��rrMr�r!r%r"�test_stdouts
s

zClosingPipesTests.test_stdoutcs$��d�}�fdd�}|�|�|S)zQ
        ProcessProtocol.transport.closeStderr actually closes the pipe.
        r=cs��|d�dSr�)r8rJr%r!r"r��
sz-ClosingPipesTests.test_stderr.<locals>._checkrQrRr!r%r"r��
s

zClosingPipesTests.test_stderrN)r)r*r+rNrMrSr�r!r!r!r"rL:
s+rLz9wrong platform or reactor doesn't support IReactorProcess�posixrO)cr,Z
__future__rrrr�r�r�rur�rpr=rr��ImportErrorrrZzope.interface.verifyr�iorZtwisted.python.logr	r
rrr
rZ
twisted.trialrZtwisted.pythonrrZtwisted.python.compatrrrrZtwisted.python.filepathrrr!r�r�rNrAr�rr�r�r�r��dictr�r.rZTestCaser-rHrTrcrtr�r�r�r�r�r�r�r�rr
rr��objectrrPrUZ
ProcessWriterr�Z
ProcessReaderr�r�r�r�r�r�r�r�r
rr(r.rGrLZskipMessagerPZIReactorProcessrOr!r!r!r"�<module>s��

Y 2(IJI)/W #]



A,',J[Z