o
    HXhUq                    @   s  d dl 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 d dlmZ d dl	Z	d dl
Z
d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlmZ zd dlZW n e y   dZY nw zd dl!Z!W n e y   dZ!Y nw zd dl"Z"W n e y   dZ"Y nw zd dl#Z#W n   dZ#Y ej$re %d	e
j&d
kZ'e'rdZ(ndZ(dZ)e*e+e,fZ-e
j.ddfa/dd Z0G dd de j1Z2G dd de3Z4G dd de	j5Z6G dd de2Z7G dd de2Z8dd Z9e :e'dG dd  d e2Z;e <e'd!G d"d# d#e2Z=G d$d% d%e j1Z>e <e?ed&d'G d(d) d)e7Z@e <e'd*G d+d, d,e2ZAG d-d. d.e2ZBeCd/krke D  dS dS )0    N)mock)support)check_sanitizer)import_helper)	os_helper)warnings_helper)FakePathztest is not helpful for PGOwin32z@import msvcrt; msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY); )Znonexisting_i_hope-cpassc                  C   sH   t d} | d u rd S t| tjr t| gjdkr"| fad S d S d S )Ntruer   )	shutilwhichosaccessX_OK
subprocessrun
returncodeZERO_RETURN_CMD)Z
shell_true r   >/opt/python-3.10.19/usr/lib/python3.10/test/test_subprocess.pysetUpModuleG   s   

r   c                   @      e Zd Zdd Zdd ZdS )BaseTestCasec                 C   s   t   d S N)r   reap_childrenselfr   r   r   setUpR   s   zBaseTestCase.setUpc                 C   sB   t stjD ]}|  qt  | tjd |   t  d S )Nzsubprocess._active not empty)		mswindowsr   _activewait_cleanupassertFalseZ
doCleanupsr   r   )r   instr   r   r   tearDownW   s   

zBaseTestCase.tearDownN__name__
__module____qualname__r    r'   r   r   r   r   r   Q   s    r   c                   @   s   e Zd ZdS )PopenTestExceptionN)r)   r*   r+   r   r   r   r   r,   d   s    r,   c                   @   s   e Zd Z	 dd ZdS )PopenExecuteChildRaisesc                 O      t d)NzForced Exception for Test)r,   r   argskwargsr   r   r   _execute_childl      z&PopenExecuteChildRaises._execute_childN)r)   r*   r+   r2   r   r   r   r   r-   h   s    r-   c                   @   s  e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Ze e!d9d:d; Z"e e!d9d<d= Z#e e!d9d>d? Z$d@dA Z%dBdC Z&dDdE Z'dFdG Z(dHdI Z)dJdK Z*e e!dLdMdN Z+e e!dLdOdP Z,dQdR Z-e e.j/e.j0kdSdTdU Z1e e.j/e.j0kdSe e23 dVdWdX Z4dYdZ Z5d[d\ Z6d]d^ Z7d_d` Z8dadb Z9dcdd Z:dedf Z;dgdh Z<didj Z=dkdl Z>dmdn Z?dodp Z@dqdr ZAdsdt ZBdudv ZCdwdx ZDeEeFo/eGeFdydzd{d| ZHeEeFo?eGeFdydzd}d~ ZIdd ZJe e.jKdkde e2Lddkde eMddddd ZNdd ZOdd ZPdd ZQdd ZRdd ZSdd ZTdd ZUdd ZVdd ZWdd ZXdd ZYdd ZZdd Z[dd Z\dd Z]dd Z^dd Z_dd Z`dd Zadd Zbdd Zcdd Zddd Zedd Zfdd Zgdd Zhdd Zidd ZjddĄ ZkddƄ ZlddȄ Zmddʄ Zndd̄ Zodd΄ ZpddЄ Zqdd҄ ZrddԄ Zsddք ZteEeGeud׃dءeEeGevdكdڡeEeGevdۃdܡddބ ZweEevjxydevz  ddd Z{e e!ddd Z|e e!ddd Z}dd Z~dS )ProcessTestCasec                 C   s   t jtt jt jt jd}z.| |jtj | |jtj | |j	tj W |j
  |j
  |j	
  |  d S |j
  |j
  |j	
  |  w )Nstdinstdoutstderr)r   Popenr   PIPEassertIsInstancer6   ioBufferedIOBaser7   r8   closer#   r   pr   r   r   test_io_buffered_by_defaultr   s    






z+ProcessTestCase.test_io_buffered_by_defaultc                 C   s   t jtt jt jt jdd}z.| |jtj | |jtj | |j	tj W |j
  |j
  |j	
  |  d S |j
  |j
  |j	
  |  w )Nr   )r6   r7   r8   bufsize)r   r9   r   r:   r;   r6   r<   	RawIOBaser7   r8   r>   r#   r?   r   r   r   test_io_unbuffered_works   s    






z(ProcessTestCase.test_io_unbuffered_worksc                 C   s"   t tjddg}| |d d S Nr   import sys; sys.exit(47)/   r   callsys
executableassertEqualr   rcr   r   r   test_call_seq   s   
zProcessTestCase.test_call_seqc                 C   s"   | j tjtjtjddgdd d S )Nr   while True: pass皙?timeout)assertRaisesr   TimeoutExpiredrI   rJ   rK   r   r   r   r   test_call_timeout   s   

z!ProcessTestCase.test_call_timeoutc                 C   s   t t}| |d d S Nr   )r   
check_callr   rL   rM   r   r   r   test_check_call_zero   s   
z$ProcessTestCase.test_check_call_zeroc                 C   R   |  tj}ttjddg W d    n1 sw   Y  | |jjd d S rE   )	rT   r   CalledProcessErrorrX   rJ   rK   rL   	exceptionr   r   cr   r   r   test_check_call_nonzero   s   
z'ProcessTestCase.test_check_call_nonzeroc                 C   s"   t tjddg}| d| d S )Nr   print('BDFL')   BDFLr   check_outputrJ   rK   assertInr   outputr   r   r   test_check_output   s   
z!ProcessTestCase.test_check_outputc                 C   rZ   )Nr   zimport sys; sys.exit(5)   )	rT   r   r[   rc   rJ   rK   rL   r\   r   r]   r   r   r   test_check_output_nonzero   s   
z)ProcessTestCase.test_check_output_nonzeroc                 C   s(   t jtjddgt jd}| d| d S )Nr   $import sys; sys.stderr.write('BDFL')r8   ra   )r   rc   rJ   rK   STDOUTrd   re   r   r   r   test_check_output_stderr   s
   
z(ProcessTestCase.test_check_output_stderrc                 C   sN   t  }| |j |d |d tjtj	ddg|d}| 
d| d S )N   pearr   r   6import sys; sys.stdout.write(sys.stdin.read().upper())r6      PEAR)tempfileTemporaryFile
addCleanupr>   writeseekr   rc   rJ   rK   rd   )r   tfrf   r   r   r   test_check_output_stdin_arg   s   

z+ProcessTestCase.test_check_output_stdin_argc                 C   s&   t jtjddgdd}| d| d S )Nr   ro   rn   inputrq   rb   re   r   r   r   test_check_output_input_arg   s   z+ProcessTestCase.test_check_output_input_argc                 C   s(   	 t jtjddgd d}| d| d S )Nr   3import sys; print('XX' if sys.stdin.read() else '')ry   s   XXr   rc   rJ   rK   assertNotInre   r   r   r   test_check_output_input_none   s   z,ProcessTestCase.test_check_output_input_nonec                 C   (   t jtjddgd dd}| d| d S )Nr   r|   T)rz   textXXr}   re   r   r   r   !test_check_output_input_none_text      z1ProcessTestCase.test_check_output_input_none_textc                 C   r   )Nr   r|   T)rz   universal_newlinesr   r}   re   r   r   r   /test_check_output_input_none_universal_newlines   r   z?ProcessTestCase.test_check_output_input_none_universal_newlinesc                 C   s*   t jtjddgd ddd}| d| d S )Nr   zprint('foo')utf-8ignore)rz   encodingerrorsfoorb   re   r   r   r   ,test_check_output_input_none_encoding_errors   s
   
z<ProcessTestCase.test_check_output_input_none_encoding_errorsc                 C   sd   |  t}tjtjddgtjd}| d W d    n1 s!w   Y  | d|j	j
d  d S )Nr   print('will not be run')r7   z-Expected ValueError when stdout arg supplied.r7   r   )rT   
ValueErrorr   rc   rJ   rK   r7   failrd   r\   r0   r   r^   rf   r   r   r   test_check_output_stdout_arg   s   
z,ProcessTestCase.test_check_output_stdout_argc                 C   s   t  }| |j |d |d | t}tj	t
jddg|dd}| d W d    n1 s5w   Y  | d|jjd  | d	|jjd  d S )
Nrn   r   r   r      harer6   rz   7Expected ValueError when stdin and input args supplied.r6   rz   )rr   rs   rt   r>   ru   rv   rT   r   r   rc   rJ   rK   r   rd   r\   r0   r   rw   r^   rf   r   r   r   &test_check_output_stdin_with_input_arg   s   


z6ProcessTestCase.test_check_output_stdin_with_input_argc                 C   s`   |  tj}tjtjddgdd}| d W d    n1 s!w   Y  | |jj	d d S )Nr   Mimport sys, time
sys.stdout.write('BDFL')
sys.stdout.flush()
time.sleep(3600)   rR   zExpected TimeoutExpired.ra   )
rT   r   rU   rc   rJ   rK   r   rL   r\   rf   r   r   r   r   test_check_output_timeout  s   	z)ProcessTestCase.test_check_output_timeoutc                 C   s8   t j }d|d< tjtjddg|d}| |d d S )NbananaFRUITr   z5import sys, os;sys.exit(os.getenv("FRUIT")=="banana")env   )r   environcopyr   rI   rJ   rK   rL   )r   newenvrN   r   r   r   test_call_kwargs  s   

z ProcessTestCase.test_call_kwargsc                 C   s~   t  )}| jttjdd tjjjj}dg|d  }| jttjg|R   W d    n1 s0w   Y  | 	|
 d d S )Nr   )Zinvalid_arg_namer   r
   )r   Zcaptured_stderrrT   	TypeErrorr   r9   __init____code__co_argcountrL   getvalue)r   sZargcountZtoo_many_argsr   r   r   test_invalid_args  s   
z!ProcessTestCase.test_invalid_argsc                 C   R   t jtjddgt jt jd}| |jj | |jj |	  | 
|jd  d S )Nr   print("banana")r7   r8   )r   r9   rJ   rK   r:   rt   r7   r>   r8   r#   rL   r6   r?   r   r   r   test_stdin_none'     zProcessTestCase.test_stdin_nonec                 C   l   d}t jtjd|gt jt jd}| |jj | |jj |	 \}}| 
|jd| | 
| d d S )Nzimport sys; from subprocess import Popen, PIPE;p = Popen([sys.executable, "-c", "print('test_stdout_none')"],          stdin=PIPE, stderr=PIPE);p.wait(); assert p.stdout is None;r   r   r   s   test_stdout_noner   r9   rJ   rK   r:   rt   r7   r>   r8   communicaterL   r   rstripr   coder@   outerrr   r   r   test_stdout_none0  s   z ProcessTestCase.test_stdout_nonec                 C   r   )Nr   r   r6   r7   )r   r9   rJ   rK   r:   rt   r7   r>   r6   r#   rL   r8   r?   r   r   r   test_stderr_noneG  r   z ProcessTestCase.test_stderr_nonec                 K   s6   |dg }t j|fi |}|  | d|j d S NrF   rG   )r   r9   r#   rL   r   )r   pre_argsr1   r0   r@   r   r   r   _assert_pythonP  s   
zProcessTestCase._assert_pythonc                 C   s0   t jt jtjd}| j|dgtjd d S Ndoesnotexistr   rK   )r   pathjoindirnamerJ   rK   r   r   r   r   r   r   test_executableX  s   zProcessTestCase.test_executablec                 C   s6   t jt jtjd}| j|dgt tjd d S r   )r   r   r   r   rJ   rK   r   fsencoder   r   r   r   test_bytes_executablec  s   


z%ProcessTestCase.test_bytes_executablec                 C   s4   t jt jtjd}| j|dgttjd d S r   )r   r   r   r   rJ   rK   r   r   r   r   r   r   test_pathlike_executablei  s   

z(ProcessTestCase.test_pathlike_executablec                 C   s0   t jdg}| | | jt| j|td d d S )Nr   r   r   )rJ   rK   r   rT   NONEXISTING_ERRORSNONEXISTING_CMD)r   r   r   r   r    test_executable_takes_precedenceo  s   


z0ProcessTestCase.test_executable_takes_precedencez"executable argument replaces shellc                 C   s   | j g tjdd d S NT)rK   shell)r   rJ   rK   r   r   r   r   test_executable_replaces_shelly  s   z.ProcessTestCase.test_executable_replaces_shellc                 C   s   | j g ttjdd d S r   )r   r   r   rJ   rK   r   r   r   r   $test_bytes_executable_replaces_shell  s   
z4ProcessTestCase.test_bytes_executable_replaces_shellc                 C   s   | j g ttjdd d S r   )r   r   rJ   rK   r   r   r   r   'test_pathlike_executable_replaces_shell  s   
z7ProcessTestCase.test_pathlike_executable_replaces_shellc                 C   s6   t | t W  d    S 1 sw   Y  d S r   )r   Z
change_cwdr   getcwd)r   cwdr   r   r   _normalize_cwd  s   $zProcessTestCase._normalize_cwdc                 C   s   t jtj}t j|S r   )r   r   realpathrJ   rK   split)r   Zpython_pathr   r   r   _split_python_path  s   z"ProcessTestCase._split_python_pathc                 K   sl   t j|ddgfdt ji|}| |jj |  | d|j t	j
j}| ||||j   d S )Nr   zcimport os, sys; buf = sys.stdout.buffer; buf.write(os.getcwd().encode()); buf.flush(); sys.exit(47)r7   rG   )r   r9   r:   rt   r7   r>   r#   rL   r   r   r   normcasereaddecode)r   Zexpected_cwdZ
python_argr1   r@   r   r   r   r   _assert_cwd  s   
zProcessTestCase._assert_cwdc                 C   s(   t  }| |}| j|tj|d d S Nr   )rr   
gettempdirr   r   rJ   rK   r   temp_dirr   r   r   test_cwd  s   
zProcessTestCase.test_cwdc                 C   s.   t  }| |}| j|tjt|d d S r   )rr   r   r   r   rJ   rK   r   r   r   r   r   r   test_cwd_with_bytes  s   
z#ProcessTestCase.test_cwd_with_bytesc                 C   s,   t  }| |}| j|tjt|d d S r   )rr   r   r   r   rJ   rK   r   r   r   r   r   test_cwd_with_pathlike  s   
z&ProcessTestCase.test_cwd_with_pathlikez"pending resolution of issue #15533c                 C   s   |   \}}tjtj|}t *}| tt	j
|g | jtt	j
|g|d | |}| j|||d W d    d S 1 s?w   Y  d S r   r   r   r   r   curdirr   Ztemp_cwdrT   FileNotFoundErrorr   r9   r   r   )r   
python_dirpython_base
rel_python	wrong_dirr   r   r   test_cwd_with_relative_arg  s   



"z*ProcessTestCase.test_cwd_with_relative_argc                 C   s   |   \}}tjtj|}d}t .}| jtt	j
|g|d | jtt	j
|g||d | |}| j||||d W d    d S 1 sEw   Y  d S )Nsomethingyoudonthaver   rK   r   r   )r   r   r   r   Zdoesntexistr   r   r   r   !test_cwd_with_relative_executable  s    




"z1ProcessTestCase.test_cwd_with_relative_executablec                 C   s   |   \}}tj||}tjtj|}t !}| jtt	j
|g|d | |}| j|||d W d    d S 1 s=w   Y  d S r   )r   r   r   r   r   r   r   rT   r   r   r9   r   r   )r   r   r   Z
abs_pythonr   r   r   r   r   test_cwd_with_absolute_arg  s   


"z*ProcessTestCase.test_cwd_with_absolute_argzTest is not venv-compatiblec                 C   s.   |   \}}| |}| j|dtj|d d S )Nr   r   )r   r   r   rJ   rK   )r   r   r   r   r   r   test_executable_with_cwd  s
   

z(ProcessTestCase.test_executable_with_cwdz#need an installed Python. See #7774c                 C   s   | j t dtjd d S )Nr   r   )r   r   r   rJ   rK   r   r   r   r   test_executable_without_cwd  s   
z+ProcessTestCase.test_executable_without_cwdc                 C   sH   t jtjddgt jd}|jd |j  |  | 	|j
d d S )Nr   0import sys; sys.exit(sys.stdin.read() == "pear")rp   rn   r   )r   r9   rJ   rK   r:   r6   ru   r>   r#   rL   r   r?   r   r   r   test_stdin_pipe  s   

zProcessTestCase.test_stdin_pipec                 C   sf   t  }| |j | }t|d t|dd tj	t
jddg|d}|  | |jd d S Nrn   r   r   r   rp   r   )rr   rs   rt   r>   filenor   ru   lseekr   r9   rJ   rK   r#   rL   r   r   rw   dr@   r   r   r   test_stdin_filedes  s   
z"ProcessTestCase.test_stdin_filedesc                 C   sX   t  }| |j |d |d tjtj	ddg|d}|
  | |jd d S r   )rr   rs   rt   r>   ru   rv   r   r9   rJ   rK   r#   rL   r   r   rw   r@   r   r   r   test_stdin_fileobj  s   


z"ProcessTestCase.test_stdin_fileobjc                 C   T   t jtjddgt jd}| | |j d W d    d S 1 s#w   Y  d S )Nr   &import sys; sys.stdout.write("orange")r      oranger   r9   rJ   rK   r:   rL   r7   r   r?   r   r   r   test_stdout_pipe!     
"z ProcessTestCase.test_stdout_pipec                 C   `   t  }| |j | }tjtjddg|d}|	  t
|dd | t
|dd d S )Nr   r   r   r      r   rr   rs   rt   r>   r   r   r9   rJ   rK   r#   r   r   rL   r   r   r   r   r   test_stdout_filedes)     
z#ProcessTestCase.test_stdout_filedesc                 C   P   t  }| |j tjtjddg|d}|  |	d | 
| d d S )Nr   r   r   r   r   rr   rs   rt   r>   r   r9   rJ   rK   r#   rv   rL   r   r   r   r   r   test_stdout_fileobj5     

