o
    g	k                    @   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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 Z/G dd de j0Z1G dd de2Z3G dd dej4Z5G dd de1Z6G dd de1Z7dd Z8e 9e&dG dd de1Z:e ;e&d G d!d" d"e1Z<G d#d$ d$e j0Z=e ;e>ed%d&G d'd( d(e6Z?e ;e&d)G d*d+ d+e1Z@G d,d- d-e1ZAeBd.kree C  dS dS )/    N)mock)support)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   J/Users/admin/.pyenv/versions/3.10.0/lib/python3.10/test/test_subprocess.pysetUpModuleF   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   setUpQ   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   tearDownV   s   

zBaseTestCase.tearDownN__name__
__module____qualname__r   r&   r   r   r   r   r   P   s    r   c                   @   s   e Zd ZdS )PopenTestExceptionN)r(   r)   r*   r   r   r   r   r+   c   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_childk      z&PopenExecuteChildRaises._execute_childN)r(   r)   r*   r1   r   r   r   r   r,   g   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ee d7d8d9 Z!ee d7d:d; Z"ee d7d<d= Z#d>d? Z$d@dA Z%dBdC Z&dDdE Z'dFdG Z(dHdI Z)ee dJdKdL Z*ee dJdMdN Z+dOdP Z,ee-j.e-j/kdQdRdS Z0ee-j.e-j/kdQee12 dTdUdV Z3dWdX 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 ZCeDeEo+eFeEdwdxdydz ZGeDeEo;eFeEdwdxd{d| ZHd}d~ ZIee-jJdkdee1Kddkddd ZLdd ZMdd 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ф ZreDeFesd҃dӡeDeFetdԃdաeDeFetdփdסddل ZueDetjvwdetx  dۡdd݄ Zyee dޡdd Zze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assertIsInstancer5   ioBufferedIOBaser6   r7   closer"   r   pr   r   r   test_io_buffered_by_defaultq   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   )r5   r6   r7   bufsize)r   r8   r   r9   r:   r5   r;   	RawIOBaser6   r7   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   TimeoutExpiredrH   rI   rJ   r   r   r   r   test_call_timeout   s   

z!ProcessTestCase.test_call_timeoutc                 C   s   t t}| |d d S Nr   )r   
check_callr   rK   rL   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 rD   )	rS   r   CalledProcessErrorrW   rI   rJ   rK   	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_outputrI   rJ   assertInr   outputr   r   r   test_check_output   s   
z!ProcessTestCase.test_check_outputc                 C   rY   )Nr
   zimport sys; sys.exit(5)   )	rS   r   rZ   rb   rI   rJ   rK   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')r7   r`   )r   rb   rI   rJ   STDOUTrc   rd   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())r5      PEAR)tempfileTemporaryFile
addCleanupr=   writeseekr   rb   rI   rJ   rc   )r   tfre   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
   rn   rm   inputrp   ra   rd   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 '')rx   s   XXr   rb   rI   rJ   assertNotInrd   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)ry   textXXr|   rd   r   r   r   !test_check_output_input_none_text      z1ProcessTestCase.test_check_output_input_none_textc                 C   r   )Nr
   r{   T)ry   universal_newlinesr   r|   rd   r   r   r   /test_check_output_input_none_universal_newlines   r   z?ProcessTestCase.test_check_output_input_none_universal_newlinesc                 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')r6   z-Expected ValueError when stdout arg supplied.r6   r   )rS   
