blob: 858a70131205863bc94df900c8d0b6c170a28e13 [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',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010049# Ignore errors that indicate the command was not found
50NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020051
Florent Xiclunab1e94e82010-02-27 22:12:37 +000052
Florent Xiclunac049d872010-03-27 22:47:23 +000053class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054 def setUp(self):
55 # Try to minimize the number of children we have so this test
56 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000057 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000058
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000059 def tearDown(self):
60 for inst in subprocess._active:
61 inst.wait()
62 subprocess._cleanup()
63 self.assertFalse(subprocess._active, "subprocess._active not empty")
Victor Stinnercc42c122017-07-28 18:00:22 +020064 self.doCleanups()
65 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000066
Florent Xiclunab1e94e82010-02-27 22:12:37 +000067 def assertStderrEqual(self, stderr, expected, msg=None):
68 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
69 # shutdown time. That frustrates tests trying to check stderr produced
70 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000071 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040072 # strip_python_stderr also strips whitespace, so we do too.
73 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000074 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075
Florent Xiclunac049d872010-03-27 22:47:23 +000076
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080077class PopenTestException(Exception):
78 pass
79
80
81class PopenExecuteChildRaises(subprocess.Popen):
82 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
83 _execute_child fails.
84 """
85 def _execute_child(self, *args, **kwargs):
86 raise PopenTestException("Forced Exception for Test")
87
88
Florent Xiclunac049d872010-03-27 22:47:23 +000089class ProcessTestCase(BaseTestCase):
90
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070091 def test_io_buffered_by_default(self):
92 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
93 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
94 stderr=subprocess.PIPE)
95 try:
96 self.assertIsInstance(p.stdin, io.BufferedIOBase)
97 self.assertIsInstance(p.stdout, io.BufferedIOBase)
98 self.assertIsInstance(p.stderr, io.BufferedIOBase)
99 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700100 p.stdin.close()
101 p.stdout.close()
102 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700103 p.wait()
104
105 def test_io_unbuffered_works(self):
106 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
107 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
108 stderr=subprocess.PIPE, bufsize=0)
109 try:
110 self.assertIsInstance(p.stdin, io.RawIOBase)
111 self.assertIsInstance(p.stdout, io.RawIOBase)
112 self.assertIsInstance(p.stderr, io.RawIOBase)
113 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700114 p.stdin.close()
115 p.stdout.close()
116 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700117 p.wait()
118
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000119 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000120 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000121 rc = subprocess.call([sys.executable, "-c",
122 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000123 self.assertEqual(rc, 47)
124
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400125 def test_call_timeout(self):
126 # call() function with timeout argument; we want to test that the child
127 # process gets killed when the timeout expires. If the child isn't
128 # killed, this call will deadlock since subprocess.call waits for the
129 # child.
130 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
131 [sys.executable, "-c", "while True: pass"],
132 timeout=0.1)
133
Peter Astrand454f7672005-01-01 09:36:35 +0000134 def test_check_call_zero(self):
135 # check_call() function with zero return code
136 rc = subprocess.check_call([sys.executable, "-c",
137 "import sys; sys.exit(0)"])
138 self.assertEqual(rc, 0)
139
140 def test_check_call_nonzero(self):
141 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000142 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000143 subprocess.check_call([sys.executable, "-c",
144 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000145 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000146
Georg Brandlf9734072008-12-07 15:30:06 +0000147 def test_check_output(self):
148 # check_output() function with zero return code
149 output = subprocess.check_output(
150 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000151 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000152
153 def test_check_output_nonzero(self):
154 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000155 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000156 subprocess.check_output(
157 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000158 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000159
160 def test_check_output_stderr(self):
161 # check_output() function stderr redirected to stdout
162 output = subprocess.check_output(
163 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
164 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000165 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000166
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300167 def test_check_output_stdin_arg(self):
168 # check_output() can be called with stdin set to a file
169 tf = tempfile.TemporaryFile()
170 self.addCleanup(tf.close)
171 tf.write(b'pear')
172 tf.seek(0)
173 output = subprocess.check_output(
174 [sys.executable, "-c",
175 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
176 stdin=tf)
177 self.assertIn(b'PEAR', output)
178
179 def test_check_output_input_arg(self):
180 # check_output() can be called with input set to a string
181 output = subprocess.check_output(
182 [sys.executable, "-c",
183 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
184 input=b'pear')
185 self.assertIn(b'PEAR', output)
186
Georg Brandlf9734072008-12-07 15:30:06 +0000187 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300188 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000189 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000190 output = subprocess.check_output(
191 [sys.executable, "-c", "print('will not be run')"],
192 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000193 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000194 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000195
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300196 def test_check_output_stdin_with_input_arg(self):
197 # check_output() refuses to accept 'stdin' with 'input'
198 tf = tempfile.TemporaryFile()
199 self.addCleanup(tf.close)
200 tf.write(b'pear')
201 tf.seek(0)
202 with self.assertRaises(ValueError) as c:
203 output = subprocess.check_output(
204 [sys.executable, "-c", "print('will not be run')"],
205 stdin=tf, input=b'hare')
206 self.fail("Expected ValueError when stdin and input args supplied.")
207 self.assertIn('stdin', c.exception.args[0])
208 self.assertIn('input', c.exception.args[0])
209
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400210 def test_check_output_timeout(self):
211 # check_output() function with timeout arg
212 with self.assertRaises(subprocess.TimeoutExpired) as c:
213 output = subprocess.check_output(
214 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200215 "import sys, time\n"
216 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400217 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200218 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400219 # Some heavily loaded buildbots (sparc Debian 3.x) require
220 # this much time to start and print.
221 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400222 self.fail("Expected TimeoutExpired.")
223 self.assertEqual(c.exception.output, b'BDFL')
224
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000225 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000226 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 newenv = os.environ.copy()
228 newenv["FRUIT"] = "banana"
229 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000230 'import sys, os;'
231 'sys.exit(os.getenv("FRUIT")=="banana")'],
232 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233 self.assertEqual(rc, 1)
234
Victor Stinner87b9bc32011-06-01 00:57:47 +0200235 def test_invalid_args(self):
236 # Popen() called with invalid arguments should raise TypeError
237 # but Popen.__del__ should not complain (issue #12085)
238 with support.captured_stderr() as s:
239 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
240 argcount = subprocess.Popen.__init__.__code__.co_argcount
241 too_many_args = [0] * (argcount + 1)
242 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
243 self.assertEqual(s.getvalue(), '')
244
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000246 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000247 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000248 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000249 self.addCleanup(p.stdout.close)
250 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251 p.wait()
252 self.assertEqual(p.stdin, None)
253
254 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200255 # .stdout is None when not redirected, and the child's stdout will
256 # be inherited from the parent. In order to test this we run a
257 # subprocess in a subprocess:
258 # this_test
259 # \-- subprocess created by this test (parent)
260 # \-- subprocess created by the parent subprocess (child)
261 # The parent doesn't specify stdout, so the child will use the
262 # parent's stdout. This test checks that the message printed by the
263 # child goes to the parent stdout. The parent also checks that the
264 # child's stdout is None. See #11963.
265 code = ('import sys; from subprocess import Popen, PIPE;'
266 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
267 ' stdin=PIPE, stderr=PIPE);'
268 'p.wait(); assert p.stdout is None;')
269 p = subprocess.Popen([sys.executable, "-c", code],
270 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
271 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000272 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200273 out, err = p.communicate()
274 self.assertEqual(p.returncode, 0, err)
275 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276
277 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000278 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000279 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000280 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000281 self.addCleanup(p.stdout.close)
282 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000283 p.wait()
284 self.assertEqual(p.stderr, None)
285
Chris Jerdonek776cb192012-10-08 15:56:43 -0700286 def _assert_python(self, pre_args, **kwargs):
287 # We include sys.exit() to prevent the test runner from hanging
288 # whenever python is found.
289 args = pre_args + ["import sys; sys.exit(47)"]
290 p = subprocess.Popen(args, **kwargs)
291 p.wait()
292 self.assertEqual(47, p.returncode)
293
294 def test_executable(self):
295 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700296 #
297 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
298 # determine where its standard library is, so we need the directory
299 # of args[0] to be valid for the Popen() call to Python to succeed.
300 # See also issue #16170 and issue #7774.
301 doesnotexist = os.path.join(os.path.dirname(sys.executable),
302 "doesnotexist")
303 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700304
305 def test_executable_takes_precedence(self):
306 # Check that the executable argument takes precedence over args[0].
307 #
308 # Verify first that the call succeeds without the executable arg.
309 pre_args = [sys.executable, "-c"]
310 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100311 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100312 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100313 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700314
315 @unittest.skipIf(mswindows, "executable argument replaces shell")
316 def test_executable_replaces_shell(self):
317 # Check that the executable argument replaces the default shell
318 # when shell=True.
319 self._assert_python([], executable=sys.executable, shell=True)
320
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700321 # For use in the test_cwd* tests below.
322 def _normalize_cwd(self, cwd):
323 # Normalize an expected cwd (for Tru64 support).
324 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
325 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300326 with support.change_cwd(cwd):
327 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700328
329 # For use in the test_cwd* tests below.
330 def _split_python_path(self):
331 # Return normalized (python_dir, python_base).
332 python_path = os.path.realpath(sys.executable)
333 return os.path.split(python_path)
334
335 # For use in the test_cwd* tests below.
336 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
337 # Invoke Python via Popen, and assert that (1) the call succeeds,
338 # and that (2) the current working directory of the child process
339 # matches *expected_cwd*.
340 p = subprocess.Popen([python_arg, "-c",
341 "import os, sys; "
342 "sys.stdout.write(os.getcwd()); "
343 "sys.exit(47)"],
344 stdout=subprocess.PIPE,
345 **kwargs)
346 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000347 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700348 self.assertEqual(47, p.returncode)
349 normcase = os.path.normcase
350 self.assertEqual(normcase(expected_cwd),
351 normcase(p.stdout.read().decode("utf-8")))
352
353 def test_cwd(self):
354 # Check that cwd changes the cwd for the child process.
355 temp_dir = tempfile.gettempdir()
356 temp_dir = self._normalize_cwd(temp_dir)
357 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
358
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530359 def test_cwd_with_pathlike(self):
360 temp_dir = tempfile.gettempdir()
361 temp_dir = self._normalize_cwd(temp_dir)
362
363 class _PathLikeObj:
364 def __fspath__(self):
365 return temp_dir
366
367 self._assert_cwd(temp_dir, sys.executable, cwd=_PathLikeObj())
368
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700369 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700370 def test_cwd_with_relative_arg(self):
371 # Check that Popen looks for args[0] relative to cwd if args[0]
372 # is relative.
373 python_dir, python_base = self._split_python_path()
374 rel_python = os.path.join(os.curdir, python_base)
375 with support.temp_cwd() as wrong_dir:
376 # Before calling with the correct cwd, confirm that the call fails
377 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700378 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700379 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700380 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700381 [rel_python], cwd=wrong_dir)
382 python_dir = self._normalize_cwd(python_dir)
383 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
384
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700385 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700386 def test_cwd_with_relative_executable(self):
387 # Check that Popen looks for executable relative to cwd if executable
388 # is relative (and that executable takes precedence over args[0]).
389 python_dir, python_base = self._split_python_path()
390 rel_python = os.path.join(os.curdir, python_base)
391 doesntexist = "somethingyoudonthave"
392 with support.temp_cwd() as wrong_dir:
393 # Before calling with the correct cwd, confirm that the call fails
394 # without cwd and with the wrong cwd.
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)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700397 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700398 [doesntexist], executable=rel_python,
399 cwd=wrong_dir)
400 python_dir = self._normalize_cwd(python_dir)
401 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
402 cwd=python_dir)
403
404 def test_cwd_with_absolute_arg(self):
405 # Check that Popen can find the executable when the cwd is wrong
406 # if args[0] is an absolute path.
407 python_dir, python_base = self._split_python_path()
408 abs_python = os.path.join(python_dir, python_base)
409 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300410 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700411 # Before calling with an absolute path, confirm that using a
412 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700413 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700414 [rel_python], cwd=wrong_dir)
415 wrong_dir = self._normalize_cwd(wrong_dir)
416 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
417
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100418 @unittest.skipIf(sys.base_prefix != sys.prefix,
419 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000420 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700421 python_dir, python_base = self._split_python_path()
422 python_dir = self._normalize_cwd(python_dir)
423 self._assert_cwd(python_dir, "somethingyoudonthave",
424 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000425
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100426 @unittest.skipIf(sys.base_prefix != sys.prefix,
427 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000428 @unittest.skipIf(sysconfig.is_python_build(),
429 "need an installed Python. See #7774")
430 def test_executable_without_cwd(self):
431 # For a normal installation, it should work without 'cwd'
432 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700433 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
434 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435
436 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000437 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438 p = subprocess.Popen([sys.executable, "-c",
439 'import sys; sys.exit(sys.stdin.read() == "pear")'],
440 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000441 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000442 p.stdin.close()
443 p.wait()
444 self.assertEqual(p.returncode, 1)
445
446 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000447 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000448 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000449 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000450 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000451 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452 os.lseek(d, 0, 0)
453 p = subprocess.Popen([sys.executable, "-c",
454 'import sys; sys.exit(sys.stdin.read() == "pear")'],
455 stdin=d)
456 p.wait()
457 self.assertEqual(p.returncode, 1)
458
459 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000460 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000461 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000462 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000463 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464 tf.seek(0)
465 p = subprocess.Popen([sys.executable, "-c",
466 'import sys; sys.exit(sys.stdin.read() == "pear")'],
467 stdin=tf)
468 p.wait()
469 self.assertEqual(p.returncode, 1)
470
471 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000472 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000473 p = subprocess.Popen([sys.executable, "-c",
474 'import sys; sys.stdout.write("orange")'],
475 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200476 with p:
477 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478
479 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000480 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000481 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000482 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483 d = tf.fileno()
484 p = subprocess.Popen([sys.executable, "-c",
485 'import sys; sys.stdout.write("orange")'],
486 stdout=d)
487 p.wait()
488 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000489 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490
491 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000492 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000493 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000494 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495 p = subprocess.Popen([sys.executable, "-c",
496 'import sys; sys.stdout.write("orange")'],
497 stdout=tf)
498 p.wait()
499 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000500 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501
502 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000503 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504 p = subprocess.Popen([sys.executable, "-c",
505 'import sys; sys.stderr.write("strawberry")'],
506 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200507 with p:
508 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000509
510 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000511 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000512 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000513 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514 d = tf.fileno()
515 p = subprocess.Popen([sys.executable, "-c",
516 'import sys; sys.stderr.write("strawberry")'],
517 stderr=d)
518 p.wait()
519 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000520 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000521
522 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000523 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000524 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000525 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526 p = subprocess.Popen([sys.executable, "-c",
527 'import sys; sys.stderr.write("strawberry")'],
528 stderr=tf)
529 p.wait()
530 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000531 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532
Martin Panterc7635892016-05-13 01:54:44 +0000533 def test_stderr_redirect_with_no_stdout_redirect(self):
534 # test stderr=STDOUT while stdout=None (not set)
535
536 # - grandchild prints to stderr
537 # - child redirects grandchild's stderr to its stdout
538 # - the parent should get grandchild's stderr in child's stdout
539 p = subprocess.Popen([sys.executable, "-c",
540 'import sys, subprocess;'
541 'rc = subprocess.call([sys.executable, "-c",'
542 ' "import sys;"'
543 ' "sys.stderr.write(\'42\')"],'
544 ' stderr=subprocess.STDOUT);'
545 'sys.exit(rc)'],
546 stdout=subprocess.PIPE,
547 stderr=subprocess.PIPE)
548 stdout, stderr = p.communicate()
549 #NOTE: stdout should get stderr from grandchild
550 self.assertStderrEqual(stdout, b'42')
551 self.assertStderrEqual(stderr, b'') # should be empty
552 self.assertEqual(p.returncode, 0)
553
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000555 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000557 'import sys;'
558 'sys.stdout.write("apple");'
559 'sys.stdout.flush();'
560 'sys.stderr.write("orange")'],
561 stdout=subprocess.PIPE,
562 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200563 with p:
564 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565
566 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000567 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000569 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000570 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000571 'import sys;'
572 'sys.stdout.write("apple");'
573 'sys.stdout.flush();'
574 'sys.stderr.write("orange")'],
575 stdout=tf,
576 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000577 p.wait()
578 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000579 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000580
Thomas Wouters89f507f2006-12-13 04:49:30 +0000581 def test_stdout_filedes_of_stdout(self):
582 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200583 # To avoid printing the text on stdout, we do something similar to
584 # test_stdout_none (see above). The parent subprocess calls the child
585 # subprocess passing stdout=1, and this test uses stdout=PIPE in
586 # order to capture and check the output of the parent. See #11963.
587 code = ('import sys, subprocess; '
588 'rc = subprocess.call([sys.executable, "-c", '
589 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
590 'b\'test with stdout=1\'))"], stdout=1); '
591 'assert rc == 18')
592 p = subprocess.Popen([sys.executable, "-c", code],
593 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
594 self.addCleanup(p.stdout.close)
595 self.addCleanup(p.stderr.close)
596 out, err = p.communicate()
597 self.assertEqual(p.returncode, 0, err)
598 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000599
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200600 def test_stdout_devnull(self):
601 p = subprocess.Popen([sys.executable, "-c",
602 'for i in range(10240):'
603 'print("x" * 1024)'],
604 stdout=subprocess.DEVNULL)
605 p.wait()
606 self.assertEqual(p.stdout, None)
607
608 def test_stderr_devnull(self):
609 p = subprocess.Popen([sys.executable, "-c",
610 'import sys\n'
611 'for i in range(10240):'
612 'sys.stderr.write("x" * 1024)'],
613 stderr=subprocess.DEVNULL)
614 p.wait()
615 self.assertEqual(p.stderr, None)
616
617 def test_stdin_devnull(self):
618 p = subprocess.Popen([sys.executable, "-c",
619 'import sys;'
620 'sys.stdin.read(1)'],
621 stdin=subprocess.DEVNULL)
622 p.wait()
623 self.assertEqual(p.stdin, None)
624
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000625 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000626 newenv = os.environ.copy()
627 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200628 with subprocess.Popen([sys.executable, "-c",
629 'import sys,os;'
630 'sys.stdout.write(os.getenv("FRUIT"))'],
631 stdout=subprocess.PIPE,
632 env=newenv) as p:
633 stdout, stderr = p.communicate()
634 self.assertEqual(stdout, b"orange")
635
Victor Stinner62d51182011-06-23 01:02:25 +0200636 # Windows requires at least the SYSTEMROOT environment variable to start
637 # Python
638 @unittest.skipIf(sys.platform == 'win32',
639 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700640 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
641 'The Python shared library cannot be loaded '
642 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200643 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700644 """Verify that env={} is as empty as possible."""
645
Gregory P. Smith85aba232017-05-30 16:21:47 -0700646 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700647 """Determine if an environment variable is under our control."""
648 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
649 # on adding even when the environment in exec is empty.
650 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700651 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400652 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000653 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
654 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700655
Victor Stinnerf1512a22011-06-21 17:18:38 +0200656 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700657 'import os; print(list(os.environ.keys()))'],
658 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200659 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700660 child_env_names = eval(stdout.strip())
661 self.assertIsInstance(child_env_names, list)
662 child_env_names = [k for k in child_env_names
663 if not is_env_var_to_ignore(k)]
664 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000665
Serhiy Storchakad174d242017-06-23 19:39:27 +0300666 def test_invalid_cmd(self):
667 # null character in the command name
668 cmd = sys.executable + '\0'
669 with self.assertRaises(ValueError):
670 subprocess.Popen([cmd, "-c", "pass"])
671
672 # null character in the command argument
673 with self.assertRaises(ValueError):
674 subprocess.Popen([sys.executable, "-c", "pass#\0"])
675
676 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300677 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300678 newenv = os.environ.copy()
679 newenv["FRUIT\0VEGETABLE"] = "cabbage"
680 with self.assertRaises(ValueError):
681 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
682
Ville Skyttä49b27342017-08-03 09:00:59 +0300683 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300684 newenv = os.environ.copy()
685 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
686 with self.assertRaises(ValueError):
687 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
688
Ville Skyttä49b27342017-08-03 09:00:59 +0300689 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300690 newenv = os.environ.copy()
691 newenv["FRUIT=ORANGE"] = "lemon"
692 with self.assertRaises(ValueError):
693 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
694
Ville Skyttä49b27342017-08-03 09:00:59 +0300695 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300696 newenv = os.environ.copy()
697 newenv["FRUIT"] = "orange=lemon"
698 with subprocess.Popen([sys.executable, "-c",
699 'import sys, os;'
700 'sys.stdout.write(os.getenv("FRUIT"))'],
701 stdout=subprocess.PIPE,
702 env=newenv) as p:
703 stdout, stderr = p.communicate()
704 self.assertEqual(stdout, b"orange=lemon")
705
Peter Astrandcbac93c2005-03-03 20:24:28 +0000706 def test_communicate_stdin(self):
707 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000708 'import sys;'
709 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000710 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000711 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000712 self.assertEqual(p.returncode, 1)
713
714 def test_communicate_stdout(self):
715 p = subprocess.Popen([sys.executable, "-c",
716 'import sys; sys.stdout.write("pineapple")'],
717 stdout=subprocess.PIPE)
718 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000719 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000720 self.assertEqual(stderr, None)
721
722 def test_communicate_stderr(self):
723 p = subprocess.Popen([sys.executable, "-c",
724 'import sys; sys.stderr.write("pineapple")'],
725 stderr=subprocess.PIPE)
726 (stdout, stderr) = p.communicate()
727 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000728 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000729
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000732 'import sys,os;'
733 'sys.stderr.write("pineapple");'
734 'sys.stdout.write(sys.stdin.read())'],
735 stdin=subprocess.PIPE,
736 stdout=subprocess.PIPE,
737 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000738 self.addCleanup(p.stdout.close)
739 self.addCleanup(p.stderr.close)
740 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000741 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000742 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000743 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000744
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400745 def test_communicate_timeout(self):
746 p = subprocess.Popen([sys.executable, "-c",
747 'import sys,os,time;'
748 'sys.stderr.write("pineapple\\n");'
749 'time.sleep(1);'
750 'sys.stderr.write("pear\\n");'
751 'sys.stdout.write(sys.stdin.read())'],
752 universal_newlines=True,
753 stdin=subprocess.PIPE,
754 stdout=subprocess.PIPE,
755 stderr=subprocess.PIPE)
756 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
757 timeout=0.3)
758 # Make sure we can keep waiting for it, and that we get the whole output
759 # after it completes.
760 (stdout, stderr) = p.communicate()
761 self.assertEqual(stdout, "banana")
762 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
763
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700764 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200765 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400766 p = subprocess.Popen([sys.executable, "-c",
767 'import sys,os,time;'
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 'time.sleep(0.2);'
774 'sys.stdout.write("a" * (64 * 1024));'],
775 stdout=subprocess.PIPE)
776 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
777 (stdout, _) = p.communicate()
778 self.assertEqual(len(stdout), 4 * 64 * 1024)
779
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000780 # Test for the fd leak reported in http://bugs.python.org/issue2791.
781 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000782 for stdin_pipe in (False, True):
783 for stdout_pipe in (False, True):
784 for stderr_pipe in (False, True):
785 options = {}
786 if stdin_pipe:
787 options['stdin'] = subprocess.PIPE
788 if stdout_pipe:
789 options['stdout'] = subprocess.PIPE
790 if stderr_pipe:
791 options['stderr'] = subprocess.PIPE
792 if not options:
793 continue
794 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
795 p.communicate()
796 if p.stdin is not None:
797 self.assertTrue(p.stdin.closed)
798 if p.stdout is not None:
799 self.assertTrue(p.stdout.closed)
800 if p.stderr is not None:
801 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000802
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000803 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000804 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000805 p = subprocess.Popen([sys.executable, "-c",
806 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000807 (stdout, stderr) = p.communicate()
808 self.assertEqual(stdout, None)
809 self.assertEqual(stderr, None)
810
811 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000812 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000813 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000814 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000815 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000816 os.close(x)
817 os.close(y)
818 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000819 'import sys,os;'
820 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200821 'sys.stderr.write("x" * %d);'
822 'sys.stdout.write(sys.stdin.read())' %
823 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000824 stdin=subprocess.PIPE,
825 stdout=subprocess.PIPE,
826 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000827 self.addCleanup(p.stdout.close)
828 self.addCleanup(p.stderr.close)
829 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200830 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000831 (stdout, stderr) = p.communicate(string_to_write)
832 self.assertEqual(stdout, string_to_write)
833
834 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000835 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000836 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000837 'import sys,os;'
838 'sys.stdout.write(sys.stdin.read())'],
839 stdin=subprocess.PIPE,
840 stdout=subprocess.PIPE,
841 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000842 self.addCleanup(p.stdout.close)
843 self.addCleanup(p.stderr.close)
844 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000845 p.stdin.write(b"banana")
846 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000847 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000848 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000849
andyclegg7fed7bd2017-10-23 03:01:19 +0100850 def test_universal_newlines_and_text(self):
851 args = [
852 sys.executable, "-c",
853 'import sys,os;' + SETBINARY +
854 'buf = sys.stdout.buffer;'
855 'buf.write(sys.stdin.readline().encode());'
856 'buf.flush();'
857 'buf.write(b"line2\\n");'
858 'buf.flush();'
859 'buf.write(sys.stdin.read().encode());'
860 'buf.flush();'
861 'buf.write(b"line4\\n");'
862 'buf.flush();'
863 'buf.write(b"line5\\r\\n");'
864 'buf.flush();'
865 'buf.write(b"line6\\r");'
866 'buf.flush();'
867 'buf.write(b"\\nline7");'
868 'buf.flush();'
869 'buf.write(b"\\nline8");']
870
871 for extra_kwarg in ('universal_newlines', 'text'):
872 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
873 'stdout': subprocess.PIPE,
874 extra_kwarg: True})
875 with p:
876 p.stdin.write("line1\n")
877 p.stdin.flush()
878 self.assertEqual(p.stdout.readline(), "line1\n")
879 p.stdin.write("line3\n")
880 p.stdin.close()
881 self.addCleanup(p.stdout.close)
882 self.assertEqual(p.stdout.readline(),
883 "line2\n")
884 self.assertEqual(p.stdout.read(6),
885 "line3\n")
886 self.assertEqual(p.stdout.read(),
887 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000888
889 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000890 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000891 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000892 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200893 'buf = sys.stdout.buffer;'
894 'buf.write(b"line2\\n");'
895 'buf.flush();'
896 'buf.write(b"line4\\n");'
897 'buf.flush();'
898 'buf.write(b"line5\\r\\n");'
899 'buf.flush();'
900 'buf.write(b"line6\\r");'
901 'buf.flush();'
902 'buf.write(b"\\nline7");'
903 'buf.flush();'
904 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200905 stderr=subprocess.PIPE,
906 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000907 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000908 self.addCleanup(p.stdout.close)
909 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000910 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200911 self.assertEqual(stdout,
912 "line2\nline4\nline5\nline6\nline7\nline8")
913
914 def test_universal_newlines_communicate_stdin(self):
915 # universal newlines through communicate(), with only stdin
916 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300917 'import sys,os;' + SETBINARY + textwrap.dedent('''
918 s = sys.stdin.readline()
919 assert s == "line1\\n", repr(s)
920 s = sys.stdin.read()
921 assert s == "line3\\n", repr(s)
922 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200923 stdin=subprocess.PIPE,
924 universal_newlines=1)
925 (stdout, stderr) = p.communicate("line1\nline3\n")
926 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000927
Andrew Svetlovf3765072012-08-14 18:35:17 +0300928 def test_universal_newlines_communicate_input_none(self):
929 # Test communicate(input=None) with universal newlines.
930 #
931 # We set stdout to PIPE because, as of this writing, a different
932 # code path is tested when the number of pipes is zero or one.
933 p = subprocess.Popen([sys.executable, "-c", "pass"],
934 stdin=subprocess.PIPE,
935 stdout=subprocess.PIPE,
936 universal_newlines=True)
937 p.communicate()
938 self.assertEqual(p.returncode, 0)
939
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300940 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300941 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300942 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300943 'import sys,os;' + SETBINARY + textwrap.dedent('''
944 s = sys.stdin.buffer.readline()
945 sys.stdout.buffer.write(s)
946 sys.stdout.buffer.write(b"line2\\r")
947 sys.stderr.buffer.write(b"eline2\\n")
948 s = sys.stdin.buffer.read()
949 sys.stdout.buffer.write(s)
950 sys.stdout.buffer.write(b"line4\\n")
951 sys.stdout.buffer.write(b"line5\\r\\n")
952 sys.stderr.buffer.write(b"eline6\\r")
953 sys.stderr.buffer.write(b"eline7\\r\\nz")
954 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300955 stdin=subprocess.PIPE,
956 stderr=subprocess.PIPE,
957 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300958 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300959 self.addCleanup(p.stdout.close)
960 self.addCleanup(p.stderr.close)
961 (stdout, stderr) = p.communicate("line1\nline3\n")
962 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300963 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300964 # Python debug build push something like "[42442 refs]\n"
965 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300966 # Don't use assertStderrEqual because it strips CR and LF from output.
967 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300968
Andrew Svetlov82860712012-08-19 22:13:41 +0300969 def test_universal_newlines_communicate_encodings(self):
970 # Check that universal newlines mode works for various encodings,
971 # in particular for encodings in the UTF-16 and UTF-32 families.
972 # See issue #15595.
973 #
974 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
975 # without, and UTF-16 and UTF-32.
976 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300977 code = ("import sys; "
978 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
979 encoding)
980 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700981 # We set stdin to be non-None because, as of this writing,
982 # a different code path is used when the number of pipes is
983 # zero or one.
984 popen = subprocess.Popen(args,
985 stdin=subprocess.PIPE,
986 stdout=subprocess.PIPE,
987 encoding=encoding)
988 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +0300989 self.assertEqual(stdout, '1\n2\n3\n4')
990
Steve Dower050acae2016-09-06 20:16:17 -0700991 def test_communicate_errors(self):
992 for errors, expected in [
993 ('ignore', ''),
994 ('replace', '\ufffd\ufffd'),
995 ('surrogateescape', '\udc80\udc80'),
996 ('backslashreplace', '\\x80\\x80'),
997 ]:
998 code = ("import sys; "
999 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1000 args = [sys.executable, '-c', code]
1001 # We set stdin to be non-None because, as of this writing,
1002 # a different code path is used when the number of pipes is
1003 # zero or one.
1004 popen = subprocess.Popen(args,
1005 stdin=subprocess.PIPE,
1006 stdout=subprocess.PIPE,
1007 encoding='utf-8',
1008 errors=errors)
1009 stdout, stderr = popen.communicate(input='')
1010 self.assertEqual(stdout, '[{}]'.format(expected))
1011
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001012 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001013 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +00001014 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001015 max_handles = 1026 # too much for most UNIX systems
1016 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001017 max_handles = 2050 # too much for (at least some) Windows setups
1018 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001019 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001020 try:
1021 for i in range(max_handles):
1022 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001023 tmpfile = os.path.join(tmpdir, support.TESTFN)
1024 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001025 except OSError as e:
1026 if e.errno != errno.EMFILE:
1027 raise
1028 break
1029 else:
1030 self.skipTest("failed to reach the file descriptor limit "
1031 "(tried %d)" % max_handles)
1032 # Close a couple of them (should be enough for a subprocess)
1033 for i in range(10):
1034 os.close(handles.pop())
1035 # Loop creating some subprocesses. If one of them leaks some fds,
1036 # the next loop iteration will fail by reaching the max fd limit.
1037 for i in range(15):
1038 p = subprocess.Popen([sys.executable, "-c",
1039 "import sys;"
1040 "sys.stdout.write(sys.stdin.read())"],
1041 stdin=subprocess.PIPE,
1042 stdout=subprocess.PIPE,
1043 stderr=subprocess.PIPE)
1044 data = p.communicate(b"lime")[0]
1045 self.assertEqual(data, b"lime")
1046 finally:
1047 for h in handles:
1048 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001049 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001050
1051 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001052 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1053 '"a b c" d e')
1054 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1055 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001056 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1057 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001058 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1059 'a\\\\\\b "de fg" h')
1060 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1061 'a\\\\\\"b c d')
1062 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1063 '"a\\\\b c" d e')
1064 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1065 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001066 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1067 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001068
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001069 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001070 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001071 "import os; os.read(0, 1)"],
1072 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001073 self.addCleanup(p.stdin.close)
1074 self.assertIsNone(p.poll())
1075 os.write(p.stdin.fileno(), b'A')
1076 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001077 # Subsequent invocations should just return the returncode
1078 self.assertEqual(p.poll(), 0)
1079
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001080 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001081 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001082 self.assertEqual(p.wait(), 0)
1083 # Subsequent invocations should just return the returncode
1084 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001085
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001086 def test_wait_timeout(self):
1087 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001088 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001089 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001090 p.wait(timeout=0.0001)
1091 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001092 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1093 # time to start.
1094 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001095
Peter Astrand738131d2004-11-30 21:04:45 +00001096 def test_invalid_bufsize(self):
1097 # an invalid type of the bufsize argument should raise
1098 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001099 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001100 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001101
Guido van Rossum46a05a72007-06-07 21:56:45 +00001102 def test_bufsize_is_none(self):
1103 # bufsize=None should be the same as bufsize=0.
1104 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1105 self.assertEqual(p.wait(), 0)
1106 # Again with keyword arg
1107 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1108 self.assertEqual(p.wait(), 0)
1109
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001110 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1111 # subprocess may deadlock with bufsize=1, see issue #21332
1112 with subprocess.Popen([sys.executable, "-c", "import sys;"
1113 "sys.stdout.write(sys.stdin.readline());"
1114 "sys.stdout.flush()"],
1115 stdin=subprocess.PIPE,
1116 stdout=subprocess.PIPE,
1117 stderr=subprocess.DEVNULL,
1118 bufsize=1,
1119 universal_newlines=universal_newlines) as p:
1120 p.stdin.write(line) # expect that it flushes the line in text mode
1121 os.close(p.stdin.fileno()) # close it without flushing the buffer
1122 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001123 with support.SuppressCrashReport():
1124 try:
1125 p.stdin.close()
1126 except OSError:
1127 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001128 p.stdin = None
1129 self.assertEqual(p.returncode, 0)
1130 self.assertEqual(read_line, expected)
1131
1132 def test_bufsize_equal_one_text_mode(self):
1133 # line is flushed in text mode with bufsize=1.
1134 # we should get the full line in return
1135 line = "line\n"
1136 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1137
1138 def test_bufsize_equal_one_binary_mode(self):
1139 # line is not flushed in binary mode with bufsize=1.
1140 # we should get empty response
1141 line = b'line' + os.linesep.encode() # assume ascii-based locale
1142 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1143
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001144 def test_leaking_fds_on_error(self):
1145 # see bug #5179: Popen leaks file descriptors to PIPEs if
1146 # the child fails to execute; this will eventually exhaust
1147 # the maximum number of open fds. 1024 seems a very common
1148 # value for that limit, but Windows has 2048, so we loop
1149 # 1024 times (each call leaked two fds).
1150 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001151 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001152 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001153 stdout=subprocess.PIPE,
1154 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001155
Victor Stinner9a83f652017-08-21 23:51:31 +02001156 def test_nonexisting_with_pipes(self):
1157 # bpo-30121: Popen with pipes must close properly pipes on error.
1158 # Previously, os.close() was called with a Windows handle which is not
1159 # a valid file descriptor.
1160 #
1161 # Run the test in a subprocess to control how the CRT reports errors
1162 # and to get stderr content.
1163 try:
1164 import msvcrt
1165 msvcrt.CrtSetReportMode
1166 except (AttributeError, ImportError):
1167 self.skipTest("need msvcrt.CrtSetReportMode")
1168
1169 code = textwrap.dedent(f"""
1170 import msvcrt
1171 import subprocess
1172
1173 cmd = {NONEXISTING_CMD!r}
1174
1175 for report_type in [msvcrt.CRT_WARN,
1176 msvcrt.CRT_ERROR,
1177 msvcrt.CRT_ASSERT]:
1178 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1179 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1180
1181 try:
1182 subprocess.Popen([cmd],
1183 stdout=subprocess.PIPE,
1184 stderr=subprocess.PIPE)
1185 except OSError:
1186 pass
1187 """)
1188 cmd = [sys.executable, "-c", code]
1189 proc = subprocess.Popen(cmd,
1190 stderr=subprocess.PIPE,
1191 universal_newlines=True)
1192 with proc:
1193 stderr = proc.communicate()[1]
1194 self.assertEqual(stderr, "")
1195 self.assertEqual(proc.returncode, 0)
1196
Antoine Pitroua8392712013-08-30 23:38:13 +02001197 def test_double_close_on_error(self):
1198 # Issue #18851
1199 fds = []
1200 def open_fds():
1201 for i in range(20):
1202 fds.extend(os.pipe())
1203 time.sleep(0.001)
1204 t = threading.Thread(target=open_fds)
1205 t.start()
1206 try:
1207 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001208 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001209 stdin=subprocess.PIPE,
1210 stdout=subprocess.PIPE,
1211 stderr=subprocess.PIPE)
1212 finally:
1213 t.join()
1214 exc = None
1215 for fd in fds:
1216 # If a double close occurred, some of those fds will
1217 # already have been closed by mistake, and os.close()
1218 # here will raise.
1219 try:
1220 os.close(fd)
1221 except OSError as e:
1222 exc = e
1223 if exc is not None:
1224 raise exc
1225
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001226 def test_threadsafe_wait(self):
1227 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1228 proc = subprocess.Popen([sys.executable, '-c',
1229 'import time; time.sleep(12)'])
1230 self.assertEqual(proc.returncode, None)
1231 results = []
1232
1233 def kill_proc_timer_thread():
1234 results.append(('thread-start-poll-result', proc.poll()))
1235 # terminate it from the thread and wait for the result.
1236 proc.kill()
1237 proc.wait()
1238 results.append(('thread-after-kill-and-wait', proc.returncode))
1239 # this wait should be a no-op given the above.
1240 proc.wait()
1241 results.append(('thread-after-second-wait', proc.returncode))
1242
1243 # This is a timing sensitive test, the failure mode is
1244 # triggered when both the main thread and this thread are in
1245 # the wait() call at once. The delay here is to allow the
1246 # main thread to most likely be blocked in its wait() call.
1247 t = threading.Timer(0.2, kill_proc_timer_thread)
1248 t.start()
1249
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001250 if mswindows:
1251 expected_errorcode = 1
1252 else:
1253 # Should be -9 because of the proc.kill() from the thread.
1254 expected_errorcode = -9
1255
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001256 # Wait for the process to finish; the thread should kill it
1257 # long before it finishes on its own. Supplying a timeout
1258 # triggers a different code path for better coverage.
1259 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001260 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001261 msg="unexpected result in wait from main thread")
1262
1263 # This should be a no-op with no change in returncode.
1264 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001265 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001266 msg="unexpected result in second main wait.")
1267
1268 t.join()
1269 # Ensure that all of the thread results are as expected.
1270 # When a race condition occurs in wait(), the returncode could
1271 # be set by the wrong thread that doesn't actually have it
1272 # leading to an incorrect value.
1273 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001274 ('thread-after-kill-and-wait', expected_errorcode),
1275 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001276 results)
1277
Victor Stinnerb3693582010-05-21 20:13:12 +00001278 def test_issue8780(self):
1279 # Ensure that stdout is inherited from the parent
1280 # if stdout=PIPE is not used
1281 code = ';'.join((
1282 'import subprocess, sys',
1283 'retcode = subprocess.call('
1284 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1285 'assert retcode == 0'))
1286 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001287 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001288
Tim Goldenaf5ac392010-08-06 13:03:56 +00001289 def test_handles_closed_on_exception(self):
1290 # If CreateProcess exits with an error, ensure the
1291 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001292 ifhandle, ifname = tempfile.mkstemp()
1293 ofhandle, ofname = tempfile.mkstemp()
1294 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001295 try:
1296 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1297 stderr=efhandle)
1298 except OSError:
1299 os.close(ifhandle)
1300 os.remove(ifname)
1301 os.close(ofhandle)
1302 os.remove(ofname)
1303 os.close(efhandle)
1304 os.remove(efname)
1305 self.assertFalse(os.path.exists(ifname))
1306 self.assertFalse(os.path.exists(ofname))
1307 self.assertFalse(os.path.exists(efname))
1308
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001309 def test_communicate_epipe(self):
1310 # Issue 10963: communicate() should hide EPIPE
1311 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1312 stdin=subprocess.PIPE,
1313 stdout=subprocess.PIPE,
1314 stderr=subprocess.PIPE)
1315 self.addCleanup(p.stdout.close)
1316 self.addCleanup(p.stderr.close)
1317 self.addCleanup(p.stdin.close)
1318 p.communicate(b"x" * 2**20)
1319
1320 def test_communicate_epipe_only_stdin(self):
1321 # Issue 10963: communicate() should hide EPIPE
1322 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1323 stdin=subprocess.PIPE)
1324 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001325 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001326 p.communicate(b"x" * 2**20)
1327
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001328 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1329 "Requires signal.SIGUSR1")
1330 @unittest.skipUnless(hasattr(os, 'kill'),
1331 "Requires os.kill")
1332 @unittest.skipUnless(hasattr(os, 'getppid'),
1333 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001334 def test_communicate_eintr(self):
1335 # Issue #12493: communicate() should handle EINTR
1336 def handler(signum, frame):
1337 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001338 old_handler = signal.signal(signal.SIGUSR1, handler)
1339 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001340
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001341 args = [sys.executable, "-c",
1342 'import os, signal;'
1343 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001344 for stream in ('stdout', 'stderr'):
1345 kw = {stream: subprocess.PIPE}
1346 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001347 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001348 process.communicate()
1349
Tim Peterse718f612004-10-12 21:51:32 +00001350
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001351 # This test is Linux-ish specific for simplicity to at least have
1352 # some coverage. It is not a platform specific bug.
1353 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1354 "Linux specific")
1355 def test_failed_child_execute_fd_leak(self):
1356 """Test for the fork() failure fd leak reported in issue16327."""
1357 fd_directory = '/proc/%d/fd' % os.getpid()
1358 fds_before_popen = os.listdir(fd_directory)
1359 with self.assertRaises(PopenTestException):
1360 PopenExecuteChildRaises(
1361 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1362 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1363
1364 # NOTE: This test doesn't verify that the real _execute_child
1365 # does not close the file descriptors itself on the way out
1366 # during an exception. Code inspection has confirmed that.
1367
1368 fds_after_exception = os.listdir(fd_directory)
1369 self.assertEqual(fds_before_popen, fds_after_exception)
1370
Gregory P. Smitha3a6df32017-08-24 18:15:02 -07001371 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001372 def test_file_not_found_includes_filename(self):
1373 with self.assertRaises(FileNotFoundError) as c:
1374 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1375 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1376
Gregory P. Smitha3a6df32017-08-24 18:15:02 -07001377 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001378 def test_file_not_found_with_bad_cwd(self):
1379 with self.assertRaises(FileNotFoundError) as c:
1380 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1381 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1382
Gregory P. Smith6e730002015-04-14 16:14:25 -07001383
1384class RunFuncTestCase(BaseTestCase):
1385 def run_python(self, code, **kwargs):
1386 """Run Python code in a subprocess using subprocess.run"""
1387 argv = [sys.executable, "-c", code]
1388 return subprocess.run(argv, **kwargs)
1389
1390 def test_returncode(self):
1391 # call() function with sequence argument
1392 cp = self.run_python("import sys; sys.exit(47)")
1393 self.assertEqual(cp.returncode, 47)
1394 with self.assertRaises(subprocess.CalledProcessError):
1395 cp.check_returncode()
1396
1397 def test_check(self):
1398 with self.assertRaises(subprocess.CalledProcessError) as c:
1399 self.run_python("import sys; sys.exit(47)", check=True)
1400 self.assertEqual(c.exception.returncode, 47)
1401
1402 def test_check_zero(self):
1403 # check_returncode shouldn't raise when returncode is zero
1404 cp = self.run_python("import sys; sys.exit(0)", check=True)
1405 self.assertEqual(cp.returncode, 0)
1406
1407 def test_timeout(self):
1408 # run() function with timeout argument; we want to test that the child
1409 # process gets killed when the timeout expires. If the child isn't
1410 # killed, this call will deadlock since subprocess.run waits for the
1411 # child.
1412 with self.assertRaises(subprocess.TimeoutExpired):
1413 self.run_python("while True: pass", timeout=0.0001)
1414
1415 def test_capture_stdout(self):
1416 # capture stdout with zero return code
1417 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1418 self.assertIn(b'BDFL', cp.stdout)
1419
1420 def test_capture_stderr(self):
1421 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1422 stderr=subprocess.PIPE)
1423 self.assertIn(b'BDFL', cp.stderr)
1424
1425 def test_check_output_stdin_arg(self):
1426 # run() can be called with stdin set to a file
1427 tf = tempfile.TemporaryFile()
1428 self.addCleanup(tf.close)
1429 tf.write(b'pear')
1430 tf.seek(0)
1431 cp = self.run_python(
1432 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1433 stdin=tf, stdout=subprocess.PIPE)
1434 self.assertIn(b'PEAR', cp.stdout)
1435
1436 def test_check_output_input_arg(self):
1437 # check_output() can be called with input set to a string
1438 cp = self.run_python(
1439 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1440 input=b'pear', stdout=subprocess.PIPE)
1441 self.assertIn(b'PEAR', cp.stdout)
1442
1443 def test_check_output_stdin_with_input_arg(self):
1444 # run() refuses to accept 'stdin' with 'input'
1445 tf = tempfile.TemporaryFile()
1446 self.addCleanup(tf.close)
1447 tf.write(b'pear')
1448 tf.seek(0)
1449 with self.assertRaises(ValueError,
1450 msg="Expected ValueError when stdin and input args supplied.") as c:
1451 output = self.run_python("print('will not be run')",
1452 stdin=tf, input=b'hare')
1453 self.assertIn('stdin', c.exception.args[0])
1454 self.assertIn('input', c.exception.args[0])
1455
1456 def test_check_output_timeout(self):
1457 with self.assertRaises(subprocess.TimeoutExpired) as c:
1458 cp = self.run_python((
1459 "import sys, time\n"
1460 "sys.stdout.write('BDFL')\n"
1461 "sys.stdout.flush()\n"
1462 "time.sleep(3600)"),
1463 # Some heavily loaded buildbots (sparc Debian 3.x) require
1464 # this much time to start and print.
1465 timeout=3, stdout=subprocess.PIPE)
1466 self.assertEqual(c.exception.output, b'BDFL')
1467 # output is aliased to stdout
1468 self.assertEqual(c.exception.stdout, b'BDFL')
1469
1470 def test_run_kwargs(self):
1471 newenv = os.environ.copy()
1472 newenv["FRUIT"] = "banana"
1473 cp = self.run_python(('import sys, os;'
1474 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1475 env=newenv)
1476 self.assertEqual(cp.returncode, 33)
1477
Anders Lorentsendd42cb72018-01-30 08:27:28 +01001478 def test_run_with_pathlike_path(self):
1479 # bpo-31961: test run(pathlike_object)
1480 class Path:
1481 def __fspath__(self):
1482 # the name of a command that can be run without
1483 # any argumenets that exit fast
1484 return 'dir' if mswindows else 'ls'
1485
1486 path = Path()
1487 if mswindows:
1488 res = subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1489 else:
1490 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1491
1492 self.assertEqual(res.returncode, 0)
1493
1494 def test_run_with_pathlike_path_and_arguments(self):
1495 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1496 class Path:
1497 def __fspath__(self):
1498 # the name of a command that can be run without
1499 # any argumenets that exits fast
1500 return sys.executable
1501
1502 path = Path()
1503
1504 args = [path, '-c', 'import sys; sys.exit(57)']
1505 res = subprocess.run(args)
1506
1507 self.assertEqual(res.returncode, 57)
1508
Bo Baylesce0f33d2018-01-30 00:40:39 -06001509 def test_capture_output(self):
1510 cp = self.run_python(("import sys;"
1511 "sys.stdout.write('BDFL'); "
1512 "sys.stderr.write('FLUFL')"),
1513 capture_output=True)
1514 self.assertIn(b'BDFL', cp.stdout)
1515 self.assertIn(b'FLUFL', cp.stderr)
1516
1517 def test_stdout_with_capture_output_arg(self):
1518 # run() refuses to accept 'stdout' with 'capture_output'
1519 tf = tempfile.TemporaryFile()
1520 self.addCleanup(tf.close)
1521 with self.assertRaises(ValueError,
1522 msg=("Expected ValueError when stdout and capture_output "
1523 "args supplied.")) as c:
1524 output = self.run_python("print('will not be run')",
1525 capture_output=True, stdout=tf)
1526 self.assertIn('stdout', c.exception.args[0])
1527 self.assertIn('capture_output', c.exception.args[0])
1528
1529 def test_stderr_with_capture_output_arg(self):
1530 # run() refuses to accept 'stderr' with 'capture_output'
1531 tf = tempfile.TemporaryFile()
1532 self.addCleanup(tf.close)
1533 with self.assertRaises(ValueError,
1534 msg=("Expected ValueError when stderr and capture_output "
1535 "args supplied.")) as c:
1536 output = self.run_python("print('will not be run')",
1537 capture_output=True, stderr=tf)
1538 self.assertIn('stderr', c.exception.args[0])
1539 self.assertIn('capture_output', c.exception.args[0])
1540
Gregory P. Smith6e730002015-04-14 16:14:25 -07001541
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001542@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001543class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001544
Gregory P. Smith5591b022012-10-10 03:34:47 -07001545 def setUp(self):
1546 super().setUp()
1547 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1548
1549 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001550 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001551 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001552 except OSError as e:
1553 # This avoids hard coding the errno value or the OS perror()
1554 # string and instead capture the exception that we want to see
1555 # below for comparison.
1556 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001557 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001558 else:
Martin Pantereb995702016-07-28 01:11:04 +00001559 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001560 self._nonexistent_dir)
1561 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001562
Gregory P. Smith5591b022012-10-10 03:34:47 -07001563 def test_exception_cwd(self):
1564 """Test error in the child raised in the parent for a bad cwd."""
1565 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001566 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001567 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001568 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001569 except OSError as e:
1570 # Test that the child process chdir failure actually makes
1571 # it up to the parent process as the correct exception.
1572 self.assertEqual(desired_exception.errno, e.errno)
1573 self.assertEqual(desired_exception.strerror, e.strerror)
1574 else:
1575 self.fail("Expected OSError: %s" % desired_exception)
1576
Gregory P. Smith5591b022012-10-10 03:34:47 -07001577 def test_exception_bad_executable(self):
1578 """Test error in the child raised in the parent for a bad executable."""
1579 desired_exception = self._get_chdir_exception()
1580 try:
1581 p = subprocess.Popen([sys.executable, "-c", ""],
1582 executable=self._nonexistent_dir)
1583 except OSError as e:
1584 # Test that the child process exec failure actually makes
1585 # it up to the parent process as the correct exception.
1586 self.assertEqual(desired_exception.errno, e.errno)
1587 self.assertEqual(desired_exception.strerror, e.strerror)
1588 else:
1589 self.fail("Expected OSError: %s" % desired_exception)
1590
1591 def test_exception_bad_args_0(self):
1592 """Test error in the child raised in the parent for a bad args[0]."""
1593 desired_exception = self._get_chdir_exception()
1594 try:
1595 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1596 except OSError as e:
1597 # Test that the child process exec failure actually makes
1598 # it up to the parent process as the correct exception.
1599 self.assertEqual(desired_exception.errno, e.errno)
1600 self.assertEqual(desired_exception.strerror, e.strerror)
1601 else:
1602 self.fail("Expected OSError: %s" % desired_exception)
1603
Ammar Askar3fc499b2017-09-06 02:41:30 -04001604 # We mock the __del__ method for Popen in the next two tests
1605 # because it does cleanup based on the pid returned by fork_exec
1606 # along with issuing a resource warning if it still exists. Since
1607 # we don't actually spawn a process in these tests we can forego
1608 # the destructor. An alternative would be to set _child_created to
1609 # False before the destructor is called but there is no easy way
1610 # to do that
1611 class PopenNoDestructor(subprocess.Popen):
1612 def __del__(self):
1613 pass
1614
1615 @mock.patch("subprocess._posixsubprocess.fork_exec")
1616 def test_exception_errpipe_normal(self, fork_exec):
1617 """Test error passing done through errpipe_write in the good case"""
1618 def proper_error(*args):
1619 errpipe_write = args[13]
1620 # Write the hex for the error code EISDIR: 'is a directory'
1621 err_code = '{:x}'.format(errno.EISDIR).encode()
1622 os.write(errpipe_write, b"OSError:" + err_code + b":")
1623 return 0
1624
1625 fork_exec.side_effect = proper_error
1626
Victor Stinner11045c92017-10-05 06:32:53 -07001627 with mock.patch("subprocess.os.waitpid",
1628 side_effect=ChildProcessError):
1629 with self.assertRaises(IsADirectoryError):
1630 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001631
1632 @mock.patch("subprocess._posixsubprocess.fork_exec")
1633 def test_exception_errpipe_bad_data(self, fork_exec):
1634 """Test error passing done through errpipe_write where its not
1635 in the expected format"""
1636 error_data = b"\xFF\x00\xDE\xAD"
1637 def bad_error(*args):
1638 errpipe_write = args[13]
1639 # Anything can be in the pipe, no assumptions should
1640 # be made about its encoding, so we'll write some
1641 # arbitrary hex bytes to test it out
1642 os.write(errpipe_write, error_data)
1643 return 0
1644
1645 fork_exec.side_effect = bad_error
1646
Victor Stinner11045c92017-10-05 06:32:53 -07001647 with mock.patch("subprocess.os.waitpid",
1648 side_effect=ChildProcessError):
1649 with self.assertRaises(subprocess.SubprocessError) as e:
1650 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001651
1652 self.assertIn(repr(error_data), str(e.exception))
1653
1654
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001655 def test_restore_signals(self):
1656 # Code coverage for both values of restore_signals to make sure it
1657 # at least does not blow up.
1658 # A test for behavior would be complex. Contributions welcome.
1659 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1660 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1661
1662 def test_start_new_session(self):
1663 # For code coverage of calling setsid(). We don't care if we get an
1664 # EPERM error from it depending on the test execution environment, that
1665 # still indicates that it was called.
1666 try:
1667 output = subprocess.check_output(
1668 [sys.executable, "-c",
1669 "import os; print(os.getpgid(os.getpid()))"],
1670 start_new_session=True)
1671 except OSError as e:
1672 if e.errno != errno.EPERM:
1673 raise
1674 else:
1675 parent_pgid = os.getpgid(os.getpid())
1676 child_pgid = int(output)
1677 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001678
1679 def test_run_abort(self):
1680 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001681 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001682 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001683 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001684 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001685 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001686
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001687 def test_CalledProcessError_str_signal(self):
1688 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1689 error_string = str(err)
1690 # We're relying on the repr() of the signal.Signals intenum to provide
1691 # the word signal, the signal name and the numeric value.
1692 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001693 # We're not being specific about the signal name as some signals have
1694 # multiple names and which name is revealed can vary.
1695 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001696 self.assertIn(str(signal.SIGABRT), error_string)
1697
1698 def test_CalledProcessError_str_unknown_signal(self):
1699 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1700 error_string = str(err)
1701 self.assertIn("unknown signal 9876543.", error_string)
1702
1703 def test_CalledProcessError_str_non_zero(self):
1704 err = subprocess.CalledProcessError(2, "fake cmd")
1705 error_string = str(err)
1706 self.assertIn("non-zero exit status 2.", error_string)
1707
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001708 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001709 # DISCLAIMER: Setting environment variables is *not* a good use
1710 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001711 p = subprocess.Popen([sys.executable, "-c",
1712 'import sys,os;'
1713 'sys.stdout.write(os.getenv("FRUIT"))'],
1714 stdout=subprocess.PIPE,
1715 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001716 with p:
1717 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001718
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001719 def test_preexec_exception(self):
1720 def raise_it():
1721 raise ValueError("What if two swallows carried a coconut?")
1722 try:
1723 p = subprocess.Popen([sys.executable, "-c", ""],
1724 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001725 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001726 self.assertTrue(
1727 subprocess._posixsubprocess,
1728 "Expected a ValueError from the preexec_fn")
1729 except ValueError as e:
1730 self.assertIn("coconut", e.args[0])
1731 else:
1732 self.fail("Exception raised by preexec_fn did not make it "
1733 "to the parent process.")
1734
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001735 class _TestExecuteChildPopen(subprocess.Popen):
1736 """Used to test behavior at the end of _execute_child."""
1737 def __init__(self, testcase, *args, **kwargs):
1738 self._testcase = testcase
1739 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001740
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001741 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001742 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001743 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001744 finally:
1745 # Open a bunch of file descriptors and verify that
1746 # none of them are the same as the ones the Popen
1747 # instance is using for stdin/stdout/stderr.
1748 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1749 for _ in range(8)]
1750 try:
1751 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001752 self._testcase.assertNotIn(
1753 fd, (self.stdin.fileno(), self.stdout.fileno(),
1754 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001755 msg="At least one fd was closed early.")
1756 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001757 for fd in devzero_fds:
1758 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001759
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001760 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1761 def test_preexec_errpipe_does_not_double_close_pipes(self):
1762 """Issue16140: Don't double close pipes on preexec error."""
1763
1764 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001765 raise subprocess.SubprocessError(
1766 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001767
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001768 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001769 self._TestExecuteChildPopen(
1770 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001771 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1772 stderr=subprocess.PIPE, preexec_fn=raise_it)
1773
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001774 def test_preexec_gc_module_failure(self):
1775 # This tests the code that disables garbage collection if the child
1776 # process will execute any Python.
1777 def raise_runtime_error():
1778 raise RuntimeError("this shouldn't escape")
1779 enabled = gc.isenabled()
1780 orig_gc_disable = gc.disable
1781 orig_gc_isenabled = gc.isenabled
1782 try:
1783 gc.disable()
1784 self.assertFalse(gc.isenabled())
1785 subprocess.call([sys.executable, '-c', ''],
1786 preexec_fn=lambda: None)
1787 self.assertFalse(gc.isenabled(),
1788 "Popen enabled gc when it shouldn't.")
1789
1790 gc.enable()
1791 self.assertTrue(gc.isenabled())
1792 subprocess.call([sys.executable, '-c', ''],
1793 preexec_fn=lambda: None)
1794 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1795
1796 gc.disable = raise_runtime_error
1797 self.assertRaises(RuntimeError, subprocess.Popen,
1798 [sys.executable, '-c', ''],
1799 preexec_fn=lambda: None)
1800
1801 del gc.isenabled # force an AttributeError
1802 self.assertRaises(AttributeError, subprocess.Popen,
1803 [sys.executable, '-c', ''],
1804 preexec_fn=lambda: None)
1805 finally:
1806 gc.disable = orig_gc_disable
1807 gc.isenabled = orig_gc_isenabled
1808 if not enabled:
1809 gc.disable()
1810
Martin Panterf7fdbda2015-12-05 09:51:52 +00001811 @unittest.skipIf(
1812 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001813 def test_preexec_fork_failure(self):
1814 # The internal code did not preserve the previous exception when
1815 # re-enabling garbage collection
1816 try:
1817 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1818 except ImportError as err:
1819 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1820 limits = getrlimit(RLIMIT_NPROC)
1821 [_, hard] = limits
1822 setrlimit(RLIMIT_NPROC, (0, hard))
1823 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001824 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001825 subprocess.call([sys.executable, '-c', ''],
1826 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001827 except BlockingIOError:
1828 # Forking should raise EAGAIN, translated to BlockingIOError
1829 pass
1830 else:
1831 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001832
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001833 def test_args_string(self):
1834 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001835 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001836 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001837 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001838 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001839 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1840 sys.executable)
1841 os.chmod(fname, 0o700)
1842 p = subprocess.Popen(fname)
1843 p.wait()
1844 os.remove(fname)
1845 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001846
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001847 def test_invalid_args(self):
1848 # invalid arguments should raise ValueError
1849 self.assertRaises(ValueError, subprocess.call,
1850 [sys.executable, "-c",
1851 "import sys; sys.exit(47)"],
1852 startupinfo=47)
1853 self.assertRaises(ValueError, subprocess.call,
1854 [sys.executable, "-c",
1855 "import sys; sys.exit(47)"],
1856 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001857
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001858 def test_shell_sequence(self):
1859 # Run command through the shell (sequence)
1860 newenv = os.environ.copy()
1861 newenv["FRUIT"] = "apple"
1862 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1863 stdout=subprocess.PIPE,
1864 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001865 with p:
1866 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001867
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001868 def test_shell_string(self):
1869 # Run command through the shell (string)
1870 newenv = os.environ.copy()
1871 newenv["FRUIT"] = "apple"
1872 p = subprocess.Popen("echo $FRUIT", shell=1,
1873 stdout=subprocess.PIPE,
1874 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001875 with p:
1876 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001877
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001878 def test_call_string(self):
1879 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001880 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001881 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001882 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001883 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001884 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1885 sys.executable)
1886 os.chmod(fname, 0o700)
1887 rc = subprocess.call(fname)
1888 os.remove(fname)
1889 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001890
Stefan Krah9542cc62010-07-19 14:20:53 +00001891 def test_specific_shell(self):
1892 # Issue #9265: Incorrect name passed as arg[0].
1893 shells = []
1894 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1895 for name in ['bash', 'ksh']:
1896 sh = os.path.join(prefix, name)
1897 if os.path.isfile(sh):
1898 shells.append(sh)
1899 if not shells: # Will probably work for any shell but csh.
1900 self.skipTest("bash or ksh required for this test")
1901 sh = '/bin/sh'
1902 if os.path.isfile(sh) and not os.path.islink(sh):
1903 # Test will fail if /bin/sh is a symlink to csh.
1904 shells.append(sh)
1905 for sh in shells:
1906 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1907 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001908 with p:
1909 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001910
Florent Xicluna4886d242010-03-08 13:27:26 +00001911 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001912 # Do not inherit file handles from the parent.
1913 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001914 # Also set the SIGINT handler to the default to make sure it's not
1915 # being ignored (some tests rely on that.)
1916 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1917 try:
1918 p = subprocess.Popen([sys.executable, "-c", """if 1:
1919 import sys, time
1920 sys.stdout.write('x\\n')
1921 sys.stdout.flush()
1922 time.sleep(30)
1923 """],
1924 close_fds=True,
1925 stdin=subprocess.PIPE,
1926 stdout=subprocess.PIPE,
1927 stderr=subprocess.PIPE)
1928 finally:
1929 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001930 # Wait for the interpreter to be completely initialized before
1931 # sending any signal.
1932 p.stdout.read(1)
1933 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001934 return p
1935
Charles-François Natali53221e32013-01-12 16:52:20 +01001936 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1937 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001938 def _kill_dead_process(self, method, *args):
1939 # Do not inherit file handles from the parent.
1940 # It should fix failures on some platforms.
1941 p = subprocess.Popen([sys.executable, "-c", """if 1:
1942 import sys, time
1943 sys.stdout.write('x\\n')
1944 sys.stdout.flush()
1945 """],
1946 close_fds=True,
1947 stdin=subprocess.PIPE,
1948 stdout=subprocess.PIPE,
1949 stderr=subprocess.PIPE)
1950 # Wait for the interpreter to be completely initialized before
1951 # sending any signal.
1952 p.stdout.read(1)
1953 # The process should end after this
1954 time.sleep(1)
1955 # This shouldn't raise even though the child is now dead
1956 getattr(p, method)(*args)
1957 p.communicate()
1958
Florent Xicluna4886d242010-03-08 13:27:26 +00001959 def test_send_signal(self):
1960 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001961 _, stderr = p.communicate()
1962 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001963 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001964
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001965 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001966 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001967 _, stderr = p.communicate()
1968 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001969 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001970
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001971 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001972 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001973 _, stderr = p.communicate()
1974 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001975 self.assertEqual(p.wait(), -signal.SIGTERM)
1976
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001977 def test_send_signal_dead(self):
1978 # Sending a signal to a dead process
1979 self._kill_dead_process('send_signal', signal.SIGINT)
1980
1981 def test_kill_dead(self):
1982 # Killing a dead process
1983 self._kill_dead_process('kill')
1984
1985 def test_terminate_dead(self):
1986 # Terminating a dead process
1987 self._kill_dead_process('terminate')
1988
Victor Stinnerdaf45552013-08-28 00:53:59 +02001989 def _save_fds(self, save_fds):
1990 fds = []
1991 for fd in save_fds:
1992 inheritable = os.get_inheritable(fd)
1993 saved = os.dup(fd)
1994 fds.append((fd, saved, inheritable))
1995 return fds
1996
1997 def _restore_fds(self, fds):
1998 for fd, saved, inheritable in fds:
1999 os.dup2(saved, fd, inheritable=inheritable)
2000 os.close(saved)
2001
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002002 def check_close_std_fds(self, fds):
2003 # Issue #9905: test that subprocess pipes still work properly with
2004 # some standard fds closed
2005 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002006 saved_fds = self._save_fds(fds)
2007 for fd, saved, inheritable in saved_fds:
2008 if fd == 0:
2009 stdin = saved
2010 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002011 try:
2012 for fd in fds:
2013 os.close(fd)
2014 out, err = subprocess.Popen([sys.executable, "-c",
2015 'import sys;'
2016 'sys.stdout.write("apple");'
2017 'sys.stdout.flush();'
2018 'sys.stderr.write("orange")'],
2019 stdin=stdin,
2020 stdout=subprocess.PIPE,
2021 stderr=subprocess.PIPE).communicate()
2022 err = support.strip_python_stderr(err)
2023 self.assertEqual((out, err), (b'apple', b'orange'))
2024 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002025 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002026
2027 def test_close_fd_0(self):
2028 self.check_close_std_fds([0])
2029
2030 def test_close_fd_1(self):
2031 self.check_close_std_fds([1])
2032
2033 def test_close_fd_2(self):
2034 self.check_close_std_fds([2])
2035
2036 def test_close_fds_0_1(self):
2037 self.check_close_std_fds([0, 1])
2038
2039 def test_close_fds_0_2(self):
2040 self.check_close_std_fds([0, 2])
2041
2042 def test_close_fds_1_2(self):
2043 self.check_close_std_fds([1, 2])
2044
2045 def test_close_fds_0_1_2(self):
2046 # Issue #10806: test that subprocess pipes still work properly with
2047 # all standard fds closed.
2048 self.check_close_std_fds([0, 1, 2])
2049
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002050 def test_small_errpipe_write_fd(self):
2051 """Issue #15798: Popen should work when stdio fds are available."""
2052 new_stdin = os.dup(0)
2053 new_stdout = os.dup(1)
2054 try:
2055 os.close(0)
2056 os.close(1)
2057
2058 # Side test: if errpipe_write fails to have its CLOEXEC
2059 # flag set this should cause the parent to think the exec
2060 # failed. Extremely unlikely: everyone supports CLOEXEC.
2061 subprocess.Popen([
2062 sys.executable, "-c",
2063 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2064 finally:
2065 # Restore original stdin and stdout
2066 os.dup2(new_stdin, 0)
2067 os.dup2(new_stdout, 1)
2068 os.close(new_stdin)
2069 os.close(new_stdout)
2070
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002071 def test_remapping_std_fds(self):
2072 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002073 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002074 try:
2075 temp_fds = [fd for fd, fname in temps]
2076
2077 # unlink the files -- we won't need to reopen them
2078 for fd, fname in temps:
2079 os.unlink(fname)
2080
2081 # write some data to what will become stdin, and rewind
2082 os.write(temp_fds[1], b"STDIN")
2083 os.lseek(temp_fds[1], 0, 0)
2084
2085 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002086 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002087 try:
2088 # duplicate the file objects over the standard fd's
2089 for fd, temp_fd in enumerate(temp_fds):
2090 os.dup2(temp_fd, fd)
2091
2092 # now use those files in the "wrong" order, so that subprocess
2093 # has to rearrange them in the child
2094 p = subprocess.Popen([sys.executable, "-c",
2095 'import sys; got = sys.stdin.read();'
2096 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2097 stdin=temp_fds[1],
2098 stdout=temp_fds[2],
2099 stderr=temp_fds[0])
2100 p.wait()
2101 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002102 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002103
2104 for fd in temp_fds:
2105 os.lseek(fd, 0, 0)
2106
2107 out = os.read(temp_fds[2], 1024)
2108 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2109 self.assertEqual(out, b"got STDIN")
2110 self.assertEqual(err, b"err")
2111
2112 finally:
2113 for fd in temp_fds:
2114 os.close(fd)
2115
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002116 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2117 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002118 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002119 temp_fds = [fd for fd, fname in temps]
2120 try:
2121 # unlink the files -- we won't need to reopen them
2122 for fd, fname in temps:
2123 os.unlink(fname)
2124
2125 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002126 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002127 try:
2128 # duplicate the temp files over the standard fd's 0, 1, 2
2129 for fd, temp_fd in enumerate(temp_fds):
2130 os.dup2(temp_fd, fd)
2131
2132 # write some data to what will become stdin, and rewind
2133 os.write(stdin_no, b"STDIN")
2134 os.lseek(stdin_no, 0, 0)
2135
2136 # now use those files in the given order, so that subprocess
2137 # has to rearrange them in the child
2138 p = subprocess.Popen([sys.executable, "-c",
2139 'import sys; got = sys.stdin.read();'
2140 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2141 stdin=stdin_no,
2142 stdout=stdout_no,
2143 stderr=stderr_no)
2144 p.wait()
2145
2146 for fd in temp_fds:
2147 os.lseek(fd, 0, 0)
2148
2149 out = os.read(stdout_no, 1024)
2150 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2151 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002152 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002153
2154 self.assertEqual(out, b"got STDIN")
2155 self.assertEqual(err, b"err")
2156
2157 finally:
2158 for fd in temp_fds:
2159 os.close(fd)
2160
2161 # When duping fds, if there arises a situation where one of the fds is
2162 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2163 # This tests all combinations of this.
2164 def test_swap_fds(self):
2165 self.check_swap_fds(0, 1, 2)
2166 self.check_swap_fds(0, 2, 1)
2167 self.check_swap_fds(1, 0, 2)
2168 self.check_swap_fds(1, 2, 0)
2169 self.check_swap_fds(2, 0, 1)
2170 self.check_swap_fds(2, 1, 0)
2171
Victor Stinner13bb71c2010-04-23 21:41:56 +00002172 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002173 def prepare():
2174 raise ValueError("surrogate:\uDCff")
2175
2176 try:
2177 subprocess.call(
2178 [sys.executable, "-c", "pass"],
2179 preexec_fn=prepare)
2180 except ValueError as err:
2181 # Pure Python implementations keeps the message
2182 self.assertIsNone(subprocess._posixsubprocess)
2183 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002184 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002185 # _posixsubprocess uses a default message
2186 self.assertIsNotNone(subprocess._posixsubprocess)
2187 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2188 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002189 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002190
Victor Stinner13bb71c2010-04-23 21:41:56 +00002191 def test_undecodable_env(self):
2192 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002193 encoded_value = value.encode("ascii", "surrogateescape")
2194
Victor Stinner13bb71c2010-04-23 21:41:56 +00002195 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002196 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002197 env = os.environ.copy()
2198 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002199 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00002200 # surrogate-escaping of \xFF in the child process; otherwise it can
2201 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00002202 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01002203 if sys.platform.startswith("aix"):
2204 # On AIX, the C locale uses the Latin1 encoding
2205 decoded_value = encoded_value.decode("latin1", "surrogateescape")
2206 else:
2207 # On other UNIXes, the C locale uses the ASCII encoding
2208 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002209 stdout = subprocess.check_output(
2210 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002211 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002212 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002213 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002214
2215 # test bytes
2216 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002217 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002218 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002219 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002220 stdout = subprocess.check_output(
2221 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002222 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002223 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002224 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002225
Victor Stinnerb745a742010-05-18 17:17:23 +00002226 def test_bytes_program(self):
2227 abs_program = os.fsencode(sys.executable)
2228 path, program = os.path.split(sys.executable)
2229 program = os.fsencode(program)
2230
2231 # absolute bytes path
2232 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002233 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002234
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002235 # absolute bytes path as a string
2236 cmd = b"'" + abs_program + b"' -c pass"
2237 exitcode = subprocess.call(cmd, shell=True)
2238 self.assertEqual(exitcode, 0)
2239
Victor Stinnerb745a742010-05-18 17:17:23 +00002240 # bytes program, unicode PATH
2241 env = os.environ.copy()
2242 env["PATH"] = path
2243 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002244 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002245
2246 # bytes program, bytes PATH
2247 envb = os.environb.copy()
2248 envb[b"PATH"] = os.fsencode(path)
2249 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002250 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002251
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002252 def test_pipe_cloexec(self):
2253 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2254 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2255
2256 p1 = subprocess.Popen([sys.executable, sleeper],
2257 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2258 stderr=subprocess.PIPE, close_fds=False)
2259
2260 self.addCleanup(p1.communicate, b'')
2261
2262 p2 = subprocess.Popen([sys.executable, fd_status],
2263 stdout=subprocess.PIPE, close_fds=False)
2264
2265 output, error = p2.communicate()
2266 result_fds = set(map(int, output.split(b',')))
2267 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2268 p1.stderr.fileno()])
2269
2270 self.assertFalse(result_fds & unwanted_fds,
2271 "Expected no fds from %r to be open in child, "
2272 "found %r" %
2273 (unwanted_fds, result_fds & unwanted_fds))
2274
2275 def test_pipe_cloexec_real_tools(self):
2276 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2277 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2278
2279 subdata = b'zxcvbn'
2280 data = subdata * 4 + b'\n'
2281
2282 p1 = subprocess.Popen([sys.executable, qcat],
2283 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2284 close_fds=False)
2285
2286 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2287 stdin=p1.stdout, stdout=subprocess.PIPE,
2288 close_fds=False)
2289
2290 self.addCleanup(p1.wait)
2291 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002292 def kill_p1():
2293 try:
2294 p1.terminate()
2295 except ProcessLookupError:
2296 pass
2297 def kill_p2():
2298 try:
2299 p2.terminate()
2300 except ProcessLookupError:
2301 pass
2302 self.addCleanup(kill_p1)
2303 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002304
2305 p1.stdin.write(data)
2306 p1.stdin.close()
2307
2308 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2309
2310 self.assertTrue(readfiles, "The child hung")
2311 self.assertEqual(p2.stdout.read(), data)
2312
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002313 p1.stdout.close()
2314 p2.stdout.close()
2315
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002316 def test_close_fds(self):
2317 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2318
2319 fds = os.pipe()
2320 self.addCleanup(os.close, fds[0])
2321 self.addCleanup(os.close, fds[1])
2322
2323 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002324 # add a bunch more fds
2325 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002326 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002327 self.addCleanup(os.close, fd)
2328 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002329
Victor Stinnerdaf45552013-08-28 00:53:59 +02002330 for fd in open_fds:
2331 os.set_inheritable(fd, True)
2332
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002333 p = subprocess.Popen([sys.executable, fd_status],
2334 stdout=subprocess.PIPE, close_fds=False)
2335 output, ignored = p.communicate()
2336 remaining_fds = set(map(int, output.split(b',')))
2337
2338 self.assertEqual(remaining_fds & open_fds, open_fds,
2339 "Some fds were closed")
2340
2341 p = subprocess.Popen([sys.executable, fd_status],
2342 stdout=subprocess.PIPE, close_fds=True)
2343 output, ignored = p.communicate()
2344 remaining_fds = set(map(int, output.split(b',')))
2345
2346 self.assertFalse(remaining_fds & open_fds,
2347 "Some fds were left open")
2348 self.assertIn(1, remaining_fds, "Subprocess failed")
2349
Gregory P. Smith8facece2012-01-21 14:01:08 -08002350 # Keep some of the fd's we opened open in the subprocess.
2351 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2352 fds_to_keep = set(open_fds.pop() for _ in range(8))
2353 p = subprocess.Popen([sys.executable, fd_status],
2354 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002355 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002356 output, ignored = p.communicate()
2357 remaining_fds = set(map(int, output.split(b',')))
2358
izbyshev2d8f0632017-12-19 03:26:49 +07002359 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002360 "Some fds not in pass_fds were left open")
2361 self.assertIn(1, remaining_fds, "Subprocess failed")
2362
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002363
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002364 @unittest.skipIf(sys.platform.startswith("freebsd") and
2365 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2366 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002367 def test_close_fds_when_max_fd_is_lowered(self):
2368 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2369 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2370
Gregory P. Smith634aa682014-06-15 17:51:04 -07002371 # This launches the meat of the test in a child process to
2372 # avoid messing with the larger unittest processes maximum
2373 # number of file descriptors.
2374 # This process launches:
2375 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2376 # a bunch of high open fds above the new lower rlimit.
2377 # Those are reported via stdout before launching a new
2378 # process with close_fds=False to run the actual test:
2379 # +--> The TEST: This one launches a fd_status.py
2380 # subprocess with close_fds=True so we can find out if
2381 # any of the fds above the lowered rlimit are still open.
2382 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2383 '''
2384 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002385 open_fds = set()
2386 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002387 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002388 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002389 open_fds.add(fd)
2390
2391 # Leave a two pairs of low ones available for use by the
2392 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002393 # We also leave 10 more open as some Python buildbots run into
2394 # "too many open files" errors during the test if we do not.
2395 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002396 os.close(fd)
2397 open_fds.remove(fd)
2398
2399 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002400 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002401 os.set_inheritable(fd, True)
2402
2403 max_fd_open = max(open_fds)
2404
Gregory P. Smith634aa682014-06-15 17:51:04 -07002405 # Communicate the open_fds to the parent unittest.TestCase process.
2406 print(','.join(map(str, sorted(open_fds))))
2407 sys.stdout.flush()
2408
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002409 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2410 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002411 # 29 is lower than the highest fds we are leaving open.
2412 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002413 # Launch a new Python interpreter with our low fd rlim_cur that
2414 # inherits open fds above that limit. It then uses subprocess
2415 # with close_fds=True to get a report of open fds in the child.
2416 # An explicit list of fds to check is passed to fd_status.py as
2417 # letting fd_status rely on its default logic would miss the
2418 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002419 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002420 [sys.executable, '-c',
2421 textwrap.dedent("""
2422 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002423 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002424 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002425 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002426 """.format(max_fd=max_fd_open+1))],
2427 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002428 finally:
2429 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002430 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002431
2432 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002433 output_lines = output.splitlines()
2434 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002435 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002436 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2437 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002438
Gregory P. Smith634aa682014-06-15 17:51:04 -07002439 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002440 msg="Some fds were left open.")
2441
2442
Victor Stinner88701e22011-06-01 13:13:04 +02002443 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2444 # descriptor of a pipe closed in the parent process is valid in the
2445 # child process according to fstat(), but the mode of the file
2446 # descriptor is invalid, and read or write raise an error.
2447 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002448 def test_pass_fds(self):
2449 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2450
2451 open_fds = set()
2452
2453 for x in range(5):
2454 fds = os.pipe()
2455 self.addCleanup(os.close, fds[0])
2456 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002457 os.set_inheritable(fds[0], True)
2458 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002459 open_fds.update(fds)
2460
2461 for fd in open_fds:
2462 p = subprocess.Popen([sys.executable, fd_status],
2463 stdout=subprocess.PIPE, close_fds=True,
2464 pass_fds=(fd, ))
2465 output, ignored = p.communicate()
2466
2467 remaining_fds = set(map(int, output.split(b',')))
2468 to_be_closed = open_fds - {fd}
2469
2470 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2471 self.assertFalse(remaining_fds & to_be_closed,
2472 "fd to be closed passed")
2473
2474 # pass_fds overrides close_fds with a warning.
2475 with self.assertWarns(RuntimeWarning) as context:
2476 self.assertFalse(subprocess.call(
2477 [sys.executable, "-c", "import sys; sys.exit(0)"],
2478 close_fds=False, pass_fds=(fd, )))
2479 self.assertIn('overriding close_fds', str(context.warning))
2480
Victor Stinnerdaf45552013-08-28 00:53:59 +02002481 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002482 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002483
2484 inheritable, non_inheritable = os.pipe()
2485 self.addCleanup(os.close, inheritable)
2486 self.addCleanup(os.close, non_inheritable)
2487 os.set_inheritable(inheritable, True)
2488 os.set_inheritable(non_inheritable, False)
2489 pass_fds = (inheritable, non_inheritable)
2490 args = [sys.executable, script]
2491 args += list(map(str, pass_fds))
2492
2493 p = subprocess.Popen(args,
2494 stdout=subprocess.PIPE, close_fds=True,
2495 pass_fds=pass_fds)
2496 output, ignored = p.communicate()
2497 fds = set(map(int, output.split(b',')))
2498
2499 # the inheritable file descriptor must be inherited, so its inheritable
2500 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002501 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002502
2503 # inheritable flag must not be changed in the parent process
2504 self.assertEqual(os.get_inheritable(inheritable), True)
2505 self.assertEqual(os.get_inheritable(non_inheritable), False)
2506
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002507 def test_stdout_stdin_are_single_inout_fd(self):
2508 with io.open(os.devnull, "r+") as inout:
2509 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2510 stdout=inout, stdin=inout)
2511 p.wait()
2512
2513 def test_stdout_stderr_are_single_inout_fd(self):
2514 with io.open(os.devnull, "r+") as inout:
2515 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2516 stdout=inout, stderr=inout)
2517 p.wait()
2518
2519 def test_stderr_stdin_are_single_inout_fd(self):
2520 with io.open(os.devnull, "r+") as inout:
2521 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2522 stderr=inout, stdin=inout)
2523 p.wait()
2524
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002525 def test_wait_when_sigchild_ignored(self):
2526 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2527 sigchild_ignore = support.findfile("sigchild_ignore.py",
2528 subdir="subprocessdata")
2529 p = subprocess.Popen([sys.executable, sigchild_ignore],
2530 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2531 stdout, stderr = p.communicate()
2532 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002533 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002534 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002535
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002536 def test_select_unbuffered(self):
2537 # Issue #11459: bufsize=0 should really set the pipes as
2538 # unbuffered (and therefore let select() work properly).
2539 select = support.import_module("select")
2540 p = subprocess.Popen([sys.executable, "-c",
2541 'import sys;'
2542 'sys.stdout.write("apple")'],
2543 stdout=subprocess.PIPE,
2544 bufsize=0)
2545 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002546 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002547 try:
2548 self.assertEqual(f.read(4), b"appl")
2549 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2550 finally:
2551 p.wait()
2552
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002553 def test_zombie_fast_process_del(self):
2554 # Issue #12650: on Unix, if Popen.__del__() was called before the
2555 # process exited, it wouldn't be added to subprocess._active, and would
2556 # remain a zombie.
2557 # spawn a Popen, and delete its reference before it exits
2558 p = subprocess.Popen([sys.executable, "-c",
2559 'import sys, time;'
2560 'time.sleep(0.2)'],
2561 stdout=subprocess.PIPE,
2562 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002563 self.addCleanup(p.stdout.close)
2564 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002565 ident = id(p)
2566 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002567 with support.check_warnings(('', ResourceWarning)):
2568 p = None
2569
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002570 # check that p is in the active processes list
2571 self.assertIn(ident, [id(o) for o in subprocess._active])
2572
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002573 def test_leak_fast_process_del_killed(self):
2574 # Issue #12650: on Unix, if Popen.__del__() was called before the
2575 # process exited, and the process got killed by a signal, it would never
2576 # be removed from subprocess._active, which triggered a FD and memory
2577 # leak.
2578 # spawn a Popen, delete its reference and kill it
2579 p = subprocess.Popen([sys.executable, "-c",
2580 'import time;'
2581 'time.sleep(3)'],
2582 stdout=subprocess.PIPE,
2583 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002584 self.addCleanup(p.stdout.close)
2585 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002586 ident = id(p)
2587 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002588 with support.check_warnings(('', ResourceWarning)):
2589 p = None
2590
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002591 os.kill(pid, signal.SIGKILL)
2592 # check that p is in the active processes list
2593 self.assertIn(ident, [id(o) for o in subprocess._active])
2594
2595 # let some time for the process to exit, and create a new Popen: this
2596 # should trigger the wait() of p
2597 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002598 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002599 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002600 stdout=subprocess.PIPE,
2601 stderr=subprocess.PIPE) as proc:
2602 pass
2603 # p should have been wait()ed on, and removed from the _active list
2604 self.assertRaises(OSError, os.waitpid, pid, 0)
2605 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2606
Charles-François Natali249cdc32013-08-25 18:24:45 +02002607 def test_close_fds_after_preexec(self):
2608 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2609
2610 # this FD is used as dup2() target by preexec_fn, and should be closed
2611 # in the child process
2612 fd = os.dup(1)
2613 self.addCleanup(os.close, fd)
2614
2615 p = subprocess.Popen([sys.executable, fd_status],
2616 stdout=subprocess.PIPE, close_fds=True,
2617 preexec_fn=lambda: os.dup2(1, fd))
2618 output, ignored = p.communicate()
2619
2620 remaining_fds = set(map(int, output.split(b',')))
2621
2622 self.assertNotIn(fd, remaining_fds)
2623
Victor Stinner8f437aa2014-10-05 17:25:19 +02002624 @support.cpython_only
2625 def test_fork_exec(self):
2626 # Issue #22290: fork_exec() must not crash on memory allocation failure
2627 # or other errors
2628 import _posixsubprocess
2629 gc_enabled = gc.isenabled()
2630 try:
2631 # Use a preexec function and enable the garbage collector
2632 # to force fork_exec() to re-enable the garbage collector
2633 # on error.
2634 func = lambda: None
2635 gc.enable()
2636
Victor Stinner8f437aa2014-10-05 17:25:19 +02002637 for args, exe_list, cwd, env_list in (
2638 (123, [b"exe"], None, [b"env"]),
2639 ([b"arg"], 123, None, [b"env"]),
2640 ([b"arg"], [b"exe"], 123, [b"env"]),
2641 ([b"arg"], [b"exe"], None, 123),
2642 ):
2643 with self.assertRaises(TypeError):
2644 _posixsubprocess.fork_exec(
2645 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002646 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002647 -1, -1, -1, -1,
2648 1, 2, 3, 4,
2649 True, True, func)
2650 finally:
2651 if not gc_enabled:
2652 gc.disable()
2653
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002654 @support.cpython_only
2655 def test_fork_exec_sorted_fd_sanity_check(self):
2656 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2657 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002658 class BadInt:
2659 first = True
2660 def __init__(self, value):
2661 self.value = value
2662 def __int__(self):
2663 if self.first:
2664 self.first = False
2665 return self.value
2666 raise ValueError
2667
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002668 gc_enabled = gc.isenabled()
2669 try:
2670 gc.enable()
2671
2672 for fds_to_keep in (
2673 (-1, 2, 3, 4, 5), # Negative number.
2674 ('str', 4), # Not an int.
2675 (18, 23, 42, 2**63), # Out of range.
2676 (5, 4), # Not sorted.
2677 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002678 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002679 ):
2680 with self.assertRaises(
2681 ValueError,
2682 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2683 _posixsubprocess.fork_exec(
2684 [b"false"], [b"false"],
2685 True, fds_to_keep, None, [b"env"],
2686 -1, -1, -1, -1,
2687 1, 2, 3, 4,
2688 True, True, None)
2689 self.assertIn('fds_to_keep', str(c.exception))
2690 finally:
2691 if not gc_enabled:
2692 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002693
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002694 def test_communicate_BrokenPipeError_stdin_close(self):
2695 # By not setting stdout or stderr or a timeout we force the fast path
2696 # that just calls _stdin_write() internally due to our mock.
2697 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2698 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2699 mock_proc_stdin.close.side_effect = BrokenPipeError
2700 proc.communicate() # Should swallow BrokenPipeError from close.
2701 mock_proc_stdin.close.assert_called_with()
2702
2703 def test_communicate_BrokenPipeError_stdin_write(self):
2704 # By not setting stdout or stderr or a timeout we force the fast path
2705 # that just calls _stdin_write() internally due to our mock.
2706 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2707 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2708 mock_proc_stdin.write.side_effect = BrokenPipeError
2709 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2710 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2711 mock_proc_stdin.close.assert_called_once_with()
2712
2713 def test_communicate_BrokenPipeError_stdin_flush(self):
2714 # Setting stdin and stdout forces the ._communicate() code path.
2715 # python -h exits faster than python -c pass (but spams stdout).
2716 proc = subprocess.Popen([sys.executable, '-h'],
2717 stdin=subprocess.PIPE,
2718 stdout=subprocess.PIPE)
2719 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2720 open(os.devnull, 'wb') as dev_null:
2721 mock_proc_stdin.flush.side_effect = BrokenPipeError
2722 # because _communicate registers a selector using proc.stdin...
2723 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2724 # _communicate() should swallow BrokenPipeError from flush.
2725 proc.communicate(b'stuff')
2726 mock_proc_stdin.flush.assert_called_once_with()
2727
2728 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2729 # Setting stdin and stdout forces the ._communicate() code path.
2730 # python -h exits faster than python -c pass (but spams stdout).
2731 proc = subprocess.Popen([sys.executable, '-h'],
2732 stdin=subprocess.PIPE,
2733 stdout=subprocess.PIPE)
2734 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2735 mock_proc_stdin.close.side_effect = BrokenPipeError
2736 # _communicate() should swallow BrokenPipeError from close.
2737 proc.communicate(timeout=999)
2738 mock_proc_stdin.close.assert_called_once_with()
2739
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002740 @unittest.skipUnless(_testcapi is not None
2741 and hasattr(_testcapi, 'W_STOPCODE'),
2742 'need _testcapi.W_STOPCODE')
2743 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002744 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002745 args = [sys.executable, '-c', 'pass']
2746 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002747
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002748 # Wait until the real process completes to avoid zombie process
2749 pid = proc.pid
2750 pid, status = os.waitpid(pid, 0)
2751 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002752
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002753 status = _testcapi.W_STOPCODE(3)
2754 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
2755 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02002756
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002757 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002758
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002759
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002760@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002761class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002762
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002763 def test_startupinfo(self):
2764 # startupinfo argument
2765 # We uses hardcoded constants, because we do not want to
2766 # depend on win32all.
2767 STARTF_USESHOWWINDOW = 1
2768 SW_MAXIMIZE = 3
2769 startupinfo = subprocess.STARTUPINFO()
2770 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2771 startupinfo.wShowWindow = SW_MAXIMIZE
2772 # Since Python is a console process, it won't be affected
2773 # by wShowWindow, but the argument should be silently
2774 # ignored
2775 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002776 startupinfo=startupinfo)
2777
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302778 def test_startupinfo_keywords(self):
2779 # startupinfo argument
2780 # We use hardcoded constants, because we do not want to
2781 # depend on win32all.
2782 STARTF_USERSHOWWINDOW = 1
2783 SW_MAXIMIZE = 3
2784 startupinfo = subprocess.STARTUPINFO(
2785 dwFlags=STARTF_USERSHOWWINDOW,
2786 wShowWindow=SW_MAXIMIZE
2787 )
2788 # Since Python is a console process, it won't be affected
2789 # by wShowWindow, but the argument should be silently
2790 # ignored
2791 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2792 startupinfo=startupinfo)
2793
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002794 def test_creationflags(self):
2795 # creationflags argument
2796 CREATE_NEW_CONSOLE = 16
2797 sys.stderr.write(" a DOS box should flash briefly ...\n")
2798 subprocess.call(sys.executable +
2799 ' -c "import time; time.sleep(0.25)"',
2800 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002801
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002802 def test_invalid_args(self):
2803 # invalid arguments should raise ValueError
2804 self.assertRaises(ValueError, subprocess.call,
2805 [sys.executable, "-c",
2806 "import sys; sys.exit(47)"],
2807 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002808
Oren Milman0b3a87e2017-09-14 22:30:28 +03002809 @support.cpython_only
2810 def test_issue31471(self):
2811 # There shouldn't be an assertion failure in Popen() in case the env
2812 # argument has a bad keys() method.
2813 class BadEnv(dict):
2814 keys = None
2815 with self.assertRaises(TypeError):
2816 subprocess.Popen([sys.executable, "-c", "pass"], env=BadEnv())
2817
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002818 def test_close_fds(self):
2819 # close file descriptors
2820 rc = subprocess.call([sys.executable, "-c",
2821 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002822 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002823 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002824
Segev Finerb2a60832017-12-18 11:28:19 +02002825 def test_close_fds_with_stdio(self):
2826 import msvcrt
2827
2828 fds = os.pipe()
2829 self.addCleanup(os.close, fds[0])
2830 self.addCleanup(os.close, fds[1])
2831
2832 handles = []
2833 for fd in fds:
2834 os.set_inheritable(fd, True)
2835 handles.append(msvcrt.get_osfhandle(fd))
2836
2837 p = subprocess.Popen([sys.executable, "-c",
2838 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2839 stdout=subprocess.PIPE, close_fds=False)
2840 stdout, stderr = p.communicate()
2841 self.assertEqual(p.returncode, 0)
2842 int(stdout.strip()) # Check that stdout is an integer
2843
2844 p = subprocess.Popen([sys.executable, "-c",
2845 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2846 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
2847 stdout, stderr = p.communicate()
2848 self.assertEqual(p.returncode, 1)
2849 self.assertIn(b"OSError", stderr)
2850
2851 # The same as the previous call, but with an empty handle_list
2852 handle_list = []
2853 startupinfo = subprocess.STARTUPINFO()
2854 startupinfo.lpAttributeList = {"handle_list": handle_list}
2855 p = subprocess.Popen([sys.executable, "-c",
2856 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2857 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
2858 startupinfo=startupinfo, close_fds=True)
2859 stdout, stderr = p.communicate()
2860 self.assertEqual(p.returncode, 1)
2861 self.assertIn(b"OSError", stderr)
2862
2863 # Check for a warning due to using handle_list and close_fds=False
2864 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
2865 startupinfo = subprocess.STARTUPINFO()
2866 startupinfo.lpAttributeList = {"handle_list": handles[:]}
2867 p = subprocess.Popen([sys.executable, "-c",
2868 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2869 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
2870 startupinfo=startupinfo, close_fds=False)
2871 stdout, stderr = p.communicate()
2872 self.assertEqual(p.returncode, 0)
2873
2874 def test_empty_attribute_list(self):
2875 startupinfo = subprocess.STARTUPINFO()
2876 startupinfo.lpAttributeList = {}
2877 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2878 startupinfo=startupinfo)
2879
2880 def test_empty_handle_list(self):
2881 startupinfo = subprocess.STARTUPINFO()
2882 startupinfo.lpAttributeList = {"handle_list": []}
2883 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2884 startupinfo=startupinfo)
2885
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002886 def test_shell_sequence(self):
2887 # Run command through the shell (sequence)
2888 newenv = os.environ.copy()
2889 newenv["FRUIT"] = "physalis"
2890 p = subprocess.Popen(["set"], shell=1,
2891 stdout=subprocess.PIPE,
2892 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002893 with p:
2894 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002895
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002896 def test_shell_string(self):
2897 # Run command through the shell (string)
2898 newenv = os.environ.copy()
2899 newenv["FRUIT"] = "physalis"
2900 p = subprocess.Popen("set", shell=1,
2901 stdout=subprocess.PIPE,
2902 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002903 with p:
2904 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002905
Steve Dower050acae2016-09-06 20:16:17 -07002906 def test_shell_encodings(self):
2907 # Run command through the shell (string)
2908 for enc in ['ansi', 'oem']:
2909 newenv = os.environ.copy()
2910 newenv["FRUIT"] = "physalis"
2911 p = subprocess.Popen("set", shell=1,
2912 stdout=subprocess.PIPE,
2913 env=newenv,
2914 encoding=enc)
2915 with p:
2916 self.assertIn("physalis", p.stdout.read(), enc)
2917
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002918 def test_call_string(self):
2919 # call() function with string argument on Windows
2920 rc = subprocess.call(sys.executable +
2921 ' -c "import sys; sys.exit(47)"')
2922 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002923
Florent Xicluna4886d242010-03-08 13:27:26 +00002924 def _kill_process(self, method, *args):
2925 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002926 p = subprocess.Popen([sys.executable, "-c", """if 1:
2927 import sys, time
2928 sys.stdout.write('x\\n')
2929 sys.stdout.flush()
2930 time.sleep(30)
2931 """],
2932 stdin=subprocess.PIPE,
2933 stdout=subprocess.PIPE,
2934 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002935 with p:
2936 # Wait for the interpreter to be completely initialized before
2937 # sending any signal.
2938 p.stdout.read(1)
2939 getattr(p, method)(*args)
2940 _, stderr = p.communicate()
2941 self.assertStderrEqual(stderr, b'')
2942 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002943 self.assertNotEqual(returncode, 0)
2944
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002945 def _kill_dead_process(self, method, *args):
2946 p = subprocess.Popen([sys.executable, "-c", """if 1:
2947 import sys, time
2948 sys.stdout.write('x\\n')
2949 sys.stdout.flush()
2950 sys.exit(42)
2951 """],
2952 stdin=subprocess.PIPE,
2953 stdout=subprocess.PIPE,
2954 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002955 with p:
2956 # Wait for the interpreter to be completely initialized before
2957 # sending any signal.
2958 p.stdout.read(1)
2959 # The process should end after this
2960 time.sleep(1)
2961 # This shouldn't raise even though the child is now dead
2962 getattr(p, method)(*args)
2963 _, stderr = p.communicate()
2964 self.assertStderrEqual(stderr, b'')
2965 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002966 self.assertEqual(rc, 42)
2967
Florent Xicluna4886d242010-03-08 13:27:26 +00002968 def test_send_signal(self):
2969 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002970
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002971 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002972 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002973
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002974 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002975 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002976
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002977 def test_send_signal_dead(self):
2978 self._kill_dead_process('send_signal', signal.SIGTERM)
2979
2980 def test_kill_dead(self):
2981 self._kill_dead_process('kill')
2982
2983 def test_terminate_dead(self):
2984 self._kill_dead_process('terminate')
2985
Martin Panter23172bd2016-04-16 11:28:10 +00002986class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08002987
2988 class RecordingPopen(subprocess.Popen):
2989 """A Popen that saves a reference to each instance for testing."""
2990 instances_created = []
2991
2992 def __init__(self, *args, **kwargs):
2993 super().__init__(*args, **kwargs)
2994 self.instances_created.append(self)
2995
2996 @mock.patch.object(subprocess.Popen, "_communicate")
2997 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
2998 **kwargs):
2999 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3000
3001 This avoids the need to actually try and get test environments to send
3002 and receive signals reliably across platforms. The net effect of a ^C
3003 happening during a blocking subprocess execution which we want to clean
3004 up from is a KeyboardInterrupt coming out of communicate() or wait().
3005 """
3006
3007 mock__communicate.side_effect = KeyboardInterrupt
3008 try:
3009 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3010 # We patch out _wait() as no signal was involved so the
3011 # child process isn't actually going to exit rapidly.
3012 mock__wait.side_effect = KeyboardInterrupt
3013 with mock.patch.object(subprocess, "Popen",
3014 self.RecordingPopen):
3015 with self.assertRaises(KeyboardInterrupt):
3016 popener([sys.executable, "-c",
3017 "import time\ntime.sleep(9)\nimport sys\n"
3018 "sys.stderr.write('\\n!runaway child!\\n')"],
3019 stdout=subprocess.DEVNULL, **kwargs)
3020 for call in mock__wait.call_args_list[1:]:
3021 self.assertNotEqual(
3022 call, mock.call(timeout=None),
3023 "no open-ended wait() after the first allowed: "
3024 f"{mock__wait.call_args_list}")
3025 sigint_calls = []
3026 for call in mock__wait.call_args_list:
3027 if call == mock.call(timeout=0.25): # from Popen.__init__
3028 sigint_calls.append(call)
3029 self.assertLessEqual(mock__wait.call_count, 2,
3030 msg=mock__wait.call_args_list)
3031 self.assertEqual(len(sigint_calls), 1,
3032 msg=mock__wait.call_args_list)
3033 finally:
3034 # cleanup the forgotten (due to our mocks) child process
3035 process = self.RecordingPopen.instances_created.pop()
3036 process.kill()
3037 process.wait()
3038 self.assertEqual([], self.RecordingPopen.instances_created)
3039
3040 def test_call_keyboardinterrupt_no_kill(self):
3041 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3042
3043 def test_run_keyboardinterrupt_no_kill(self):
3044 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3045
3046 def test_context_manager_keyboardinterrupt_no_kill(self):
3047 def popen_via_context_manager(*args, **kwargs):
3048 with subprocess.Popen(*args, **kwargs) as unused_process:
3049 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3050 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3051
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003052 def test_getoutput(self):
3053 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3054 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3055 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003056
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003057 # we use mkdtemp in the next line to create an empty directory
3058 # under our exclusive control; from that, we can invent a pathname
3059 # that we _know_ won't exist. This is guaranteed to fail.
3060 dir = None
3061 try:
3062 dir = tempfile.mkdtemp()
3063 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003064 status, output = subprocess.getstatusoutput(
3065 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003066 self.assertNotEqual(status, 0)
3067 finally:
3068 if dir is not None:
3069 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003070
Gregory P. Smithace55862015-04-07 15:57:54 -07003071 def test__all__(self):
3072 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00003073 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003074 exported = set(subprocess.__all__)
3075 possible_exports = set()
3076 import types
3077 for name, value in subprocess.__dict__.items():
3078 if name.startswith('_'):
3079 continue
3080 if isinstance(value, (types.ModuleType,)):
3081 continue
3082 possible_exports.add(name)
3083 self.assertEqual(exported, possible_exports - intentionally_excluded)
3084
3085
Martin Panter23172bd2016-04-16 11:28:10 +00003086@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3087 "Test needs selectors.PollSelector")
3088class ProcessTestCaseNoPoll(ProcessTestCase):
3089 def setUp(self):
3090 self.orig_selector = subprocess._PopenSelector
3091 subprocess._PopenSelector = selectors.SelectSelector
3092 ProcessTestCase.setUp(self)
3093
3094 def tearDown(self):
3095 subprocess._PopenSelector = self.orig_selector
3096 ProcessTestCase.tearDown(self)
3097
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003098
Tim Golden126c2962010-08-11 14:20:40 +00003099@unittest.skipUnless(mswindows, "Windows-specific tests")
3100class CommandsWithSpaces (BaseTestCase):
3101
3102 def setUp(self):
3103 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003104 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003105 self.fname = fname.lower ()
3106 os.write(f, b"import sys;"
3107 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3108 )
3109 os.close(f)
3110
3111 def tearDown(self):
3112 os.remove(self.fname)
3113 super().tearDown()
3114
3115 def with_spaces(self, *args, **kwargs):
3116 kwargs['stdout'] = subprocess.PIPE
3117 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003118 with p:
3119 self.assertEqual(
3120 p.stdout.read ().decode("mbcs"),
3121 "2 [%r, 'ab cd']" % self.fname
3122 )
Tim Golden126c2962010-08-11 14:20:40 +00003123
3124 def test_shell_string_with_spaces(self):
3125 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003126 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3127 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003128
3129 def test_shell_sequence_with_spaces(self):
3130 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003131 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003132
3133 def test_noshell_string_with_spaces(self):
3134 # call() function with string argument with spaces on Windows
3135 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3136 "ab cd"))
3137
3138 def test_noshell_sequence_with_spaces(self):
3139 # call() function with sequence argument with spaces on Windows
3140 self.with_spaces([sys.executable, self.fname, "ab cd"])
3141
Brian Curtin79cdb662010-12-03 02:46:02 +00003142
Georg Brandla86b2622012-02-20 21:34:57 +01003143class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003144
3145 def test_pipe(self):
3146 with subprocess.Popen([sys.executable, "-c",
3147 "import sys;"
3148 "sys.stdout.write('stdout');"
3149 "sys.stderr.write('stderr');"],
3150 stdout=subprocess.PIPE,
3151 stderr=subprocess.PIPE) as proc:
3152 self.assertEqual(proc.stdout.read(), b"stdout")
3153 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3154
3155 self.assertTrue(proc.stdout.closed)
3156 self.assertTrue(proc.stderr.closed)
3157
3158 def test_returncode(self):
3159 with subprocess.Popen([sys.executable, "-c",
3160 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003161 pass
3162 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003163 self.assertEqual(proc.returncode, 100)
3164
3165 def test_communicate_stdin(self):
3166 with subprocess.Popen([sys.executable, "-c",
3167 "import sys;"
3168 "sys.exit(sys.stdin.read() == 'context')"],
3169 stdin=subprocess.PIPE) as proc:
3170 proc.communicate(b"context")
3171 self.assertEqual(proc.returncode, 1)
3172
3173 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003174 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003175 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003176 stdout=subprocess.PIPE,
3177 stderr=subprocess.PIPE) as proc:
3178 pass
3179
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003180 def test_broken_pipe_cleanup(self):
3181 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003182 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01003183 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003184 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003185 proc = proc.__enter__()
3186 # Prepare to send enough data to overflow any OS pipe buffering and
3187 # guarantee a broken pipe error. Data is held in BufferedWriter
3188 # buffer until closed.
3189 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003190 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003191 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003192 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003193 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003194 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003195
Brian Curtin79cdb662010-12-03 02:46:02 +00003196
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003197if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003198 unittest.main()