z#ProcessTestCase.test_stdout_fileobjc                 C   r   )Nr   *import sys; sys.stderr.write("strawberry")rk   
   strawberry)r   r9   rJ   rK   r:   rL   r8   r   r?   r   r   r   test_stderr_pipe@  r   z ProcessTestCase.test_stderr_pipec                 C   r  )Nr   r
  rk   r   r  r  r  r   r   r   r   test_stderr_filedesH  r  z#ProcessTestCase.test_stderr_filedesc                 C   r  )Nr   r
  rk   r   r  r  r   r   r   r   test_stderr_fileobjT  r	  z#ProcessTestCase.test_stderr_fileobjc                 C   sR   t jtjddgt jt jd}| \}}| |d | |d | |jd d S )Nr   zimport sys, subprocess;rc = subprocess.call([sys.executable, "-c",    "import sys;"    "sys.stderr.write('42')"],    stderr=subprocess.STDOUT);sys.exit(rc)r   s   42    r   r   r9   rJ   rK   r:   r   rL   r   r   r@   r7   r8   r   r   r   ,test_stderr_redirect_with_no_stdout_redirect_  s   
	z<ProcessTestCase.test_stderr_redirect_with_no_stdout_redirectc                 C   sX   t jtjddgt jt jd}| | |j d W d    d S 1 s%w   Y  d S )Nr   Rimport sys;sys.stdout.write("apple");sys.stdout.flush();sys.stderr.write("orange")r      appleorange)	r   r9   rJ   rK   r:   rl   rL   r7   r   r?   r   r   r   test_stdout_stderr_pipet  s   
"z'ProcessTestCase.test_stdout_stderr_pipec                 C   sR   t  }| |j tjtjddg||d}|  |	d | 
| d d S )Nr   r  r   r   r  r  r   r   r   r   test_stdout_stderr_file  s   

z'ProcessTestCase.test_stdout_stderr_filec                 C   r   )Nzimport sys, subprocess; rc = subprocess.call([sys.executable, "-c",     "import os, sys; sys.exit(os.write(sys.stdout.fileno(), b'test with stdout=1'))"], stdout=1); assert rc == 18r   r   r   s   test with stdout=1r   r   r   r   r   test_stdout_filedes_of_stdout  s   z-ProcessTestCase.test_stdout_filedes_of_stdoutc                 C   2   t jtjddgt jd}|  | |jd  d S )Nr   z'for i in range(10240):print("x" * 1024)r   )r   r9   rJ   rK   DEVNULLr#   rL   r7   r?   r   r   r   test_stdout_devnull     
z#ProcessTestCase.test_stdout_devnullc                 C   r  )Nr   z=import sys
for i in range(10240):sys.stderr.write("x" * 1024)rk   )r   r9   rJ   rK   r  r#   rL   r8   r?   r   r   r   test_stderr_devnull  s   
z#ProcessTestCase.test_stderr_devnullc                 C   r  )Nr   zimport sys;sys.stdin.read(1)rp   )r   r9   rJ   rK   r  r#   rL   r6   r?   r   r   r   test_stdin_devnull  r  z"ProcessTestCase.test_stdin_devnullF_GETPIPE_SZz%fcntl.F_GETPIPE_SZ required for test.c              	   C   s   t  \}}zt|tj}W t | t | nt | t | w |d }|dk r2tdtjt	j
ddgtjtjtj|d}z.|j|j|jfD ]}| t| tj| qL|jd |j  W |  |  d S |  |  w )N   i   z+default pipesize too small to perform test.r   Qimport sys; sys.stdin.read(); sys.stdout.write("out"); sys.stderr.write("error!")r6   r7   r8   pipesizern   )r   pipefcntlr  r>   unittestSkipTestr   r9   rJ   rK   r:   r6   r7   r8   rL   r   ru   killr#   )r   Ztest_pipe_rZtest_pipe_wZpipesize_defaultr"  r@   fifor   r   r   test_pipesizes  s>   


zProcessTestCase.test_pipesizesc              	   C   s   t jtjddgt jt jt jdd}zMt \}}z+t|tj}|j	|j
|jfD ]}| t| tj| q(W t| t| nt| t| w |j	  W |  |  d S |  |  w )Nr   r   r!  )r   r9   rJ   rK   r:   r   r#  r$  r  r6   r7   r8   rL   r   r>   r'  r#   )r   r@   Zfp_rZfp_wZdefault_pipesizer(  r   r   r   test_pipesize_default  s4   


z%ProcessTestCase.test_pipesize_defaultc                 C   sj   t j }d|d< tjtjddgtj|d}| \}}| 	|d W d    d S 1 s.w   Y  d S )Noranger   r   2import sys,os;sys.stdout.write(os.getenv("FRUIT"))r7   r   r   )
r   r   r   r   r9   rJ   rK   r:   r   rL   r   r   r@   r7   r8   r   r   r   test_env  s   

"zProcessTestCase.test_envr	   z#cannot test an empty env on WindowsZPy_ENABLE_SHAREDr   zEThe Python shared library cannot be loaded with an empty environment.T)addressz)AddressSanitizer adds to the environment.c                    s   	 dd  t jtjddgt ji d*}| \}}t| }| |t	  fdd|D }| 
|g  W d    d S 1 s?w   Y  d S )Nc                 S   s,   	 d| v pd| v p| dkp|  dp| dkS )NZ	VERSIONERZ__CFZ
LD_PRELOADZSANDBOXLC_CTYPE)
startswith)nr   r   r   is_env_var_to_ignore  s   z<ProcessTestCase.test_empty_env.<locals>.is_env_var_to_ignorer   z)import os; print(list(os.environ.keys()))r.  c                    s   g | ]} |s|qS r   r   ).0kr5  r   r   
<listcomp>  s    
z2ProcessTestCase.test_empty_env.<locals>.<listcomp>)r   r9   rJ   rK   r:   r   evalstripr;   listrL   )r   r@   r7   r8   Zchild_env_namesr   r8  r   test_empty_env  s   
	"zProcessTestCase.test_empty_envc                 C   s   t jd }| t t|ddg W d    n1 sw   Y  | t tt jddg W d    d S 1 s<w   Y  d S )N r   r   zpass# )rJ   rK   rT   r   r   r9   )r   cmdr   r   r   test_invalid_cmd"  s   
"z ProcessTestCase.test_invalid_cmdc                 C   sH  t j }d|d< | t tjt|d W d    n1 s w   Y  t j }d|d< | t tjt|d W d    n1 sEw   Y  t j }d|d< | t tjt|d W d    n1 sjw   Y  t j }d|d< tjtj	d	d
gtj
|d}| \}}| |d W d    d S 1 sw   Y  d S )NZcabbagezFRUIT VEGETABLEr   zorange VEGETABLE=cabbager   ZlemonzFRUIT=ORANGEzorange=lemonr   z3import sys, os;sys.stdout.write(os.getenv("FRUIT"))r.  s   orange=lemon)r   r   r   rT   r   r   r9   r   rJ   rK   r:   r   rL   r/  r   r   r   test_invalid_env,  s6   




"z ProcessTestCase.test_invalid_envc                 C   s4   t jtjddgt jd}|d | |jd d S )Nr   z/import sys;sys.exit(sys.stdin.read() == "pear")rp   rn   r   r  r?   r   r   r   test_communicate_stdinJ  s   

z&ProcessTestCase.test_communicate_stdinc                 C   s@   t jtjddgt jd}| \}}| |d | |d  d S )Nr   z)import sys; sys.stdout.write("pineapple")r   	   pineappler   r9   rJ   rK   r:   r   rL   r  r   r   r   test_communicate_stdoutR     
z'ProcessTestCase.test_communicate_stdoutc                 C   s@   t jtjddgt jd}| \}}| |d  | |d d S )Nr   z)import sys; sys.stderr.write("pineapple")rk   rC  rD  r  r   r   r   test_communicate_stderrZ  rF  z'ProcessTestCase.test_communicate_stderrc                 C   st   t jtjddgt jt jt jd}| |jj | |jj | |j	j |
d\}}| |d | |d d S )Nr   zNimport sys,os;sys.stderr.write("pineapple");sys.stdout.write(sys.stdin.read())r5      bananarC  )r   r9   rJ   rK   r:   rt   r7   r>   r8   r6   r   rL   r  r   r   r   test_communicateb  s   
z ProcessTestCase.test_communicatec                 C   sd   t jtjddgdt jt jt jd}| jt j|jddd | \}}| |d | |	 d d S )	Nr   z~import sys,os,time;sys.stderr.write("pineapple\n");time.sleep(1);sys.stderr.write("pear\n");sys.stdout.write(sys.stdin.read())T)r   r6   r7   r8   r   g333333?rR   s   pineapple
pear
)
r   r9   rJ   rK   r:   rT   rU   r   rL   encoder  r   r   r   test_communicate_timeoutq  s   

z(ProcessTestCase.test_communicate_timeoutc                 C   sL   t jtjddgt jd}| jt j|jdd | \}}| t	|d d S )Nr   zimport sys,os,time;sys.stdout.write("a" * (64 * 1024));time.sleep(0.2);sys.stdout.write("a" * (64 * 1024));time.sleep(0.2);sys.stdout.write("a" * (64 * 1024));time.sleep(0.2);sys.stdout.write("a" * (64 * 1024));r   g?rR   i   )
r   r9   rJ   rK   r:   rT   rU   r   rL   len)r   r@   r7   _r   r   r   %test_communicate_timeout_large_output  s   
	
z5ProcessTestCase.test_communicate_timeout_large_outputc                 C   s   dD ]W}dD ]R}dD ]M}i }|rt j|d< |rt j|d< |r#t j|d< |s&q
t jtfi |}|  |jd ur?| |jj |jd urK| |jj |j	d urW| |j	j q
qqd S )NFTr6   r7   r8   )
r   r:   r9   r   r   r6   
assertTrueclosedr7   r8   )r   Z
stdin_pipeZstdout_pipeZstderr_pipeoptionsr@   r   r   r   test_communicate_pipe_fd_leak  s0   