ValueErrorr   rb   rI   rJ   r6   failrc   r[   r/   r   r]   re   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 )
Nrm   r   r
   r      harer5   ry   7Expected ValueError when stdin and input args supplied.r5   ry   )rq   rr   rs   r=   rt   ru   rS   r   r   rb   rI   rJ   r   rc   r[   r/   r   rv   r]   re   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)   rQ   zExpected TimeoutExpired.r`   )
rS   r   rT   rb   rI   rJ   r   rK   r[   re   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   rH   rI   rJ   rK   )r   newenvrM   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_stderrrS   	TypeErrorr   r8   __init____code__co_argcountrK   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")r6   r7   )r   r8   rI   rJ   r9   rs   r6   r=   r7   r"   rK   r5   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   r8   rI   rJ   r9   rs   r6   r=   r7   communicaterK   r   rstripr   coder?   outerrr   r   r   test_stdout_none)  s   z ProcessTestCase.test_stdout_nonec                 C   r   )Nr
   r   r5   r6   )r   r8   rI   rJ   r9   rs   r6   r=   r5   r"   rK   r7   r>   r   r   r   test_stderr_none@  r   z ProcessTestCase.test_stderr_nonec                 K   s6   |dg }t j|fi |}|  | d|j d S NrE   rF   )r   r8   r"   rK   r   )r   pre_argsr0   r/   r?   r   r   r   _assert_pythonI  s   
zProcessTestCase._assert_pythonc                 C   s0   t jt jtjd}| j|dgtjd d S Ndoesnotexistr
   rJ   )r   pathjoindirnamerI   rJ   r   r   r   r   r   r   test_executableQ  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   rI   rJ   r   fsencoder   r   r   r   test_bytes_executable\  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   rI   rJ   r   r   r   r   r   r   test_pathlike_executableb  s   

z(ProcessTestCase.test_pathlike_executablec                 C   s0   t jdg}| | | jt| j|td d d S )Nr
   r   r   )rI   rJ   r   rS   NONEXISTING_ERRORSNONEXISTING_CMD)r   r   r   r   r    test_executable_takes_precedenceh  s   


z0ProcessTestCase.test_executable_takes_precedencez"executable argument replaces shellc                 C   s   | j g tjdd d S NT)rJ   shell)r   rI   rJ   r   r   r   r   test_executable_replaces_shellr  s   z.ProcessTestCase.test_executable_replaces_shellc                 C   s   | j g ttjdd d S r   )r   r   r   rI   rJ   r   r   r   r   $test_bytes_executable_replaces_shellx  s   
z4ProcessTestCase.test_bytes_executable_replaces_shellc                 C   s   | j g ttjdd d S r   )r   r   rI   rJ   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   realpathrI   rJ   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)r6   rF   )r   r8   r9   rs   r6   r=   r"   rK   r   r   r   normcasereaddecode)r   Zexpected_cwdZ
python_argr0   r?   r   r   r   r   _assert_cwd  s   
zProcessTestCase._assert_cwdc                 C   s(   t  }| |}| j|tj|d d S Nr   )rq   
gettempdirr   r   rI   rJ   r   temp_dirr   r   r   test_cwd  s   
zProcessTestCase.test_cwdc                 C   s.   t  }| |}| j|tjt|d d S r   )rq   r   r   r   rI   rJ   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   )rq   r   r   r   rI   rJ   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_cwdrS   FileNotFoundErrorr   r8   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   rJ   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   rS   r   r   r8   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   rI   rJ   )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   rI   rJ   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")ro   rm   r   )r   r8   rI   rJ   r9   r5   rt   r=   r"   rK   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 Nrm   r   r
   r   ro   r   )rq   rr   rs   r=   filenor   rt   lseekr   r8   rI   rJ   r"   rK   r   r   rv   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   )rq   rr   rs   r=   rt   ru   r   r8   rI   rJ   r"   rK   r   r   rv   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   r8   rI   rJ   r9   rK   r6   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   rq   rr   rs   r=   r   r   r8   rI   rJ   r"   r   r   rK   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   rq   rr   rs   r=   r   r8   rI   rJ   r"   ru   rK   r   r   r   r   r   test_stdout_fileobj.     

z#ProcessTestCase.test_stdout_fileobjc                 C   r   )Nr
   *import sys; sys.stderr.write("strawberry")rj   
   strawberry)r   r8   rI   rJ   r9   rK   r7   r   r>   r   r   r   test_stderr_pipe9  r   z ProcessTestCase.test_stderr_pipec                 C   r   )Nr
   r  rj   r   r   r  r   r   r   r   r   test_stderr_filedesA  r   z#ProcessTestCase.test_stderr_filedesc                 C   r   )Nr
   r  rj   r   r  r   r   r   r   r   test_stderr_fileobjM  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   r8   rI   rJ   r9   r   rK   r   r   r?   r6   r7   r   r   r   ,test_stderr_redirect_with_no_stdout_redirectX  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   r8   rI   rJ   r9   rk   rK   r6   r   r>   r   r   r   test_stdout_stderr_pipem  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_filey  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   r8   rI   rJ   DEVNULLr"   rK   r6   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)rj   )r   r8   rI   rJ   r  r"   rK   r7   r>   r   r   r   test_stderr_devnull  s   
z#ProcessTestCase.test_stderr_devnullc                 C   r  )Nr
   zimport sys;sys.stdin.read(1)ro   )r   r8   rI   rJ   r  r"   rK   r5   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!")r5   r6   r7   pipesizerm   )r   pipefcntlr  r=   unittestZSkitTestr   r8   rI   rJ   r9   r5   r6   r7   rK   r   rt   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   r8   rI   rJ   r9   r   r  r  r  r5   r6   r7   rK   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"))r6   r   r   )
r   r   r   r   r8   rI   rJ   r9   r   rK   r   r   r?   r6   r7   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.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r,  r   r   
<listcomp>  s    
z2ProcessTestCase.test_empty_env.<locals>.<listcomp>)r   r8   rI   rJ   r9   r   evalstripr:   listrK   )r   r?   r6   r7   Zchild_env_namesr   r/  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# )rI   rJ   rS   r   r   r8   )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   rS   r   r   r8   r   rI   rJ   r9   r   rK   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")ro   rm   r   r	  r>   r   r   r   test_communicate_stdinA  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   r8   rI   rJ   r9   r   rK   r
  r   r   r   test_communicate_stdoutI     
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")rj   r:  r;  r
  r   r   r   test_communicate_stderrQ  r=  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())r4      bananar:  )r   r8   rI   rJ   r9   rs   r6   r=   r7   r5   r   rK   r
  r   r   r   test_communicateY  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   r5   r6   r7   r   g333333?rQ   s   pineapple
pear
)
r   r8   rI   rJ   r9   rS   rT   r   rK   encoder
  r   r   r   test_communicate_timeouth  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?rQ   i   )
r   r8   rI   rJ   r9   rS   rT   r   rK   len)r   r?   r6   _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FTr5   r6   r7   )
r   r9   r8   r   r   r5   
assertTrueclosedr6   r7   )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
   rE   )r   r8   rI   rJ   r   rK   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())r4      a)r   r  r=   r   r8   rI   rJ   r   PIPE_MAX_SIZEr9   rs   r6   r7   r5   r   rK   )r   xyr?   Zstring_to_writer6   r7   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())r4   r?  s   splits   bananasplitr  )r   r8   rI   rJ   r9   rs   r6   r=   r7   r5   rt   r   rK   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    q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   r5   r6   Tzline1
zline3
zline2
   zline4
line5
line6
line7
line8)rI   rJ   	SETBINARYr   r8   r9   r5   rt   flushrK   r6   readliner=   rs   r   )r   r/   Zextra_kwargr?   r   r   r    test_universal_newlines_and_text  s8   

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
   rR  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   )r7   r6   r   z#line2
line4
line5
line6
line7
line8)r   r8   rI   rJ   rT  r9   rs   r6   r=   r7   r   rK   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
   rR  a  
                               s = sys.stdin.readline()
                               assert s == "line1\n", repr(s)
                               s = sys.stdin.read()
                               assert s == "line3\n", repr(s)
                              r   )r5   r   line1
line3
r   )r   r8   rI   rJ   rT  textwrapdedentr9   r   rK   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)r5   r6   r   r   )r   r8   r   r9   r   rK   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
   rR  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)r5   r7   r6   r   rY  r   zline1
line2
line3
line4
line5
zeline2
eline6
eline7
)r   r8   rI   rJ   rT  rZ  r[  r9   rs   r6   r=   r7   r   rK   r   rG  r*  r
  r   r   r   7test_universal_newlines_communicate_stdin_stdout_stderr+  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
   )r5   r6   encodingr	   rx   z1
2
3
4)rI   rJ   r   r8   r9   r   rK   )r   r_  r   r/   popenr6   r7   r   r   r   -test_universal_newlines_communicate_encodingsG  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))ignorer	   )replaceu   ��)surrogateescapeu   )backslashreplacez\x80\x80z2import sys; sys.stdout.buffer.write(b'[\x80\x80]')r
   utf-8)r5   r6   r_  errorsr	   rx   z[{}])rI   rJ   r   r8   r9   r   rK   format)r   rg  expectedr   r/   r`  r6   r7   r   r   r   test_communicate_errors]  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 }~ qMd }~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())r4   s   limer   )r    rq   mkdtempranger   r   r   r   ZTESTFNappendopenO_WRONLYO_CREATOSErrorerrnoZEMFILEskipTestr=   popr   r8   rI   rJ   r9   r   rK   r   rmtree)
