blob: 00dc37bc2c729a32c5d19c2c26fc7ff9527300da [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00002from unittest import mock
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
Gregory P. Smith50e16e32017-01-22 17:28:38 -08006import platform
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04008import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Charles-François Natali3a4586a2013-11-08 19:56:59 +010013import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000015import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040016import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020017import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050018import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030019import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050020
21try:
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080022 import ctypes
23except ImportError:
24 ctypes = None
Gregory P. Smith56bc3b72017-05-23 07:49:13 -070025else:
26 import ctypes.util
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080027
28try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020029 import _testcapi
30except ImportError:
31 _testcapi = None
32
Steve Dower22d06982016-09-06 19:38:15 -070033if support.PGO:
34 raise unittest.SkipTest("test is not helpful for PGO")
35
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000036mswindows = (sys.platform == "win32")
37
38#
39# Depends on the following external programs: Python
40#
41
42if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000043 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
44 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000045else:
46 SETBINARY = ''
47
Victor Stinner9a83f652017-08-21 23:51:31 +020048NONEXISTING_CMD = ('nonexisting_i_hope',)
49
Florent Xiclunab1e94e82010-02-27 22:12:37 +000050
Florent Xiclunac049d872010-03-27 22:47:23 +000051class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000052 def setUp(self):
53 # Try to minimize the number of children we have so this test
54 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000055 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000056
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000057 def tearDown(self):
58 for inst in subprocess._active:
59 inst.wait()
60 subprocess._cleanup()
61 self.assertFalse(subprocess._active, "subprocess._active not empty")
Victor Stinnercc42c122017-07-28 18:00:22 +020062 self.doCleanups()
63 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000064
Florent Xiclunab1e94e82010-02-27 22:12:37 +000065 def assertStderrEqual(self, stderr, expected, msg=None):
66 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
67 # shutdown time. That frustrates tests trying to check stderr produced
68 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000069 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040070 # strip_python_stderr also strips whitespace, so we do too.
71 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000072 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073
Florent Xiclunac049d872010-03-27 22:47:23 +000074
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080075class PopenTestException(Exception):
76 pass
77
78
79class PopenExecuteChildRaises(subprocess.Popen):
80 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
81 _execute_child fails.
82 """
83 def _execute_child(self, *args, **kwargs):
84 raise PopenTestException("Forced Exception for Test")
85
86
Florent Xiclunac049d872010-03-27 22:47:23 +000087class ProcessTestCase(BaseTestCase):
88
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070089 def test_io_buffered_by_default(self):
90 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
91 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
92 stderr=subprocess.PIPE)
93 try:
94 self.assertIsInstance(p.stdin, io.BufferedIOBase)
95 self.assertIsInstance(p.stdout, io.BufferedIOBase)
96 self.assertIsInstance(p.stderr, io.BufferedIOBase)
97 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070098 p.stdin.close()
99 p.stdout.close()
100 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700101 p.wait()
102
103 def test_io_unbuffered_works(self):
104 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
105 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
106 stderr=subprocess.PIPE, bufsize=0)
107 try:
108 self.assertIsInstance(p.stdin, io.RawIOBase)
109 self.assertIsInstance(p.stdout, io.RawIOBase)
110 self.assertIsInstance(p.stderr, io.RawIOBase)
111 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700112 p.stdin.close()
113 p.stdout.close()
114 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700115 p.wait()
116
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000117 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000118 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000119 rc = subprocess.call([sys.executable, "-c",
120 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000121 self.assertEqual(rc, 47)
122
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400123 def test_call_timeout(self):
124 # call() function with timeout argument; we want to test that the child
125 # process gets killed when the timeout expires. If the child isn't
126 # killed, this call will deadlock since subprocess.call waits for the
127 # child.
128 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
129 [sys.executable, "-c", "while True: pass"],
130 timeout=0.1)
131
Peter Astrand454f7672005-01-01 09:36:35 +0000132 def test_check_call_zero(self):
133 # check_call() function with zero return code
134 rc = subprocess.check_call([sys.executable, "-c",
135 "import sys; sys.exit(0)"])
136 self.assertEqual(rc, 0)
137
138 def test_check_call_nonzero(self):
139 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000140 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000141 subprocess.check_call([sys.executable, "-c",
142 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000143 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000144
Georg Brandlf9734072008-12-07 15:30:06 +0000145 def test_check_output(self):
146 # check_output() function with zero return code
147 output = subprocess.check_output(
148 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000149 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000150
151 def test_check_output_nonzero(self):
152 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000153 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000154 subprocess.check_output(
155 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000156 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000157
158 def test_check_output_stderr(self):
159 # check_output() function stderr redirected to stdout
160 output = subprocess.check_output(
161 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
162 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000163 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000164
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300165 def test_check_output_stdin_arg(self):
166 # check_output() can be called with stdin set to a file
167 tf = tempfile.TemporaryFile()
168 self.addCleanup(tf.close)
169 tf.write(b'pear')
170 tf.seek(0)
171 output = subprocess.check_output(
172 [sys.executable, "-c",
173 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
174 stdin=tf)
175 self.assertIn(b'PEAR', output)
176
177 def test_check_output_input_arg(self):
178 # check_output() can be called with input set to a string
179 output = subprocess.check_output(
180 [sys.executable, "-c",
181 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
182 input=b'pear')
183 self.assertIn(b'PEAR', output)
184
Georg Brandlf9734072008-12-07 15:30:06 +0000185 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300186 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000187 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000188 output = subprocess.check_output(
189 [sys.executable, "-c", "print('will not be run')"],
190 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000191 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000192 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000193
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300194 def test_check_output_stdin_with_input_arg(self):
195 # check_output() refuses to accept 'stdin' with 'input'
196 tf = tempfile.TemporaryFile()
197 self.addCleanup(tf.close)
198 tf.write(b'pear')
199 tf.seek(0)
200 with self.assertRaises(ValueError) as c:
201 output = subprocess.check_output(
202 [sys.executable, "-c", "print('will not be run')"],
203 stdin=tf, input=b'hare')
204 self.fail("Expected ValueError when stdin and input args supplied.")
205 self.assertIn('stdin', c.exception.args[0])
206 self.assertIn('input', c.exception.args[0])
207
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400208 def test_check_output_timeout(self):
209 # check_output() function with timeout arg
210 with self.assertRaises(subprocess.TimeoutExpired) as c:
211 output = subprocess.check_output(
212 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200213 "import sys, time\n"
214 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400215 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200216 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400217 # Some heavily loaded buildbots (sparc Debian 3.x) require
218 # this much time to start and print.
219 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400220 self.fail("Expected TimeoutExpired.")
221 self.assertEqual(c.exception.output, b'BDFL')
222
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000224 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000225 newenv = os.environ.copy()
226 newenv["FRUIT"] = "banana"
227 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000228 'import sys, os;'
229 'sys.exit(os.getenv("FRUIT")=="banana")'],
230 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000231 self.assertEqual(rc, 1)
232
Victor Stinner87b9bc32011-06-01 00:57:47 +0200233 def test_invalid_args(self):
234 # Popen() called with invalid arguments should raise TypeError
235 # but Popen.__del__ should not complain (issue #12085)
236 with support.captured_stderr() as s:
237 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
238 argcount = subprocess.Popen.__init__.__code__.co_argcount
239 too_many_args = [0] * (argcount + 1)
240 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
241 self.assertEqual(s.getvalue(), '')
242
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000243 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000244 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000245 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000246 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000247 self.addCleanup(p.stdout.close)
248 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000249 p.wait()
250 self.assertEqual(p.stdin, None)
251
252 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200253 # .stdout is None when not redirected, and the child's stdout will
254 # be inherited from the parent. In order to test this we run a
255 # subprocess in a subprocess:
256 # this_test
257 # \-- subprocess created by this test (parent)
258 # \-- subprocess created by the parent subprocess (child)
259 # The parent doesn't specify stdout, so the child will use the
260 # parent's stdout. This test checks that the message printed by the
261 # child goes to the parent stdout. The parent also checks that the
262 # child's stdout is None. See #11963.
263 code = ('import sys; from subprocess import Popen, PIPE;'
264 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
265 ' stdin=PIPE, stderr=PIPE);'
266 'p.wait(); assert p.stdout is None;')
267 p = subprocess.Popen([sys.executable, "-c", code],
268 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
269 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000270 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200271 out, err = p.communicate()
272 self.assertEqual(p.returncode, 0, err)
273 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274
275 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000276 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000277 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000278 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000279 self.addCleanup(p.stdout.close)
280 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281 p.wait()
282 self.assertEqual(p.stderr, None)
283
Chris Jerdonek776cb192012-10-08 15:56:43 -0700284 def _assert_python(self, pre_args, **kwargs):
285 # We include sys.exit() to prevent the test runner from hanging
286 # whenever python is found.
287 args = pre_args + ["import sys; sys.exit(47)"]
288 p = subprocess.Popen(args, **kwargs)
289 p.wait()
290 self.assertEqual(47, p.returncode)
291
292 def test_executable(self):
293 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700294 #
295 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
296 # determine where its standard library is, so we need the directory
297 # of args[0] to be valid for the Popen() call to Python to succeed.
298 # See also issue #16170 and issue #7774.
299 doesnotexist = os.path.join(os.path.dirname(sys.executable),
300 "doesnotexist")
301 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700302
303 def test_executable_takes_precedence(self):
304 # Check that the executable argument takes precedence over args[0].
305 #
306 # Verify first that the call succeeds without the executable arg.
307 pre_args = [sys.executable, "-c"]
308 self._assert_python(pre_args)
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100309 self.assertRaises((FileNotFoundError, PermissionError),
310 self._assert_python, pre_args,
Chris Jerdonek776cb192012-10-08 15:56:43 -0700311 executable="doesnotexist")
312
313 @unittest.skipIf(mswindows, "executable argument replaces shell")
314 def test_executable_replaces_shell(self):
315 # Check that the executable argument replaces the default shell
316 # when shell=True.
317 self._assert_python([], executable=sys.executable, shell=True)
318
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700319 # For use in the test_cwd* tests below.
320 def _normalize_cwd(self, cwd):
321 # Normalize an expected cwd (for Tru64 support).
322 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
323 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300324 with support.change_cwd(cwd):
325 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700326
327 # For use in the test_cwd* tests below.
328 def _split_python_path(self):
329 # Return normalized (python_dir, python_base).
330 python_path = os.path.realpath(sys.executable)
331 return os.path.split(python_path)
332
333 # For use in the test_cwd* tests below.
334 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
335 # Invoke Python via Popen, and assert that (1) the call succeeds,
336 # and that (2) the current working directory of the child process
337 # matches *expected_cwd*.
338 p = subprocess.Popen([python_arg, "-c",
339 "import os, sys; "
340 "sys.stdout.write(os.getcwd()); "
341 "sys.exit(47)"],
342 stdout=subprocess.PIPE,
343 **kwargs)
344 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000345 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700346 self.assertEqual(47, p.returncode)
347 normcase = os.path.normcase
348 self.assertEqual(normcase(expected_cwd),
349 normcase(p.stdout.read().decode("utf-8")))
350
351 def test_cwd(self):
352 # Check that cwd changes the cwd for the child process.
353 temp_dir = tempfile.gettempdir()
354 temp_dir = self._normalize_cwd(temp_dir)
355 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
356
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530357 def test_cwd_with_pathlike(self):
358 temp_dir = tempfile.gettempdir()
359 temp_dir = self._normalize_cwd(temp_dir)
360
361 class _PathLikeObj:
362 def __fspath__(self):
363 return temp_dir
364
365 self._assert_cwd(temp_dir, sys.executable, cwd=_PathLikeObj())
366
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700367 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700368 def test_cwd_with_relative_arg(self):
369 # Check that Popen looks for args[0] relative to cwd if args[0]
370 # is relative.
371 python_dir, python_base = self._split_python_path()
372 rel_python = os.path.join(os.curdir, python_base)
373 with support.temp_cwd() as wrong_dir:
374 # Before calling with the correct cwd, confirm that the call fails
375 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700376 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700377 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700378 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700379 [rel_python], cwd=wrong_dir)
380 python_dir = self._normalize_cwd(python_dir)
381 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
382
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700383 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700384 def test_cwd_with_relative_executable(self):
385 # Check that Popen looks for executable relative to cwd if executable
386 # is relative (and that executable takes precedence over args[0]).
387 python_dir, python_base = self._split_python_path()
388 rel_python = os.path.join(os.curdir, python_base)
389 doesntexist = "somethingyoudonthave"
390 with support.temp_cwd() as wrong_dir:
391 # Before calling with the correct cwd, confirm that the call fails
392 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700393 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700394 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700395 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700396 [doesntexist], executable=rel_python,
397 cwd=wrong_dir)
398 python_dir = self._normalize_cwd(python_dir)
399 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
400 cwd=python_dir)
401
402 def test_cwd_with_absolute_arg(self):
403 # Check that Popen can find the executable when the cwd is wrong
404 # if args[0] is an absolute path.
405 python_dir, python_base = self._split_python_path()
406 abs_python = os.path.join(python_dir, python_base)
407 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300408 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700409 # Before calling with an absolute path, confirm that using a
410 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700411 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700412 [rel_python], cwd=wrong_dir)
413 wrong_dir = self._normalize_cwd(wrong_dir)
414 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
415
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100416 @unittest.skipIf(sys.base_prefix != sys.prefix,
417 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000418 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700419 python_dir, python_base = self._split_python_path()
420 python_dir = self._normalize_cwd(python_dir)
421 self._assert_cwd(python_dir, "somethingyoudonthave",
422 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000423
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100424 @unittest.skipIf(sys.base_prefix != sys.prefix,
425 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000426 @unittest.skipIf(sysconfig.is_python_build(),
427 "need an installed Python. See #7774")
428 def test_executable_without_cwd(self):
429 # For a normal installation, it should work without 'cwd'
430 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700431 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
432 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433
434 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000435 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000436 p = subprocess.Popen([sys.executable, "-c",
437 'import sys; sys.exit(sys.stdin.read() == "pear")'],
438 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000439 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000440 p.stdin.close()
441 p.wait()
442 self.assertEqual(p.returncode, 1)
443
444 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000445 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000446 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000447 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000448 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000449 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000450 os.lseek(d, 0, 0)
451 p = subprocess.Popen([sys.executable, "-c",
452 'import sys; sys.exit(sys.stdin.read() == "pear")'],
453 stdin=d)
454 p.wait()
455 self.assertEqual(p.returncode, 1)
456
457 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000458 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000460 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000461 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000462 tf.seek(0)
463 p = subprocess.Popen([sys.executable, "-c",
464 'import sys; sys.exit(sys.stdin.read() == "pear")'],
465 stdin=tf)
466 p.wait()
467 self.assertEqual(p.returncode, 1)
468
469 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000470 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471 p = subprocess.Popen([sys.executable, "-c",
472 'import sys; sys.stdout.write("orange")'],
473 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200474 with p:
475 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476
477 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000478 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000479 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000480 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481 d = tf.fileno()
482 p = subprocess.Popen([sys.executable, "-c",
483 'import sys; sys.stdout.write("orange")'],
484 stdout=d)
485 p.wait()
486 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000487 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488
489 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000490 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000491 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000492 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000493 p = subprocess.Popen([sys.executable, "-c",
494 'import sys; sys.stdout.write("orange")'],
495 stdout=tf)
496 p.wait()
497 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000498 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000499
500 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000501 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502 p = subprocess.Popen([sys.executable, "-c",
503 'import sys; sys.stderr.write("strawberry")'],
504 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200505 with p:
506 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507
508 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000509 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000510 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000511 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 d = tf.fileno()
513 p = subprocess.Popen([sys.executable, "-c",
514 'import sys; sys.stderr.write("strawberry")'],
515 stderr=d)
516 p.wait()
517 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000518 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000519
520 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000521 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000522 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000523 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000524 p = subprocess.Popen([sys.executable, "-c",
525 'import sys; sys.stderr.write("strawberry")'],
526 stderr=tf)
527 p.wait()
528 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000529 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530
Martin Panterc7635892016-05-13 01:54:44 +0000531 def test_stderr_redirect_with_no_stdout_redirect(self):
532 # test stderr=STDOUT while stdout=None (not set)
533
534 # - grandchild prints to stderr
535 # - child redirects grandchild's stderr to its stdout
536 # - the parent should get grandchild's stderr in child's stdout
537 p = subprocess.Popen([sys.executable, "-c",
538 'import sys, subprocess;'
539 'rc = subprocess.call([sys.executable, "-c",'
540 ' "import sys;"'
541 ' "sys.stderr.write(\'42\')"],'
542 ' stderr=subprocess.STDOUT);'
543 'sys.exit(rc)'],
544 stdout=subprocess.PIPE,
545 stderr=subprocess.PIPE)
546 stdout, stderr = p.communicate()
547 #NOTE: stdout should get stderr from grandchild
548 self.assertStderrEqual(stdout, b'42')
549 self.assertStderrEqual(stderr, b'') # should be empty
550 self.assertEqual(p.returncode, 0)
551
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000552 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000553 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000555 'import sys;'
556 'sys.stdout.write("apple");'
557 'sys.stdout.flush();'
558 'sys.stderr.write("orange")'],
559 stdout=subprocess.PIPE,
560 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200561 with p:
562 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563
564 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000565 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000566 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000567 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000569 'import sys;'
570 'sys.stdout.write("apple");'
571 'sys.stdout.flush();'
572 'sys.stderr.write("orange")'],
573 stdout=tf,
574 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000575 p.wait()
576 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000577 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578
Thomas Wouters89f507f2006-12-13 04:49:30 +0000579 def test_stdout_filedes_of_stdout(self):
580 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200581 # To avoid printing the text on stdout, we do something similar to
582 # test_stdout_none (see above). The parent subprocess calls the child
583 # subprocess passing stdout=1, and this test uses stdout=PIPE in
584 # order to capture and check the output of the parent. See #11963.
585 code = ('import sys, subprocess; '
586 'rc = subprocess.call([sys.executable, "-c", '
587 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
588 'b\'test with stdout=1\'))"], stdout=1); '
589 'assert rc == 18')
590 p = subprocess.Popen([sys.executable, "-c", code],
591 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
592 self.addCleanup(p.stdout.close)
593 self.addCleanup(p.stderr.close)
594 out, err = p.communicate()
595 self.assertEqual(p.returncode, 0, err)
596 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000597
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200598 def test_stdout_devnull(self):
599 p = subprocess.Popen([sys.executable, "-c",
600 'for i in range(10240):'
601 'print("x" * 1024)'],
602 stdout=subprocess.DEVNULL)
603 p.wait()
604 self.assertEqual(p.stdout, None)
605
606 def test_stderr_devnull(self):
607 p = subprocess.Popen([sys.executable, "-c",
608 'import sys\n'
609 'for i in range(10240):'
610 'sys.stderr.write("x" * 1024)'],
611 stderr=subprocess.DEVNULL)
612 p.wait()
613 self.assertEqual(p.stderr, None)
614
615 def test_stdin_devnull(self):
616 p = subprocess.Popen([sys.executable, "-c",
617 'import sys;'
618 'sys.stdin.read(1)'],
619 stdin=subprocess.DEVNULL)
620 p.wait()
621 self.assertEqual(p.stdin, None)
622
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000623 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624 newenv = os.environ.copy()
625 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200626 with subprocess.Popen([sys.executable, "-c",
627 'import sys,os;'
628 'sys.stdout.write(os.getenv("FRUIT"))'],
629 stdout=subprocess.PIPE,
630 env=newenv) as p:
631 stdout, stderr = p.communicate()
632 self.assertEqual(stdout, b"orange")
633
Victor Stinner62d51182011-06-23 01:02:25 +0200634 # Windows requires at least the SYSTEMROOT environment variable to start
635 # Python
636 @unittest.skipIf(sys.platform == 'win32',
637 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700638 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
639 'The Python shared library cannot be loaded '
640 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200641 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700642 """Verify that env={} is as empty as possible."""
643
Gregory P. Smith85aba232017-05-30 16:21:47 -0700644 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700645 """Determine if an environment variable is under our control."""
646 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
647 # on adding even when the environment in exec is empty.
648 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700649 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400650 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000651 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
652 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700653
Victor Stinnerf1512a22011-06-21 17:18:38 +0200654 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700655 'import os; print(list(os.environ.keys()))'],
656 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200657 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700658 child_env_names = eval(stdout.strip())
659 self.assertIsInstance(child_env_names, list)
660 child_env_names = [k for k in child_env_names
661 if not is_env_var_to_ignore(k)]
662 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663
Serhiy Storchakad174d242017-06-23 19:39:27 +0300664 def test_invalid_cmd(self):
665 # null character in the command name
666 cmd = sys.executable + '\0'
667 with self.assertRaises(ValueError):
668 subprocess.Popen([cmd, "-c", "pass"])
669
670 # null character in the command argument
671 with self.assertRaises(ValueError):
672 subprocess.Popen([sys.executable, "-c", "pass#\0"])
673
674 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300675 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300676 newenv = os.environ.copy()
677 newenv["FRUIT\0VEGETABLE"] = "cabbage"
678 with self.assertRaises(ValueError):
679 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
680
Ville Skyttä49b27342017-08-03 09:00:59 +0300681 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300682 newenv = os.environ.copy()
683 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
684 with self.assertRaises(ValueError):
685 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
686
Ville Skyttä49b27342017-08-03 09:00:59 +0300687 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300688 newenv = os.environ.copy()
689 newenv["FRUIT=ORANGE"] = "lemon"
690 with self.assertRaises(ValueError):
691 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
692
Ville Skyttä49b27342017-08-03 09:00:59 +0300693 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300694 newenv = os.environ.copy()
695 newenv["FRUIT"] = "orange=lemon"
696 with subprocess.Popen([sys.executable, "-c",
697 'import sys, os;'
698 'sys.stdout.write(os.getenv("FRUIT"))'],
699 stdout=subprocess.PIPE,
700 env=newenv) as p:
701 stdout, stderr = p.communicate()
702 self.assertEqual(stdout, b"orange=lemon")
703
Peter Astrandcbac93c2005-03-03 20:24:28 +0000704 def test_communicate_stdin(self):
705 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000706 'import sys;'
707 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000708 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000709 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000710 self.assertEqual(p.returncode, 1)
711
712 def test_communicate_stdout(self):
713 p = subprocess.Popen([sys.executable, "-c",
714 'import sys; sys.stdout.write("pineapple")'],
715 stdout=subprocess.PIPE)
716 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000717 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000718 self.assertEqual(stderr, None)
719
720 def test_communicate_stderr(self):
721 p = subprocess.Popen([sys.executable, "-c",
722 'import sys; sys.stderr.write("pineapple")'],
723 stderr=subprocess.PIPE)
724 (stdout, stderr) = p.communicate()
725 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000726 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000727
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000728 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000729 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000730 'import sys,os;'
731 'sys.stderr.write("pineapple");'
732 'sys.stdout.write(sys.stdin.read())'],
733 stdin=subprocess.PIPE,
734 stdout=subprocess.PIPE,
735 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000736 self.addCleanup(p.stdout.close)
737 self.addCleanup(p.stderr.close)
738 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000739 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000740 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000741 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000742
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400743 def test_communicate_timeout(self):
744 p = subprocess.Popen([sys.executable, "-c",
745 'import sys,os,time;'
746 'sys.stderr.write("pineapple\\n");'
747 'time.sleep(1);'
748 'sys.stderr.write("pear\\n");'
749 'sys.stdout.write(sys.stdin.read())'],
750 universal_newlines=True,
751 stdin=subprocess.PIPE,
752 stdout=subprocess.PIPE,
753 stderr=subprocess.PIPE)
754 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
755 timeout=0.3)
756 # Make sure we can keep waiting for it, and that we get the whole output
757 # after it completes.
758 (stdout, stderr) = p.communicate()
759 self.assertEqual(stdout, "banana")
760 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
761
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700762 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200763 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400764 p = subprocess.Popen([sys.executable, "-c",
765 'import sys,os,time;'
766 'sys.stdout.write("a" * (64 * 1024));'
767 'time.sleep(0.2);'
768 'sys.stdout.write("a" * (64 * 1024));'
769 'time.sleep(0.2);'
770 'sys.stdout.write("a" * (64 * 1024));'
771 'time.sleep(0.2);'
772 'sys.stdout.write("a" * (64 * 1024));'],
773 stdout=subprocess.PIPE)
774 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
775 (stdout, _) = p.communicate()
776 self.assertEqual(len(stdout), 4 * 64 * 1024)
777
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000778 # Test for the fd leak reported in http://bugs.python.org/issue2791.
779 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000780 for stdin_pipe in (False, True):
781 for stdout_pipe in (False, True):
782 for stderr_pipe in (False, True):
783 options = {}
784 if stdin_pipe:
785 options['stdin'] = subprocess.PIPE
786 if stdout_pipe:
787 options['stdout'] = subprocess.PIPE
788 if stderr_pipe:
789 options['stderr'] = subprocess.PIPE
790 if not options:
791 continue
792 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
793 p.communicate()
794 if p.stdin is not None:
795 self.assertTrue(p.stdin.closed)
796 if p.stdout is not None:
797 self.assertTrue(p.stdout.closed)
798 if p.stderr is not None:
799 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000800
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000801 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000802 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000803 p = subprocess.Popen([sys.executable, "-c",
804 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000805 (stdout, stderr) = p.communicate()
806 self.assertEqual(stdout, None)
807 self.assertEqual(stderr, None)
808
809 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000810 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000811 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000812 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000813 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000814 os.close(x)
815 os.close(y)
816 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000817 'import sys,os;'
818 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200819 'sys.stderr.write("x" * %d);'
820 'sys.stdout.write(sys.stdin.read())' %
821 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000822 stdin=subprocess.PIPE,
823 stdout=subprocess.PIPE,
824 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000825 self.addCleanup(p.stdout.close)
826 self.addCleanup(p.stderr.close)
827 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200828 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000829 (stdout, stderr) = p.communicate(string_to_write)
830 self.assertEqual(stdout, string_to_write)
831
832 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000833 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000834 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000835 'import sys,os;'
836 'sys.stdout.write(sys.stdin.read())'],
837 stdin=subprocess.PIPE,
838 stdout=subprocess.PIPE,
839 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000840 self.addCleanup(p.stdout.close)
841 self.addCleanup(p.stderr.close)
842 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000843 p.stdin.write(b"banana")
844 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000845 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000846 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000847
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000850 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200851 'buf = sys.stdout.buffer;'
852 'buf.write(sys.stdin.readline().encode());'
853 'buf.flush();'
854 'buf.write(b"line2\\n");'
855 'buf.flush();'
856 'buf.write(sys.stdin.read().encode());'
857 'buf.flush();'
858 'buf.write(b"line4\\n");'
859 'buf.flush();'
860 'buf.write(b"line5\\r\\n");'
861 'buf.flush();'
862 'buf.write(b"line6\\r");'
863 'buf.flush();'
864 'buf.write(b"\\nline7");'
865 'buf.flush();'
866 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200867 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000868 stdout=subprocess.PIPE,
869 universal_newlines=1)
Victor Stinner7438c612016-05-20 12:43:15 +0200870 with p:
871 p.stdin.write("line1\n")
872 p.stdin.flush()
873 self.assertEqual(p.stdout.readline(), "line1\n")
874 p.stdin.write("line3\n")
875 p.stdin.close()
876 self.addCleanup(p.stdout.close)
877 self.assertEqual(p.stdout.readline(),
878 "line2\n")
879 self.assertEqual(p.stdout.read(6),
880 "line3\n")
881 self.assertEqual(p.stdout.read(),
882 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000883
884 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000885 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000886 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000887 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200888 'buf = sys.stdout.buffer;'
889 'buf.write(b"line2\\n");'
890 'buf.flush();'
891 'buf.write(b"line4\\n");'
892 'buf.flush();'
893 'buf.write(b"line5\\r\\n");'
894 'buf.flush();'
895 'buf.write(b"line6\\r");'
896 'buf.flush();'
897 'buf.write(b"\\nline7");'
898 'buf.flush();'
899 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200900 stderr=subprocess.PIPE,
901 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000902 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000903 self.addCleanup(p.stdout.close)
904 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000905 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200906 self.assertEqual(stdout,
907 "line2\nline4\nline5\nline6\nline7\nline8")
908
909 def test_universal_newlines_communicate_stdin(self):
910 # universal newlines through communicate(), with only stdin
911 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300912 'import sys,os;' + SETBINARY + textwrap.dedent('''
913 s = sys.stdin.readline()
914 assert s == "line1\\n", repr(s)
915 s = sys.stdin.read()
916 assert s == "line3\\n", repr(s)
917 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200918 stdin=subprocess.PIPE,
919 universal_newlines=1)
920 (stdout, stderr) = p.communicate("line1\nline3\n")
921 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000922
Andrew Svetlovf3765072012-08-14 18:35:17 +0300923 def test_universal_newlines_communicate_input_none(self):
924 # Test communicate(input=None) with universal newlines.
925 #
926 # We set stdout to PIPE because, as of this writing, a different
927 # code path is tested when the number of pipes is zero or one.
928 p = subprocess.Popen([sys.executable, "-c", "pass"],
929 stdin=subprocess.PIPE,
930 stdout=subprocess.PIPE,
931 universal_newlines=True)
932 p.communicate()
933 self.assertEqual(p.returncode, 0)
934
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300935 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300936 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300937 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300938 'import sys,os;' + SETBINARY + textwrap.dedent('''
939 s = sys.stdin.buffer.readline()
940 sys.stdout.buffer.write(s)
941 sys.stdout.buffer.write(b"line2\\r")
942 sys.stderr.buffer.write(b"eline2\\n")
943 s = sys.stdin.buffer.read()
944 sys.stdout.buffer.write(s)
945 sys.stdout.buffer.write(b"line4\\n")
946 sys.stdout.buffer.write(b"line5\\r\\n")
947 sys.stderr.buffer.write(b"eline6\\r")
948 sys.stderr.buffer.write(b"eline7\\r\\nz")
949 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300950 stdin=subprocess.PIPE,
951 stderr=subprocess.PIPE,
952 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300953 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300954 self.addCleanup(p.stdout.close)
955 self.addCleanup(p.stderr.close)
956 (stdout, stderr) = p.communicate("line1\nline3\n")
957 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300958 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300959 # Python debug build push something like "[42442 refs]\n"
960 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300961 # Don't use assertStderrEqual because it strips CR and LF from output.
962 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300963
Andrew Svetlov82860712012-08-19 22:13:41 +0300964 def test_universal_newlines_communicate_encodings(self):
965 # Check that universal newlines mode works for various encodings,
966 # in particular for encodings in the UTF-16 and UTF-32 families.
967 # See issue #15595.
968 #
969 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
970 # without, and UTF-16 and UTF-32.
971 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300972 code = ("import sys; "
973 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
974 encoding)
975 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700976 # We set stdin to be non-None because, as of this writing,
977 # a different code path is used when the number of pipes is
978 # zero or one.
979 popen = subprocess.Popen(args,
980 stdin=subprocess.PIPE,
981 stdout=subprocess.PIPE,
982 encoding=encoding)
983 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +0300984 self.assertEqual(stdout, '1\n2\n3\n4')
985
Steve Dower050acae2016-09-06 20:16:17 -0700986 def test_communicate_errors(self):
987 for errors, expected in [
988 ('ignore', ''),
989 ('replace', '\ufffd\ufffd'),
990 ('surrogateescape', '\udc80\udc80'),
991 ('backslashreplace', '\\x80\\x80'),
992 ]:
993 code = ("import sys; "
994 r"sys.stdout.buffer.write(b'[\x80\x80]')")
995 args = [sys.executable, '-c', code]
996 # We set stdin to be non-None because, as of this writing,
997 # a different code path is used when the number of pipes is
998 # zero or one.
999 popen = subprocess.Popen(args,
1000 stdin=subprocess.PIPE,
1001 stdout=subprocess.PIPE,
1002 encoding='utf-8',
1003 errors=errors)
1004 stdout, stderr = popen.communicate(input='')
1005 self.assertEqual(stdout, '[{}]'.format(expected))
1006
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001007 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001008 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +00001009 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001010 max_handles = 1026 # too much for most UNIX systems
1011 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001012 max_handles = 2050 # too much for (at least some) Windows setups
1013 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001014 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001015 try:
1016 for i in range(max_handles):
1017 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001018 tmpfile = os.path.join(tmpdir, support.TESTFN)
1019 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001020 except OSError as e:
1021 if e.errno != errno.EMFILE:
1022 raise
1023 break
1024 else:
1025 self.skipTest("failed to reach the file descriptor limit "
1026 "(tried %d)" % max_handles)
1027 # Close a couple of them (should be enough for a subprocess)
1028 for i in range(10):
1029 os.close(handles.pop())
1030 # Loop creating some subprocesses. If one of them leaks some fds,
1031 # the next loop iteration will fail by reaching the max fd limit.
1032 for i in range(15):
1033 p = subprocess.Popen([sys.executable, "-c",
1034 "import sys;"
1035 "sys.stdout.write(sys.stdin.read())"],
1036 stdin=subprocess.PIPE,
1037 stdout=subprocess.PIPE,
1038 stderr=subprocess.PIPE)
1039 data = p.communicate(b"lime")[0]
1040 self.assertEqual(data, b"lime")
1041 finally:
1042 for h in handles:
1043 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001044 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001045
1046 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001047 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1048 '"a b c" d e')
1049 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1050 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001051 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1052 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001053 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1054 'a\\\\\\b "de fg" h')
1055 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1056 'a\\\\\\"b c d')
1057 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1058 '"a\\\\b c" d e')
1059 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1060 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001061 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1062 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001063
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001064 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001065 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001066 "import os; os.read(0, 1)"],
1067 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001068 self.addCleanup(p.stdin.close)
1069 self.assertIsNone(p.poll())
1070 os.write(p.stdin.fileno(), b'A')
1071 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001072 # Subsequent invocations should just return the returncode
1073 self.assertEqual(p.poll(), 0)
1074
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001075 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001076 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001077 self.assertEqual(p.wait(), 0)
1078 # Subsequent invocations should just return the returncode
1079 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001080
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001081 def test_wait_timeout(self):
1082 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001083 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001084 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001085 p.wait(timeout=0.0001)
1086 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001087 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1088 # time to start.
1089 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001090
Peter Astrand738131d2004-11-30 21:04:45 +00001091 def test_invalid_bufsize(self):
1092 # an invalid type of the bufsize argument should raise
1093 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001094 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001095 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001096
Guido van Rossum46a05a72007-06-07 21:56:45 +00001097 def test_bufsize_is_none(self):
1098 # bufsize=None should be the same as bufsize=0.
1099 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1100 self.assertEqual(p.wait(), 0)
1101 # Again with keyword arg
1102 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1103 self.assertEqual(p.wait(), 0)
1104
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001105 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1106 # subprocess may deadlock with bufsize=1, see issue #21332
1107 with subprocess.Popen([sys.executable, "-c", "import sys;"
1108 "sys.stdout.write(sys.stdin.readline());"
1109 "sys.stdout.flush()"],
1110 stdin=subprocess.PIPE,
1111 stdout=subprocess.PIPE,
1112 stderr=subprocess.DEVNULL,
1113 bufsize=1,
1114 universal_newlines=universal_newlines) as p:
1115 p.stdin.write(line) # expect that it flushes the line in text mode
1116 os.close(p.stdin.fileno()) # close it without flushing the buffer
1117 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001118 with support.SuppressCrashReport():
1119 try:
1120 p.stdin.close()
1121 except OSError:
1122 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001123 p.stdin = None
1124 self.assertEqual(p.returncode, 0)
1125 self.assertEqual(read_line, expected)
1126
1127 def test_bufsize_equal_one_text_mode(self):
1128 # line is flushed in text mode with bufsize=1.
1129 # we should get the full line in return
1130 line = "line\n"
1131 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1132
1133 def test_bufsize_equal_one_binary_mode(self):
1134 # line is not flushed in binary mode with bufsize=1.
1135 # we should get empty response
1136 line = b'line' + os.linesep.encode() # assume ascii-based locale
1137 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1138
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001139 def test_leaking_fds_on_error(self):
1140 # see bug #5179: Popen leaks file descriptors to PIPEs if
1141 # the child fails to execute; this will eventually exhaust
1142 # the maximum number of open fds. 1024 seems a very common
1143 # value for that limit, but Windows has 2048, so we loop
1144 # 1024 times (each call leaked two fds).
1145 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001146 with self.assertRaises(OSError) as c:
Victor Stinner9a83f652017-08-21 23:51:31 +02001147 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001148 stdout=subprocess.PIPE,
1149 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001150 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001151 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001152 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001153
Victor Stinner9a83f652017-08-21 23:51:31 +02001154 def test_nonexisting_with_pipes(self):
1155 # bpo-30121: Popen with pipes must close properly pipes on error.
1156 # Previously, os.close() was called with a Windows handle which is not
1157 # a valid file descriptor.
1158 #
1159 # Run the test in a subprocess to control how the CRT reports errors
1160 # and to get stderr content.
1161 try:
1162 import msvcrt
1163 msvcrt.CrtSetReportMode
1164 except (AttributeError, ImportError):
1165 self.skipTest("need msvcrt.CrtSetReportMode")
1166
1167 code = textwrap.dedent(f"""
1168 import msvcrt
1169 import subprocess
1170
1171 cmd = {NONEXISTING_CMD!r}
1172
1173 for report_type in [msvcrt.CRT_WARN,
1174 msvcrt.CRT_ERROR,
1175 msvcrt.CRT_ASSERT]:
1176 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1177 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1178
1179 try:
1180 subprocess.Popen([cmd],
1181 stdout=subprocess.PIPE,
1182 stderr=subprocess.PIPE)
1183 except OSError:
1184 pass
1185 """)
1186 cmd = [sys.executable, "-c", code]
1187 proc = subprocess.Popen(cmd,
1188 stderr=subprocess.PIPE,
1189 universal_newlines=True)
1190 with proc:
1191 stderr = proc.communicate()[1]
1192 self.assertEqual(stderr, "")
1193 self.assertEqual(proc.returncode, 0)
1194
Antoine Pitroua8392712013-08-30 23:38:13 +02001195 def test_double_close_on_error(self):
1196 # Issue #18851
1197 fds = []
1198 def open_fds():
1199 for i in range(20):
1200 fds.extend(os.pipe())
1201 time.sleep(0.001)
1202 t = threading.Thread(target=open_fds)
1203 t.start()
1204 try:
1205 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001206 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001207 stdin=subprocess.PIPE,
1208 stdout=subprocess.PIPE,
1209 stderr=subprocess.PIPE)
1210 finally:
1211 t.join()
1212 exc = None
1213 for fd in fds:
1214 # If a double close occurred, some of those fds will
1215 # already have been closed by mistake, and os.close()
1216 # here will raise.
1217 try:
1218 os.close(fd)
1219 except OSError as e:
1220 exc = e
1221 if exc is not None:
1222 raise exc
1223
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001224 def test_threadsafe_wait(self):
1225 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1226 proc = subprocess.Popen([sys.executable, '-c',
1227 'import time; time.sleep(12)'])
1228 self.assertEqual(proc.returncode, None)
1229 results = []
1230
1231 def kill_proc_timer_thread():
1232 results.append(('thread-start-poll-result', proc.poll()))
1233 # terminate it from the thread and wait for the result.
1234 proc.kill()
1235 proc.wait()
1236 results.append(('thread-after-kill-and-wait', proc.returncode))
1237 # this wait should be a no-op given the above.
1238 proc.wait()
1239 results.append(('thread-after-second-wait', proc.returncode))
1240
1241 # This is a timing sensitive test, the failure mode is
1242 # triggered when both the main thread and this thread are in
1243 # the wait() call at once. The delay here is to allow the
1244 # main thread to most likely be blocked in its wait() call.
1245 t = threading.Timer(0.2, kill_proc_timer_thread)
1246 t.start()
1247
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001248 if mswindows:
1249 expected_errorcode = 1
1250 else:
1251 # Should be -9 because of the proc.kill() from the thread.
1252 expected_errorcode = -9
1253
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001254 # Wait for the process to finish; the thread should kill it
1255 # long before it finishes on its own. Supplying a timeout
1256 # triggers a different code path for better coverage.
1257 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001258 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001259 msg="unexpected result in wait from main thread")
1260
1261 # This should be a no-op with no change in returncode.
1262 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001263 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001264 msg="unexpected result in second main wait.")
1265
1266 t.join()
1267 # Ensure that all of the thread results are as expected.
1268 # When a race condition occurs in wait(), the returncode could
1269 # be set by the wrong thread that doesn't actually have it
1270 # leading to an incorrect value.
1271 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001272 ('thread-after-kill-and-wait', expected_errorcode),
1273 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001274 results)
1275
Victor Stinnerb3693582010-05-21 20:13:12 +00001276 def test_issue8780(self):
1277 # Ensure that stdout is inherited from the parent
1278 # if stdout=PIPE is not used
1279 code = ';'.join((
1280 'import subprocess, sys',
1281 'retcode = subprocess.call('
1282 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1283 'assert retcode == 0'))
1284 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001285 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001286
Tim Goldenaf5ac392010-08-06 13:03:56 +00001287 def test_handles_closed_on_exception(self):
1288 # If CreateProcess exits with an error, ensure the
1289 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001290 ifhandle, ifname = tempfile.mkstemp()
1291 ofhandle, ofname = tempfile.mkstemp()
1292 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001293 try:
1294 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1295 stderr=efhandle)
1296 except OSError:
1297 os.close(ifhandle)
1298 os.remove(ifname)
1299 os.close(ofhandle)
1300 os.remove(ofname)
1301 os.close(efhandle)
1302 os.remove(efname)
1303 self.assertFalse(os.path.exists(ifname))
1304 self.assertFalse(os.path.exists(ofname))
1305 self.assertFalse(os.path.exists(efname))
1306
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001307 def test_communicate_epipe(self):
1308 # Issue 10963: communicate() should hide EPIPE
1309 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1310 stdin=subprocess.PIPE,
1311 stdout=subprocess.PIPE,
1312 stderr=subprocess.PIPE)
1313 self.addCleanup(p.stdout.close)
1314 self.addCleanup(p.stderr.close)
1315 self.addCleanup(p.stdin.close)
1316 p.communicate(b"x" * 2**20)
1317
1318 def test_communicate_epipe_only_stdin(self):
1319 # Issue 10963: communicate() should hide EPIPE
1320 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1321 stdin=subprocess.PIPE)
1322 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001323 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001324 p.communicate(b"x" * 2**20)
1325
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001326 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1327 "Requires signal.SIGUSR1")
1328 @unittest.skipUnless(hasattr(os, 'kill'),
1329 "Requires os.kill")
1330 @unittest.skipUnless(hasattr(os, 'getppid'),
1331 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001332 def test_communicate_eintr(self):
1333 # Issue #12493: communicate() should handle EINTR
1334 def handler(signum, frame):
1335 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001336 old_handler = signal.signal(signal.SIGUSR1, handler)
1337 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001338
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001339 args = [sys.executable, "-c",
1340 'import os, signal;'
1341 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001342 for stream in ('stdout', 'stderr'):
1343 kw = {stream: subprocess.PIPE}
1344 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001345 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001346 process.communicate()
1347
Tim Peterse718f612004-10-12 21:51:32 +00001348
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001349 # This test is Linux-ish specific for simplicity to at least have
1350 # some coverage. It is not a platform specific bug.
1351 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1352 "Linux specific")
1353 def test_failed_child_execute_fd_leak(self):
1354 """Test for the fork() failure fd leak reported in issue16327."""
1355 fd_directory = '/proc/%d/fd' % os.getpid()
1356 fds_before_popen = os.listdir(fd_directory)
1357 with self.assertRaises(PopenTestException):
1358 PopenExecuteChildRaises(
1359 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1360 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1361
1362 # NOTE: This test doesn't verify that the real _execute_child
1363 # does not close the file descriptors itself on the way out
1364 # during an exception. Code inspection has confirmed that.
1365
1366 fds_after_exception = os.listdir(fd_directory)
1367 self.assertEqual(fds_before_popen, fds_after_exception)
1368
Gregory P. Smitha3a6df32017-08-24 18:15:02 -07001369 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001370 def test_file_not_found_includes_filename(self):
1371 with self.assertRaises(FileNotFoundError) as c:
1372 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1373 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1374
Gregory P. Smitha3a6df32017-08-24 18:15:02 -07001375 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001376 def test_file_not_found_with_bad_cwd(self):
1377 with self.assertRaises(FileNotFoundError) as c:
1378 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1379 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1380
Gregory P. Smith6e730002015-04-14 16:14:25 -07001381
1382class RunFuncTestCase(BaseTestCase):
1383 def run_python(self, code, **kwargs):
1384 """Run Python code in a subprocess using subprocess.run"""
1385 argv = [sys.executable, "-c", code]
1386 return subprocess.run(argv, **kwargs)
1387
1388 def test_returncode(self):
1389 # call() function with sequence argument
1390 cp = self.run_python("import sys; sys.exit(47)")
1391 self.assertEqual(cp.returncode, 47)
1392 with self.assertRaises(subprocess.CalledProcessError):
1393 cp.check_returncode()
1394
1395 def test_check(self):
1396 with self.assertRaises(subprocess.CalledProcessError) as c:
1397 self.run_python("import sys; sys.exit(47)", check=True)
1398 self.assertEqual(c.exception.returncode, 47)
1399
1400 def test_check_zero(self):
1401 # check_returncode shouldn't raise when returncode is zero
1402 cp = self.run_python("import sys; sys.exit(0)", check=True)
1403 self.assertEqual(cp.returncode, 0)
1404
1405 def test_timeout(self):
1406 # run() function with timeout argument; we want to test that the child
1407 # process gets killed when the timeout expires. If the child isn't
1408 # killed, this call will deadlock since subprocess.run waits for the
1409 # child.
1410 with self.assertRaises(subprocess.TimeoutExpired):
1411 self.run_python("while True: pass", timeout=0.0001)
1412
1413 def test_capture_stdout(self):
1414 # capture stdout with zero return code
1415 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1416 self.assertIn(b'BDFL', cp.stdout)
1417
1418 def test_capture_stderr(self):
1419 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1420 stderr=subprocess.PIPE)
1421 self.assertIn(b'BDFL', cp.stderr)
1422
1423 def test_check_output_stdin_arg(self):
1424 # run() can be called with stdin set to a file
1425 tf = tempfile.TemporaryFile()
1426 self.addCleanup(tf.close)
1427 tf.write(b'pear')
1428 tf.seek(0)
1429 cp = self.run_python(
1430 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1431 stdin=tf, stdout=subprocess.PIPE)
1432 self.assertIn(b'PEAR', cp.stdout)
1433
1434 def test_check_output_input_arg(self):
1435 # check_output() can be called with input set to a string
1436 cp = self.run_python(
1437 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1438 input=b'pear', stdout=subprocess.PIPE)
1439 self.assertIn(b'PEAR', cp.stdout)
1440
1441 def test_check_output_stdin_with_input_arg(self):
1442 # run() refuses to accept 'stdin' with 'input'
1443 tf = tempfile.TemporaryFile()
1444 self.addCleanup(tf.close)
1445 tf.write(b'pear')
1446 tf.seek(0)
1447 with self.assertRaises(ValueError,
1448 msg="Expected ValueError when stdin and input args supplied.") as c:
1449 output = self.run_python("print('will not be run')",
1450 stdin=tf, input=b'hare')
1451 self.assertIn('stdin', c.exception.args[0])
1452 self.assertIn('input', c.exception.args[0])
1453
1454 def test_check_output_timeout(self):
1455 with self.assertRaises(subprocess.TimeoutExpired) as c:
1456 cp = self.run_python((
1457 "import sys, time\n"
1458 "sys.stdout.write('BDFL')\n"
1459 "sys.stdout.flush()\n"
1460 "time.sleep(3600)"),
1461 # Some heavily loaded buildbots (sparc Debian 3.x) require
1462 # this much time to start and print.
1463 timeout=3, stdout=subprocess.PIPE)
1464 self.assertEqual(c.exception.output, b'BDFL')
1465 # output is aliased to stdout
1466 self.assertEqual(c.exception.stdout, b'BDFL')
1467
1468 def test_run_kwargs(self):
1469 newenv = os.environ.copy()
1470 newenv["FRUIT"] = "banana"
1471 cp = self.run_python(('import sys, os;'
1472 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1473 env=newenv)
1474 self.assertEqual(cp.returncode, 33)
1475
1476
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001477@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001478class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001479
Gregory P. Smith5591b022012-10-10 03:34:47 -07001480 def setUp(self):
1481 super().setUp()
1482 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1483
1484 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001485 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001486 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001487 except OSError as e:
1488 # This avoids hard coding the errno value or the OS perror()
1489 # string and instead capture the exception that we want to see
1490 # below for comparison.
1491 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001492 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001493 else:
Martin Pantereb995702016-07-28 01:11:04 +00001494 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001495 self._nonexistent_dir)
1496 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001497
Gregory P. Smith5591b022012-10-10 03:34:47 -07001498 def test_exception_cwd(self):
1499 """Test error in the child raised in the parent for a bad cwd."""
1500 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001501 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001502 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001503 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001504 except OSError as e:
1505 # Test that the child process chdir failure actually makes
1506 # it up to the parent process as the correct exception.
1507 self.assertEqual(desired_exception.errno, e.errno)
1508 self.assertEqual(desired_exception.strerror, e.strerror)
1509 else:
1510 self.fail("Expected OSError: %s" % desired_exception)
1511
Gregory P. Smith5591b022012-10-10 03:34:47 -07001512 def test_exception_bad_executable(self):
1513 """Test error in the child raised in the parent for a bad executable."""
1514 desired_exception = self._get_chdir_exception()
1515 try:
1516 p = subprocess.Popen([sys.executable, "-c", ""],
1517 executable=self._nonexistent_dir)
1518 except OSError as e:
1519 # Test that the child process exec failure actually makes
1520 # it up to the parent process as the correct exception.
1521 self.assertEqual(desired_exception.errno, e.errno)
1522 self.assertEqual(desired_exception.strerror, e.strerror)
1523 else:
1524 self.fail("Expected OSError: %s" % desired_exception)
1525
1526 def test_exception_bad_args_0(self):
1527 """Test error in the child raised in the parent for a bad args[0]."""
1528 desired_exception = self._get_chdir_exception()
1529 try:
1530 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1531 except OSError as e:
1532 # Test that the child process exec failure actually makes
1533 # it up to the parent process as the correct exception.
1534 self.assertEqual(desired_exception.errno, e.errno)
1535 self.assertEqual(desired_exception.strerror, e.strerror)
1536 else:
1537 self.fail("Expected OSError: %s" % desired_exception)
1538
Ammar Askar3fc499b2017-09-06 02:41:30 -04001539 # We mock the __del__ method for Popen in the next two tests
1540 # because it does cleanup based on the pid returned by fork_exec
1541 # along with issuing a resource warning if it still exists. Since
1542 # we don't actually spawn a process in these tests we can forego
1543 # the destructor. An alternative would be to set _child_created to
1544 # False before the destructor is called but there is no easy way
1545 # to do that
1546 class PopenNoDestructor(subprocess.Popen):
1547 def __del__(self):
1548 pass
1549
1550 @mock.patch("subprocess._posixsubprocess.fork_exec")
1551 def test_exception_errpipe_normal(self, fork_exec):
1552 """Test error passing done through errpipe_write in the good case"""
1553 def proper_error(*args):
1554 errpipe_write = args[13]
1555 # Write the hex for the error code EISDIR: 'is a directory'
1556 err_code = '{:x}'.format(errno.EISDIR).encode()
1557 os.write(errpipe_write, b"OSError:" + err_code + b":")
1558 return 0
1559
1560 fork_exec.side_effect = proper_error
1561
1562 with self.assertRaises(IsADirectoryError):
1563 self.PopenNoDestructor(["non_existent_command"])
1564
1565 @mock.patch("subprocess._posixsubprocess.fork_exec")
1566 def test_exception_errpipe_bad_data(self, fork_exec):
1567 """Test error passing done through errpipe_write where its not
1568 in the expected format"""
1569 error_data = b"\xFF\x00\xDE\xAD"
1570 def bad_error(*args):
1571 errpipe_write = args[13]
1572 # Anything can be in the pipe, no assumptions should
1573 # be made about its encoding, so we'll write some
1574 # arbitrary hex bytes to test it out
1575 os.write(errpipe_write, error_data)
1576 return 0
1577
1578 fork_exec.side_effect = bad_error
1579
1580 with self.assertRaises(subprocess.SubprocessError) as e:
1581 self.PopenNoDestructor(["non_existent_command"])
1582
1583 self.assertIn(repr(error_data), str(e.exception))
1584
1585
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001586 def test_restore_signals(self):
1587 # Code coverage for both values of restore_signals to make sure it
1588 # at least does not blow up.
1589 # A test for behavior would be complex. Contributions welcome.
1590 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1591 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1592
1593 def test_start_new_session(self):
1594 # For code coverage of calling setsid(). We don't care if we get an
1595 # EPERM error from it depending on the test execution environment, that
1596 # still indicates that it was called.
1597 try:
1598 output = subprocess.check_output(
1599 [sys.executable, "-c",
1600 "import os; print(os.getpgid(os.getpid()))"],
1601 start_new_session=True)
1602 except OSError as e:
1603 if e.errno != errno.EPERM:
1604 raise
1605 else:
1606 parent_pgid = os.getpgid(os.getpid())
1607 child_pgid = int(output)
1608 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001609
1610 def test_run_abort(self):
1611 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001612 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001613 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001614 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001615 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001616 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001617
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001618 def test_CalledProcessError_str_signal(self):
1619 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1620 error_string = str(err)
1621 # We're relying on the repr() of the signal.Signals intenum to provide
1622 # the word signal, the signal name and the numeric value.
1623 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001624 # We're not being specific about the signal name as some signals have
1625 # multiple names and which name is revealed can vary.
1626 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001627 self.assertIn(str(signal.SIGABRT), error_string)
1628
1629 def test_CalledProcessError_str_unknown_signal(self):
1630 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1631 error_string = str(err)
1632 self.assertIn("unknown signal 9876543.", error_string)
1633
1634 def test_CalledProcessError_str_non_zero(self):
1635 err = subprocess.CalledProcessError(2, "fake cmd")
1636 error_string = str(err)
1637 self.assertIn("non-zero exit status 2.", error_string)
1638
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001639 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001640 # DISCLAIMER: Setting environment variables is *not* a good use
1641 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001642 p = subprocess.Popen([sys.executable, "-c",
1643 'import sys,os;'
1644 'sys.stdout.write(os.getenv("FRUIT"))'],
1645 stdout=subprocess.PIPE,
1646 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001647 with p:
1648 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001649
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001650 def test_preexec_exception(self):
1651 def raise_it():
1652 raise ValueError("What if two swallows carried a coconut?")
1653 try:
1654 p = subprocess.Popen([sys.executable, "-c", ""],
1655 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001656 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001657 self.assertTrue(
1658 subprocess._posixsubprocess,
1659 "Expected a ValueError from the preexec_fn")
1660 except ValueError as e:
1661 self.assertIn("coconut", e.args[0])
1662 else:
1663 self.fail("Exception raised by preexec_fn did not make it "
1664 "to the parent process.")
1665
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001666 class _TestExecuteChildPopen(subprocess.Popen):
1667 """Used to test behavior at the end of _execute_child."""
1668 def __init__(self, testcase, *args, **kwargs):
1669 self._testcase = testcase
1670 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001671
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001672 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001673 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001674 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001675 finally:
1676 # Open a bunch of file descriptors and verify that
1677 # none of them are the same as the ones the Popen
1678 # instance is using for stdin/stdout/stderr.
1679 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1680 for _ in range(8)]
1681 try:
1682 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001683 self._testcase.assertNotIn(
1684 fd, (self.stdin.fileno(), self.stdout.fileno(),
1685 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001686 msg="At least one fd was closed early.")
1687 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001688 for fd in devzero_fds:
1689 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001690
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001691 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1692 def test_preexec_errpipe_does_not_double_close_pipes(self):
1693 """Issue16140: Don't double close pipes on preexec error."""
1694
1695 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001696 raise subprocess.SubprocessError(
1697 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001698
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001699 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001700 self._TestExecuteChildPopen(
1701 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001702 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1703 stderr=subprocess.PIPE, preexec_fn=raise_it)
1704
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001705 def test_preexec_gc_module_failure(self):
1706 # This tests the code that disables garbage collection if the child
1707 # process will execute any Python.
1708 def raise_runtime_error():
1709 raise RuntimeError("this shouldn't escape")
1710 enabled = gc.isenabled()
1711 orig_gc_disable = gc.disable
1712 orig_gc_isenabled = gc.isenabled
1713 try:
1714 gc.disable()
1715 self.assertFalse(gc.isenabled())
1716 subprocess.call([sys.executable, '-c', ''],
1717 preexec_fn=lambda: None)
1718 self.assertFalse(gc.isenabled(),
1719 "Popen enabled gc when it shouldn't.")
1720
1721 gc.enable()
1722 self.assertTrue(gc.isenabled())
1723 subprocess.call([sys.executable, '-c', ''],
1724 preexec_fn=lambda: None)
1725 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1726
1727 gc.disable = raise_runtime_error
1728 self.assertRaises(RuntimeError, subprocess.Popen,
1729 [sys.executable, '-c', ''],
1730 preexec_fn=lambda: None)
1731
1732 del gc.isenabled # force an AttributeError
1733 self.assertRaises(AttributeError, subprocess.Popen,
1734 [sys.executable, '-c', ''],
1735 preexec_fn=lambda: None)
1736 finally:
1737 gc.disable = orig_gc_disable
1738 gc.isenabled = orig_gc_isenabled
1739 if not enabled:
1740 gc.disable()
1741
Martin Panterf7fdbda2015-12-05 09:51:52 +00001742 @unittest.skipIf(
1743 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001744 def test_preexec_fork_failure(self):
1745 # The internal code did not preserve the previous exception when
1746 # re-enabling garbage collection
1747 try:
1748 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1749 except ImportError as err:
1750 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1751 limits = getrlimit(RLIMIT_NPROC)
1752 [_, hard] = limits
1753 setrlimit(RLIMIT_NPROC, (0, hard))
1754 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001755 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001756 subprocess.call([sys.executable, '-c', ''],
1757 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001758 except BlockingIOError:
1759 # Forking should raise EAGAIN, translated to BlockingIOError
1760 pass
1761 else:
1762 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001763
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001764 def test_args_string(self):
1765 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001766 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001767 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001768 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001769 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001770 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1771 sys.executable)
1772 os.chmod(fname, 0o700)
1773 p = subprocess.Popen(fname)
1774 p.wait()
1775 os.remove(fname)
1776 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001777
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001778 def test_invalid_args(self):
1779 # invalid arguments should raise ValueError
1780 self.assertRaises(ValueError, subprocess.call,
1781 [sys.executable, "-c",
1782 "import sys; sys.exit(47)"],
1783 startupinfo=47)
1784 self.assertRaises(ValueError, subprocess.call,
1785 [sys.executable, "-c",
1786 "import sys; sys.exit(47)"],
1787 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001788
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001789 def test_shell_sequence(self):
1790 # Run command through the shell (sequence)
1791 newenv = os.environ.copy()
1792 newenv["FRUIT"] = "apple"
1793 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1794 stdout=subprocess.PIPE,
1795 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001796 with p:
1797 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001798
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001799 def test_shell_string(self):
1800 # Run command through the shell (string)
1801 newenv = os.environ.copy()
1802 newenv["FRUIT"] = "apple"
1803 p = subprocess.Popen("echo $FRUIT", shell=1,
1804 stdout=subprocess.PIPE,
1805 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001806 with p:
1807 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001808
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001809 def test_call_string(self):
1810 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001811 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001812 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001813 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001814 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001815 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1816 sys.executable)
1817 os.chmod(fname, 0o700)
1818 rc = subprocess.call(fname)
1819 os.remove(fname)
1820 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001821
Stefan Krah9542cc62010-07-19 14:20:53 +00001822 def test_specific_shell(self):
1823 # Issue #9265: Incorrect name passed as arg[0].
1824 shells = []
1825 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1826 for name in ['bash', 'ksh']:
1827 sh = os.path.join(prefix, name)
1828 if os.path.isfile(sh):
1829 shells.append(sh)
1830 if not shells: # Will probably work for any shell but csh.
1831 self.skipTest("bash or ksh required for this test")
1832 sh = '/bin/sh'
1833 if os.path.isfile(sh) and not os.path.islink(sh):
1834 # Test will fail if /bin/sh is a symlink to csh.
1835 shells.append(sh)
1836 for sh in shells:
1837 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1838 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001839 with p:
1840 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001841
Florent Xicluna4886d242010-03-08 13:27:26 +00001842 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001843 # Do not inherit file handles from the parent.
1844 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001845 # Also set the SIGINT handler to the default to make sure it's not
1846 # being ignored (some tests rely on that.)
1847 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1848 try:
1849 p = subprocess.Popen([sys.executable, "-c", """if 1:
1850 import sys, time
1851 sys.stdout.write('x\\n')
1852 sys.stdout.flush()
1853 time.sleep(30)
1854 """],
1855 close_fds=True,
1856 stdin=subprocess.PIPE,
1857 stdout=subprocess.PIPE,
1858 stderr=subprocess.PIPE)
1859 finally:
1860 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001861 # Wait for the interpreter to be completely initialized before
1862 # sending any signal.
1863 p.stdout.read(1)
1864 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001865 return p
1866
Charles-François Natali53221e32013-01-12 16:52:20 +01001867 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1868 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001869 def _kill_dead_process(self, method, *args):
1870 # Do not inherit file handles from the parent.
1871 # It should fix failures on some platforms.
1872 p = subprocess.Popen([sys.executable, "-c", """if 1:
1873 import sys, time
1874 sys.stdout.write('x\\n')
1875 sys.stdout.flush()
1876 """],
1877 close_fds=True,
1878 stdin=subprocess.PIPE,
1879 stdout=subprocess.PIPE,
1880 stderr=subprocess.PIPE)
1881 # Wait for the interpreter to be completely initialized before
1882 # sending any signal.
1883 p.stdout.read(1)
1884 # The process should end after this
1885 time.sleep(1)
1886 # This shouldn't raise even though the child is now dead
1887 getattr(p, method)(*args)
1888 p.communicate()
1889
Florent Xicluna4886d242010-03-08 13:27:26 +00001890 def test_send_signal(self):
1891 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001892 _, stderr = p.communicate()
1893 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001894 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001895
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001896 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001897 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001898 _, stderr = p.communicate()
1899 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001900 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001901
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001902 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001903 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001904 _, stderr = p.communicate()
1905 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001906 self.assertEqual(p.wait(), -signal.SIGTERM)
1907
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001908 def test_send_signal_dead(self):
1909 # Sending a signal to a dead process
1910 self._kill_dead_process('send_signal', signal.SIGINT)
1911
1912 def test_kill_dead(self):
1913 # Killing a dead process
1914 self._kill_dead_process('kill')
1915
1916 def test_terminate_dead(self):
1917 # Terminating a dead process
1918 self._kill_dead_process('terminate')
1919
Victor Stinnerdaf45552013-08-28 00:53:59 +02001920 def _save_fds(self, save_fds):
1921 fds = []
1922 for fd in save_fds:
1923 inheritable = os.get_inheritable(fd)
1924 saved = os.dup(fd)
1925 fds.append((fd, saved, inheritable))
1926 return fds
1927
1928 def _restore_fds(self, fds):
1929 for fd, saved, inheritable in fds:
1930 os.dup2(saved, fd, inheritable=inheritable)
1931 os.close(saved)
1932
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001933 def check_close_std_fds(self, fds):
1934 # Issue #9905: test that subprocess pipes still work properly with
1935 # some standard fds closed
1936 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001937 saved_fds = self._save_fds(fds)
1938 for fd, saved, inheritable in saved_fds:
1939 if fd == 0:
1940 stdin = saved
1941 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001942 try:
1943 for fd in fds:
1944 os.close(fd)
1945 out, err = subprocess.Popen([sys.executable, "-c",
1946 'import sys;'
1947 'sys.stdout.write("apple");'
1948 'sys.stdout.flush();'
1949 'sys.stderr.write("orange")'],
1950 stdin=stdin,
1951 stdout=subprocess.PIPE,
1952 stderr=subprocess.PIPE).communicate()
1953 err = support.strip_python_stderr(err)
1954 self.assertEqual((out, err), (b'apple', b'orange'))
1955 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001956 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001957
1958 def test_close_fd_0(self):
1959 self.check_close_std_fds([0])
1960
1961 def test_close_fd_1(self):
1962 self.check_close_std_fds([1])
1963
1964 def test_close_fd_2(self):
1965 self.check_close_std_fds([2])
1966
1967 def test_close_fds_0_1(self):
1968 self.check_close_std_fds([0, 1])
1969
1970 def test_close_fds_0_2(self):
1971 self.check_close_std_fds([0, 2])
1972
1973 def test_close_fds_1_2(self):
1974 self.check_close_std_fds([1, 2])
1975
1976 def test_close_fds_0_1_2(self):
1977 # Issue #10806: test that subprocess pipes still work properly with
1978 # all standard fds closed.
1979 self.check_close_std_fds([0, 1, 2])
1980
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001981 def test_small_errpipe_write_fd(self):
1982 """Issue #15798: Popen should work when stdio fds are available."""
1983 new_stdin = os.dup(0)
1984 new_stdout = os.dup(1)
1985 try:
1986 os.close(0)
1987 os.close(1)
1988
1989 # Side test: if errpipe_write fails to have its CLOEXEC
1990 # flag set this should cause the parent to think the exec
1991 # failed. Extremely unlikely: everyone supports CLOEXEC.
1992 subprocess.Popen([
1993 sys.executable, "-c",
1994 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1995 finally:
1996 # Restore original stdin and stdout
1997 os.dup2(new_stdin, 0)
1998 os.dup2(new_stdout, 1)
1999 os.close(new_stdin)
2000 os.close(new_stdout)
2001
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002002 def test_remapping_std_fds(self):
2003 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002004 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002005 try:
2006 temp_fds = [fd for fd, fname in temps]
2007
2008 # unlink the files -- we won't need to reopen them
2009 for fd, fname in temps:
2010 os.unlink(fname)
2011
2012 # write some data to what will become stdin, and rewind
2013 os.write(temp_fds[1], b"STDIN")
2014 os.lseek(temp_fds[1], 0, 0)
2015
2016 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002017 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002018 try:
2019 # duplicate the file objects over the standard fd's
2020 for fd, temp_fd in enumerate(temp_fds):
2021 os.dup2(temp_fd, fd)
2022
2023 # now use those files in the "wrong" order, so that subprocess
2024 # has to rearrange them in the child
2025 p = subprocess.Popen([sys.executable, "-c",
2026 'import sys; got = sys.stdin.read();'
2027 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2028 stdin=temp_fds[1],
2029 stdout=temp_fds[2],
2030 stderr=temp_fds[0])
2031 p.wait()
2032 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002033 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002034
2035 for fd in temp_fds:
2036 os.lseek(fd, 0, 0)
2037
2038 out = os.read(temp_fds[2], 1024)
2039 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2040 self.assertEqual(out, b"got STDIN")
2041 self.assertEqual(err, b"err")
2042
2043 finally:
2044 for fd in temp_fds:
2045 os.close(fd)
2046
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002047 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2048 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002049 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002050 temp_fds = [fd for fd, fname in temps]
2051 try:
2052 # unlink the files -- we won't need to reopen them
2053 for fd, fname in temps:
2054 os.unlink(fname)
2055
2056 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002057 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002058 try:
2059 # duplicate the temp files over the standard fd's 0, 1, 2
2060 for fd, temp_fd in enumerate(temp_fds):
2061 os.dup2(temp_fd, fd)
2062
2063 # write some data to what will become stdin, and rewind
2064 os.write(stdin_no, b"STDIN")
2065 os.lseek(stdin_no, 0, 0)
2066
2067 # now use those files in the given order, so that subprocess
2068 # has to rearrange them in the child
2069 p = subprocess.Popen([sys.executable, "-c",
2070 'import sys; got = sys.stdin.read();'
2071 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2072 stdin=stdin_no,
2073 stdout=stdout_no,
2074 stderr=stderr_no)
2075 p.wait()
2076
2077 for fd in temp_fds:
2078 os.lseek(fd, 0, 0)
2079
2080 out = os.read(stdout_no, 1024)
2081 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2082 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002083 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002084
2085 self.assertEqual(out, b"got STDIN")
2086 self.assertEqual(err, b"err")
2087
2088 finally:
2089 for fd in temp_fds:
2090 os.close(fd)
2091
2092 # When duping fds, if there arises a situation where one of the fds is
2093 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2094 # This tests all combinations of this.
2095 def test_swap_fds(self):
2096 self.check_swap_fds(0, 1, 2)
2097 self.check_swap_fds(0, 2, 1)
2098 self.check_swap_fds(1, 0, 2)
2099 self.check_swap_fds(1, 2, 0)
2100 self.check_swap_fds(2, 0, 1)
2101 self.check_swap_fds(2, 1, 0)
2102
Victor Stinner13bb71c2010-04-23 21:41:56 +00002103 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002104 def prepare():
2105 raise ValueError("surrogate:\uDCff")
2106
2107 try:
2108 subprocess.call(
2109 [sys.executable, "-c", "pass"],
2110 preexec_fn=prepare)
2111 except ValueError as err:
2112 # Pure Python implementations keeps the message
2113 self.assertIsNone(subprocess._posixsubprocess)
2114 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002115 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002116 # _posixsubprocess uses a default message
2117 self.assertIsNotNone(subprocess._posixsubprocess)
2118 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2119 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002120 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002121
Victor Stinner13bb71c2010-04-23 21:41:56 +00002122 def test_undecodable_env(self):
2123 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002124 encoded_value = value.encode("ascii", "surrogateescape")
2125
Victor Stinner13bb71c2010-04-23 21:41:56 +00002126 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002127 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002128 env = os.environ.copy()
2129 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002130 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00002131 # surrogate-escaping of \xFF in the child process; otherwise it can
2132 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00002133 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01002134 if sys.platform.startswith("aix"):
2135 # On AIX, the C locale uses the Latin1 encoding
2136 decoded_value = encoded_value.decode("latin1", "surrogateescape")
2137 else:
2138 # On other UNIXes, the C locale uses the ASCII encoding
2139 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002140 stdout = subprocess.check_output(
2141 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002142 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002143 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002144 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002145
2146 # test bytes
2147 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002148 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002149 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002150 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002151 stdout = subprocess.check_output(
2152 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002153 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002154 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002155 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002156
Victor Stinnerb745a742010-05-18 17:17:23 +00002157 def test_bytes_program(self):
2158 abs_program = os.fsencode(sys.executable)
2159 path, program = os.path.split(sys.executable)
2160 program = os.fsencode(program)
2161
2162 # absolute bytes path
2163 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002164 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002165
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002166 # absolute bytes path as a string
2167 cmd = b"'" + abs_program + b"' -c pass"
2168 exitcode = subprocess.call(cmd, shell=True)
2169 self.assertEqual(exitcode, 0)
2170
Victor Stinnerb745a742010-05-18 17:17:23 +00002171 # bytes program, unicode PATH
2172 env = os.environ.copy()
2173 env["PATH"] = path
2174 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002175 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002176
2177 # bytes program, bytes PATH
2178 envb = os.environb.copy()
2179 envb[b"PATH"] = os.fsencode(path)
2180 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002181 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002182
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002183 def test_pipe_cloexec(self):
2184 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2185 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2186
2187 p1 = subprocess.Popen([sys.executable, sleeper],
2188 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2189 stderr=subprocess.PIPE, close_fds=False)
2190
2191 self.addCleanup(p1.communicate, b'')
2192
2193 p2 = subprocess.Popen([sys.executable, fd_status],
2194 stdout=subprocess.PIPE, close_fds=False)
2195
2196 output, error = p2.communicate()
2197 result_fds = set(map(int, output.split(b',')))
2198 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2199 p1.stderr.fileno()])
2200
2201 self.assertFalse(result_fds & unwanted_fds,
2202 "Expected no fds from %r to be open in child, "
2203 "found %r" %
2204 (unwanted_fds, result_fds & unwanted_fds))
2205
2206 def test_pipe_cloexec_real_tools(self):
2207 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2208 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2209
2210 subdata = b'zxcvbn'
2211 data = subdata * 4 + b'\n'
2212
2213 p1 = subprocess.Popen([sys.executable, qcat],
2214 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2215 close_fds=False)
2216
2217 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2218 stdin=p1.stdout, stdout=subprocess.PIPE,
2219 close_fds=False)
2220
2221 self.addCleanup(p1.wait)
2222 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002223 def kill_p1():
2224 try:
2225 p1.terminate()
2226 except ProcessLookupError:
2227 pass
2228 def kill_p2():
2229 try:
2230 p2.terminate()
2231 except ProcessLookupError:
2232 pass
2233 self.addCleanup(kill_p1)
2234 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002235
2236 p1.stdin.write(data)
2237 p1.stdin.close()
2238
2239 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2240
2241 self.assertTrue(readfiles, "The child hung")
2242 self.assertEqual(p2.stdout.read(), data)
2243
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002244 p1.stdout.close()
2245 p2.stdout.close()
2246
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002247 def test_close_fds(self):
2248 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2249
2250 fds = os.pipe()
2251 self.addCleanup(os.close, fds[0])
2252 self.addCleanup(os.close, fds[1])
2253
2254 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002255 # add a bunch more fds
2256 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002257 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002258 self.addCleanup(os.close, fd)
2259 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002260
Victor Stinnerdaf45552013-08-28 00:53:59 +02002261 for fd in open_fds:
2262 os.set_inheritable(fd, True)
2263
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002264 p = subprocess.Popen([sys.executable, fd_status],
2265 stdout=subprocess.PIPE, close_fds=False)
2266 output, ignored = p.communicate()
2267 remaining_fds = set(map(int, output.split(b',')))
2268
2269 self.assertEqual(remaining_fds & open_fds, open_fds,
2270 "Some fds were closed")
2271
2272 p = subprocess.Popen([sys.executable, fd_status],
2273 stdout=subprocess.PIPE, close_fds=True)
2274 output, ignored = p.communicate()
2275 remaining_fds = set(map(int, output.split(b',')))
2276
2277 self.assertFalse(remaining_fds & open_fds,
2278 "Some fds were left open")
2279 self.assertIn(1, remaining_fds, "Subprocess failed")
2280
Gregory P. Smith8facece2012-01-21 14:01:08 -08002281 # Keep some of the fd's we opened open in the subprocess.
2282 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2283 fds_to_keep = set(open_fds.pop() for _ in range(8))
2284 p = subprocess.Popen([sys.executable, fd_status],
2285 stdout=subprocess.PIPE, close_fds=True,
2286 pass_fds=())
2287 output, ignored = p.communicate()
2288 remaining_fds = set(map(int, output.split(b',')))
2289
2290 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2291 "Some fds not in pass_fds were left open")
2292 self.assertIn(1, remaining_fds, "Subprocess failed")
2293
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002294
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002295 @unittest.skipIf(sys.platform.startswith("freebsd") and
2296 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2297 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002298 def test_close_fds_when_max_fd_is_lowered(self):
2299 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2300 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2301
Gregory P. Smith634aa682014-06-15 17:51:04 -07002302 # This launches the meat of the test in a child process to
2303 # avoid messing with the larger unittest processes maximum
2304 # number of file descriptors.
2305 # This process launches:
2306 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2307 # a bunch of high open fds above the new lower rlimit.
2308 # Those are reported via stdout before launching a new
2309 # process with close_fds=False to run the actual test:
2310 # +--> The TEST: This one launches a fd_status.py
2311 # subprocess with close_fds=True so we can find out if
2312 # any of the fds above the lowered rlimit are still open.
2313 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2314 '''
2315 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002316 open_fds = set()
2317 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002318 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002319 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002320 open_fds.add(fd)
2321
2322 # Leave a two pairs of low ones available for use by the
2323 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002324 # We also leave 10 more open as some Python buildbots run into
2325 # "too many open files" errors during the test if we do not.
2326 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002327 os.close(fd)
2328 open_fds.remove(fd)
2329
2330 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002331 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002332 os.set_inheritable(fd, True)
2333
2334 max_fd_open = max(open_fds)
2335
Gregory P. Smith634aa682014-06-15 17:51:04 -07002336 # Communicate the open_fds to the parent unittest.TestCase process.
2337 print(','.join(map(str, sorted(open_fds))))
2338 sys.stdout.flush()
2339
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002340 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2341 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002342 # 29 is lower than the highest fds we are leaving open.
2343 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002344 # Launch a new Python interpreter with our low fd rlim_cur that
2345 # inherits open fds above that limit. It then uses subprocess
2346 # with close_fds=True to get a report of open fds in the child.
2347 # An explicit list of fds to check is passed to fd_status.py as
2348 # letting fd_status rely on its default logic would miss the
2349 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002350 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002351 [sys.executable, '-c',
2352 textwrap.dedent("""
2353 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002354 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002355 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002356 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002357 """.format(max_fd=max_fd_open+1))],
2358 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002359 finally:
2360 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002361 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002362
2363 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002364 output_lines = output.splitlines()
2365 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002366 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002367 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2368 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002369
Gregory P. Smith634aa682014-06-15 17:51:04 -07002370 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002371 msg="Some fds were left open.")
2372
2373
Victor Stinner88701e22011-06-01 13:13:04 +02002374 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2375 # descriptor of a pipe closed in the parent process is valid in the
2376 # child process according to fstat(), but the mode of the file
2377 # descriptor is invalid, and read or write raise an error.
2378 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002379 def test_pass_fds(self):
2380 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2381
2382 open_fds = set()
2383
2384 for x in range(5):
2385 fds = os.pipe()
2386 self.addCleanup(os.close, fds[0])
2387 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002388 os.set_inheritable(fds[0], True)
2389 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002390 open_fds.update(fds)
2391
2392 for fd in open_fds:
2393 p = subprocess.Popen([sys.executable, fd_status],
2394 stdout=subprocess.PIPE, close_fds=True,
2395 pass_fds=(fd, ))
2396 output, ignored = p.communicate()
2397
2398 remaining_fds = set(map(int, output.split(b',')))
2399 to_be_closed = open_fds - {fd}
2400
2401 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2402 self.assertFalse(remaining_fds & to_be_closed,
2403 "fd to be closed passed")
2404
2405 # pass_fds overrides close_fds with a warning.
2406 with self.assertWarns(RuntimeWarning) as context:
2407 self.assertFalse(subprocess.call(
2408 [sys.executable, "-c", "import sys; sys.exit(0)"],
2409 close_fds=False, pass_fds=(fd, )))
2410 self.assertIn('overriding close_fds', str(context.warning))
2411
Victor Stinnerdaf45552013-08-28 00:53:59 +02002412 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002413 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002414
2415 inheritable, non_inheritable = os.pipe()
2416 self.addCleanup(os.close, inheritable)
2417 self.addCleanup(os.close, non_inheritable)
2418 os.set_inheritable(inheritable, True)
2419 os.set_inheritable(non_inheritable, False)
2420 pass_fds = (inheritable, non_inheritable)
2421 args = [sys.executable, script]
2422 args += list(map(str, pass_fds))
2423
2424 p = subprocess.Popen(args,
2425 stdout=subprocess.PIPE, close_fds=True,
2426 pass_fds=pass_fds)
2427 output, ignored = p.communicate()
2428 fds = set(map(int, output.split(b',')))
2429
2430 # the inheritable file descriptor must be inherited, so its inheritable
2431 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002432 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002433
2434 # inheritable flag must not be changed in the parent process
2435 self.assertEqual(os.get_inheritable(inheritable), True)
2436 self.assertEqual(os.get_inheritable(non_inheritable), False)
2437
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002438 def test_stdout_stdin_are_single_inout_fd(self):
2439 with io.open(os.devnull, "r+") as inout:
2440 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2441 stdout=inout, stdin=inout)
2442 p.wait()
2443
2444 def test_stdout_stderr_are_single_inout_fd(self):
2445 with io.open(os.devnull, "r+") as inout:
2446 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2447 stdout=inout, stderr=inout)
2448 p.wait()
2449
2450 def test_stderr_stdin_are_single_inout_fd(self):
2451 with io.open(os.devnull, "r+") as inout:
2452 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2453 stderr=inout, stdin=inout)
2454 p.wait()
2455
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002456 def test_wait_when_sigchild_ignored(self):
2457 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2458 sigchild_ignore = support.findfile("sigchild_ignore.py",
2459 subdir="subprocessdata")
2460 p = subprocess.Popen([sys.executable, sigchild_ignore],
2461 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2462 stdout, stderr = p.communicate()
2463 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002464 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002465 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002466
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002467 def test_select_unbuffered(self):
2468 # Issue #11459: bufsize=0 should really set the pipes as
2469 # unbuffered (and therefore let select() work properly).
2470 select = support.import_module("select")
2471 p = subprocess.Popen([sys.executable, "-c",
2472 'import sys;'
2473 'sys.stdout.write("apple")'],
2474 stdout=subprocess.PIPE,
2475 bufsize=0)
2476 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002477 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002478 try:
2479 self.assertEqual(f.read(4), b"appl")
2480 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2481 finally:
2482 p.wait()
2483
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002484 def test_zombie_fast_process_del(self):
2485 # Issue #12650: on Unix, if Popen.__del__() was called before the
2486 # process exited, it wouldn't be added to subprocess._active, and would
2487 # remain a zombie.
2488 # spawn a Popen, and delete its reference before it exits
2489 p = subprocess.Popen([sys.executable, "-c",
2490 'import sys, time;'
2491 'time.sleep(0.2)'],
2492 stdout=subprocess.PIPE,
2493 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002494 self.addCleanup(p.stdout.close)
2495 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002496 ident = id(p)
2497 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002498 with support.check_warnings(('', ResourceWarning)):
2499 p = None
2500
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002501 # check that p is in the active processes list
2502 self.assertIn(ident, [id(o) for o in subprocess._active])
2503
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002504 def test_leak_fast_process_del_killed(self):
2505 # Issue #12650: on Unix, if Popen.__del__() was called before the
2506 # process exited, and the process got killed by a signal, it would never
2507 # be removed from subprocess._active, which triggered a FD and memory
2508 # leak.
2509 # spawn a Popen, delete its reference and kill it
2510 p = subprocess.Popen([sys.executable, "-c",
2511 'import time;'
2512 'time.sleep(3)'],
2513 stdout=subprocess.PIPE,
2514 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002515 self.addCleanup(p.stdout.close)
2516 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002517 ident = id(p)
2518 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002519 with support.check_warnings(('', ResourceWarning)):
2520 p = None
2521
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002522 os.kill(pid, signal.SIGKILL)
2523 # check that p is in the active processes list
2524 self.assertIn(ident, [id(o) for o in subprocess._active])
2525
2526 # let some time for the process to exit, and create a new Popen: this
2527 # should trigger the wait() of p
2528 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002529 with self.assertRaises(OSError) as c:
Victor Stinner9a83f652017-08-21 23:51:31 +02002530 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002531 stdout=subprocess.PIPE,
2532 stderr=subprocess.PIPE) as proc:
2533 pass
2534 # p should have been wait()ed on, and removed from the _active list
2535 self.assertRaises(OSError, os.waitpid, pid, 0)
2536 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2537
Charles-François Natali249cdc32013-08-25 18:24:45 +02002538 def test_close_fds_after_preexec(self):
2539 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2540
2541 # this FD is used as dup2() target by preexec_fn, and should be closed
2542 # in the child process
2543 fd = os.dup(1)
2544 self.addCleanup(os.close, fd)
2545
2546 p = subprocess.Popen([sys.executable, fd_status],
2547 stdout=subprocess.PIPE, close_fds=True,
2548 preexec_fn=lambda: os.dup2(1, fd))
2549 output, ignored = p.communicate()
2550
2551 remaining_fds = set(map(int, output.split(b',')))
2552
2553 self.assertNotIn(fd, remaining_fds)
2554
Victor Stinner8f437aa2014-10-05 17:25:19 +02002555 @support.cpython_only
2556 def test_fork_exec(self):
2557 # Issue #22290: fork_exec() must not crash on memory allocation failure
2558 # or other errors
2559 import _posixsubprocess
2560 gc_enabled = gc.isenabled()
2561 try:
2562 # Use a preexec function and enable the garbage collector
2563 # to force fork_exec() to re-enable the garbage collector
2564 # on error.
2565 func = lambda: None
2566 gc.enable()
2567
Victor Stinner8f437aa2014-10-05 17:25:19 +02002568 for args, exe_list, cwd, env_list in (
2569 (123, [b"exe"], None, [b"env"]),
2570 ([b"arg"], 123, None, [b"env"]),
2571 ([b"arg"], [b"exe"], 123, [b"env"]),
2572 ([b"arg"], [b"exe"], None, 123),
2573 ):
2574 with self.assertRaises(TypeError):
2575 _posixsubprocess.fork_exec(
2576 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002577 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002578 -1, -1, -1, -1,
2579 1, 2, 3, 4,
2580 True, True, func)
2581 finally:
2582 if not gc_enabled:
2583 gc.disable()
2584
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002585 @support.cpython_only
2586 def test_fork_exec_sorted_fd_sanity_check(self):
2587 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2588 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002589 class BadInt:
2590 first = True
2591 def __init__(self, value):
2592 self.value = value
2593 def __int__(self):
2594 if self.first:
2595 self.first = False
2596 return self.value
2597 raise ValueError
2598
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002599 gc_enabled = gc.isenabled()
2600 try:
2601 gc.enable()
2602
2603 for fds_to_keep in (
2604 (-1, 2, 3, 4, 5), # Negative number.
2605 ('str', 4), # Not an int.
2606 (18, 23, 42, 2**63), # Out of range.
2607 (5, 4), # Not sorted.
2608 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002609 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002610 ):
2611 with self.assertRaises(
2612 ValueError,
2613 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2614 _posixsubprocess.fork_exec(
2615 [b"false"], [b"false"],
2616 True, fds_to_keep, None, [b"env"],
2617 -1, -1, -1, -1,
2618 1, 2, 3, 4,
2619 True, True, None)
2620 self.assertIn('fds_to_keep', str(c.exception))
2621 finally:
2622 if not gc_enabled:
2623 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002624
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002625 def test_communicate_BrokenPipeError_stdin_close(self):
2626 # By not setting stdout or stderr or a timeout we force the fast path
2627 # that just calls _stdin_write() internally due to our mock.
2628 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2629 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2630 mock_proc_stdin.close.side_effect = BrokenPipeError
2631 proc.communicate() # Should swallow BrokenPipeError from close.
2632 mock_proc_stdin.close.assert_called_with()
2633
2634 def test_communicate_BrokenPipeError_stdin_write(self):
2635 # By not setting stdout or stderr or a timeout we force the fast path
2636 # that just calls _stdin_write() internally due to our mock.
2637 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2638 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2639 mock_proc_stdin.write.side_effect = BrokenPipeError
2640 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2641 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2642 mock_proc_stdin.close.assert_called_once_with()
2643
2644 def test_communicate_BrokenPipeError_stdin_flush(self):
2645 # Setting stdin and stdout forces the ._communicate() code path.
2646 # python -h exits faster than python -c pass (but spams stdout).
2647 proc = subprocess.Popen([sys.executable, '-h'],
2648 stdin=subprocess.PIPE,
2649 stdout=subprocess.PIPE)
2650 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2651 open(os.devnull, 'wb') as dev_null:
2652 mock_proc_stdin.flush.side_effect = BrokenPipeError
2653 # because _communicate registers a selector using proc.stdin...
2654 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2655 # _communicate() should swallow BrokenPipeError from flush.
2656 proc.communicate(b'stuff')
2657 mock_proc_stdin.flush.assert_called_once_with()
2658
2659 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2660 # Setting stdin and stdout forces the ._communicate() code path.
2661 # python -h exits faster than python -c pass (but spams stdout).
2662 proc = subprocess.Popen([sys.executable, '-h'],
2663 stdin=subprocess.PIPE,
2664 stdout=subprocess.PIPE)
2665 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2666 mock_proc_stdin.close.side_effect = BrokenPipeError
2667 # _communicate() should swallow BrokenPipeError from close.
2668 proc.communicate(timeout=999)
2669 mock_proc_stdin.close.assert_called_once_with()
2670
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002671 @unittest.skipUnless(_testcapi is not None
2672 and hasattr(_testcapi, 'W_STOPCODE'),
2673 'need _testcapi.W_STOPCODE')
2674 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002675 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002676 args = [sys.executable, '-c', 'pass']
2677 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002678
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002679 # Wait until the real process completes to avoid zombie process
2680 pid = proc.pid
2681 pid, status = os.waitpid(pid, 0)
2682 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002683
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002684 status = _testcapi.W_STOPCODE(3)
2685 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
2686 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02002687
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002688 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002689
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002690
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002691@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002692class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002693
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002694 def test_startupinfo(self):
2695 # startupinfo argument
2696 # We uses hardcoded constants, because we do not want to
2697 # depend on win32all.
2698 STARTF_USESHOWWINDOW = 1
2699 SW_MAXIMIZE = 3
2700 startupinfo = subprocess.STARTUPINFO()
2701 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2702 startupinfo.wShowWindow = SW_MAXIMIZE
2703 # Since Python is a console process, it won't be affected
2704 # by wShowWindow, but the argument should be silently
2705 # ignored
2706 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002707 startupinfo=startupinfo)
2708
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302709 def test_startupinfo_keywords(self):
2710 # startupinfo argument
2711 # We use hardcoded constants, because we do not want to
2712 # depend on win32all.
2713 STARTF_USERSHOWWINDOW = 1
2714 SW_MAXIMIZE = 3
2715 startupinfo = subprocess.STARTUPINFO(
2716 dwFlags=STARTF_USERSHOWWINDOW,
2717 wShowWindow=SW_MAXIMIZE
2718 )
2719 # Since Python is a console process, it won't be affected
2720 # by wShowWindow, but the argument should be silently
2721 # ignored
2722 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2723 startupinfo=startupinfo)
2724
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002725 def test_creationflags(self):
2726 # creationflags argument
2727 CREATE_NEW_CONSOLE = 16
2728 sys.stderr.write(" a DOS box should flash briefly ...\n")
2729 subprocess.call(sys.executable +
2730 ' -c "import time; time.sleep(0.25)"',
2731 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002732
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002733 def test_invalid_args(self):
2734 # invalid arguments should raise ValueError
2735 self.assertRaises(ValueError, subprocess.call,
2736 [sys.executable, "-c",
2737 "import sys; sys.exit(47)"],
2738 preexec_fn=lambda: 1)
2739 self.assertRaises(ValueError, subprocess.call,
2740 [sys.executable, "-c",
2741 "import sys; sys.exit(47)"],
2742 stdout=subprocess.PIPE,
2743 close_fds=True)
2744
Oren Milman0b3a87e2017-09-14 22:30:28 +03002745 @support.cpython_only
2746 def test_issue31471(self):
2747 # There shouldn't be an assertion failure in Popen() in case the env
2748 # argument has a bad keys() method.
2749 class BadEnv(dict):
2750 keys = None
2751 with self.assertRaises(TypeError):
2752 subprocess.Popen([sys.executable, "-c", "pass"], env=BadEnv())
2753
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002754 def test_close_fds(self):
2755 # close file descriptors
2756 rc = subprocess.call([sys.executable, "-c",
2757 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002758 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002759 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002760
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002761 def test_shell_sequence(self):
2762 # Run command through the shell (sequence)
2763 newenv = os.environ.copy()
2764 newenv["FRUIT"] = "physalis"
2765 p = subprocess.Popen(["set"], shell=1,
2766 stdout=subprocess.PIPE,
2767 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002768 with p:
2769 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002770
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002771 def test_shell_string(self):
2772 # Run command through the shell (string)
2773 newenv = os.environ.copy()
2774 newenv["FRUIT"] = "physalis"
2775 p = subprocess.Popen("set", shell=1,
2776 stdout=subprocess.PIPE,
2777 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002778 with p:
2779 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002780
Steve Dower050acae2016-09-06 20:16:17 -07002781 def test_shell_encodings(self):
2782 # Run command through the shell (string)
2783 for enc in ['ansi', 'oem']:
2784 newenv = os.environ.copy()
2785 newenv["FRUIT"] = "physalis"
2786 p = subprocess.Popen("set", shell=1,
2787 stdout=subprocess.PIPE,
2788 env=newenv,
2789 encoding=enc)
2790 with p:
2791 self.assertIn("physalis", p.stdout.read(), enc)
2792
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002793 def test_call_string(self):
2794 # call() function with string argument on Windows
2795 rc = subprocess.call(sys.executable +
2796 ' -c "import sys; sys.exit(47)"')
2797 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002798
Florent Xicluna4886d242010-03-08 13:27:26 +00002799 def _kill_process(self, method, *args):
2800 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002801 p = subprocess.Popen([sys.executable, "-c", """if 1:
2802 import sys, time
2803 sys.stdout.write('x\\n')
2804 sys.stdout.flush()
2805 time.sleep(30)
2806 """],
2807 stdin=subprocess.PIPE,
2808 stdout=subprocess.PIPE,
2809 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002810 with p:
2811 # Wait for the interpreter to be completely initialized before
2812 # sending any signal.
2813 p.stdout.read(1)
2814 getattr(p, method)(*args)
2815 _, stderr = p.communicate()
2816 self.assertStderrEqual(stderr, b'')
2817 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002818 self.assertNotEqual(returncode, 0)
2819
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002820 def _kill_dead_process(self, method, *args):
2821 p = subprocess.Popen([sys.executable, "-c", """if 1:
2822 import sys, time
2823 sys.stdout.write('x\\n')
2824 sys.stdout.flush()
2825 sys.exit(42)
2826 """],
2827 stdin=subprocess.PIPE,
2828 stdout=subprocess.PIPE,
2829 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002830 with p:
2831 # Wait for the interpreter to be completely initialized before
2832 # sending any signal.
2833 p.stdout.read(1)
2834 # The process should end after this
2835 time.sleep(1)
2836 # This shouldn't raise even though the child is now dead
2837 getattr(p, method)(*args)
2838 _, stderr = p.communicate()
2839 self.assertStderrEqual(stderr, b'')
2840 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002841 self.assertEqual(rc, 42)
2842
Florent Xicluna4886d242010-03-08 13:27:26 +00002843 def test_send_signal(self):
2844 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002845
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002846 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002847 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002848
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002849 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002850 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002851
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002852 def test_send_signal_dead(self):
2853 self._kill_dead_process('send_signal', signal.SIGTERM)
2854
2855 def test_kill_dead(self):
2856 self._kill_dead_process('kill')
2857
2858 def test_terminate_dead(self):
2859 self._kill_dead_process('terminate')
2860
Martin Panter23172bd2016-04-16 11:28:10 +00002861class MiscTests(unittest.TestCase):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002862 def test_getoutput(self):
2863 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2864 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2865 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002866
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002867 # we use mkdtemp in the next line to create an empty directory
2868 # under our exclusive control; from that, we can invent a pathname
2869 # that we _know_ won't exist. This is guaranteed to fail.
2870 dir = None
2871 try:
2872 dir = tempfile.mkdtemp()
2873 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002874 status, output = subprocess.getstatusoutput(
2875 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002876 self.assertNotEqual(status, 0)
2877 finally:
2878 if dir is not None:
2879 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002880
Gregory P. Smithace55862015-04-07 15:57:54 -07002881 def test__all__(self):
2882 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00002883 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07002884 exported = set(subprocess.__all__)
2885 possible_exports = set()
2886 import types
2887 for name, value in subprocess.__dict__.items():
2888 if name.startswith('_'):
2889 continue
2890 if isinstance(value, (types.ModuleType,)):
2891 continue
2892 possible_exports.add(name)
2893 self.assertEqual(exported, possible_exports - intentionally_excluded)
2894
2895
Martin Panter23172bd2016-04-16 11:28:10 +00002896@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2897 "Test needs selectors.PollSelector")
2898class ProcessTestCaseNoPoll(ProcessTestCase):
2899 def setUp(self):
2900 self.orig_selector = subprocess._PopenSelector
2901 subprocess._PopenSelector = selectors.SelectSelector
2902 ProcessTestCase.setUp(self)
2903
2904 def tearDown(self):
2905 subprocess._PopenSelector = self.orig_selector
2906 ProcessTestCase.tearDown(self)
2907
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002908
Tim Golden126c2962010-08-11 14:20:40 +00002909@unittest.skipUnless(mswindows, "Windows-specific tests")
2910class CommandsWithSpaces (BaseTestCase):
2911
2912 def setUp(self):
2913 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002914 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002915 self.fname = fname.lower ()
2916 os.write(f, b"import sys;"
2917 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2918 )
2919 os.close(f)
2920
2921 def tearDown(self):
2922 os.remove(self.fname)
2923 super().tearDown()
2924
2925 def with_spaces(self, *args, **kwargs):
2926 kwargs['stdout'] = subprocess.PIPE
2927 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02002928 with p:
2929 self.assertEqual(
2930 p.stdout.read ().decode("mbcs"),
2931 "2 [%r, 'ab cd']" % self.fname
2932 )
Tim Golden126c2962010-08-11 14:20:40 +00002933
2934 def test_shell_string_with_spaces(self):
2935 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002936 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2937 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002938
2939 def test_shell_sequence_with_spaces(self):
2940 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002941 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002942
2943 def test_noshell_string_with_spaces(self):
2944 # call() function with string argument with spaces on Windows
2945 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2946 "ab cd"))
2947
2948 def test_noshell_sequence_with_spaces(self):
2949 # call() function with sequence argument with spaces on Windows
2950 self.with_spaces([sys.executable, self.fname, "ab cd"])
2951
Brian Curtin79cdb662010-12-03 02:46:02 +00002952
Georg Brandla86b2622012-02-20 21:34:57 +01002953class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002954
2955 def test_pipe(self):
2956 with subprocess.Popen([sys.executable, "-c",
2957 "import sys;"
2958 "sys.stdout.write('stdout');"
2959 "sys.stderr.write('stderr');"],
2960 stdout=subprocess.PIPE,
2961 stderr=subprocess.PIPE) as proc:
2962 self.assertEqual(proc.stdout.read(), b"stdout")
2963 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2964
2965 self.assertTrue(proc.stdout.closed)
2966 self.assertTrue(proc.stderr.closed)
2967
2968 def test_returncode(self):
2969 with subprocess.Popen([sys.executable, "-c",
2970 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002971 pass
2972 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002973 self.assertEqual(proc.returncode, 100)
2974
2975 def test_communicate_stdin(self):
2976 with subprocess.Popen([sys.executable, "-c",
2977 "import sys;"
2978 "sys.exit(sys.stdin.read() == 'context')"],
2979 stdin=subprocess.PIPE) as proc:
2980 proc.communicate(b"context")
2981 self.assertEqual(proc.returncode, 1)
2982
2983 def test_invalid_args(self):
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +01002984 with self.assertRaises((FileNotFoundError, PermissionError)) as c:
Victor Stinner9a83f652017-08-21 23:51:31 +02002985 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00002986 stdout=subprocess.PIPE,
2987 stderr=subprocess.PIPE) as proc:
2988 pass
2989
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002990 def test_broken_pipe_cleanup(self):
2991 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002992 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002993 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002994 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002995 proc = proc.__enter__()
2996 # Prepare to send enough data to overflow any OS pipe buffering and
2997 # guarantee a broken pipe error. Data is held in BufferedWriter
2998 # buffer until closed.
2999 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003000 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003001 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003002 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003003 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003004 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003005
Brian Curtin79cdb662010-12-03 02:46:02 +00003006
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003007if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003008 unittest.main()