z-ProcessTestCase.test_communicate_pipe_fd_leakc                 C   s:   t tjddg}| \}}| |d  | |d  d S )Nr   rF   )r   r9   rJ   rK   r   rL   r  r   r   r   test_communicate_returns  s   
z(ProcessTestCase.test_communicate_returnsc                 C   s   t  \}}t | t | tjtjddtj gtj	tj	tj	d}| 
|jj | 
|jj | 
|jj dtj }||\}}| || d S )Nr   zpimport sys,os;sys.stdout.write(sys.stdin.read(47));sys.stderr.write("x" * %d);sys.stdout.write(sys.stdin.read())r5      a)r   r#  r>   r   r9   rJ   rK   r   PIPE_MAX_SIZEr:   rt   r7   r8   r6   r   rL   )r   xyr@   Zstring_to_writer7   r8   r   r   r   test_communicate_pipe_buf  s$   


	
z)ProcessTestCase.test_communicate_pipe_bufc                 C   s   t jtjddgt jt jt jd}| |jj | |jj | |j	j |j	
d |d\}}| |d | |d d S )Nr   z0import sys,os;sys.stdout.write(sys.stdin.read())r5   rH  s   splits   bananasplitr  )r   r9   rJ   rK   r:   rt   r7   r>   r8   r6   ru   r   rL   r  r   r   r   test_writes_before_communicate  s   
z.ProcessTestCase.test_writes_before_communicatec              
   C   s   t jddt d g}dD ]g}tj|fi dtjdtj|di}|J |jd |j  | 	|j
 d |jd	 |j  | |j
j | 	|j
 d
 | 	|j
dd	 | 	|j
 d W d    n1 snw   Y  qd S )Nr   import sys,os;a@  buf = sys.stdout.buffer;buf.write(sys.stdin.readline().encode());buf.flush();buf.write(b"line2\n");buf.flush();buf.write(sys.stdin.read().encode());buf.flush();buf.write(b"line4\n");buf.flush();buf.write(b"line5\r\n");buf.flush();buf.write(b"line6\r");buf.flush();buf.write(b"\nline7");buf.flush();buf.write(b"\nline8");)r   r   r6   r7   Tzline1
zline3
zline2
   zline4
line5
line6
line7
line8)rJ   rK   	SETBINARYr   r9   r:   r6   ru   flushrL   r7   readliner>   rt   r   )r   r0   Zextra_kwargr@   r   r   r    test_universal_newlines_and_text  s:   

z0ProcessTestCase.test_universal_newlines_and_textc                 C   s^   t jtjddt d gt jt jdd}| |jj | |j	j |
 \}}| |d d S )Nr   r[  zbuf = sys.stdout.buffer;buf.write(b"line2\n");buf.flush();buf.write(b"line4\n");buf.flush();buf.write(b"line5\r\n");buf.flush();buf.write(b"line6\r");buf.flush();buf.write(b"\nline7");buf.flush();buf.write(b"\nline8");r   )r8   r7   r   z#line2
line4
line5
line6
line7
line8)r   r9   rJ   rK   r]  r:   rt   r7   r>   r8   r   rL   r  r   r   r   #test_universal_newlines_communicate  s   
z3ProcessTestCase.test_universal_newlines_communicatec                 C   sH   t jtjddt td gt jdd}|d\}}| 	|j
d d S )Nr   r[  a  
                               s = sys.stdin.readline()
                               assert s == "line1\n", repr(s)
                               s = sys.stdin.read()
                               assert s == "line3\n", repr(s)
                              r   )r6   r   line1
line3
r   )r   r9   rJ   rK   r]  textwrapdedentr:   r   rL   r   r  r   r   r   )test_universal_newlines_communicate_stdin  s   
	z9ProcessTestCase.test_universal_newlines_communicate_stdinc                 C   s0   t jtt jt jdd}|  | |jd d S )NT)r6   r7   r   r   )r   r9   r   r:   r   rL   r   r?   r   r   r   .test_universal_newlines_communicate_input_none(  s   z>ProcessTestCase.test_universal_newlines_communicate_input_nonec                 C   s   t jtjddt td gt jt jt jdd}| |j	j
 | |jj
 |d\}}| |jd | d| | |d	 d S )
Nr   r[  a  
                               s = sys.stdin.buffer.readline()
                               sys.stdout.buffer.write(s)
                               sys.stdout.buffer.write(b"line2\r")
                               sys.stderr.buffer.write(b"eline2\n")
                               s = sys.stdin.buffer.read()
                               sys.stdout.buffer.write(s)
                               sys.stdout.buffer.write(b"line4\n")
                               sys.stdout.buffer.write(b"line5\r\n")
                               sys.stderr.buffer.write(b"eline6\r")
                               sys.stderr.buffer.write(b"eline7\r\nz")
                              T)r6   r8   r7   r   rb  r   zline1
line2
line3
line4
line5
zeline2
eline6
eline7
)r   r9   rJ   rK   r]  rc  rd  r:   rt   r7   r>   r8   r   rL   r   rP  r3  r  r   r   r   7test_universal_newlines_communicate_stdin_stdout_stderr4  s   
zGProcessTestCase.test_universal_newlines_communicate_stdin_stdout_stderrc                 C   sT   dD ]%}d| }t jd|g}tj|tjtj|d}|jdd\}}| |d qd S )N)zutf-16z	utf-32-bez@import sys; sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))r   )r6   r7   r   r
   ry   z1
2
3
4)rJ   rK   r   r9   r:   r   rL   )r   r   r   r0   popenr7   r8   r   r   r   -test_universal_newlines_communicate_encodingsP  s   z=ProcessTestCase.test_universal_newlines_communicate_encodingsc                 C   s\   dD ])\}}d}t jd|g}tj|tjtjd|d}|jdd\}}| |d| qd S )	N))r   r
   )replaceu   ��)surrogateescapeu   )backslashreplacez\x80\x80z2import sys; sys.stdout.buffer.write(b'[\x80\x80]')r   r   )r6   r7   r   r   r
   ry   z[{}])rJ   rK   r   r9   r:   r   rL   format)r   r   expectedr   r0   rh  r7   r8   r   r   r   test_communicate_errorsf  s   z'ProcessTestCase.test_communicate_errorsc           
      C   sB  t sd}nd}g }t }zt|D ]3}ztj|tj}|	t
|tjtjB  W q tyE } z|jtjkr: W Y d }~ nd }~ww | d|  tdD ]	}t|  qQtdD ]}tjtjddgtjtjtjd}|d	d
 }| |d	 q_W |D ]}	t|	 qt| d S |D ]}	t|	 qt| w )Ni  i  z4failed to reach the file descriptor limit (tried %d)
      r   z-import sys;sys.stdout.write(sys.stdin.read())r5   s   limer   )r!   rr   mkdtempranger   r   r   r   ZTESTFNappendopenO_WRONLYO_CREATOSErrorerrnoZEMFILEskipTestr>   popr   r9   rJ   rK   r:   r   rL   r   rmtree)
r   Zmax_handleshandlestmpdiriZtmpfileer@   datahr   r   r   test_no_leaking{  sL   

zProcessTestCase.test_no_leakingc                 C   s   |  tg dd |  tg dd |  tg dd |  tg dd |  tg d	d
 |  tg dd |  tg dd |  tddgd d S )N)za b cr   r  z"a b c" d e)ab"c\r   z	ab\"c \ d)r  z \r   zab\"c " \\" d)za\\\bzde fgr  za\\\b "de fg" h)za\"br^   r   z
a\\\"b c d)za\\b cr   r  z"a\\b c" d e)za\\b\ cr   r  z"a\\b\ c" d eabr
   zab "")rL   r   list2cmdliner   r   r   r   test_list2cmdline  s0   z!ProcessTestCase.test_list2cmdlinec                 C   sb   t jtjddgt jd}| |jj | |	  t
|j d |  | |	 d d S )Nr   zimport os; os.read(0, 1)rp      Ar   )r   r9   rJ   rK   r:   rt   r6   r>   assertIsNonepollr   ru   r   r#   rL   r?   r   r   r   	test_poll  s   
zProcessTestCase.test_pollc                 C   s.   t t}| | d | | d d S rW   r   r9   r   rL   r#   r?   r   r   r   	test_wait  s   
zProcessTestCase.test_waitc                 C   sv   t tjddg}| t j}|jdd W d    n1 s w   Y  | dt|j	 | 
|jtjdd d S )Nr   zimport time; time.sleep(0.3)-C6?rR   z0.0001r   )r   r9   rJ   rK   rT   rU   r#   rd   strr\   rL   r   SHORT_TIMEOUT)r   r@   r^   r   r   r   test_wait_timeout  s   z!ProcessTestCase.test_wait_timeoutc                 C   s<   |  t ttd W d    d S 1 sw   Y  d S )Nr,  )rT   r   r   r9   r   r   r   r   r   test_invalid_bufsize  s   "z$ProcessTestCase.test_invalid_bufsizec                 C   s>   t td }| | d t jtd d}| | d d S )Nr   )rB   r  r?   r   r   r   test_bufsize_is_none  s   z$ProcessTestCase.test_bufsize_is_nonec              
   C   s   t jtjddgt jt jt jd|dC}|j| t	|j
  |j }t  z|j	  W n	 ty;   Y nw W d    n1 sFw   Y  d |_W d    n1 sXw   Y  | |jd | || d S )Nr   zDimport sys;sys.stdout.write(sys.stdin.readline());sys.stdout.flush()r   )r6   r7   r8   rB   r   r   )r   r9   rJ   rK   r:   r  r6   ru   r   r>   r   r7   r_  r   SuppressCrashReportrx  rL   r   )r   linern  r   r@   Z	read_liner   r   r   _test_bufsize_equal_one  s.   

z'ProcessTestCase._test_bufsize_equal_onec                 C   s   d}| j ||dd d S )Nzline
Tr   )r  r   r  r   r   r    test_bufsize_equal_one_text_mode  s   z0ProcessTestCase.test_bufsize_equal_one_text_modec                 C   sP   dt j  }| td | j|ddd W d    d S 1 s!w   Y  d S )Ns   linezline bufferingr  Fr  )r   lineseprJ  ZassertWarnsRegexRuntimeWarningr  r  r   r   r   "test_bufsize_equal_one_binary_mode  s   "z2ProcessTestCase.test_bufsize_equal_one_binary_modec              	   C   sP   t dD ]!}| t tjttjtjd W d    n1 s w   Y  qd S )Nr  r   )rs  rT   r   r   r9   r   r:   )r   r  r   r   r   test_leaking_fds_on_error  s   z)ProcessTestCase.test_leaking_fds_on_errorc              	   C   s   z	dd l }|j W n ttfy   | d Y nw tdtd}tj	d|g}t
j|t
jdd}| | d }W d    n1 sEw   Y  | |d	 | |jd d S )
Nr   zneed msvcrt.CrtSetReportModezL
            import msvcrt
            import subprocess

            cmd = a  

            for report_type in [msvcrt.CRT_WARN,
                                msvcrt.CRT_ERROR,
                                msvcrt.CRT_ASSERT]:
                msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
                msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)

            try:
                subprocess.Popen(cmd,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            except OSError:
                pass
        r   T)r8   r   r   r
   )msvcrtZCrtSetReportModeAttributeErrorImportErrorrz  rc  rd  r   rJ   rK   r   r9   r:   r   rL   r   )r   r  r   r?  procr8   r   r   r   test_nonexisting_with_pipes
  s&   

z+ProcessTestCase.test_nonexisting_with_pipesc                    s   g   fdd}t j|d}|  zP| t tjttjtjtjd W d    n1 s/w   Y  W |	  d } D ]}zt
| W q= tyZ } z|}W Y d }~q=d }~ww |d ura|d S |	  d } D ]}zt
| W qk ty } z|}W Y d }~qkd }~ww |d ur|w )Nc                     s*   t dD ]}  t  td qd S )N   gMbP?)rs  extendr   r#  timesleep)r  fdsr   r   open_fds6  s   z<ProcessTestCase.test_double_close_on_error.<locals>.open_fds)targetr5   )	threadingThreadstartrT   EnvironmentErrorr   r9   r   r:   r   r   r>   rx  )r   r  texcfdr  r   r  r   test_double_close_on_error3  sH   z*ProcessTestCase.test_double_close_on_errorc                    s   	 t tjddg |  jd  g  fdd}td|}|  t	r)d}nd} j
tjd | j j|d	d
  
  | j j|dd
 |  | dd|fd|fg d S )Nr   zimport time; time.sleep(12)c                      sN    d  f        d jf     d jf d S )Nthread-start-poll-resultthread-after-kill-and-waitthread-after-second-wait)rt  r  r'  r#   r   r   r  resultsr   r   kill_proc_timer_threadW  s   zDProcessTestCase.test_threadsafe_wait.<locals>.kill_proc_timer_thread皙?r   irR   z*unexpected result in wait from main threadmsgz&unexpected result in second main wait.)r  Nr  r  )r   r9   rJ   rK   rL   r   r  Timerr  r!   r#   r   r  r   )r   r  r  Zexpected_errorcoder   r  r   test_threadsafe_waitP  s6   


z$ProcessTestCase.test_threadsafe_waitc                 C   s6   d d}ttjd|g}| |dt| d S )N;)zimport subprocess, syszJretcode = subprocess.call([sys.executable, '-c', 'print("Hello World!")'])zassert retcode == 0r   s   Hello World!)r   r   rc   rJ   rK   rP  r3  ascii)r   r   rf   r   r   r   test_issue8780  s   
zProcessTestCase.test_issue8780c                 C   s   t  \}}t  \}}t  \}}ztjdg|||d W n' tyE   t| t| t| t| t| t| Y nw | tj	
| | tj	
| | tj	
| d S )N*r5   )rr   mkstempr   r9   rx  r   r>   remover%   r   exists)r   ZifhandleZifnameZofhandleZofnameZefhandleZefnamer   r   r    test_handles_closed_on_exception  s$   





z0ProcessTestCase.test_handles_closed_on_exceptionc                 C   sT   t jtt jt jt jd}| |jj | |jj | |jj |	dd  d S )Nr5      x   )
r   r9   r   r:   rt   r7   r>   r8   r6   r   r?   r   r   r   test_communicate_epipe  s   z&ProcessTestCase.test_communicate_epipec           	   
   C   s   t d}|jj}dddgdd dfg ddd df|dd	d