r   Zmax_handleshandlestmpdiriZtmpfileer?   datahr   r   r   test_no_leakingr  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 "")rK   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)ro      Ar   )r   r8   rI   rJ   r9   rs   r5   r=   assertIsNonepollr   rt   r   r"   rK   r>   r   r   r   	test_poll  s   
zProcessTestCase.test_pollc                 C   s.   t t}| | d | | d d S rV   r   r8   r   rK   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?rQ   z0.0001r   )r   r8   rI   rJ   rS   rT   r"   rc   strr[   rK   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$  )rS   r   r   r8   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   )rA   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   )r5   r6   r7   rA   r   r   )r   r8   rI   rJ   r9   r  r5   rt   r   r=   r   r6   rV  r   SuppressCrashReportrs  rK   r   )r   lineri  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   lineseprA  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    q1 s w   Y  qd S )Nr   r   )rn  rS   r   r   r8   r   r9   )r   rz  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)r7   r   r   r	   )msvcrtZCrtSetReportModeAttributeErrorImportErrorru  rZ  r[  r   rI   rJ   r   r8   r9   r   rK   r   )r   r  r   r6  procr7   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?)rn  extendr   r  timesleep)rz  fdsr   r   open_fds-  s   z<ProcessTestCase.test_double_close_on_error.<locals>.open_fds)targetr4   )	threadingThreadstartrS   EnvironmentErrorr   r8   r   r9   r   r   r=   rs  )r   r  texcfdr{  r   r  r   test_double_close_on_error*  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)ro  r  r  r"   r   r   r  resultsr   r   kill_proc_timer_threadN  s   zDProcessTestCase.test_threadsafe_wait.<locals>.kill_proc_timer_thread皙?r   irQ   z*unexpected result in wait from main threadmsgz&unexpected result in second main wait.)r  Nr  r  )r   r8   rI   rJ   rK   r   r  Timerr  r    r"   r   r  r   )r   r  r  Zexpected_errorcoder   r  r   test_threadsafe_waitG  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   rb   rI   rJ   rG  r*  ascii)r   r   re   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*r4   )rq   mkstempr   r8   rs  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 )Nr4      x   )
r   r8   r   r9   rs   r6   r=   r7   r5   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')>r1   r   )pathlibPath	__class__r(   r  r   patchobjectr   r8   r   rK   repr)	r   Zpath_cmdZpathlib_clscasesr6  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 )Nro   r  r  )	r   r8   r   r9   rs   r5   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    q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  rs   rI   rJ   r   r9   r8   r   )r   r  old_handlerr/   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  r4   )
r   getpidlistdirrS   r+   r,   r   r   r9   rK   )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somer/   r  )rS   r   r   rH   rK   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   )rS   r   r   r8   rK   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   r8   bytestypesGenericAliasCompletedProcessr  r   r   r   r   test_class_getitems  s   z#ProcessTestCase.test_class_getitemsN)}r(   r)   r*   r@   rC   rN   rU   rX   r^   rf   rh   rl   rw   rz   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   rI   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#  r(  platformZget_config_varr4  r7  r8  r9  r<  r>  r@  rB  rE  rJ  rK  rP  rQ  rW  rX  r\  r]  r^  ra  rj  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   r3   o   s"   		

		













	
 

'')4