| dfg}tjjtj	d$ |D ]\}}}}tj	||d}||_
| t|| q/W d    d S 1 sSw   Y  d S )Nz
my-tool.py)lsT{   z#<Popen: returncode: 123 args: 'ls'>)daaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaTr   zP<Popen: returncode: 0 args: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...>r  Fz&<Popen: returncode: None args: ['ls']>)r  z	--my-optsr  zP<Popen: returncode: None args: ['ls', '--my-opts', 'aaaaaaaaaaaaaaaaaaaaaaaa...>   z<Popen: returncode: 7 args: z('my-tool.py')>r2   r   )pathlibPath	__class__r)   r%  r   patchobjectr   r9   r   rL   repr)	r   Zpath_cmdZpathlib_clscasesr?  r   r   Zsxr@   r   r   r   	test_repr  s"   

	"zProcessTestCase.test_reprc                 C   s8   t jtt jd}| |jj |  |dd  d S )Nrp   r  r  )	r   r9   r   r:   rt   r6   r>   r#   r   r?   r   r   r   !test_communicate_epipe_only_stdin  s   z1ProcessTestCase.test_communicate_epipe_only_stdinSIGUSR1zRequires signal.SIGUSR1r'  zRequires os.killgetppidzRequires os.getppidc              	   C   s   dd }t  t j|}| t j t j| tjddg}dD ]$}|tji}tj|fi |}|  W d    n1 s;w   Y  qd S )Nc                 S      d S r   r   )signumframer   r   r   handler     z7ProcessTestCase.test_communicate_eintr.<locals>.handlerr   z7import os, signal;os.kill(os.getppid(), signal.SIGUSR1)r   )	signalr  rt   rJ   rK   r   r:   r9   r   )r   r  old_handlerr0   streamkwprocessr   r   r   test_communicate_eintr  s   

z&ProcessTestCase.test_communicate_eintr/proc/%d/fdzLinux specificc                 C   sr   	 dt   }t |}| t tttjtjtjd W d    n1 s'w   Y  t |}| 	|| d S )Nr  r5   )
r   getpidlistdirrT   r,   r-   r   r   r:   rL   )r   Zfd_directoryZfds_before_popenZfds_after_exceptionr   r   r   !test_failed_child_execute_fd_leak  s   

	z1ProcessTestCase.test_failed_child_execute_fd_leakz+behavior currently not supported on Windowsc                 C   sL   |  t}tg d W d    n1 sw   Y  | |jjd d S )N)/opt/nonexistent_binarywithZsomer0   r  )rT   r   r   rI   rL   r\   filenamer]   r   r   r   %test_file_not_found_includes_filename  s   z5ProcessTestCase.test_file_not_found_includes_filenamec                 C   sP   |  t}tjddgdd W d    n1 sw   Y  | |jjd d S )Nexit0z/some/nonexistent/directoryr   )rT   r   r   r9   rL   r\   r  r]   r   r   r    test_file_not_found_with_bad_cwd  s   z0ProcessTestCase.test_file_not_found_with_bad_cwdc                 C   s,   |  tjt tj |  tjt tj d S r   )r;   r   r9   bytestypesGenericAliasCompletedProcessr  r   r   r   r   test_class_getitems   s   z#ProcessTestCase.test_class_getitemsN)r)   r*   r+   rA   rD   rO   rV   rY   r_   rg   ri   rm   rx   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r%  skipIfr!   r   r   r   r   r   r   r   r   r   r   r   r   rJ   base_prefixprefixr   	sysconfigZis_python_buildr   r   r   r   r   r  r  r  r  r  r  r  r  r  r  r  r  
skipUnlessr$  hasattrr)  r+  r0  platformget_config_varr   r=  r@  rA  rB  rE  rG  rI  rK  rN  rS  rT  rY  rZ  r`  ra  re  rf  rg  ri  ro  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r   isdirr  r  r  r  r  r   r   r   r   r4   p   s*   		

		













	
 

'')4




r4   c                   @   s   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zeed%d&d' Zeed( d)d*d+ Zd,S )-RunFuncTestCasec                 K   s    	 t jd|g}tj|fi |S )Nr   )rJ   rK   r   r   )r   r   r1   argvr   r   r   
run_python  s   zRunFuncTestCase.run_pythonc                 C   sR   |  d}| |jd | tj |  W d    d S 1 s"w   Y  d S r   )r   rL   r   rT   r   r[   check_returncoder   cpr   r   r   test_returncode
  s
   

"zRunFuncTestCase.test_returncodec                 C   sN   |  tj}| jddd W d    n1 sw   Y  | |jjd d S )NrF   TcheckrG   )rT   r   r[   r   rL   r\   r   r]   r   r   r   
test_check  s   zRunFuncTestCase.test_checkc                 C   s    t jtdd}| |jd d S )NTr  r   )r   r   r   rL   r   r  r   r   r   test_check_zero  s   zRunFuncTestCase.test_check_zeroc                 C   s@   |  tj | jddd W d    d S 1 sw   Y  d S )NrP   r  rR   )rT   r   rU   r   r   r   r   r   test_timeout  s   "zRunFuncTestCase.test_timeoutc                 C   "   | j dtjd}| d|j d S )Nr`   r   ra   r   r   r:   rd   r7   r  r   r   r   test_capture_stdout#  s   z#RunFuncTestCase.test_capture_stdoutc                 C   r
  )Nrj   rk   ra   )r   r   r:   rd   r8   r  r   r   r   test_capture_stderr(  s   z#RunFuncTestCase.test_capture_stderrc                 C   sL   t  }| |j |d |d | jd|tjd}| 	d|j
 d S )Nrn   r   ro   r   rq   )rr   rs   rt   r>   ru   rv   r   r   r:   rd   r7   )r   rw   r  r   r   r   rx   -  s   

z+RunFuncTestCase.test_check_output_stdin_argc                 C   s$   | j ddtjd}| d|j d S )Nro   rn   )rz   r7   rq   r  r  r   r   r   r{   8  s
   z+RunFuncTestCase.test_check_output_input_argc                 C   s   t  }| |j |d |d | jtdd}| jd|dd}W d    n1 s.w   Y  | 	d|j
jd  | 	d	|j
jd  d S )
Nrn   r   r   r  r   r   r   r6   rz   )rr   rs   rt   r>   ru   rv   rT   r   r   rd   r\   r0   r   r   r   r   r   ?  s   

z6RunFuncTestCase.test_check_output_stdin_with_input_argc                 C   sb   |  tj}| jddtjd}W d    n1 sw   Y  | |jjd | |jjd d S )Nr   r   )rS   r7   ra   )	rT   r   rU   r   r:   rL   r\   rf   r7   )r   r^   r  r   r   r   r   L  s   	z)RunFuncTestCase.test_check_output_timeoutc                 C   s2   t j }d|d< | jd|d}| |jd d S )Nr   r   zCimport sys, os;sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)r   !   )r   r   r   r   rL   r   )r   r   r  r   r   r   test_run_kwargsZ  s   
zRunFuncTestCase.test_run_kwargsc                 C   s   t rdnd}t|}|d u r| | d t|}tj|tjd}| |j	d | 
t tj|tjdd W d    d S 1 sDw   Y  d S )Nztree.comr  z required for this testr   r   T)r7   r   )r!   r   r   rz  r   r   r   r  rL   r   rT   r   )r   progr   resr   r   r   test_run_with_pathlike_pathb  s   
"z+RunFuncTestCase.test_run_with_pathlike_pathc                 C   s2   t tj}|ddg}t|}| |jd d S )Nr   s   import sys; sys.exit(57)9   )r   r   rJ   rK   r   r   rL   r   r   r   r0   r  r   r   r   &test_run_with_bytes_path_and_argumentsp  s   

z6RunFuncTestCase.test_run_with_bytes_path_and_argumentsc                 C   s0   t tj}|ddg}t|}| |jd d S )Nr   zimport sys; sys.exit(57)r  )r   rJ   rK   r   r   rL   r   r  r   r   r   )test_run_with_pathlike_path_and_argumentsw  s   


z9RunFuncTestCase.test_run_with_pathlike_path_and_argumentsc                 C   s.   | j ddd}| d|j | d|j d S )Nz>import sys;sys.stdout.write('BDFL'); sys.stderr.write('FLUFL')T)capture_outputra   s   FLUFL)r   rd   r7   r8   r  r   r   r   test_capture_output~  s
   z#RunFuncTestCase.test_capture_outputc                 C   ~   t  }| |j | jtdd}| jdd|d}W d    n1 s$w   Y  | d|jj	d  | d|jj	d  d S )	NzAExpected ValueError when stdout and capture_output args supplied.r  r   T)r  r7   r7   r   r  
rr   rs   rt   r>   rT   r   r   rd   r\   r0   r   r   r   r   #test_stdout_with_capture_output_arg     z3RunFuncTestCase.test_stdout_with_capture_output_argc                 C   r  )	NzAExpected ValueError when stderr and capture_output args supplied.r  r   T)r  r8   r8   r   r  r  r   r   r   r   #test_stderr_with_capture_output_arg  r  z3RunFuncTestCase.test_stderr_with_capture_output_argz)requires posix like 'sleep' shell commandc              
   C   s   	 t  }ztjddddd W n tjy+ } zt  }t }W Y d }~n
d }~ww | d | j|| dd| dd	 d S )
Nzsleep 3TrQ   )r   rS   r  zTimeoutExpired not raised.g      ?z/TimeoutExpired was delayed! Bad traceback:
```
z```r  )	r  	monotonicr   r   rU   	traceback
format_excr   Z
assertLess)r   Zbefore_secsr  Z
after_secsZstacksr   r   r   .test_run_with_shell_timeout_and_capture_output  s"   



z>RunFuncTestCase.test_run_with_shell_timeout_and_capture_outputZ
HAVE_VFORKz!vfork() not enabled by configure.c                 C   s   |  tj tjtdd | j| djddd W d    n1 s%w   Y  G dd d}tjtd| # | j| djdd	d t`| j| djdd
d W d    d S 1 s`w   Y  d S )N
_USE_VFORKFr   r   zFalse _USE_VFORK failedr  c                   @      e Zd Zdd ZdS )z4RunFuncTestCase.test__use_vfork.<locals>.RaisingBoolc                 S   r.   )Nz"force PyObject_IsTrue to return -1)RuntimeErrorr   r   r   r   __bool__  r3   z=RunFuncTestCase.test__use_vfork.<locals>.RaisingBool.__bool__N)r)   r*   r+   r%  r   r   r   r   RaisingBool      r&  z"odd bool()-error _USE_VFORK failedz%lack of a _USE_VFORK attribute failed)	rP  r   r"  r   r  r  rL   r   r   )r   r&  r   r   r   test__use_vfork  s    "zRunFuncTestCase.test__use_vforkN)r)   r*   r+   r   r  r  r  r	  r  r  rx   r{   r   r   r  r  r  r  r  r  r  r%  r  r!   r!  r  r  r(  r   r   r   r   r    s2    

r  c               	   C   s@   dD ]} t rz
t |  W |   S  ty   Y qw qtd)N)ZstaffZnogroupgrpnobodyZ	nfsnobodyz?No identified group name to use for this test on this platform.)r)  getgrnamKeyErrorr%  r&  )
name_groupr   r   r   _get_test_grp_name  s   
r.  zPOSIX specific testsc                       s  e Zd Z fddZdd Zdd Zdd Zd	d
 ZG dd dej	Z
eddd Zeddd Zeejd ddd Zdd Zeeedddd Zeeedddd Zeeedd d!d" Zeeedd#d$d% Zeeed&d'd(d) Zeeed&d*d+d, Zeepeed- d.d/d0 Zd1d2 Z d3d4 Z!d5d6 Z"d7d8 Z#d9d: Z$d;d< Z%G d=d> d>ej	Z&eejd? d@dAdB Z'dCdD Z(ee)j*dEkdFdGdH Z+dIdJ Z,dKdL Z-dMdN Z.dOdP Z/dQdR Z0dSdT Z1dUdV Z2ee)j*3dWdXdYdZ Z4d[d\ Z5d]d^ Z6d_d` Z7dadb Z8dcdd Z9dedf Z:dgdh Z;didj Z<dkdl Z=dmdn Z>dodp Z?dqdr Z@dsdt ZAdudv ZBdwdx ZCdydz ZDd{d| ZEd}d~ ZFdd ZGdd ZHdd ZIdd ZJdd ZKdd ZLdd ZMdd ZNdd ZOdd ZPee)j*3doeQdjReQdjRkddd ZSeTUdddd ZVdd ZWdd ZXdd ZYdd ZZdd Z[dd Z\dd Z]dd Z^dd Z_dd Z`eTjadd ZbeTjadd Zcdd Zddd Zedd Zfdd Zgeehduoeehdddd ZiddÄ Zjddń ZkddǄ Zl  ZmS )POSIXProcessTestCasec                    s   t    d| _d S )Nz/_this/pa.th/does/not/exist)superr    _nonexistent_dirr   r  r   r   r      s   

zPOSIXProcessTestCase.setUpc              
   C   sP   zt | j W n ty } z	|}W Y d }~|S d }~ww | d| j  |S )Nz,chdir to nonexistent directory %s succeeded.)r   chdirr1  rx  r   )r   r  desired_exceptionr   r   r   _get_chdir_exception  s   z)POSIXProcessTestCase._get_chdir_exceptionc              
   C      	 |   }ztjtjddg| jd}W n+ ty> } z| |j|j | |j	|j	 | |j
|j
 W Y d }~d S d }~ww | d|  d S )Nr   r
   r   Expected OSError: %sr5  r   r9   rJ   rK   r1  rx  rL   ry  strerrorr  r   r   r4  r@   r  r   r   r   test_exception_cwd     
z'POSIXProcessTestCase.test_exception_cwdc              
   C   r6  )Nr   r
   r   r7  r8  r:  r   r   r   test_exception_bad_executable  r<  z2POSIXProcessTestCase.test_exception_bad_executablec              
   C   s   	 |   }zt| jddg}W n+ ty; } z| |j|j | |j|j | |j|j W Y d }~d S d }~ww | 	d|  d S )Nr   r
   r7  )
r5  r   r9   r1  rx  rL   ry  r9  r  r   r:  r   r   r   test_exception_bad_args_0  s   z.POSIXProcessTestCase.test_exception_bad_args_0c                   @   r#  )z&POSIXProcessTestCase.PopenNoDestructorc                 C   r  r   r   r   r   r   r   __del__  r  z.POSIXProcessTestCase.PopenNoDestructor.__del__N)r)   r*   r+   r?  r   r   r   r   PopenNoDestructor  r'  r@  z%subprocess._posixsubprocess.fork_execc              	   C   s   	 dd }||_ tjdtd, | t | dg W d    n1 s&w   Y  W d    d S W d    d S 1 s>w   Y  d S )Nc                  W   s0   | d }d tj }t|d| d  dS )N   z{:x}s   OSError:   :r   )rm  ry  ZEISDIRrJ  r   ru   )r0   errpipe_writeZerr_coder   r   r   proper_error#  s   zHPOSIXProcessTestCase.test_exception_errpipe_normal.<locals>.proper_errorsubprocess.os.waitpidside_effectnon_existent_command)rG  r   r  ChildProcessErrorrT   IsADirectoryErrorr@  )r   	fork_execrD  r   r   r   test_exception_errpipe_normal   s   "z2POSIXProcessTestCase.test_exception_errpipe_normalc              	      s   	 d  fdd}||_ tjdtd$ | tj}| dg W d    n1 s+w   Y  W d    n1 s:w   Y  | t	 t
|j d S )Ns    ޭc                     s   | d }t |  dS )NrA  r   )r   ru   )r0   rC  Z
error_datar   r   	bad_error6  s   zGPOSIXProcessTestCase.test_exception_errpipe_bad_data.<locals>.bad_errorrE  rF  rH  )rG  r   r  rI  rT   r   SubprocessErrorr@  rd   r  r  r\   )r   rK  rN  r  r   rM  r   test_exception_errpipe_bad_data1  s   z4POSIXProcessTestCase.test_exception_errpipe_bad_data/proc/self/statuszneed /proc/self/statusc                 C   s   t jddgdd}| D ]}|dr|} nq| d t jddgdd}| D ]}|dr6|} nq+| j||dd	 d S )
NcatrQ  F)restore_signalss   SigIgnz&SigIgn not found in /proc/self/status.Tz=restore_signals=True should've unblocked SIGPIPE and friends.r  )r   rc   
splitlinesr3  rz  assertNotEqual)r   Zdefault_proc_statusr  Zdefault_sig_ign_maskZrestored_proc_statusZrestored_sig_ign_maskr   r   r   test_restore_signalsG  s,   



z)POSIXProcessTestCase.test_restore_signalsc              
   C   sr   zt jtjddgdd}W n ty' } z|jtjkr W Y d }~d S d }~ww td}t	|}| 
|| d S )Nr   zimport os; print(os.getsid(0))T)start_new_sessionr   )r   rc   rJ   rK   rx  ry  EPERMr   getsidintrU  )r   rf   r  Z
parent_sidZ	child_sidr   r   r   test_start_new_session_  s   


z+POSIXProcessTestCase.test_start_new_sessionsetreuidzno setreuid on platformc           
      C   s  t  }|dkr
dnd|g}tjdkrdnd}td ur3zt| || W n ty2   d }Y nw |D ]i}dD ]d}| j||dS zt	j
tjdd	g||d}W n$ tyZ   Y n4 tyu } z|jtjtjfvrk W Y d }~nd }~ww t|trt|j}n|}t|}	| |	| W d    n1 sw   Y  q9q5| t t	jtd
d W d    n1 sw   Y  | t t	jtt jt jdd W d    n1 sw   Y  td u r|d ur| t t	jt|d W d    d S 1 sw   Y  d S d S d S )N    darwinr*  unknownrO  )user	close_fdsr   zimport os; print(os.getuid())r*  ra              )r   r   ra  )r   geteuidrJ   r  pwdgetpwnamrt  r,  subTestr   rc   rK   PermissionErrorrx  ry  ZEACCESrX  
isinstancer  pw_uidrZ  rL   rT   r   rX   r   OverflowErrorr   r   )
r   uidZ
test_usersZname_uidra  rb  rf   r  Zuser_uidZ
child_userr   r   r   	test_usero  sf   



"zPOSIXProcessTestCase.test_userz setreuid() available on platformc                 C   >   |  t tjtdd W d    d S 1 sw   Y  d S )N  rc  rT   r   r   rX   r   r   r   r   r   test_user_error     "z$POSIXProcessTestCase.test_user_errorsetregidzno setregid() on platformc           	      C   s  t  }|dkr
dndg}t }td ur|| ||g D ]N}dD ]I}| j||d8 ztjtj	ddg||d}W n	 t
yC   Y nw t|trPt|j}n|}t|}| || W d    n1 sfw   Y  q"q| t tjtdd W d    n1 sw   Y  | t tjtt jt jd	d
 W d    n1 sw   Y  td u r| t tjt|d W d    d S 1 sw   Y  d S d S )Nr]  r^  rO  )grouprb  r   zimport os; print(os.getgid())r*  ru  rd  )r   r   ru  )r   getegidr.  r)  rt  rh  r   rc   rJ   rK   ri  rj  r  r+  gr_gidrZ  rL   rT   r   rX   r   rl  r   r   )	r   gid
group_listr-  ru  rb  rf   Z	group_gidZchild_groupr   r   r   
test_group  sR   



"zPOSIXProcessTestCase.test_groupz setregid() available on platformc                 C   ro  )Nrp  rv  rq  r   r   r   r   test_group_error  rs  z%POSIXProcessTestCase.test_group_error	setgroupszno setgroups() on platformc           
   
   C   s  t  }|dkr
dndg}t }d}td ur|| ztjtjddg|d}W n t	yC } z|j
t
jkr7 d}W Y d }~n3d }~ww t  }t|}td urYdd	 |D }	n|}	|rh| t|t| n
| t|	t| | t tjtd
gd W d    n1 sw   Y  | t tjtt jt jdgd W d    n1 sw   Y  td u r| t tjt|gd W d    d S 1 sw   Y  d S d S )Nr]  r^  Fr   z;import os, sys, json; json.dump(os.getgroups(), sys.stdout)extra_groupsTc                 S   s&   g | ]}t |trt|jn|qS r   )rj  r  r)  r+  rx  )r6  gr   r   r   r9    s    z:POSIXProcessTestCase.test_extra_groups.<locals>.<listcomp>r*  rd  )r   r   r  )r   rw  r.  r)  rt  r   rc   rJ   rK   rx  ry  rX  	getgroupsjsonloadsrL   setrT   r   rX   r   r   r   )
r   ry  rz  r-  Z
perm_errorrf   exZparent_groupsZchild_groupsZdesired_gidsr   r   r   test_extra_groups  sZ   


"z&POSIXProcessTestCase.test_extra_groupsz!setgroups() available on platformc                 C   s>   |  t tjtg d W d    d S 1 sw   Y  d S )Nr~  rq  r   r   r   r   test_extra_groups_error  rs  z,POSIXProcessTestCase.test_extra_groups_errorumaskzPOSIX umask() is not available.c              	   C   s   d }zCt  }tj|d}tjtjdd|dgdd t	|j
d@ }d}| j||t| d	t| d
 W |d urDt| d S d S |d urPt| w w )NZbeansr   zopen(z, 'w').close()+   )r  i  i  z != r  )rr   rr  r   r   r   r   rX   rJ   rK   statst_moderL   octr   r|  )r   r~  namer  Zexpected_moder   r   r   
test_umask  s$   zPOSIXProcessTestCase.test_umaskc                 C   sX   t   ttjddg}|  W d    n1 sw   Y  | |j t	j
 d S )Nr   zimport os; os.abort())r   r  r   r9   rJ   rK   r#   rL   r   r  SIGABRTr?   r   r   r   test_run_abort#  s   


z#POSIXProcessTestCase.test_run_abortc                 C   sN   t ttj d}t|}| d|  | d| | ttj| d S )Nfake cmdr  ZSIG)r   r[   rZ  r  r  r  rd   lowerr   r   Zerror_stringr   r   r   "test_CalledProcessError_str_signal+  s
   z7POSIXProcessTestCase.test_CalledProcessError_str_signalc                 C   $   t dd}t|}| d| d S )NiKir  zunknown signal 9876543.r   r[   r  rd   r  r   r   r   *test_CalledProcessError_str_unknown_signal6     z?POSIXProcessTestCase.test_CalledProcessError_str_unknown_signalc                 C   r  )Nr  r  znon-zero exit status 2.r  r  r   r   r   $test_CalledProcessError_str_non_zero;  r  z9POSIXProcessTestCase.test_CalledProcessError_str_non_zeroc                 C   sZ   t jtjddgt jdd d}| | |j d W d    d S 1 s&w   Y  d S )Nr   r-  c                   S   s   t ddS )Nr   apple)r   putenvr   r   r   r   <lambda>G      z3POSIXProcessTestCase.test_preexec.<locals>.<lambda>)r7   
preexec_fn   appler   r?   r   r   r   test_preexec@  s   
"z!POSIXProcessTestCase.test_preexecc              
   C   s   dd }zt jtjddg|d}W n6 t jy, } z| t jd W Y d }~d S d }~w tyG } z| d|j	d  W Y d }~d S d }~ww | 
d	 d S )
Nc                   S   r.   )Nz'What if two swallows carried a coconut?r   r   r   r   r   raise_itL  r3   z=POSIXProcessTestCase.test_preexec_exception.<locals>.raise_itr   r
   r  z)Expected a ValueError from the preexec_fnZcoconutr   zEException raised by preexec_fn did not make it to the parent process.)r   r9   rJ   rK   rO  rP  _posixsubprocessr   rd   r0   r   )r   r  r@   r  r   r   r   test_preexec_exceptionK  s    
 z+POSIXProcessTestCase.test_preexec_exceptionc                   @   s   e Zd Z	 dd Zdd ZdS )z+POSIXProcessTestCase._TestExecuteChildPopenc                 O   s$   || _ tjj| g|R i | d S r   )	_testcaser   r9   r   )r   Ztestcaser0   r1   r   r   r   r   ]  s   z4POSIXProcessTestCase._TestExecuteChildPopen.__init__c                 O   s  zJt jj| g|R i | W dd tdD }z'|D ]}| jj|| j | j | j	 fdd qW |D ]}t
| q6d S |D ]}t
| qBw dd tdD }z&|D ]}| jj|| j | j | j	 fdd qWW |D ]}t
| qrw |D ]}t
| q}w )Nc                 S   s   g | ]	}t d t jqS )	/dev/zero)r   ru  O_RDONLYr6  rM  r   r   r   r9  h  s    zNPOSIXProcessTestCase._TestExecuteChildPopen._execute_child.<locals>.<listcomp>   z!At least one fd was closed early.r  )r   r9   r2   rs  r  r~   r6   r   r7   r8   r   r>   )r   r0   r1   Zdevzero_fdsr  r   r   r   r2   a  sH   
z:POSIXProcessTestCase._TestExecuteChildPopen._execute_childN)r)   r*   r+   r   r2   r   r   r   r   _TestExecuteChildPopen[  s    r  r  z/dev/zero required.c              	   C   sX   	 dd }|  tj | j| ttjtjtj|d W d    d S 1 s%w   Y  d S )Nc                   S   s
   t d)Nz-force the _execute_child() errpipe_data path.)r   rO  r   r   r   r   r  x  s   zWPOSIXProcessTestCase.test_preexec_errpipe_does_not_double_close_pipes.<locals>.raise_it)r6   r7   r8   r  )rT   r   rO  r  r   r:   )r   r  r   r   r   0test_preexec_errpipe_does_not_double_close_pipest  s   "zEPOSIXProcessTestCase.test_preexec_errpipe_does_not_double_close_pipesc                 C   s   t  }zKt   | t   tjtjddgdd d | t  d t   | 	t   tjtjddgdd d | 	t  d W |sNt   d S d S |sWt   w w )	Nr   r
   c                   S   r  r   r   r   r   r   r   r        zEPOSIXProcessTestCase.test_preexec_gc_module_failure.<locals>.<lambda>r  z#Popen enabled gc when it shouldn't.c                   S   r  r   r   r   r   r   r   r    r  zPopen left gc disabled.)
gc	isenableddisabler%   r   rI   rJ   rK   enablerP  )r   Zenabledr   r   r   test_preexec_gc_module_failure  s*   

z3POSIXProcessTestCase.test_preexec_gc_module_failurer_  z!setrlimit() seems to fail on OS Xc              
   C   s   zddl m}m}m} W n ty# } z| | W Y d }~nd }~ww ||}|\}}||d|f | ||| ztjt	j
ddgdd d W n
 tyS   Y d S w | d d S )	Nr   )	getrlimit	setrlimitRLIMIT_NPROCr   r
   c                   S   r  r   r   r   r   r   r   r    r  z@POSIXProcessTestCase.test_preexec_fork_failure.<locals>.<lambda>r  z.RLIMIT_NPROC had no effect; probably superuser)Zresourcer  r  r  r  rz  rt   r   rI   rJ   rK   BlockingIOError)r   r  r  r  r   ZlimitsrM  Zhardr   r   r   test_preexec_fork_failure  s$   
z.POSIXProcessTestCase.test_preexec_fork_failurec                 C   s   t  \}}t|ddd}|dtj  |dtj  W d    n1 s(w   Y  t	|d t
|}|  t| | |jd d S Nwrk  )r   z#!%s
z(exec '%s' -c 'import sys; sys.exit(47)'
i  rG   )rr   r  ru  ru   r   
unix_shellrJ   rK   r   chmodr   r9   r#   r  rL   r   )r   r  fnamefobjr@   r   r   r   test_args_string  s   

z%POSIXProcessTestCase.test_args_stringc                 C   s<   | j ttjtjddgdd | j ttjtjddgdd d S )Nr   rF   rG   startupinfocreationflagsrT   r   r   rI   rJ   rK   r   r   r   r   r     s   


z&POSIXProcessTestCase.test_invalid_argsc                 C   sj   t j }d|d< tjdgdtj|d}| | |j 	dd W d    d S 1 s.w   Y  d S Nr  r   zecho $FRUITr   r   r7   r   s    	
r  
r   r   r   r   r9   r:   rL   r7   r   r;  r   r   r@   r   r   r   test_shell_sequence  s   

"z(POSIXProcessTestCase.test_shell_sequencec                 C   sh   t j }d|d< tjddtj|d}| | |j 	dd W d    d S 1 s-w   Y  d S r  r  r  r   r   r   test_shell_string  s   
"z&POSIXProcessTestCase.test_shell_stringc                 C   s   t  \}}t|ddd}|dtj  |dtj  W d    n1 s(w   Y  t	|d t
|}t| | |d d S r  )rr   r  ru  ru   r   r  rJ   rK   r   r  r   rI   r  rL   )r   r  r  r  rN   r   r   r   test_call_string  s   

z%POSIXProcessTestCase.test_call_stringc              	   C   s   g }dD ]}dD ]}t j||}t j|r|| qq|s%| d d}t j|r8t j|s8|| |D ],}tjd|dtj	d}| | 
|j  t|d W d    n1 saw   Y  q:d S )	N)z/binz	/usr/bin/z/usr/local/bin)ZbashZkshz"bash or ksh required for this testz/bin/shzecho $0T)rK   r   r7   r  )r   r   r   isfilert  rz  islinkr   r9   r:   rL   r7   r   r;  r  )r   Zshellsr  r  shr@   r   r   r   test_specific_shell  s,   



z(POSIXProcessTestCase.test_specific_shellc              
   G   st   t  t jt j}ztjtjddgdtjtjtjd}W t  t j| nt  t j| w |j	d t
|||  |S )Nr   zif 1:
                                 import sys, time
                                 sys.stdout.write('x\n')
                                 sys.stdout.flush()
                                 time.sleep(30)
                                 Trb  r6   r7   r8   r   )r  SIGINTdefault_int_handlerr   r9   rJ   rK   r:   r7   r   getattr)r   methodr0   r  r@   r   r   r   _kill_process  s    z"POSIXProcessTestCase._kill_process)ZnetbsdZopenbsdz"Due to known OS bug (issue #16762)c                 G   sR   t jtjddgdt jt jt jd}|jd td t	|||  |
  d S )Nr   zif 1:
                             import sys, time
                             sys.stdout.write('x\n')
                             sys.stdout.flush()
                             Tr  r   )r   r9   rJ   rK   r:   r7   r   r  r  r  r   )r   r  r0   r@   r   r   r   _kill_dead_process	  s   
z'POSIXProcessTestCase._kill_dead_processc                 C   s:   |  dtj}| \}}| d| | | d d S )Nsend_signals   KeyboardInterruptr   )r  r  r  r   rd   rU  r#   r   r@   rM  r8   r   r   r   test_send_signal+	  s   z%POSIXProcessTestCase.test_send_signalc                 C   :   |  d}| \}}| |d | | tj  d S )Nr'  r  )r  r   rL   r#   r  SIGKILLr  r   r   r   	test_kill1	     
zPOSIXProcessTestCase.test_killc                 C   r  )N	terminater  )r  r   rL   r#   r  SIGTERMr  r   r   r   test_terminate7	  r  z#POSIXProcessTestCase.test_terminatec                 C      |  dtj d S Nr  )r  r  r  r   r   r   r   test_send_signal_dead=	  s   z*POSIXProcessTestCase.test_send_signal_deadc                 C      |  d d S Nr'  r  r   r   r   r   test_kill_deadA	     z#POSIXProcessTestCase.test_kill_deadc                 C   r  Nr  r  r   r   r   r   test_terminate_deadE	  r  z(POSIXProcessTestCase.test_terminate_deadc                 C   s6   g }|D ]}t |}t |}||||f q|S r   )r   get_inheritableduprt  )r   Zsave_fdsr  r  inheritablesavedr   r   r   	_save_fdsI	  s   

zPOSIXProcessTestCase._save_fdsc                 C   s.   |D ]\}}}t j|||d t | qd S )N)r  )r   dup2r>   )r   r  r  r  r  r   r   r   _restore_fdsQ	  s   z!POSIXProcessTestCase._restore_fdsc           	   	   C   s   d}|  |}|D ]\}}}|dkr|} nq	z1|D ]}t| qtjtjddg|tjtjd \}}| 	|d | 	|d W | 
| d S | 
| w )Nr   r   r  r5   r  r   )r  r   r>   r   r9   rJ   rK   r:   r   rL   r  )	r   r  r6   	saved_fdsr  r  r  r   r   r   r   r   check_close_std_fdsV	  s,   

z(POSIXProcessTestCase.check_close_std_fdsc                 C      |  dg d S rW   r  r   r   r   r   test_close_fd_0o	     z$POSIXProcessTestCase.test_close_fd_0c                 C   r  Nr   r  r   r   r   r   test_close_fd_1r	  r  z$POSIXProcessTestCase.test_close_fd_1c                 C   r  )Nr  r  r   r   r   r   test_close_fd_2u	  r  z$POSIXProcessTestCase.test_close_fd_2c                 C      |  ddg d S )Nr   r   r  r   r   r   r   test_close_fds_0_1x	     z'POSIXProcessTestCase.test_close_fds_0_1c                 C   r  )Nr   r  r  r   r   r   r   test_close_fds_0_2{	  r  z'POSIXProcessTestCase.test_close_fds_0_2c                 C   r  )Nr   r  r  r   r   r   r   test_close_fds_1_2~	  r  z'POSIXProcessTestCase.test_close_fds_1_2c                 C   s   |  g d d S )N)r   r   r  r  r   r   r   r   test_close_fds_0_1_2	  s   z)POSIXProcessTestCase.test_close_fds_0_1_2c              
   C   s   	 t d}t d}z.t d t d ttjddg  W t |d t |d t | t | d S t |d t |d t | t | w )Nr   r   r   z*print('AssertionError:0:CLOEXEC failure.'))	r   r  r>   r   r9   rJ   rK   r#   r  )r   Z	new_stdinZ
new_stdoutr   r   r   test_small_errpipe_write_fd	  s&   





z0POSIXProcessTestCase.test_small_errpipe_write_fdc           
   
   C   sV  dd t dD }zdd |D }|D ]	\}}t| qt|d d t|d dd | t d}z-t|D ]
\}}t|| q:tj	t
jdd	g|d |d
 |d d}|  W | | n| | w |D ]	}t|dd qkt|d
 d}t|d d }	| |d | |	d W |D ]}t| qd S |D ]}t| qw )Nc                 S      g | ]}t  qS r   rr   r  r6  r  r   r   r   r9  	      z?POSIXProcessTestCase.test_remapping_std_fds.<locals>.<listcomp>r   c                 S      g | ]\}}|qS r   r   r6  r  r  r   r   r   r9  	  r  r      STDINr   r   Zimport sys; got = sys.stdin.read();sys.stdout.write("got %s"%got); sys.stderr.write("err")r  r5   r  	   got STDIN   err)rs  r   unlinkru   r   r  	enumerater  r   r9   rJ   rK   r#   r  r   r;  rL   r>   )
r   tempstemp_fdsr  r  r  temp_fdr@   r   r   r   r   r   test_remapping_std_fds	  s>   

z+POSIXProcessTestCase.test_remapping_std_fdsc              
   C   s:  dd t dD }dd |D }z|D ]	\}}t| q| t d}zNt|D ]
\}}	t|	| q)t|d t|dd tj	t
jddg|||d	}
|
  |D ]	}t|dd qTt|d
}t|d
 }W | | n| | w | |d | |d W |D ]}t| qd S |D ]}t| qw )Nc                 S   r  r   r  r  r   r   r   r9  	  r  z7POSIXProcessTestCase.check_swap_fds.<locals>.<listcomp>r   c                 S   r  r   r   r  r   r   r   r9  	  r  r  r   r   r  r5   r  r	  r
  )rs  r   r  r  r  r  ru   r   r   r9   rJ   rK   r#   r   r;  r  rL   r>   )r   Zstdin_noZ	stdout_noZ	stderr_nor  r  r  r  r  r  r@   r   r   r   r   r   check_swap_fds	  s>   
z#POSIXProcessTestCase.check_swap_fdsc                 C   sX   |  ddd |  ddd |  ddd |  ddd |  ddd |  ddd d S )Nr   r   r  )r  r   r   r   r   test_swap_fds	  s   z"POSIXProcessTestCase.test_swap_fdsc                 C   s  |  td}z|D ]}t }t| | W d    n1 s#w   Y  q
ttdt|  }t	| g d}i }t
||D ]
\}}	||||	 < qEtd}
ttdt|  }tjtjd|
t|gfi |}| |d t
||D ]9\}}	t|dtj t|d}ttt|d}td| d	| d
| d| d|	 d}| |	g|| q|W | | d S | | w )Nr   r5   z
                import os, sys
                skipped_fd = int(sys.argv[1])
                for fd in range(3):
                    if fd != skipped_fd:
                        os.write(fd, str(fd).encode('ascii'))
            r   r   r  r  z"
                    When testing z to z4 redirection,
                    parent descriptor z5 got redirected
                    to descriptor(s) z instead of descriptor z.
                )r  rs  rr   rs   r   r  r   r  r{  r>   ziprc  rd  r   rI   rJ   rK   r  rL   r   SEEK_SETr   r<  maprZ  r   r  )r   from_fdsto_fdsr  Zfrom_fdfZfd_to_closeZ	arg_namesr1   Zto_fdr   Z
skipped_fdrN   
read_bytesZread_fdsr  r   r   r   #_check_swap_std_fds_with_one_closed 
  sJ   



z8POSIXProcessTestCase._check_swap_std_fds_with_one_closedc                 C   s<   t tddD ]}t tddD ]}| || qqd S )Nr   r  )	itertoolscombinationsrs  permutationsr  )r   r  r  r   r   r   !test_swap_std_fds_with_one_closed,
  s
   z6POSIXProcessTestCase.test_swap_std_fds_with_one_closedc              
   C   s   dd }z	t jt|d W nB ty. } z| t j | t|d W Y d }~d S d }~w t jyO } z| 	t j | t|d W Y d }~d S d }~ww | 
d d S )Nc                   S   r.   )N   surrogate:r  r   r   r   r   prepare2
  r3   zCPOSIXProcessTestCase.test_surrogates_error_message.<locals>.preparer  r  z!Exception occurred in preexec_fn.z1Expected ValueError or subprocess.SubprocessError)r   rI   r   r   r  r  rL   r  rO  assertIsNotNoner   )r   r   r   r   r   r   test_surrogates_error_message1
  s    
z2POSIXProcessTestCase.test_surrogates_error_messagec                 C   s   dD ]j\}}| dd}dt| }tj }|||< d|d< |}tjtjd|g|d}|	d	}| 
|dt| | dd}d
t| }tj }|||< tjtjd|g|d}|	d	}| 
|dt| qd S )N))testu   abc)u   testZ42r  rk  z&import os; print(ascii(os.getenv(%s)))CLC_ALLr   r   s   
z'import os; print(ascii(os.getenvb(%s))))rJ  r  r   r   r   r   rc   rJ   rK   r   rL   r   r  )r   keyvalueZencoded_valuescriptr   Zdecoded_valuer7   r   r   r   test_undecodable_envD
  s0   





z)POSIXProcessTestCase.test_undecodable_envc           	      C   s   t td }ttdd  }t jtd \}}t |}t|g| }| |d d|d	|
df }tj|dd}| |d t j }||d< tj|g| |d	}| |d t j }t ||d
< tj|g| |d	}| |d d S )Nr   r   s   '%s' %s r   Tr  PATHr   s   PATH)r   r   r   r<  r   r   r   rI   rL   r   rJ  r   r   environb)	r   Zabs_programr0   r   Zprogramexitcoder?  r   Zenvbr   r   r   test_bytes_programa
  s"   


z'POSIXProcessTestCase.test_bytes_programc           	      C   s   t jddd}t jddd}tjtj|gtjtjtjdd}| |jd tjtj|gtjdd}| \}}t	t
t|d	}t	|j |j |j g}| ||@ d
|||@ f  d S )Nzinput_reader.pysubprocessdataZsubdirfd_status.pyF)r6   r7   r8   rb  r  r7   rb     ,z5Expected no fds from %r to be open in child, found %r)r   findfiler   r9   rJ   rK   r:   rt   r   r  r  rZ  r   r6   r   r7   r8   r%   )	r   Zsleeper	fd_statusp1p2rf   errorZ
result_fdsZunwanted_fdsr   r   r   test_pipe_cloexec|
  s(   

z&POSIXProcessTestCase.test_pipe_cloexecc           
         s  t jddd}t jddd}d}|d d }tjtj|gtjtjdd	 tjtj||g jtjdd	|  j	 | j	  fd
d}fdd}| | | |  j
|  j
  tjgg g d\}}}	| |d | j |  j  j  d S )Nzqcat.pyr/  r0  zqgrep.pys   zxcvbn      
F)r6   r7   rb  c                      $   z    W d S  ty   Y d S w r   r  ProcessLookupErrorr   )r6  r   r   kill_p1
  
   zBPOSIXProcessTestCase.test_pipe_cloexec_real_tools.<locals>.kill_p1c                      r<  r   r=  r   )r7  r   r   kill_p2
  r@  zBPOSIXProcessTestCase.test_pipe_cloexec_real_tools.<locals>.kill_p2rp  zThe child hung)r   r4  r   r9   rJ   rK   r:   r7   rt   r#   r6   ru   r>   selectrP  rL   r   )
r   ZqcatZqgrepZsubdatar  r?  rA  Z	readfilesZignored1Zignored2r   )r6  r7  r   test_pipe_cloexec_real_tools
  s2   



z1POSIXProcessTestCase.test_pipe_cloexec_real_toolsc           
         s  t jddd}t }| tj|d  | tj|d  t| tdD ]}ttj	tj
}| tj|  | q% D ]}t|d q>tjtj|gtjdd	}| \}}ttt|d
}| | @  d tjtj|gtjdd	}| \}}ttt|d
}| | @ d | d|d t fddtdD }	tjtj|gtjd|	d}| \}}ttt|d
}| ||	  @ d | d|d d S )Nr1  r/  r0  r   r   	   TFr2  r3  zSome fds were closedzSome fds were left openzSubprocess failedc                 3   s    | ]}   V  qd S r   )r{  r  r  r   r   	<genexpr>
  s    z6POSIXProcessTestCase.test_close_fds.<locals>.<genexpr>r  r7   rb  pass_fdsz'Some fds not in pass_fds were left open)r   r4  r   r#  rt   r>   r  rs  ru  devnullr  addset_inheritabler   r9   rJ   rK   r:   r   r  rZ  r   rL   r%   rd   )
r   r5  r  rM  r  r@   rf   ignoredremaining_fdsfds_to_keepr   rE  r   test_close_fds
  sN   
z#POSIXProcessTestCase.test_close_fdsZfreebsdz/devz/dev/fdz.Requires fdescfs mounted on /dev/fd on FreeBSDc                 C   s   	 t jddd}tjtjdtd| gtjd}|	 \}}|
 }| jt|dd| d	 ttt|d
  d}ttt|d  d}| j||@ dd	 d S )Nr1  r/  r0  r   aK  
        import os, resource, subprocess, sys, textwrap
        open_fds = set()
        # Add a bunch more fds to pass down.
        for _ in range(40):
            fd = os.open(os.devnull, os.O_RDONLY)
            open_fds.add(fd)

        # Leave a two pairs of low ones available for use by the
        # internal child error pipe and the stdout pipe.
        # We also leave 10 more open as some Python buildbots run into
        # "too many open files" errors during the test if we do not.
        for fd in sorted(open_fds)[:14]:
            os.close(fd)
            open_fds.remove(fd)

        for fd in open_fds:
            #self.addCleanup(os.close, fd)
            os.set_inheritable(fd, True)

        max_fd_open = max(open_fds)

        # Communicate the open_fds to the parent unittest.TestCase process.
        print(','.join(map(str, sorted(open_fds))))
        sys.stdout.flush()

        rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
        try:
            # 29 is lower than the highest fds we are leaving open.
            resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
            # Launch a new Python interpreter with our low fd rlim_cur that
            # inherits open fds above that limit.  It then uses subprocess
            # with close_fds=True to get a report of open fds in the child.
            # An explicit list of fds to check is passed to fd_status.py as
            # letting fd_status rely on its default logic would miss the
            # fds above rlim_cur as it normally only checks up to that limit.
            subprocess.Popen(
                [sys.executable, '-c',
                 textwrap.dedent("""
                     import subprocess, sys
                     subprocess.Popen([sys.executable, %r] +
                                      [str(x) for x in range({max_fd})],
                                      close_fds=True).wait()
                     """.format(max_fd=max_fd_open+1))],
                close_fds=False).wait()
        finally:
            resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
        r   r  z(expected exactly two lines of output:
%rr  r   r3  r   zSome fds were left open.)r   r4  r   r9   rJ   rK   rc  rd  r:   r   rT  rL   rL  r  r  rZ  r;  r   r%   )r   r5  r@   rf   Zunused_stderrZoutput_linesZ
opened_fdsrM  r   r   r   %test_close_fds_when_max_fd_is_lowered
  s&   /02

z:POSIXProcessTestCase.test_close_fds_when_max_fd_is_loweredrp  rh   c              	   C   s>  t jddd}t }tdD ]-}t }| tj|d  | tj|d  t|d d t|d d |	| q|D ]^}t
jtj|gt
jd|fd}| \}}ttt|d	}	||h }
| ||	d
 | |	|
@ d | t}| t
jtd|fd W d    n1 sw   Y  | dt|j q>d S )Nr1  r/  r0  rh   r   r   TrG  r3  zfd to be passed not passedzfd to be closed passedF)rb  rH  zoverriding close_fds)r   r4  r  rs  r   r#  rt   r>   rK  updater   r9   rJ   rK   r:   r   r  rZ  r   rd   r%   ZassertWarnsr  rI   r   r  warning)r   r5  r  rW  r  r  r@   rf   rL  rM  Zto_be_closedcontextr   r   r   test_pass_fds?  s:   


z"POSIXProcessTestCase.test_pass_fdsc           
      C   s   t jddd}t \}}| tj| | tj| t|d t|d ||f}tj|g}|t	t
t|7 }tj|tjd|d}| \}}tt
t|d}	| |	t|d|  | t|d | t|d d S )	Nr1  r/  r0  TFrG  r3  z	output=%a)r   r4  r   r#  rt   r>   rK  rJ   rK   r<  r  r  r   r9   r:   r   r  rZ  r   rL   r  )
r   r(  r  Znon_inheritablerH  r0   r@   rf   rL  r  r   r   r   test_pass_fds_inheritablea  s$   
z.POSIXProcessTestCase.test_pass_fds_inheritablec           	      C   s
  	 t jddd}g }tdD ]}ttjtj}| tj| |	| qt
 \}}| tj| | tj| |d| tjtj|g|d |d |d d|d t|d	}W d    n1 sdw   Y  d
d |dD }| |h dt|B d| d S )Nr1  r/  r0  r  r   r   T)r6   r7   r8   rb  rH  r  c                 S   s   h | ]}t |qS r   )rZ  )r6  numr   r   r   	<setcomp>  r  z@POSIXProcessTestCase.test_pass_fds_redirected.<locals>.<setcomp>r3  >   r   r   r  zoutput=)r   r4  rs  r   ru  rI  O_RDWRrt   r>   rt  r#  insertr   r9   rJ   rK   r   r   rL   	frozenset)	r   r5  rH  rM  r  Zstdout_rZstdout_wrf   r  r   r   r   test_pass_fds_redirected  s,   $z-POSIXProcessTestCase.test_pass_fds_redirectedc                 C   L   t tjd}tjt||d}|  W d    d S 1 sw   Y  d S )Nr+)r7   r6   r<   ru  r   rI  r   r9   r   r#   r   Zinoutr@   r   r   r   %test_stdout_stdin_are_single_inout_fd     
"z:POSIXProcessTestCase.test_stdout_stdin_are_single_inout_fdc                 C   r\  )Nr]  r   r^  r_  r   r   r   &test_stdout_stderr_are_single_inout_fd  ra  z;POSIXProcessTestCase.test_stdout_stderr_are_single_inout_fdc                 C   r\  )Nr]  )r8   r6   r^  r_  r   r   r   %test_stderr_stdin_are_single_inout_fd  ra  z:POSIXProcessTestCase.test_stderr_stdin_are_single_inout_fdc                 C   sR   t jddd}tjtj|gtjtjd}| \}}| d|j	d|
d  d S )Nzsigchild_ignore.pyr/  r0  r   r   z6sigchild_ignore.py exited non-zero with this error:
%sr   )r   r4  r   r9   rJ   rK   r:   r   rL   r   r   )r   Zsigchild_ignorer@   r7   r8   r   r   r   test_wait_when_sigchild_ignored  s   
z4POSIXProcessTestCase.test_wait_when_sigchild_ignoredc              	   C   s   t d}tjtjddgtjdd}|j}| |j	 z| 
|dd | |||gg g dd  W |  d S |  w )	NrB  r   z$import sys;sys.stdout.write("apple")r   )r7   rB   r:  s   applg        )r   import_moduler   r9   rJ   rK   r:   r7   rt   r>   rL   r   rd   rB  r#   )r   rB  r@   r  r   r   r   test_select_unbuffered  s   

 z+POSIXProcessTestCase.test_select_unbufferedc                 C   s   t jtjddgt jt jd}| |jj | |jj t	|}|j
}tdtf
 d }W d    n1 s7w   Y  trF| t j d S | |dd t jD  d S )Nr   z import sys, time;time.sleep(0.2)r   r
   c                 S      g | ]}t |qS r   idr6  or   r   r   r9    r  zEPOSIXProcessTestCase.test_zombie_fast_process_del.<locals>.<listcomp>)r   r9   rJ   rK   r:   rt   r7   r>   r8   ri  pidr   check_warningsResourceWarningr!   r  r"   rd   )r   r@   identrl  r   r   r   test_zombie_fast_process_del  s    
z1POSIXProcessTestCase.test_zombie_fast_process_delc              	   C   sb  t jtjddgt jt jd}| |jj | |jj t	|}|j
}tdtf d }t  W d    n1 s;w   Y  t|tj trP| t j n| |dd t jD  td | t" t jtt jt jd}W d    n1 s|w   Y  W d    n1 sw   Y  | ttj|d tr| t j d S | |d	d t jD  d S )
Nr   zimport time;time.sleep(3)r   r
   c                 S   rg  r   rh  rj  r   r   r   r9    r  zJPOSIXProcessTestCase.test_leak_fast_process_del_killed.<locals>.<listcomp>r  r   c                 S   rg  r   rh  rj  r   r   r   r9    r  )r   r9   rJ   rK   r:   rt   r7   r>   r8   ri  rl  r   rm  rn  r   
gc_collectr   r'  r  r  r!   r  r"   rd   r  r  rT   rx  r   waitpidr~   )r   r@   ro  rl  r  r   r   r   !test_leak_fast_process_del_killed  sB   


z6POSIXProcessTestCase.test_leak_fast_process_del_killedc                    sx   t jddd}td | tj  tjtj	|gtj
d fddd}| \}}ttt|d	}|  | d S )
Nr1  r/  r0  r   Tc                      s   t d S r  )r   r  r   r  r   r   r    r  zCPOSIXProcessTestCase.test_close_fds_after_preexec.<locals>.<lambda>)r7   rb  r  r3  )r   r4  r   r  rt   r>   r   r9   rJ   rK   r:   r   r  r  rZ  r   r~   )r   r5  r@   rf   rL  rM  r   rt  r   test_close_fds_after_preexec
  s   

z1POSIXProcessTestCase.test_close_fds_after_preexecc           	      C   s  dd l }t }zpdd }t  ddgd dgfdgdd dgfdgdgddgfdgdgd dffD ]=\}}}}| t!}|||dd	||d
d
d
d
dddddddg dd
| W d    n1 s_w   Y  | dt|j	 q0W |swt
  d S d S |st
  w w )Nr   c                   S   r  r   r   r   r   r   r   r  %  r  z5POSIXProcessTestCase.test_fork_exec.<locals>.<lambda>r  s   exe   envs   argTr   r*  r   r  r   r:  Fztakes exactly)r  r  r  r  rT   r   rK  r~   r  r\   r  )	r   r  
gc_enabledfuncr0   Zexe_listr   env_listr   r   r   r   test_fork_exec  s8   
z#POSIXProcessTestCase.test_fork_execc                 C   s   dd l }G dd d}t }z_t  ddddd|d	|d
ffD ]A}| jtd|d$}|dgdgd|d dgddddd	d
ddddd d d dd  W d    n1 sUw   Y  | dt	|j
 q"W |smt  d S d S |svt  w w )Nr   c                   @   s    e Zd ZdZdd Zdd ZdS )zJPOSIXProcessTestCase.test_fork_exec_sorted_fd_sanity_check.<locals>.BadIntTc                 S   s
   || _ d S r   )r'  )r   r'  r   r   r   r   I  s   
zSPOSIXProcessTestCase.test_fork_exec_sorted_fd_sanity_check.<locals>.BadInt.__init__c                 S   s   | j r	d| _ | jS t)NF)firstr'  r   r   r   r   r   __int__K  s   zRPOSIXProcessTestCase.test_fork_exec_sorted_fd_sanity_check.<locals>.BadInt.__int__N)r)   r*   r+   r{  r   r|  r   r   r   r   BadIntG  s    r}  )r*  r  r   r:  rh   )r  r:  )      *   l            )rh   r:  )r\  r  r  r  r   r  zfds_to_keep={}r  s   falseTrv  r*  r   r:  rN  )r  r  r  r  rT   r   rm  rK  rd   r  r\   r  )r   r  r}  rw  rN  r^   r   r   r   %test_fork_exec_sorted_fd_sanity_checkC  sD   


z:POSIXProcessTestCase.test_fork_exec_sorted_fd_sanity_checkc              	   C   s   t t}|5 tj|d}t|j_|	  |j
  W d    n1 s'w   Y  W d    d S W d    d S 1 s?w   Y  d S )Nr6   )r   r9   r   r   r  r  BrokenPipeErrorr>   rG  r   Zassert_called_withr   r  mock_proc_stdinr   r   r   ,test_communicate_BrokenPipeError_stdin_closem  s   
PzAPOSIXProcessTestCase.test_communicate_BrokenPipeError_stdin_closec              	   C   s   t t}|< tj|d}t|j_|	d |j
d |j
  W d    n1 s.w   Y  W d    d S W d    d S 1 sFw   Y  d S )Nr6      stuff)r   r9   r   r   r  r  r  ru   rG  r   assert_called_once_withr>   r  r   r   r   ,test_communicate_BrokenPipeError_stdin_writev  s   

PzAPOSIXProcessTestCase.test_communicate_BrokenPipeError_stdin_writec              
   C   s   t jtjdgt jt jd}|R tj|d2}tt	j
d}t|j_| |j_|d |j  W d    n1 s=w   Y  W d    n1 sLw   Y  W d    d S W d    d S 1 sdw   Y  d S )N-hr   r6   wbr  )r   r9   rJ   rK   r:   r   r  r  ru  r   rI  r  r^  rG  r   return_valuer   r  )r   r  r  Zdev_nullr   r   r   ,test_communicate_BrokenPipeError_stdin_flush  s   

P zAPOSIXProcessTestCase.test_communicate_BrokenPipeError_stdin_flushc              	   C   s   t jtjdgt jt jd}|7 tj|d}t|j	_
|jdd |j	  W d    n1 s1w   Y  W d    d S W d    d S 1 sIw   Y  d S )Nr  r   r6   i  rR   )r   r9   rJ   rK   r:   r   r  r  r  r>   rG  r   r  r  r   r   r   9test_communicate_BrokenPipeError_stdin_close_with_timeout  s   PzNPOSIXProcessTestCase.test_communicate_BrokenPipeError_stdin_close_with_timeoutN
W_STOPCODEzneed _testcapi.W_STOPCODEc                 C   sv   	 t }t|}tj|jdd td}tj	d|j|fd |
 }W d    n1 s.w   Y  | |d d S )Nr   r-  r   rE  )r  )r   r   r9   r   wait_processrl  	_testcapir  r   r  r#   rL   )r   r0   r  statusr   r   r   r   test_stopped  s   


z!POSIXProcessTestCase.test_stoppedc                 C   st   t t}tj|jdd | |j t	d}|
tj W d    n1 s)w   Y  |  | |j d S )Nr   r  zos.kill)r   r9   r   r   r  rl  r  r   r   r  r  r  r  Zassert_not_calledr!  )r   r  Z	mock_killr   r   r   test_send_signal_race  s   
z*POSIXProcessTestCase.test_send_signal_racec                 C   st   t tjddg}|js|  |jrtjj|ddd d d |_|	t
j W d    d S 1 s3w   Y  d S )Nr   zexit(1)r  c                   S   r  r   r   r   r   r   r   r    r  z=POSIXProcessTestCase.test_send_signal_race2.<locals>.<lambda>)new)r   r9   rJ   rK   r   r  r   r  r  r  r  r  r?   r   r   r   test_send_signal_race2  s   "z+POSIXProcessTestCase.test_send_signal_race2c                 C   sD   t jtjddgt jd}	 z	|jdd W d S  t jy    Y nw q)Nr   z+import os, time; os.close(1), time.sleep(2)r   TrQ   rR   )r   r9   rJ   rK   r:   r   rU   r   r  r   r   r   1test_communicate_repeated_call_after_stdout_close  s   
zFPOSIXProcessTestCase.test_communicate_repeated_call_after_stdout_close)nr)   r*   r+   r    r5  r;  r=  r>  r   r9   r@  r   r  rL  rP  r%  r  r   r   r  rV  r[  r  r  rn  rr  r{  r|  r  r  r!   r  r  r  r  r  r  r  r  r  r  rJ   r  r  r  r   r  r  r  r  r  r3  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.  r9  rC  rO  r  st_devrP  r   Zrequires_mac_verrT  rU  r[  r`  rb  rc  rd  rf  rp  rs  ru  cpython_onlyrz  r  r  r  r  r  r  r  r  r  r  __classcell__r   r   r2  r   r/    s    