r3   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d(S ))RunFuncTestCasec                 K   s    	 t jd|g}tj|fi |S )Nr
   )rI   rJ   r   r   )r   r   r0   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  rK   r   rS   r   rZ   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 )NrE   TcheckrF   )rS   r   rZ   r  rK   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   rK   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 )NrO   r  rQ   )rS   r   rT   r  r   r   r   r   test_timeout  s   "zRunFuncTestCase.test_timeoutc                 C   "   | j dtjd}| d|j d S )Nr_   r   r`   r  r   r9   rc   r6   r  r   r   r   test_capture_stdout  s   z#RunFuncTestCase.test_capture_stdoutc                 C   r  )Nri   rj   r`   )r  r   r9   rc   r7   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 )Nrm   r   rn   r   rp   )rq   rr   rs   r=   rt   ru   r  r   r9   rc   r6   )r   rv   r  r   r   r   rw   $  s   

z+RunFuncTestCase.test_check_output_stdin_argc                 C   s$   | j ddtjd}| d|j d S )Nrn   rm   )ry   r6   rp   r  r  r   r   r   rz   /  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 )
Nrm   r   r   r  r   r   r   r5   ry   )rq   rr   rs   r=   rt   ru   rS   r   r  rc   r[   r/   r   r   r   r   r   6  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   )rR   r6   r`   )	rS   r   rT   r  r9   rK   r[   re   r6   )r   r]   r  r   r   r   r   C  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  rK   r   )r   r   r  r   r   r   test_run_kwargsQ  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)r6   r   )r    r   r   ru  r   r   r   r  rK   r   rS   r   )r   progr   resr   r   r   test_run_with_pathlike_pathY  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   rI   rJ   r   r   rK   r   r   r   r/   r  r   r   r   &test_run_with_bytes_path_and_argumentsg  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   rI   rJ   r   r   rK   r   r  r   r   r   )test_run_with_pathlike_path_and_argumentsn  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_outputr`   s   FLUFL)r  rc   r6   r7   r  r   r   r   test_capture_outputu  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  r6   r6   r   r  
rq   rr   rs   r=   rS   r   r  rc   r[   r/   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  r7   r7   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 3TrP   )r   rR   r  zTimeoutExpired not raised.g      ?z/TimeoutExpired was delayed! Bad traceback:
```
z```r  )	r  	monotonicr   r   rT   	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_outputN)r(   r)   r*   r  r  r  r  r  r  r  rw   rz   r   r   r	  r  r  r  r  r  r  r  r  r    r  r   r   r   r   r    s*    
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  SkipTest)
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   chdirr%  rs  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r)  r   r8   rI   rJ   r%  rs  rK   rt  strerrorr  r   r   r(  r?   r{  r   r   r   test_exception_cwd     
z'POSIXProcessTestCase.test_exception_cwdc              
   C   r*  )Nr
   r	   r   r+  r,  r.  r   r   r   test_exception_bad_executable  r0  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	   r+  )
r)  r   r8   r%  rs  rK   rt  r-  r  r   r.  r   r   r   test_exception_bad_args_0  s   z.POSIXProcessTestCase.test_exception_bad_args_0c                   @   s   e Zd Zdd ZdS )z&POSIXProcessTestCase.PopenNoDestructorc                 C   r  r   r   r   r   r   r   __del__  r  z.POSIXProcessTestCase.PopenNoDestructor.__del__N)r(   r)   r*   r3  r   r   r   r   PopenNoDestructor  s    r4  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   )rh  rt  ZEISDIRrA  r   rt   )r/   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)r;  r   r  ChildProcessErrorrS   IsADirectoryErrorr4  )r   	fork_execr8  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 )Nr5  r   )r   rt   )r/   r7  Z
error_datar   r   	bad_error  s   zGPOSIXProcessTestCase.test_exception_errpipe_bad_data.<locals>.bad_errorr9  r:  r<  )r;  r   r  r=  rS   r   SubprocessErrorr4  rc   r  r  r[   )r   r?  rB  r{  r   rA  r   test_exception_errpipe_bad_data  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|} qq| d t jddgdd}| D ]}|dr6|} q7q+| j||dd	 d S )
NcatrE  F)restore_signalss   SigIgnz&SigIgn not found in /proc/self/status.Tz=restore_signals=True should've unblocked SIGPIPE and friends.r  )r   rb   
splitlinesr*  ru  assertNotEqual)r   Zdefault_proc_statusr  Zdefault_sig_ign_maskZrestored_proc_statusZrestored_sig_ign_maskr   r   r   test_restore_signals(  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   rb   rI   rJ   rs  rt  EPERMr   getsidintrI  )r   re   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    q91 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  unknownrF  )user	close_fdsr
   zimport os; print(os.getuid())r"  rU              )r   r   rU  )r   geteuidrI   r  pwdgetpwnamro  r  subTestr   rb   rJ   PermissionErrorrs  rt  ZEACCESrL  