3

)

0







-0,)0

P
!+
'
)	

r/  zWindows specific testsc                   @   s   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zej	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-S ).Win32ProcessTestCasec                 C   s.   d}d}t  }||_||_t jt|d d S )Nr   r   r  )r   STARTUPINFOdwFlagswShowWindowrI   r   )r   STARTF_USESHOWWINDOWSW_MAXIMIZEr  r   r   r   test_startupinfo  s   
z%Win32ProcessTestCase.test_startupinfoc                 C   s(   d}d}t j||d}t jt|d d S )Nr   r   )r  r  r  )r   r  rI   r   )r   ZSTARTF_USERSHOWWINDOWr  r  r   r   r   test_startupinfo_keywords  s   
z.Win32ProcessTestCase.test_startupinfo_keywordsc              
   C   s   t  }t j|_t j|_tdD ]l}t}tt	j
d/}t j||t j|d}| |  W d    n1 s6w   Y  | |jd W d    n1 sLw   Y  | |jt j | |j | |j | |j | |jt j | |jdg i qd S )Nr  r  )r7   r8   r  r   handle_list)r   r  r  r  ZSW_HIDEr  rs  r   ru  r   rI  r9   rl   r   rL   r   r  Z	hStdInputZ
hStdOutputZ	hStdErrorlpAttributeList)r   r  rM  r?  Znullr  r   r   r   test_startupinfo_copy  s2   
	z*Win32ProcessTestCase.test_startupinfo_copyc                 C   s(   d}t jd tjt jd |d d S )N   z'    a DOS box should flash briefly ...
z# -c "import time; time.sleep(0.25)"r  )rJ   r8   ru   r   rI   rK   )r   ZCREATE_NEW_CONSOLEr   r   r   test_creationflags  s   
z'Win32ProcessTestCase.test_creationflagsc                 C   s$   | j ttjtjddgdd d d S )Nr   rF   c                   S   s   dS r  r   r   r   r   r   r  %  r  z8Win32ProcessTestCase.test_invalid_args.<locals>.<lambda>r  r  r   r   r   r   r      s   

z&Win32ProcessTestCase.test_invalid_argsc                 C   sP   G dd dt }| t tjt| d W d    d S 1 s!w   Y  d S )Nc                   @   s   e Zd ZdZdS )z4Win32ProcessTestCase.test_issue31471.<locals>.BadEnvN)r)   r*   r+   keysr   r   r   r   BadEnv+  s    r  r   )dictrT   r   r   r9   r   )r   r  r   r   r   test_issue31471'  s   "z$Win32ProcessTestCase.test_issue31471c                 C   s&   t jtjddgdd}| |d d S )Nr   rF   T)rb  rG   rH   rM   r   r   r   rO  0  s   
z#Win32ProcessTestCase.test_close_fdsc           
      C   s  dd l }t }| tj|d  | tj|d  g }|D ]}t|d ||| qtj	t