isinstancer  pw_uidrN  rK   rS   r   rW   r   OverflowErrorr   r   )
r   uidZ
test_usersZname_uidrU  rV  re   r{  Zuser_uidZ
child_userr   r   r   	test_userP  sd   



"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  rW  rS   r   r   rW   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    q"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 )NrQ  rR  rF  )grouprV  r
   zimport os; print(os.getgid())r"  ri  rX  )r   r   ri  )r   getegidr"  r  ro  r\  r   rb   rI   rJ   r]  r^  r  r  gr_gidrN  rK   rS   r   rW   r   r`  r   r   )	r   gid
group_listr!  ri  rV  re   Z	group_gidZchild_groupr   r   r   
test_group  sP   



"zPOSIXProcessTestCase.test_groupz setregid() available on platformc                 C   rc  )Nrd  rj  re  r   r   r   r   test_group_error  rg  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 )NrQ  rR  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   )r^  r  r  r  rl  )r-  gr   r   r   r0    s    z:POSIXProcessTestCase.test_extra_groups.<locals>.<listcomp>r"  rX  )r   r   rs  )r   rk  r"  r  ro  r   rb   rI   rJ   rs  rt  rL  	getgroupsjsonloadsrK   setrS   r   rW   r   r   r   )
r   rm  rn  r!  Z
perm_errorre   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 )Nrr  re  r   r   r   r   test_extra_groups_error  rg  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  )rq   rm  r   r   r   r   rW   rI   rJ   statst_moderK   octr   rw  )r   ry  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   r8   rI   rJ   r"   rK   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   rZ   rN  r  r  r  rc   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   rZ   r  rc   r  r   r   r   *test_CalledProcessError_str_unknown_signal     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>(      z3POSIXProcessTestCase.test_preexec.<locals>.<lambda>)r6   
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_it-  r2   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   r8   rI   rJ   rC  rG  _posixsubprocessr   rc   r/   r   )r   r  r?   r{  r   r   r   test_preexec_exception,  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   r8   r   )r   Ztestcaser/   r0   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
| q6|D ]}t
| q@w d S 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   rp  O_RDONLYr-  rD  r   r   r   r0  I  s    zNPOSIXProcessTestCase._TestExecuteChildPopen._execute_child.<locals>.<listcomp>   z!At least one fd was closed early.r  )r   r8   r1   rn  r  r}   r5   r   r6   r7   r   r=   )r   r/   r0   Zdevzero_fdsr  r   r   r   r1   B  sH   
z:POSIXProcessTestCase._TestExecuteChildPopen._execute_childN)r(   r)   r*   r   r1   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   rC  r   r   r   r   r  Y  s   zWPOSIXProcessTestCase.test_preexec_errpipe_does_not_double_close_pipes.<locals>.raise_it)r5   r6   r7   r  )rS   r   rC  r  r   r9   )r   r  r   r   r   0test_preexec_errpipe_does_not_double_close_pipesU  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  k      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  r  zPopen left gc disabled.)
gc	isenableddisabler$   r   rH   rI   rJ   enablerG  )r   Zenabledr   r   r   test_preexec_gc_module_failurec  s*   

z3POSIXProcessTestCase.test_preexec_gc_module_failurerS  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)resourcer  r  r  r  ru  rs   r   rH   rI   rJ   BlockingIOError)r   r  r  r  r   ZlimitsrD  Zhardr   r   r   test_preexec_fork_failurex  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wrd  )rg  z#!%s
z(exec '%s' -c 'import sys; sys.exit(47)'
i  rF   )rq   r  rp  rt   r   
unix_shellrI   rJ   r   chmodr   r8   r"   r  rK   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
   rE   rF   startupinfocreationflagsrS   r   r   rH   rI   rJ   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   r6   r   s    	
r  
r   r   r   r   r8   r9   rK   r6   r   r2  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  )rq   r  rp  rt   r   r  rI   rJ   r   r  r   rH   r  rK   )r   r  r  r  rM   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    q: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)rJ   r   r6   r  )r   r   r   isfilero  ru  islinkr   r8   r9   rK   r6   r   r2  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rV  r5   r6   r7   r   )r  SIGINTdefault_int_handlerr   r8   rI   rJ   r9   r6   r   getattr)r   methodr/   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   r8   rI   rJ   r9   r6   r   r  r  r  r   )r   r  r/   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   rc   rI  r"   r   r?   rD  r7   r   r   r   test_send_signal	  s   z%POSIXProcessTestCase.test_send_signalc                 C   :   |  d}| \}}| |d | | tj  d S )Nr  r  )r  r   rK   r"   r  SIGKILLr  r   r   r   	test_kill	     
zPOSIXProcessTestCase.test_killc                 C   r  )N	terminater  )r  r   rK   r"   r  SIGTERMr  r   r   r   test_terminate	  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_dead"	     z#POSIXProcessTestCase.test_kill_deadc                 C   r  Nr  r  r   r   r   r   test_terminate_dead&	  r  z(POSIXProcessTestCase.test_terminate_deadc                 C   s6   g }|D ]}t |}t |}||||f q|S r   )r   get_inheritabledupro  )r   Zsave_fdsr  r  inheritablesavedr   r   r   	_save_fds*	  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_fds2	  s   z!POSIXProcessTestCase._restore_fdsc           	   	   C   s   d}|  |}|D ]\}}}|dkr|} q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  r4   r  r   )r  r   r=   r   r8   rI   rJ   r9   r   rK   r  )	r   r  r5   	saved_fdsr  r  r  r   r   r   r   r   check_close_std_fds7	  s,   

z(POSIXProcessTestCase.check_close_std_fdsc                 C      |  dg d S rV   r  r   r   r   r   test_close_fd_0P	     z$POSIXProcessTestCase.test_close_fd_0c                 C   r  Nr   r  r   r   r   r   test_close_fd_1S	  r  z$POSIXProcessTestCase.test_close_fd_1c                 C   r  )Nr  r  r   r   r   r   test_close_fd_2V	  r  z$POSIXProcessTestCase.test_close_fd_2c                 C      |  ddg d S )Nr   r   r  r   r   r   r   test_close_fds_0_1Y	     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_2b	  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   r8   rI   rJ   r"   r  )r   Z	new_stdinZ
new_stdoutr   r   r   test_small_errpipe_write_fdg	  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   rq   r  r-  rz  r   r   r   r0  ~	      z?POSIXProcessTestCase.test_remapping_std_fds.<locals>.<listcomp>r   c                 S      g | ]\}}|qS r   r   r-  r  r  r   r   r   r0  	  r  r      STDINr   r
   Zimport sys; got = sys.stdin.read();sys.stdout.write("got %s"%got); sys.stderr.write("err")r  r4   r   	   got STDIN   err)rn  r   unlinkrt   r   r  	enumerater  r   r8   rI   rJ   r"   r  r   r2  rK   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   r0  	  r  z7POSIXProcessTestCase.check_swap_fds.<locals>.<listcomp>r   c                 S   r  r   r   r  r   r   r   r0  	  r  r  r   r
   r  r4   r   r  r  )rn  r   r   r  r  r  rt   r   r   r8   rI   rJ   r"   r   r2  r  rK   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    q
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   r4   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  rn  rq   rr   r   r  r   rx  rv  r=   ziprZ  r[  r   rH   rI   rJ   r  rK   r   SEEK_SETr   r3  maprN  r   r  )r   from_fdsto_fdsr  Zfrom_fdfZfd_to_closeZ	arg_namesr0   Zto_fdr   Z
skipped_fdrM   
read_bytesZread_fdsr  r   r   r   #_check_swap_std_fds_with_one_closed	  sH   



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combinationsrn  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   prepare
  r2   zCPOSIXProcessTestCase.test_surrogates_error_message.<locals>.preparer  r  z!Exception occurred in preexec_fn.z1Expected ValueError or subprocess.SubprocessError)r   rH   r   r   r  r  rK   r  rC  assertIsNotNoner   )r   r  r   r   r   r   test_surrogates_error_message
  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  rd  z&import os; print(ascii(os.getenv(%s)))CLC_ALLr
   r   s   
z'import os; print(ascii(os.getenvb(%s))))rA  r  r   r   r   r   rb   rI   rJ   r   rK   r   r  )r   keyvalueZencoded_valuescriptr   Zdecoded_valuer6   r   r   r   test_undecodable_env%
  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 rf  Tr  PATHr   s   PATH)r   r   r   r3  r   r   r   rH   rK   r   rA  r   r   environb)	r   Zabs_programr/   r   Zprogramexitcoder6  r   Zenvbr   r   r   test_bytes_programB
  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)r5   r6   r7   rV  r  r6   rV     ,z5Expected no fds from %r to be open in child, found %r)r   findfiler   r8   rI   rJ   r9   rs   r   rx  r
  rN  r   r5   r   r6   r7   r$   )	r   Zsleeper	fd_statusp1p2re   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$  r%  zqgrep.pys   zxcvbn      
F)r5   r6   rV  c                      $   z    W d S  ty   Y d S w r   r  ProcessLookupErrorr   )r+  r   r   kill_p1
  
   zBPOSIXProcessTestCase.test_pipe_cloexec_real_tools.<locals>.kill_p1c                      r1  r   r2  r   )r,  r   r   kill_p2
  r5  zBPOSIXProcessTestCase.test_pipe_cloexec_real_tools.<locals>.kill_p2rk  zThe child hung)r   r)  r   r8   rI   rJ   r9   r6   rs   r"   r5   rt   r=   selectrG  rK   r   )
r   ZqcatZqgrepZsubdatar|  r4  r6  Z	readfilesZignored1Zignored2r   )r+  r,  r   test_pipe_cloexec_real_toolst
  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 )Nr&  r$  r%  r   r   	   TFr'  r(  zSome fds were closedzSome fds were left openzSubprocess failedc                 3   s    | ]}   V  qd S r   )rv  r  r  r   r   	<genexpr>
  s    z6POSIXProcessTestCase.test_close_fds.<locals>.<genexpr>r  r6   rV  pass_fdsz'Some fds not in pass_fds were left open)r   r)  r   r  rs   r=   rx  rn  rp  devnullr  addset_inheritabler   r8   rI   rJ   r9   r   r
  rN  r   rK   r$   rc   )
r   r*  r  rD  r  r?   re   ignoredremaining_fdsfds_to_keepr   r:  r   test_close_fds
  sN   
z#POSIXProcessTestCase.test_close_fdsZfreebsdz/devz/dev/fdz/Requires fdescfs mounted on /dev/fd on FreeBSD.c                 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 )Nr&  r$  r%  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   r(  r   zSome fds were left open.)r   r)  r   r8   rI   rJ   rZ  r[  r9   r   rH  rK   rC  rx  r
  rN  r2  r   r$   )r   r*  r?   re   Zunused_stderrZoutput_linesZ
opened_fdsrB  r   r   r   %test_close_fds_when_max_fd_is_lowered
  s&   /02

z:POSIXProcessTestCase.test_close_fds_when_max_fd_is_loweredrk  rg   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 )Nr&  r$  r%  rg   r   r   Tr<  r(  zfd to be passed not passedzfd to be closed passedF)rV  r=  zoverriding close_fds)r   r)  rx  rn  r   r  rs   r=   r@  updater   r8   rI   rJ   r9   r   r
  rN  r   rc   r$   ZassertWarnsr  rH   r   r  warning)r   r*  r  rN  r  r  r?   re   rA  rB  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 )	Nr&  r$  r%  TFr<  r(  z	output=%a)r   r)  r   r  rs   r=   r@  rI   rJ   r3  r
  r  r   r8   r9   r   rx  rN  r   rK   r  )
r   r  r  Znon_inheritabler=  r/   r?   re   rA  r  r   r   r   test_pass_fds_inheritableB  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 )Nr&  r$  r%  r  r   r   T)r5   r6   r7   rV  r=  r   c                 S   s   h | ]}t |qS r   )rN  )r-  numr   r   r   	<setcomp>u  r  z@POSIXProcessTestCase.test_pass_fds_redirected.<locals>.<setcomp>r(  >   r   r   r  zoutput=)r   r)  rn  r   rp  r>  O_RDWRrs   r=   ro  r  insertr   r8   rI   rJ   r   r   rK   	frozenset)	r   r*  r=  rD  r  Zstdout_rZstdout_wre   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+)r6   r5   r;   rp  r   r>  r   r8   r   r"   r   Zinoutr?   r   r   r   %test_stdout_stdin_are_single_inout_fdz     
"z:POSIXProcessTestCase.test_stdout_stdin_are_single_inout_fdc                 C   rQ  )NrR  r   rS  rT  r   r   r   &test_stdout_stderr_are_single_inout_fd  rV  z;POSIXProcessTestCase.test_stdout_stderr_are_single_inout_fdc                 C   rQ  )NrR  )r7   r5   rS  rT  r   r   r   %test_stderr_stdin_are_single_inout_fd  rV  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$  r%  r   r   z6sigchild_ignore.py exited non-zero with this error:
%srf  )r   r)  r   r8   rI   rJ   r9   r   rK   r   r   )r   Zsigchild_ignorer?   r6   r7   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 )	Nr7  r
   z$import sys;sys.stdout.write("apple")r   )r6   rA   r/  s   applg        )r   import_moduler   r8   rI   rJ   r9   r6   rs   r=   rK   r   rc   r7  r"   )r   r7  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r-  or   r   r   r0    r  zEPOSIXProcessTestCase.test_zombie_fast_process_del.<locals>.<listcomp>)r   r8   rI   rJ   r9   rs   r6   r=   r7   r^  pidr   check_warningsResourceWarningr    r  r!   rc   )r   r?   identra  r   r   r   test_zombie_fast_process_del  s    
z1POSIXProcessTestCase.test_zombie_fast_process_delc              	   C   sZ  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|tj trL| t j n| |dd t jD  td | t" t jtt jt jd}W d    n1 sxw   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   r\  r   r]  r_  r   r   r   r0    r  zJPOSIXProcessTestCase.test_leak_fast_process_del_killed.<locals>.<listcomp>r  r   c                 S   r\  r   r]  r_  r   r   r   r0    r  )r   r8   rI   rJ   r9   rs   r6   r=   r7   r^  ra  r   rb  rc  r   r  r  r  r    r  r!   rc   r  r  rS   rs  r   waitpidr}   )r   r?   rd  ra  r  r   r   r   !test_leak_fast_process_del_killed  s@   

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 )
Nr&  r$  r%  r   Tc                      s   t d S r  )r   r  r   r  r   r   r    r  zCPOSIXProcessTestCase.test_close_fds_after_preexec.<locals>.<lambda>)r6   rV  r  r(  )r   r)  r   r  rs   r=   r   r8   rI   rJ   r9   r   rx  r
  rN  r   r}   )r   r*  r?   re   rA  rB  r   rh  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  rS   r   r?  r}   r  r[   r  )	r   r  
gc_enabledfuncr/   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   )  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__+  s   zRPOSIXProcessTestCase.test_fork_exec_sorted_fd_sanity_check.<locals>.BadInt.__int__N)r(   r)   r*   ro  r   rp  r   r   r   r   BadInt'  s    rq  )r"  r  r   r/  rg   )r  r/  )      *   l            )rg   r/  )rS  r  r  r  r   r  zfds_to_keep={}r  s   falseTrj  r"  r   r/  rC  )r  r  r  r  rS   r   rh  r?  rc   r  r[   r  )r   r  rq  rk  rC  r]   r   r   r   %test_fork_exec_sorted_fd_sanity_check#  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 )Nr5   )r   r8   r   r   r  r  BrokenPipeErrorr=   r;  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 )Nr5      stuff)r   r8   r   r   r  r  rv  rt   r;  r   assert_called_once_withr=   rw  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   r5   wbrz  )r   r8   rI   rJ   r9   r   r  r  rp  r   r>  rv  rU  r;  r   return_valuer   r{  )r   r  rx  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   r5   i  rQ   )r   r8   rI   rJ   r9   r   r  r  rv  r=   r;  r   r{  rw  r   r   r   9test_communicate_BrokenPipeError_stdin_close_with_timeouto  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   r9  )r  )r   r   r8   r   wait_processra  	_testcapir  r   r  r"   rK   )r   r/   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   r8   r   r   r  ra  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   r8   rI   rJ   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   TrP   rQ   )r   r8   rI   rJ   r9   r   rT   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   r)  r/  r1  r2  r   r8   r4  r   r  r@  rD  r  r  r   r   r  rJ  rO  r  r  rb  rf  ro  rp  rz  r{  r    r  r  r  r  r  r  r  r  r  r  rI   r  r  r  r   r  r  r  r  r  r*  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r#  r.  r8  rD  r~  st_devrE  r   Zrequires_mac_verrI  rJ  rP  rU  rW  rX  rY  r[  re  rg  ri  cpython_onlyrn  ru  ry  r|  r  r  r  r  r  r  r  __classcell__r   r   r&  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wShowWindowrH   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  rH   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  )r6   r7   r  r   handle_list)r   r  r  r  ZSW_HIDEr  rn  r   rp  r   r>  r8   rk   r   rK   r   r  Z	hStdInputZ
hStdOutputZ	hStdErrorlpAttributeList)r   r  rD  r6  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  )rI   r7   rt   r   rH   rJ   )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
   rE   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   )dictrS   r   r   r8   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
   rE   T)rV  rF   rG   rL   r   r   r   rD    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))Fr'  )r6   r7   rV  s   OSErrorr  )r6   r7   r  rV  z.*overriding close_fds)r  r   r  rs   r=   r@  ro  Zget_osfhandler   r8   rI   rJ   rh  r9   r   rK   r   rN  r2  rc   r  r  r   rb  r  )
r   r  r  rx  r  r?   r6   r7   r  r  r   r   r   test_close_fds_with_stdio  sd   





"z.Win32ProcessTestCase.test_close_fds_with_stdioc                 C   s    t  }i |_t jt|d d S )Nr  r   r  r  rH   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   rx  r   r  s   physalis	r   r   r   r   r8   r9   rc   r6   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    q1 s/w   Y  qd S )N)ansiZoemr  r   rx  r   )r   r6   r   r_  r  )r   encr   r?   r   r   r   test_shell_encodingsi  s   
z)Win32ProcessTestCase.test_shell_encodingsc                 C   s    t tjd }| |d d S )Nz -c "import sys; sys.exit(47)"rF   rG   rL   r   r   r   r  u  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)
                             r4   r   r  r   )r   r8   rI   rJ   r9   r6   r   r  r   rK   r"   rI  )r   r  r/   r?   rD  r7   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)
                             r4   r   r  rt  )r   r8   rI   rJ   r9   r6   r   r  r  r  r   rK   r"   )r   r  r/   r?   rD  r7   rM   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  rD  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   )r$  r   instances_createdro  r.   r&  r   r   r     s   z!MiscTests.RecordingPopen.__init__)r(   r)   r*   r  r   r  r   r   r&  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_waitr8   r
   zLimport time
time.sleep(9)
import sys
sys.stderr.write('\n!runaway child!\n')r6   r   rQ   z.no open-ended wait() after the first allowed: g      ?r  r  )KeyboardInterruptr;  r   r  r  r   r8   r  rS   rI   rJ   r  Zcall_args_listrI  rH   ro  ZassertLessEqualZ
call_countrK   rC  r  rv  r  r"   )r   ZpopenerZmock__communicater0   Z
mock__waitrH   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㥛 @rQ   )r  r   rH   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   r8   r  )r/   r0   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  Zfooztype zcat r   )rK   r   	getoutputgetstatusoutputrq   rm  r   r   r   r    rI  rmdir)r   dirr  r  re   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>   rZ  r  Handler  r  r   rD  )rx  r   __all__r  __dict__itemsr*  r^  
ModuleTyper?  rK   )r   Zintentionally_excludedZexportedZpossible_exportsr  r  r  r   r   r   test__all__  s   

zMiscTests.test__all__N)r(   r)   r*   r   r8   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SelectSelectorr3   r   r   r   r   r   r      s   zProcessTestCaseNoPoll.setUpc                 C   s   | j t_t|  d S r   )r  r   r  r3   r&   r   r   r   r   r&   %  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])))	r$  r   rq   r  r  r  r   rt   r=   )r   r  r  r&  r   r   r   -  s
   

zCommandsWithSpaces.setUpc                    s   t | j t   d S r   )r   r  r  r$  r&   r   r&  r   r   r&   6  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 )Nr6   mbcsz2 [%r, 'ab cd'])r   r9   r8   rK   r6   r   r   r  )r   r/   r0   r?   r   r   r   with_spaces:  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  rI   rJ   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   r&  r   r  *  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   r8   rI   rJ   r9   rK   r6   r   r7   rG  rH  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   r8   rI   rJ   rK   r   r  r   r   r   r  e  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')ro   s   contextr   r	  r  r   r   r   r9  l  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   )rS   r   r   r8   r   r9   r  r   r   r   r   t  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  )r5   rA   r  r   )r   r8   r   r9   r   rM  	__enter__r5   rt   r  r   rS   rs  __exit__rK   rG  rH  r  r   r   r   test_broken_pipe_cleanup{  s   z,ContextManagerTests.test_broken_pipe_cleanupN)r(   r)   r*   r  r  r9  r   r  r   r   r   r   r  V  s    r  __main__)Dr  r   r  r   Ztest.supportr   r   r   r   rI   r  r;   r  r   rt  rq   r  r  r  r  r  r7  r   r  r  rZ  rv  r  Ztest.support.os_helperr   r  r  rZ  r  r  ZPGOr   r  r    rT  r   r   NotADirectoryErrorr]  r   rJ   r   r   ZTestCaser   	Exceptionr+   r8   r,   r3   r  r"  r  r#  r  r  r  r  r  r  r  r(   mainr   r   r   r   <module>   s    



            0
            
 ~d
+
6