jdd|d gtjdd}| \}}| |jd t|  tj	t
jdd|d gtjtjdd}| \}}| |jd | d	| g }t }	d
|i|	_tj	t
jdd|d gtjtj|	dd}| \}}| |jd | d	| tdtf8 t }	d
|d d  i|	_tj	t
jdd|d gtjtj|	dd}| \}}| |jd W d    d S 1 sw   Y  d S )Nr   r   Tr   z2import msvcrt; print(msvcrt.open_osfhandle({}, 0))Fr2  )r7   r8   rb  s   OSErrorr  )r7   r8   r  rb  z.*overriding close_fds)r  r   r#  rt   r>   rK  rt  Zget_osfhandler   r9   rJ   rK   rm  r:   r   rL   r   rZ  r;  rd   r  r  r   rm  r  )
r   r  r  r}  r  r@   r7   r8   r  r  r   r   r   test_close_fds_with_stdio7  sd   





"z.Win32ProcessTestCase.test_close_fds_with_stdioc                 C   s    t  }i |_t jt|d d S )Nr  r   r  r  rI   r   r   r  r   r   r   test_empty_attribute_listi  s
   
z.Win32ProcessTestCase.test_empty_attribute_listc                 C   s$   t  }dg i|_t jt|d d S )Nr  r  r  r  r   r   r   test_empty_handle_listo  s
   

z+Win32ProcessTestCase.test_empty_handle_listc                 C   sd   t j }d|d< tjdgdtj|d}| | d|j  W d    d S 1 s+w   Y  d S Nphysalisr   r  r   r  s   physalis	r   r   r   r   r9   r:   rd   r7   r   r  r   r   r   r  u  s   

"z(Win32ProcessTestCase.test_shell_sequencec                 C   sb   t j }d|d< tjddtj|d}| | d|j  W d    d S 1 s*w   Y  d S r  r  r  r   r   r   r    s   
"z&Win32ProcessTestCase.test_shell_stringc              	   C   sn   dD ]2}t j }d|d< tjddtj||d}| | d|j | W d    n1 s/w   Y  qd S )N)ansiZoemr  r   r  r   )r   r7   r   r   r  )r   encr   r@   r   r   r   test_shell_encodings  s   
z)Win32ProcessTestCase.test_shell_encodingsc                 C   s    t tjd }| |d d S )Nz -c "import sys; sys.exit(47)"rG   rH   rM   r   r   r   r    s   z%Win32ProcessTestCase.test_call_stringc                 G   s   t jtjddgt jt jt jd}|% |jd t|||  | \}}| 	|d |
 }W d    n1 s:w   Y  | |d d S )Nr   zif 1:
                             import sys, time
                             sys.stdout.write('x\n')
                             sys.stdout.flush()
                             time.sleep(30)
                             r5   r   r  r   )r   r9   rJ   rK   r:   r7   r   r  r   rL   r#   rU  )r   r  r0   r@   rM  r8   r   r   r   r   r    s   	
z"Win32ProcessTestCase._kill_processc                 G   s   t jtjddgt jt jt jd}|* |jd td t	|||  |
 \}}| |d | }W d    n1 s?w   Y  | |d d S )Nr   zif 1:
                             import sys, time
                             sys.stdout.write('x\n')
                             sys.stdout.flush()
                             sys.exit(42)
                             r5   r   r  r  )r   r9   rJ   rK   r:   r7   r   r  r  r  r   rL   r#   )r   r  r0   r@   rM  r8   rN   r   r   r   r    s   	

z'Win32ProcessTestCase._kill_dead_processc                 C   r  r  )r  r  r  r   r   r   r   r    r  z%Win32ProcessTestCase.test_send_signalc                 C   r  r  r  r   r   r   r   r       zWin32ProcessTestCase.test_killc                 C   r  r  r  r   r   r   r   r    r  z#Win32ProcessTestCase.test_terminatec                 C   r  r  )r  r  r  r   r   r   r   r    r  z*Win32ProcessTestCase.test_send_signal_deadc                 C   r  r  r  r   r   r   r   r    r  z#Win32ProcessTestCase.test_kill_deadc                 C   r  r  r  r   r   r   r   r    r  z(Win32ProcessTestCase.test_terminate_deadN)r)   r*   r+   r  r  r  r  r   r   r  r  rO  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r   r   r    s0    
2

r  c                   @   s^   e Zd ZG dd dejZejejddd Z	dd Z
dd	 Zd
d Zdd Zdd ZdS )	MiscTestsc                       s"   e Zd Z	 g Z fddZ  ZS )zMiscTests.RecordingPopenc                    s"   t  j|i | | j|  d S r   )r0  r   instances_createdrt  r/   r2  r   r   r     s   z!MiscTests.RecordingPopen.__init__)r)   r*   r+   r  r   r  r   r   r2  r   RecordingPopen  s    r  _communicatec              
   K   s  	 t |_ztjtjd}t |_tjtd| j, | t  |t	j
ddgfdtji| W d    n1 s:w   Y  W d    n1 sIw   Y  |jdd  D ]}| |tjd dd|j  qUg }|jD ]}|tjd	dkr{|| ql| j|jd
|jd | jt|d|jd W d    n!1 sw   Y  W | jj }|  |  | g | jj d S W | jj }|  |  | g | jj d S | jj }|  |  | g | jj w )N_waitr9   r   zLimport time
time.sleep(9)
import sys
sys.stderr.write('\n!runaway child!\n')r7   r   rR   z.no open-ended wait() after the first allowed: g      ?r  r  )KeyboardInterruptrG  r   r  r  r   r9   r  rT   rJ   rK   r  Zcall_args_listrU  rI   rt  ZassertLessEqualZ
call_countrL   rL  r  r{  r'  r#   )r   ZpopenerZmock__communicater1   Z
mock__waitrI   Zsigint_callsr  r   r   r   _test_keyboardinterrupt_no_kill  sf   



z)MiscTests._test_keyboardinterrupt_no_killc                 C      | j tjdd d S NgT㥛 @rR   )r  r   rI   r   r   r   r   #test_call_keyboardinterrupt_no_kill     z-MiscTests.test_call_keyboardinterrupt_no_killc                 C   r  r  )r  r   r   r   r   r   r   "test_run_keyboardinterrupt_no_kill  r  z,MiscTests.test_run_keyboardinterrupt_no_killc                 C   s   dd }|  | d S )Nc                  _   s*   t j| i |}t1 sw   Y  d S r   )r   r9   r  )r0   r1   Zunused_processr   r   r   popen_via_context_manager  s   z[MiscTests.test_context_manager_keyboardinterrupt_no_kill.<locals>.popen_via_context_manager)r  )r   r  r   r   r   .test_context_manager_keyboardinterrupt_no_kill  s   z8MiscTests.test_context_manager_keyboardinterrupt_no_killc              	   C   s   |  tdd |  tdd d }z,t }tj|d}tt	r&dnd| \}}| 
|d W |d ur?t| d S d S |d urKt| w w )Nz
echo xyzzyxyzzy)r   r  r   ztype zcat r   )rL   r   	getoutputgetstatusoutputrr   rr  r   r   r   r!   rU  rmdir)r   dirr  r  rf   r   r   r   test_getoutput  s"   zMiscTests.test_getoutputc                 C   sp   	 h d}t tj}t  }dd l}tj D ]\}}|dr qt||jfr(q|	| q| 
|||  d S )N>   r)  Handler$  r  rf  r   rM  )r  r   __all__r  __dict__itemsr3  rj  
ModuleTyperJ  rL   )r   Zintentionally_excludedZexportedZpossible_exportsr  r  r'  r   r   r   test__all__.  s   

zMiscTests.test__all__N)r)   r*   r+   r   r9   r  r   r  r  r  r  r  r  r  r  r   r   r   r   r    s    
+r  PollSelectorz!Test needs selectors.PollSelectorc                   @   r   )ProcessTestCaseNoPollc                 C   s   t j| _tjt _t|  d S r   )r   _PopenSelectororig_selector	selectorsSelectSelectorr4   r    r   r   r   r   r    @  s   zProcessTestCaseNoPoll.setUpc                 C   s   | j t_t|  d S r   )r  r   r  r4   r'   r   r   r   r   r'   E  s   zProcessTestCaseNoPoll.tearDownNr(   r   r   r   r   r  =  s    r  zWindows-specific testsc                       sP   e Zd Z fddZ fddZdd Zdd Zd	d
 Zdd Zdd Z	  Z
S )CommandsWithSpacesc                    s>   t    tdd\}}| | _t|d t| d S )Nz.pyzte stsV   import sys;sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv])))	r0  r    rr   r  r  r  r   ru   r>   )r   r  r  r2  r   r   r    M  s
   

zCommandsWithSpaces.setUpc                    s   t | j t   d S r   )r   r  r  r0  r'   r   r2  r   r   r'   V  s   zCommandsWithSpaces.tearDownc                 O   sb   t j|d< t j|i |}| | |j dd| j  W d    d S 1 s*w   Y  d S )Nr7   mbcsz2 [%r, 'ab cd'])r   r:   r9   rL   r7   r   r   r  )r   r0   r1   r@   r   r   r   with_spacesZ  s   
"zCommandsWithSpaces.with_spacesc                 C   s    | j dtj| jdf dd d S )N"%s" "%s" "%s"ab cdr   r  r  rJ   rK   r  r   r   r   r   test_shell_string_with_spacesc  s
   
z0CommandsWithSpaces.test_shell_string_with_spacesc                 C   s   | j tj| jdgdd d S )Nr  r   r  r  r   r   r   r   test_shell_sequence_with_spacesh  s   z2CommandsWithSpaces.test_shell_sequence_with_spacesc                 C   s   |  dtj| jdf  d S )Nr  r  r  r   r   r   r   test_noshell_string_with_spacesl  s   z2CommandsWithSpaces.test_noshell_string_with_spacesc                 C   s   |  tj| jdg d S )Nr  r  r   r   r   r   !test_noshell_sequence_with_spacesq  s   z4CommandsWithSpaces.test_noshell_sequence_with_spaces)r)   r*   r+   r    r'   r  r  r  r  r  r  r   r   r2  r   r  J  s    		r  c                   @   s4   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZdS )ContextManagerTestsc                 C   s   t jtjddgt jt jd}| |j d | |j d W d    n1 s+w   Y  | 	|jj
 | 	|jj
 d S )Nr   zAimport sys;sys.stdout.write('stdout');sys.stderr.write('stderr');r   s   stdouts   stderr)r   r9   rJ   rK   r:   rL   r7   r   r8   rP  rQ  r  r   r   r   	test_pipex  s   
	zContextManagerTests.test_pipec                 C   sD   t tjddg}W d    n1 sw   Y  | |jd d S )Nr   zimport sys; sys.exit(100)d   )r   r9   rJ   rK   rL   r   r  r   r   r   r    s   
z#ContextManagerTests.test_returncodec                 C   sV   t jtjddgt jd}|d | |jd W d    d S 1 s$w   Y  d S )Nr   z2import sys;sys.exit(sys.stdin.read() == 'context')rp   s   contextr   r  r  r   r   r   rB    s   

"z*ContextManagerTests.test_communicate_stdinc              	   C   st   |  t+ tjttjtjd}W d    n1 sw   Y  W d    d S W d    d S 1 s3w   Y  d S )Nr   )rT   r   r   r9   r   r:   r  r   r   r   r     s   "z%ContextManagerTests.test_invalid_argsc                 C   st   	 t jtt jtjd d}| }|jdtj  | 	|j
 | t|jd d d  | |j
d | |jj d S )Nr  )r6   rB   r  r   )r   r9   r   r:   r   rV  	__enter__r6   ru   r  r   rT   rx  __exit__rL   rP  rQ  r  r   r   r   test_broken_pipe_cleanup  s   z,ContextManagerTests.test_broken_pipe_cleanupN)r)   r*   r+   r  r  rB  r   r  r   r   r   r   r  v  s    r  __main__)Er%  r   r#  r   Ztest.supportr   r   r   r   r   rJ   r  r<   r  r   ry  rr   r  r  r  r  r  rB  r   r  r  rc  r  r  Ztest.support.os_helperr   r  r  rf  r)  r$  ZPGOr&  r  r!   r]  r   r   NotADirectoryErrorri  r   rK   r   r   ZTestCaser   	Exceptionr,   r9   r-   r4   r  r.  r  r/  r  r  r  r  r  r  r  r)   mainr   r   r   r   <module>   s    



            F
            
 ~d
+
6