blob: 82e0b870af0fae717cb208ad07e8cce2e632bc6f [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
Benjamin Petersonb870aa12011-12-10 12:44:25 -050017import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030018import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050019
20try:
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080021 import ctypes
22except ImportError:
23 ctypes = None
24
25try:
Antoine Pitroua8392712013-08-30 23:38:13 +020026 import threading
27except ImportError:
28 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050029
Steve Dower22d06982016-09-06 19:38:15 -070030if support.PGO:
31 raise unittest.SkipTest("test is not helpful for PGO")
32
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000033mswindows = (sys.platform == "win32")
34
35#
36# Depends on the following external programs: Python
37#
38
39if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000040 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
41 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000042else:
43 SETBINARY = ''
44
Florent Xiclunab1e94e82010-02-27 22:12:37 +000045
Florent Xiclunac049d872010-03-27 22:47:23 +000046class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000047 def setUp(self):
48 # Try to minimize the number of children we have so this test
49 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000050 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000051
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000052 def tearDown(self):
53 for inst in subprocess._active:
54 inst.wait()
55 subprocess._cleanup()
56 self.assertFalse(subprocess._active, "subprocess._active not empty")
57
Florent Xiclunab1e94e82010-02-27 22:12:37 +000058 def assertStderrEqual(self, stderr, expected, msg=None):
59 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
60 # shutdown time. That frustrates tests trying to check stderr produced
61 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000062 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040063 # strip_python_stderr also strips whitespace, so we do too.
64 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000065 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066
Florent Xiclunac049d872010-03-27 22:47:23 +000067
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080068class PopenTestException(Exception):
69 pass
70
71
72class PopenExecuteChildRaises(subprocess.Popen):
73 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
74 _execute_child fails.
75 """
76 def _execute_child(self, *args, **kwargs):
77 raise PopenTestException("Forced Exception for Test")
78
79
Florent Xiclunac049d872010-03-27 22:47:23 +000080class ProcessTestCase(BaseTestCase):
81
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070082 def test_io_buffered_by_default(self):
83 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
84 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
85 stderr=subprocess.PIPE)
86 try:
87 self.assertIsInstance(p.stdin, io.BufferedIOBase)
88 self.assertIsInstance(p.stdout, io.BufferedIOBase)
89 self.assertIsInstance(p.stderr, io.BufferedIOBase)
90 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070091 p.stdin.close()
92 p.stdout.close()
93 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070094 p.wait()
95
96 def test_io_unbuffered_works(self):
97 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
98 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
99 stderr=subprocess.PIPE, bufsize=0)
100 try:
101 self.assertIsInstance(p.stdin, io.RawIOBase)
102 self.assertIsInstance(p.stdout, io.RawIOBase)
103 self.assertIsInstance(p.stderr, io.RawIOBase)
104 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700105 p.stdin.close()
106 p.stdout.close()
107 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700108 p.wait()
109
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000110 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000111 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000112 rc = subprocess.call([sys.executable, "-c",
113 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 self.assertEqual(rc, 47)
115
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400116 def test_call_timeout(self):
117 # call() function with timeout argument; we want to test that the child
118 # process gets killed when the timeout expires. If the child isn't
119 # killed, this call will deadlock since subprocess.call waits for the
120 # child.
121 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
122 [sys.executable, "-c", "while True: pass"],
123 timeout=0.1)
124
Peter Astrand454f7672005-01-01 09:36:35 +0000125 def test_check_call_zero(self):
126 # check_call() function with zero return code
127 rc = subprocess.check_call([sys.executable, "-c",
128 "import sys; sys.exit(0)"])
129 self.assertEqual(rc, 0)
130
131 def test_check_call_nonzero(self):
132 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000133 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000134 subprocess.check_call([sys.executable, "-c",
135 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000136 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000137
Georg Brandlf9734072008-12-07 15:30:06 +0000138 def test_check_output(self):
139 # check_output() function with zero return code
140 output = subprocess.check_output(
141 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000142 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000143
144 def test_check_output_nonzero(self):
145 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000146 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000147 subprocess.check_output(
148 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000149 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000150
151 def test_check_output_stderr(self):
152 # check_output() function stderr redirected to stdout
153 output = subprocess.check_output(
154 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
155 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000156 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000157
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300158 def test_check_output_stdin_arg(self):
159 # check_output() can be called with stdin set to a file
160 tf = tempfile.TemporaryFile()
161 self.addCleanup(tf.close)
162 tf.write(b'pear')
163 tf.seek(0)
164 output = subprocess.check_output(
165 [sys.executable, "-c",
166 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
167 stdin=tf)
168 self.assertIn(b'PEAR', output)
169
170 def test_check_output_input_arg(self):
171 # check_output() can be called with input set to a string
172 output = subprocess.check_output(
173 [sys.executable, "-c",
174 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
175 input=b'pear')
176 self.assertIn(b'PEAR', output)
177
Georg Brandlf9734072008-12-07 15:30:06 +0000178 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300179 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000180 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000181 output = subprocess.check_output(
182 [sys.executable, "-c", "print('will not be run')"],
183 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000184 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000185 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000186
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300187 def test_check_output_stdin_with_input_arg(self):
188 # check_output() refuses to accept 'stdin' with 'input'
189 tf = tempfile.TemporaryFile()
190 self.addCleanup(tf.close)
191 tf.write(b'pear')
192 tf.seek(0)
193 with self.assertRaises(ValueError) as c:
194 output = subprocess.check_output(
195 [sys.executable, "-c", "print('will not be run')"],
196 stdin=tf, input=b'hare')
197 self.fail("Expected ValueError when stdin and input args supplied.")
198 self.assertIn('stdin', c.exception.args[0])
199 self.assertIn('input', c.exception.args[0])
200
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400201 def test_check_output_timeout(self):
202 # check_output() function with timeout arg
203 with self.assertRaises(subprocess.TimeoutExpired) as c:
204 output = subprocess.check_output(
205 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200206 "import sys, time\n"
207 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400208 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200209 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400210 # Some heavily loaded buildbots (sparc Debian 3.x) require
211 # this much time to start and print.
212 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400213 self.fail("Expected TimeoutExpired.")
214 self.assertEqual(c.exception.output, b'BDFL')
215
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000216 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000217 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000218 newenv = os.environ.copy()
219 newenv["FRUIT"] = "banana"
220 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000221 'import sys, os;'
222 'sys.exit(os.getenv("FRUIT")=="banana")'],
223 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000224 self.assertEqual(rc, 1)
225
Victor Stinner87b9bc32011-06-01 00:57:47 +0200226 def test_invalid_args(self):
227 # Popen() called with invalid arguments should raise TypeError
228 # but Popen.__del__ should not complain (issue #12085)
229 with support.captured_stderr() as s:
230 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
231 argcount = subprocess.Popen.__init__.__code__.co_argcount
232 too_many_args = [0] * (argcount + 1)
233 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
234 self.assertEqual(s.getvalue(), '')
235
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000237 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000238 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000240 self.addCleanup(p.stdout.close)
241 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 p.wait()
243 self.assertEqual(p.stdin, None)
244
245 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200246 # .stdout is None when not redirected, and the child's stdout will
247 # be inherited from the parent. In order to test this we run a
248 # subprocess in a subprocess:
249 # this_test
250 # \-- subprocess created by this test (parent)
251 # \-- subprocess created by the parent subprocess (child)
252 # The parent doesn't specify stdout, so the child will use the
253 # parent's stdout. This test checks that the message printed by the
254 # child goes to the parent stdout. The parent also checks that the
255 # child's stdout is None. See #11963.
256 code = ('import sys; from subprocess import Popen, PIPE;'
257 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
258 ' stdin=PIPE, stderr=PIPE);'
259 'p.wait(); assert p.stdout is None;')
260 p = subprocess.Popen([sys.executable, "-c", code],
261 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
262 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000263 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200264 out, err = p.communicate()
265 self.assertEqual(p.returncode, 0, err)
266 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000267
268 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000269 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000270 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000272 self.addCleanup(p.stdout.close)
273 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274 p.wait()
275 self.assertEqual(p.stderr, None)
276
Chris Jerdonek776cb192012-10-08 15:56:43 -0700277 def _assert_python(self, pre_args, **kwargs):
278 # We include sys.exit() to prevent the test runner from hanging
279 # whenever python is found.
280 args = pre_args + ["import sys; sys.exit(47)"]
281 p = subprocess.Popen(args, **kwargs)
282 p.wait()
283 self.assertEqual(47, p.returncode)
284
285 def test_executable(self):
286 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700287 #
288 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
289 # determine where its standard library is, so we need the directory
290 # of args[0] to be valid for the Popen() call to Python to succeed.
291 # See also issue #16170 and issue #7774.
292 doesnotexist = os.path.join(os.path.dirname(sys.executable),
293 "doesnotexist")
294 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700295
296 def test_executable_takes_precedence(self):
297 # Check that the executable argument takes precedence over args[0].
298 #
299 # Verify first that the call succeeds without the executable arg.
300 pre_args = [sys.executable, "-c"]
301 self._assert_python(pre_args)
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100302 self.assertRaises((FileNotFoundError, PermissionError),
303 self._assert_python, pre_args,
Chris Jerdonek776cb192012-10-08 15:56:43 -0700304 executable="doesnotexist")
305
306 @unittest.skipIf(mswindows, "executable argument replaces shell")
307 def test_executable_replaces_shell(self):
308 # Check that the executable argument replaces the default shell
309 # when shell=True.
310 self._assert_python([], executable=sys.executable, shell=True)
311
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700312 # For use in the test_cwd* tests below.
313 def _normalize_cwd(self, cwd):
314 # Normalize an expected cwd (for Tru64 support).
315 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
316 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300317 with support.change_cwd(cwd):
318 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700319
320 # For use in the test_cwd* tests below.
321 def _split_python_path(self):
322 # Return normalized (python_dir, python_base).
323 python_path = os.path.realpath(sys.executable)
324 return os.path.split(python_path)
325
326 # For use in the test_cwd* tests below.
327 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
328 # Invoke Python via Popen, and assert that (1) the call succeeds,
329 # and that (2) the current working directory of the child process
330 # matches *expected_cwd*.
331 p = subprocess.Popen([python_arg, "-c",
332 "import os, sys; "
333 "sys.stdout.write(os.getcwd()); "
334 "sys.exit(47)"],
335 stdout=subprocess.PIPE,
336 **kwargs)
337 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000338 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700339 self.assertEqual(47, p.returncode)
340 normcase = os.path.normcase
341 self.assertEqual(normcase(expected_cwd),
342 normcase(p.stdout.read().decode("utf-8")))
343
344 def test_cwd(self):
345 # Check that cwd changes the cwd for the child process.
346 temp_dir = tempfile.gettempdir()
347 temp_dir = self._normalize_cwd(temp_dir)
348 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
349
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700350 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700351 def test_cwd_with_relative_arg(self):
352 # Check that Popen looks for args[0] relative to cwd if args[0]
353 # is relative.
354 python_dir, python_base = self._split_python_path()
355 rel_python = os.path.join(os.curdir, python_base)
356 with support.temp_cwd() as wrong_dir:
357 # Before calling with the correct cwd, confirm that the call fails
358 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700359 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700360 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700361 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700362 [rel_python], cwd=wrong_dir)
363 python_dir = self._normalize_cwd(python_dir)
364 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
365
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700366 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700367 def test_cwd_with_relative_executable(self):
368 # Check that Popen looks for executable relative to cwd if executable
369 # is relative (and that executable takes precedence over args[0]).
370 python_dir, python_base = self._split_python_path()
371 rel_python = os.path.join(os.curdir, python_base)
372 doesntexist = "somethingyoudonthave"
373 with support.temp_cwd() as wrong_dir:
374 # Before calling with the correct cwd, confirm that the call fails
375 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700376 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700377 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700378 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700379 [doesntexist], executable=rel_python,
380 cwd=wrong_dir)
381 python_dir = self._normalize_cwd(python_dir)
382 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
383 cwd=python_dir)
384
385 def test_cwd_with_absolute_arg(self):
386 # Check that Popen can find the executable when the cwd is wrong
387 # if args[0] is an absolute path.
388 python_dir, python_base = self._split_python_path()
389 abs_python = os.path.join(python_dir, python_base)
390 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300391 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700392 # Before calling with an absolute path, confirm that using a
393 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700394 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700395 [rel_python], cwd=wrong_dir)
396 wrong_dir = self._normalize_cwd(wrong_dir)
397 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
398
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100399 @unittest.skipIf(sys.base_prefix != sys.prefix,
400 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000401 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700402 python_dir, python_base = self._split_python_path()
403 python_dir = self._normalize_cwd(python_dir)
404 self._assert_cwd(python_dir, "somethingyoudonthave",
405 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000406
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100407 @unittest.skipIf(sys.base_prefix != sys.prefix,
408 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000409 @unittest.skipIf(sysconfig.is_python_build(),
410 "need an installed Python. See #7774")
411 def test_executable_without_cwd(self):
412 # For a normal installation, it should work without 'cwd'
413 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700414 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
415 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416
417 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000418 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000419 p = subprocess.Popen([sys.executable, "-c",
420 'import sys; sys.exit(sys.stdin.read() == "pear")'],
421 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000422 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 p.stdin.close()
424 p.wait()
425 self.assertEqual(p.returncode, 1)
426
427 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000428 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000429 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000430 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000431 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000432 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433 os.lseek(d, 0, 0)
434 p = subprocess.Popen([sys.executable, "-c",
435 'import sys; sys.exit(sys.stdin.read() == "pear")'],
436 stdin=d)
437 p.wait()
438 self.assertEqual(p.returncode, 1)
439
440 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000441 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000442 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000443 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000444 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000445 tf.seek(0)
446 p = subprocess.Popen([sys.executable, "-c",
447 'import sys; sys.exit(sys.stdin.read() == "pear")'],
448 stdin=tf)
449 p.wait()
450 self.assertEqual(p.returncode, 1)
451
452 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000453 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454 p = subprocess.Popen([sys.executable, "-c",
455 'import sys; sys.stdout.write("orange")'],
456 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200457 with p:
458 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459
460 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000461 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000462 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000463 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464 d = tf.fileno()
465 p = subprocess.Popen([sys.executable, "-c",
466 'import sys; sys.stdout.write("orange")'],
467 stdout=d)
468 p.wait()
469 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000470 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471
472 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000473 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000474 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000475 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476 p = subprocess.Popen([sys.executable, "-c",
477 'import sys; sys.stdout.write("orange")'],
478 stdout=tf)
479 p.wait()
480 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000481 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482
483 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000484 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 p = subprocess.Popen([sys.executable, "-c",
486 'import sys; sys.stderr.write("strawberry")'],
487 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200488 with p:
489 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490
491 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000492 # stderr is set to open file descriptor
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 d = tf.fileno()
496 p = subprocess.Popen([sys.executable, "-c",
497 'import sys; sys.stderr.write("strawberry")'],
498 stderr=d)
499 p.wait()
500 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000501 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502
503 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000504 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000505 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000506 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507 p = subprocess.Popen([sys.executable, "-c",
508 'import sys; sys.stderr.write("strawberry")'],
509 stderr=tf)
510 p.wait()
511 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000512 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000513
Martin Panterc7635892016-05-13 01:54:44 +0000514 def test_stderr_redirect_with_no_stdout_redirect(self):
515 # test stderr=STDOUT while stdout=None (not set)
516
517 # - grandchild prints to stderr
518 # - child redirects grandchild's stderr to its stdout
519 # - the parent should get grandchild's stderr in child's stdout
520 p = subprocess.Popen([sys.executable, "-c",
521 'import sys, subprocess;'
522 'rc = subprocess.call([sys.executable, "-c",'
523 ' "import sys;"'
524 ' "sys.stderr.write(\'42\')"],'
525 ' stderr=subprocess.STDOUT);'
526 'sys.exit(rc)'],
527 stdout=subprocess.PIPE,
528 stderr=subprocess.PIPE)
529 stdout, stderr = p.communicate()
530 #NOTE: stdout should get stderr from grandchild
531 self.assertStderrEqual(stdout, b'42')
532 self.assertStderrEqual(stderr, b'') # should be empty
533 self.assertEqual(p.returncode, 0)
534
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000535 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000536 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000538 'import sys;'
539 'sys.stdout.write("apple");'
540 'sys.stdout.flush();'
541 'sys.stderr.write("orange")'],
542 stdout=subprocess.PIPE,
543 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200544 with p:
545 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546
547 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000548 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000550 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000552 'import sys;'
553 'sys.stdout.write("apple");'
554 'sys.stdout.flush();'
555 'sys.stderr.write("orange")'],
556 stdout=tf,
557 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558 p.wait()
559 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000560 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561
Thomas Wouters89f507f2006-12-13 04:49:30 +0000562 def test_stdout_filedes_of_stdout(self):
563 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200564 # To avoid printing the text on stdout, we do something similar to
565 # test_stdout_none (see above). The parent subprocess calls the child
566 # subprocess passing stdout=1, and this test uses stdout=PIPE in
567 # order to capture and check the output of the parent. See #11963.
568 code = ('import sys, subprocess; '
569 'rc = subprocess.call([sys.executable, "-c", '
570 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
571 'b\'test with stdout=1\'))"], stdout=1); '
572 'assert rc == 18')
573 p = subprocess.Popen([sys.executable, "-c", code],
574 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
575 self.addCleanup(p.stdout.close)
576 self.addCleanup(p.stderr.close)
577 out, err = p.communicate()
578 self.assertEqual(p.returncode, 0, err)
579 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000580
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200581 def test_stdout_devnull(self):
582 p = subprocess.Popen([sys.executable, "-c",
583 'for i in range(10240):'
584 'print("x" * 1024)'],
585 stdout=subprocess.DEVNULL)
586 p.wait()
587 self.assertEqual(p.stdout, None)
588
589 def test_stderr_devnull(self):
590 p = subprocess.Popen([sys.executable, "-c",
591 'import sys\n'
592 'for i in range(10240):'
593 'sys.stderr.write("x" * 1024)'],
594 stderr=subprocess.DEVNULL)
595 p.wait()
596 self.assertEqual(p.stderr, None)
597
598 def test_stdin_devnull(self):
599 p = subprocess.Popen([sys.executable, "-c",
600 'import sys;'
601 'sys.stdin.read(1)'],
602 stdin=subprocess.DEVNULL)
603 p.wait()
604 self.assertEqual(p.stdin, None)
605
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000606 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000607 newenv = os.environ.copy()
608 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200609 with subprocess.Popen([sys.executable, "-c",
610 'import sys,os;'
611 'sys.stdout.write(os.getenv("FRUIT"))'],
612 stdout=subprocess.PIPE,
613 env=newenv) as p:
614 stdout, stderr = p.communicate()
615 self.assertEqual(stdout, b"orange")
616
Victor Stinner62d51182011-06-23 01:02:25 +0200617 # Windows requires at least the SYSTEMROOT environment variable to start
618 # Python
619 @unittest.skipIf(sys.platform == 'win32',
620 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200621 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200622 'the python library cannot be loaded '
623 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200624 def test_empty_env(self):
625 with subprocess.Popen([sys.executable, "-c",
626 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200627 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200628 stdout=subprocess.PIPE,
629 env={}) as p:
630 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200631 self.assertIn(stdout.strip(),
632 (b"[]",
633 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
634 # environment
635 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000636
Peter Astrandcbac93c2005-03-03 20:24:28 +0000637 def test_communicate_stdin(self):
638 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000639 'import sys;'
640 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000641 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000642 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000643 self.assertEqual(p.returncode, 1)
644
645 def test_communicate_stdout(self):
646 p = subprocess.Popen([sys.executable, "-c",
647 'import sys; sys.stdout.write("pineapple")'],
648 stdout=subprocess.PIPE)
649 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000650 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000651 self.assertEqual(stderr, None)
652
653 def test_communicate_stderr(self):
654 p = subprocess.Popen([sys.executable, "-c",
655 'import sys; sys.stderr.write("pineapple")'],
656 stderr=subprocess.PIPE)
657 (stdout, stderr) = p.communicate()
658 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000659 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000660
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000661 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000662 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000663 'import sys,os;'
664 'sys.stderr.write("pineapple");'
665 'sys.stdout.write(sys.stdin.read())'],
666 stdin=subprocess.PIPE,
667 stdout=subprocess.PIPE,
668 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000669 self.addCleanup(p.stdout.close)
670 self.addCleanup(p.stderr.close)
671 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000672 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000673 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000674 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000675
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400676 def test_communicate_timeout(self):
677 p = subprocess.Popen([sys.executable, "-c",
678 'import sys,os,time;'
679 'sys.stderr.write("pineapple\\n");'
680 'time.sleep(1);'
681 'sys.stderr.write("pear\\n");'
682 'sys.stdout.write(sys.stdin.read())'],
683 universal_newlines=True,
684 stdin=subprocess.PIPE,
685 stdout=subprocess.PIPE,
686 stderr=subprocess.PIPE)
687 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
688 timeout=0.3)
689 # Make sure we can keep waiting for it, and that we get the whole output
690 # after it completes.
691 (stdout, stderr) = p.communicate()
692 self.assertEqual(stdout, "banana")
693 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
694
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700695 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200696 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400697 p = subprocess.Popen([sys.executable, "-c",
698 'import sys,os,time;'
699 'sys.stdout.write("a" * (64 * 1024));'
700 'time.sleep(0.2);'
701 'sys.stdout.write("a" * (64 * 1024));'
702 'time.sleep(0.2);'
703 'sys.stdout.write("a" * (64 * 1024));'
704 'time.sleep(0.2);'
705 'sys.stdout.write("a" * (64 * 1024));'],
706 stdout=subprocess.PIPE)
707 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
708 (stdout, _) = p.communicate()
709 self.assertEqual(len(stdout), 4 * 64 * 1024)
710
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000711 # Test for the fd leak reported in http://bugs.python.org/issue2791.
712 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000713 for stdin_pipe in (False, True):
714 for stdout_pipe in (False, True):
715 for stderr_pipe in (False, True):
716 options = {}
717 if stdin_pipe:
718 options['stdin'] = subprocess.PIPE
719 if stdout_pipe:
720 options['stdout'] = subprocess.PIPE
721 if stderr_pipe:
722 options['stderr'] = subprocess.PIPE
723 if not options:
724 continue
725 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
726 p.communicate()
727 if p.stdin is not None:
728 self.assertTrue(p.stdin.closed)
729 if p.stdout is not None:
730 self.assertTrue(p.stdout.closed)
731 if p.stderr is not None:
732 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000733
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000735 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000736 p = subprocess.Popen([sys.executable, "-c",
737 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738 (stdout, stderr) = p.communicate()
739 self.assertEqual(stdout, None)
740 self.assertEqual(stderr, None)
741
742 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000743 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000744 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000745 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000746 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000747 os.close(x)
748 os.close(y)
749 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000750 'import sys,os;'
751 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200752 'sys.stderr.write("x" * %d);'
753 'sys.stdout.write(sys.stdin.read())' %
754 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000755 stdin=subprocess.PIPE,
756 stdout=subprocess.PIPE,
757 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000758 self.addCleanup(p.stdout.close)
759 self.addCleanup(p.stderr.close)
760 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200761 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000762 (stdout, stderr) = p.communicate(string_to_write)
763 self.assertEqual(stdout, string_to_write)
764
765 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000766 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000767 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000768 'import sys,os;'
769 'sys.stdout.write(sys.stdin.read())'],
770 stdin=subprocess.PIPE,
771 stdout=subprocess.PIPE,
772 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000773 self.addCleanup(p.stdout.close)
774 self.addCleanup(p.stderr.close)
775 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000776 p.stdin.write(b"banana")
777 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000778 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000779 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000780
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000781 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000782 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000783 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200784 'buf = sys.stdout.buffer;'
785 'buf.write(sys.stdin.readline().encode());'
786 'buf.flush();'
787 'buf.write(b"line2\\n");'
788 'buf.flush();'
789 'buf.write(sys.stdin.read().encode());'
790 'buf.flush();'
791 'buf.write(b"line4\\n");'
792 'buf.flush();'
793 'buf.write(b"line5\\r\\n");'
794 'buf.flush();'
795 'buf.write(b"line6\\r");'
796 'buf.flush();'
797 'buf.write(b"\\nline7");'
798 'buf.flush();'
799 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200800 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000801 stdout=subprocess.PIPE,
802 universal_newlines=1)
Victor Stinner7438c612016-05-20 12:43:15 +0200803 with p:
804 p.stdin.write("line1\n")
805 p.stdin.flush()
806 self.assertEqual(p.stdout.readline(), "line1\n")
807 p.stdin.write("line3\n")
808 p.stdin.close()
809 self.addCleanup(p.stdout.close)
810 self.assertEqual(p.stdout.readline(),
811 "line2\n")
812 self.assertEqual(p.stdout.read(6),
813 "line3\n")
814 self.assertEqual(p.stdout.read(),
815 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000816
817 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000818 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000819 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000820 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200821 'buf = sys.stdout.buffer;'
822 'buf.write(b"line2\\n");'
823 'buf.flush();'
824 'buf.write(b"line4\\n");'
825 'buf.flush();'
826 'buf.write(b"line5\\r\\n");'
827 'buf.flush();'
828 'buf.write(b"line6\\r");'
829 'buf.flush();'
830 'buf.write(b"\\nline7");'
831 'buf.flush();'
832 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200833 stderr=subprocess.PIPE,
834 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000835 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000836 self.addCleanup(p.stdout.close)
837 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000838 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200839 self.assertEqual(stdout,
840 "line2\nline4\nline5\nline6\nline7\nline8")
841
842 def test_universal_newlines_communicate_stdin(self):
843 # universal newlines through communicate(), with only stdin
844 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300845 'import sys,os;' + SETBINARY + textwrap.dedent('''
846 s = sys.stdin.readline()
847 assert s == "line1\\n", repr(s)
848 s = sys.stdin.read()
849 assert s == "line3\\n", repr(s)
850 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200851 stdin=subprocess.PIPE,
852 universal_newlines=1)
853 (stdout, stderr) = p.communicate("line1\nline3\n")
854 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855
Andrew Svetlovf3765072012-08-14 18:35:17 +0300856 def test_universal_newlines_communicate_input_none(self):
857 # Test communicate(input=None) with universal newlines.
858 #
859 # We set stdout to PIPE because, as of this writing, a different
860 # code path is tested when the number of pipes is zero or one.
861 p = subprocess.Popen([sys.executable, "-c", "pass"],
862 stdin=subprocess.PIPE,
863 stdout=subprocess.PIPE,
864 universal_newlines=True)
865 p.communicate()
866 self.assertEqual(p.returncode, 0)
867
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300868 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300869 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300870 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300871 'import sys,os;' + SETBINARY + textwrap.dedent('''
872 s = sys.stdin.buffer.readline()
873 sys.stdout.buffer.write(s)
874 sys.stdout.buffer.write(b"line2\\r")
875 sys.stderr.buffer.write(b"eline2\\n")
876 s = sys.stdin.buffer.read()
877 sys.stdout.buffer.write(s)
878 sys.stdout.buffer.write(b"line4\\n")
879 sys.stdout.buffer.write(b"line5\\r\\n")
880 sys.stderr.buffer.write(b"eline6\\r")
881 sys.stderr.buffer.write(b"eline7\\r\\nz")
882 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300883 stdin=subprocess.PIPE,
884 stderr=subprocess.PIPE,
885 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300886 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300887 self.addCleanup(p.stdout.close)
888 self.addCleanup(p.stderr.close)
889 (stdout, stderr) = p.communicate("line1\nline3\n")
890 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300891 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300892 # Python debug build push something like "[42442 refs]\n"
893 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300894 # Don't use assertStderrEqual because it strips CR and LF from output.
895 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300896
Andrew Svetlov82860712012-08-19 22:13:41 +0300897 def test_universal_newlines_communicate_encodings(self):
898 # Check that universal newlines mode works for various encodings,
899 # in particular for encodings in the UTF-16 and UTF-32 families.
900 # See issue #15595.
901 #
902 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
903 # without, and UTF-16 and UTF-32.
904 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300905 code = ("import sys; "
906 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
907 encoding)
908 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700909 # We set stdin to be non-None because, as of this writing,
910 # a different code path is used when the number of pipes is
911 # zero or one.
912 popen = subprocess.Popen(args,
913 stdin=subprocess.PIPE,
914 stdout=subprocess.PIPE,
915 encoding=encoding)
916 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +0300917 self.assertEqual(stdout, '1\n2\n3\n4')
918
Steve Dower050acae2016-09-06 20:16:17 -0700919 def test_communicate_errors(self):
920 for errors, expected in [
921 ('ignore', ''),
922 ('replace', '\ufffd\ufffd'),
923 ('surrogateescape', '\udc80\udc80'),
924 ('backslashreplace', '\\x80\\x80'),
925 ]:
926 code = ("import sys; "
927 r"sys.stdout.buffer.write(b'[\x80\x80]')")
928 args = [sys.executable, '-c', code]
929 # We set stdin to be non-None because, as of this writing,
930 # a different code path is used when the number of pipes is
931 # zero or one.
932 popen = subprocess.Popen(args,
933 stdin=subprocess.PIPE,
934 stdout=subprocess.PIPE,
935 encoding='utf-8',
936 errors=errors)
937 stdout, stderr = popen.communicate(input='')
938 self.assertEqual(stdout, '[{}]'.format(expected))
939
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000941 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000942 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000943 max_handles = 1026 # too much for most UNIX systems
944 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000945 max_handles = 2050 # too much for (at least some) Windows setups
946 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400947 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000948 try:
949 for i in range(max_handles):
950 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400951 tmpfile = os.path.join(tmpdir, support.TESTFN)
952 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000953 except OSError as e:
954 if e.errno != errno.EMFILE:
955 raise
956 break
957 else:
958 self.skipTest("failed to reach the file descriptor limit "
959 "(tried %d)" % max_handles)
960 # Close a couple of them (should be enough for a subprocess)
961 for i in range(10):
962 os.close(handles.pop())
963 # Loop creating some subprocesses. If one of them leaks some fds,
964 # the next loop iteration will fail by reaching the max fd limit.
965 for i in range(15):
966 p = subprocess.Popen([sys.executable, "-c",
967 "import sys;"
968 "sys.stdout.write(sys.stdin.read())"],
969 stdin=subprocess.PIPE,
970 stdout=subprocess.PIPE,
971 stderr=subprocess.PIPE)
972 data = p.communicate(b"lime")[0]
973 self.assertEqual(data, b"lime")
974 finally:
975 for h in handles:
976 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400977 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000978
979 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000980 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
981 '"a b c" d e')
982 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
983 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000984 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
985 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000986 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
987 'a\\\\\\b "de fg" h')
988 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
989 'a\\\\\\"b c d')
990 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
991 '"a\\\\b c" d e')
992 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
993 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000994 self.assertEqual(subprocess.list2cmdline(['ab', '']),
995 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000996
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000997 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200998 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200999 "import os; os.read(0, 1)"],
1000 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001001 self.addCleanup(p.stdin.close)
1002 self.assertIsNone(p.poll())
1003 os.write(p.stdin.fileno(), b'A')
1004 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001005 # Subsequent invocations should just return the returncode
1006 self.assertEqual(p.poll(), 0)
1007
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001008 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001009 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001010 self.assertEqual(p.wait(), 0)
1011 # Subsequent invocations should just return the returncode
1012 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001013
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001014 def test_wait_timeout(self):
1015 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001016 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001017 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001018 p.wait(timeout=0.0001)
1019 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001020 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1021 # time to start.
1022 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001023
Peter Astrand738131d2004-11-30 21:04:45 +00001024 def test_invalid_bufsize(self):
1025 # an invalid type of the bufsize argument should raise
1026 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001027 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001028 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001029
Guido van Rossum46a05a72007-06-07 21:56:45 +00001030 def test_bufsize_is_none(self):
1031 # bufsize=None should be the same as bufsize=0.
1032 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1033 self.assertEqual(p.wait(), 0)
1034 # Again with keyword arg
1035 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1036 self.assertEqual(p.wait(), 0)
1037
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001038 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1039 # subprocess may deadlock with bufsize=1, see issue #21332
1040 with subprocess.Popen([sys.executable, "-c", "import sys;"
1041 "sys.stdout.write(sys.stdin.readline());"
1042 "sys.stdout.flush()"],
1043 stdin=subprocess.PIPE,
1044 stdout=subprocess.PIPE,
1045 stderr=subprocess.DEVNULL,
1046 bufsize=1,
1047 universal_newlines=universal_newlines) as p:
1048 p.stdin.write(line) # expect that it flushes the line in text mode
1049 os.close(p.stdin.fileno()) # close it without flushing the buffer
1050 read_line = p.stdout.readline()
1051 try:
1052 p.stdin.close()
1053 except OSError:
1054 pass
1055 p.stdin = None
1056 self.assertEqual(p.returncode, 0)
1057 self.assertEqual(read_line, expected)
1058
1059 def test_bufsize_equal_one_text_mode(self):
1060 # line is flushed in text mode with bufsize=1.
1061 # we should get the full line in return
1062 line = "line\n"
1063 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1064
1065 def test_bufsize_equal_one_binary_mode(self):
1066 # line is not flushed in binary mode with bufsize=1.
1067 # we should get empty response
1068 line = b'line' + os.linesep.encode() # assume ascii-based locale
1069 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1070
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001071 def test_leaking_fds_on_error(self):
1072 # see bug #5179: Popen leaks file descriptors to PIPEs if
1073 # the child fails to execute; this will eventually exhaust
1074 # the maximum number of open fds. 1024 seems a very common
1075 # value for that limit, but Windows has 2048, so we loop
1076 # 1024 times (each call leaked two fds).
1077 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001078 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001079 subprocess.Popen(['nonexisting_i_hope'],
1080 stdout=subprocess.PIPE,
1081 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001082 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001083 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001084 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001085
Antoine Pitroua8392712013-08-30 23:38:13 +02001086 @unittest.skipIf(threading is None, "threading required")
1087 def test_double_close_on_error(self):
1088 # Issue #18851
1089 fds = []
1090 def open_fds():
1091 for i in range(20):
1092 fds.extend(os.pipe())
1093 time.sleep(0.001)
1094 t = threading.Thread(target=open_fds)
1095 t.start()
1096 try:
1097 with self.assertRaises(EnvironmentError):
1098 subprocess.Popen(['nonexisting_i_hope'],
1099 stdin=subprocess.PIPE,
1100 stdout=subprocess.PIPE,
1101 stderr=subprocess.PIPE)
1102 finally:
1103 t.join()
1104 exc = None
1105 for fd in fds:
1106 # If a double close occurred, some of those fds will
1107 # already have been closed by mistake, and os.close()
1108 # here will raise.
1109 try:
1110 os.close(fd)
1111 except OSError as e:
1112 exc = e
1113 if exc is not None:
1114 raise exc
1115
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001116 @unittest.skipIf(threading is None, "threading required")
1117 def test_threadsafe_wait(self):
1118 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1119 proc = subprocess.Popen([sys.executable, '-c',
1120 'import time; time.sleep(12)'])
1121 self.assertEqual(proc.returncode, None)
1122 results = []
1123
1124 def kill_proc_timer_thread():
1125 results.append(('thread-start-poll-result', proc.poll()))
1126 # terminate it from the thread and wait for the result.
1127 proc.kill()
1128 proc.wait()
1129 results.append(('thread-after-kill-and-wait', proc.returncode))
1130 # this wait should be a no-op given the above.
1131 proc.wait()
1132 results.append(('thread-after-second-wait', proc.returncode))
1133
1134 # This is a timing sensitive test, the failure mode is
1135 # triggered when both the main thread and this thread are in
1136 # the wait() call at once. The delay here is to allow the
1137 # main thread to most likely be blocked in its wait() call.
1138 t = threading.Timer(0.2, kill_proc_timer_thread)
1139 t.start()
1140
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001141 if mswindows:
1142 expected_errorcode = 1
1143 else:
1144 # Should be -9 because of the proc.kill() from the thread.
1145 expected_errorcode = -9
1146
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001147 # Wait for the process to finish; the thread should kill it
1148 # long before it finishes on its own. Supplying a timeout
1149 # triggers a different code path for better coverage.
1150 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001151 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001152 msg="unexpected result in wait from main thread")
1153
1154 # This should be a no-op with no change in returncode.
1155 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001156 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001157 msg="unexpected result in second main wait.")
1158
1159 t.join()
1160 # Ensure that all of the thread results are as expected.
1161 # When a race condition occurs in wait(), the returncode could
1162 # be set by the wrong thread that doesn't actually have it
1163 # leading to an incorrect value.
1164 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001165 ('thread-after-kill-and-wait', expected_errorcode),
1166 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001167 results)
1168
Victor Stinnerb3693582010-05-21 20:13:12 +00001169 def test_issue8780(self):
1170 # Ensure that stdout is inherited from the parent
1171 # if stdout=PIPE is not used
1172 code = ';'.join((
1173 'import subprocess, sys',
1174 'retcode = subprocess.call('
1175 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1176 'assert retcode == 0'))
1177 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001178 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001179
Tim Goldenaf5ac392010-08-06 13:03:56 +00001180 def test_handles_closed_on_exception(self):
1181 # If CreateProcess exits with an error, ensure the
1182 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001183 ifhandle, ifname = tempfile.mkstemp()
1184 ofhandle, ofname = tempfile.mkstemp()
1185 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001186 try:
1187 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1188 stderr=efhandle)
1189 except OSError:
1190 os.close(ifhandle)
1191 os.remove(ifname)
1192 os.close(ofhandle)
1193 os.remove(ofname)
1194 os.close(efhandle)
1195 os.remove(efname)
1196 self.assertFalse(os.path.exists(ifname))
1197 self.assertFalse(os.path.exists(ofname))
1198 self.assertFalse(os.path.exists(efname))
1199
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001200 def test_communicate_epipe(self):
1201 # Issue 10963: communicate() should hide EPIPE
1202 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1203 stdin=subprocess.PIPE,
1204 stdout=subprocess.PIPE,
1205 stderr=subprocess.PIPE)
1206 self.addCleanup(p.stdout.close)
1207 self.addCleanup(p.stderr.close)
1208 self.addCleanup(p.stdin.close)
1209 p.communicate(b"x" * 2**20)
1210
1211 def test_communicate_epipe_only_stdin(self):
1212 # Issue 10963: communicate() should hide EPIPE
1213 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1214 stdin=subprocess.PIPE)
1215 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001216 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001217 p.communicate(b"x" * 2**20)
1218
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001219 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1220 "Requires signal.SIGUSR1")
1221 @unittest.skipUnless(hasattr(os, 'kill'),
1222 "Requires os.kill")
1223 @unittest.skipUnless(hasattr(os, 'getppid'),
1224 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001225 def test_communicate_eintr(self):
1226 # Issue #12493: communicate() should handle EINTR
1227 def handler(signum, frame):
1228 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001229 old_handler = signal.signal(signal.SIGUSR1, handler)
1230 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001231
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001232 args = [sys.executable, "-c",
1233 'import os, signal;'
1234 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001235 for stream in ('stdout', 'stderr'):
1236 kw = {stream: subprocess.PIPE}
1237 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001238 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001239 process.communicate()
1240
Tim Peterse718f612004-10-12 21:51:32 +00001241
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001242 # This test is Linux-ish specific for simplicity to at least have
1243 # some coverage. It is not a platform specific bug.
1244 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1245 "Linux specific")
1246 def test_failed_child_execute_fd_leak(self):
1247 """Test for the fork() failure fd leak reported in issue16327."""
1248 fd_directory = '/proc/%d/fd' % os.getpid()
1249 fds_before_popen = os.listdir(fd_directory)
1250 with self.assertRaises(PopenTestException):
1251 PopenExecuteChildRaises(
1252 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1253 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1254
1255 # NOTE: This test doesn't verify that the real _execute_child
1256 # does not close the file descriptors itself on the way out
1257 # during an exception. Code inspection has confirmed that.
1258
1259 fds_after_exception = os.listdir(fd_directory)
1260 self.assertEqual(fds_before_popen, fds_after_exception)
1261
Gregory P. Smith6e730002015-04-14 16:14:25 -07001262
1263class RunFuncTestCase(BaseTestCase):
1264 def run_python(self, code, **kwargs):
1265 """Run Python code in a subprocess using subprocess.run"""
1266 argv = [sys.executable, "-c", code]
1267 return subprocess.run(argv, **kwargs)
1268
1269 def test_returncode(self):
1270 # call() function with sequence argument
1271 cp = self.run_python("import sys; sys.exit(47)")
1272 self.assertEqual(cp.returncode, 47)
1273 with self.assertRaises(subprocess.CalledProcessError):
1274 cp.check_returncode()
1275
1276 def test_check(self):
1277 with self.assertRaises(subprocess.CalledProcessError) as c:
1278 self.run_python("import sys; sys.exit(47)", check=True)
1279 self.assertEqual(c.exception.returncode, 47)
1280
1281 def test_check_zero(self):
1282 # check_returncode shouldn't raise when returncode is zero
1283 cp = self.run_python("import sys; sys.exit(0)", check=True)
1284 self.assertEqual(cp.returncode, 0)
1285
1286 def test_timeout(self):
1287 # run() function with timeout argument; we want to test that the child
1288 # process gets killed when the timeout expires. If the child isn't
1289 # killed, this call will deadlock since subprocess.run waits for the
1290 # child.
1291 with self.assertRaises(subprocess.TimeoutExpired):
1292 self.run_python("while True: pass", timeout=0.0001)
1293
1294 def test_capture_stdout(self):
1295 # capture stdout with zero return code
1296 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1297 self.assertIn(b'BDFL', cp.stdout)
1298
1299 def test_capture_stderr(self):
1300 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1301 stderr=subprocess.PIPE)
1302 self.assertIn(b'BDFL', cp.stderr)
1303
1304 def test_check_output_stdin_arg(self):
1305 # run() can be called with stdin set to a file
1306 tf = tempfile.TemporaryFile()
1307 self.addCleanup(tf.close)
1308 tf.write(b'pear')
1309 tf.seek(0)
1310 cp = self.run_python(
1311 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1312 stdin=tf, stdout=subprocess.PIPE)
1313 self.assertIn(b'PEAR', cp.stdout)
1314
1315 def test_check_output_input_arg(self):
1316 # check_output() can be called with input set to a string
1317 cp = self.run_python(
1318 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1319 input=b'pear', stdout=subprocess.PIPE)
1320 self.assertIn(b'PEAR', cp.stdout)
1321
1322 def test_check_output_stdin_with_input_arg(self):
1323 # run() refuses to accept 'stdin' with 'input'
1324 tf = tempfile.TemporaryFile()
1325 self.addCleanup(tf.close)
1326 tf.write(b'pear')
1327 tf.seek(0)
1328 with self.assertRaises(ValueError,
1329 msg="Expected ValueError when stdin and input args supplied.") as c:
1330 output = self.run_python("print('will not be run')",
1331 stdin=tf, input=b'hare')
1332 self.assertIn('stdin', c.exception.args[0])
1333 self.assertIn('input', c.exception.args[0])
1334
1335 def test_check_output_timeout(self):
1336 with self.assertRaises(subprocess.TimeoutExpired) as c:
1337 cp = self.run_python((
1338 "import sys, time\n"
1339 "sys.stdout.write('BDFL')\n"
1340 "sys.stdout.flush()\n"
1341 "time.sleep(3600)"),
1342 # Some heavily loaded buildbots (sparc Debian 3.x) require
1343 # this much time to start and print.
1344 timeout=3, stdout=subprocess.PIPE)
1345 self.assertEqual(c.exception.output, b'BDFL')
1346 # output is aliased to stdout
1347 self.assertEqual(c.exception.stdout, b'BDFL')
1348
1349 def test_run_kwargs(self):
1350 newenv = os.environ.copy()
1351 newenv["FRUIT"] = "banana"
1352 cp = self.run_python(('import sys, os;'
1353 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1354 env=newenv)
1355 self.assertEqual(cp.returncode, 33)
1356
1357
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001358@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001359class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001360
Gregory P. Smith5591b022012-10-10 03:34:47 -07001361 def setUp(self):
1362 super().setUp()
1363 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1364
1365 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001366 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001367 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001368 except OSError as e:
1369 # This avoids hard coding the errno value or the OS perror()
1370 # string and instead capture the exception that we want to see
1371 # below for comparison.
1372 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001373 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001374 else:
Martin Pantereb995702016-07-28 01:11:04 +00001375 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001376 self._nonexistent_dir)
1377 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001378
Gregory P. Smith5591b022012-10-10 03:34:47 -07001379 def test_exception_cwd(self):
1380 """Test error in the child raised in the parent for a bad cwd."""
1381 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001382 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001383 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001384 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001385 except OSError as e:
1386 # Test that the child process chdir failure actually makes
1387 # it up to the parent process as the correct exception.
1388 self.assertEqual(desired_exception.errno, e.errno)
1389 self.assertEqual(desired_exception.strerror, e.strerror)
1390 else:
1391 self.fail("Expected OSError: %s" % desired_exception)
1392
Gregory P. Smith5591b022012-10-10 03:34:47 -07001393 def test_exception_bad_executable(self):
1394 """Test error in the child raised in the parent for a bad executable."""
1395 desired_exception = self._get_chdir_exception()
1396 try:
1397 p = subprocess.Popen([sys.executable, "-c", ""],
1398 executable=self._nonexistent_dir)
1399 except OSError as e:
1400 # Test that the child process exec failure actually makes
1401 # it up to the parent process as the correct exception.
1402 self.assertEqual(desired_exception.errno, e.errno)
1403 self.assertEqual(desired_exception.strerror, e.strerror)
1404 else:
1405 self.fail("Expected OSError: %s" % desired_exception)
1406
1407 def test_exception_bad_args_0(self):
1408 """Test error in the child raised in the parent for a bad args[0]."""
1409 desired_exception = self._get_chdir_exception()
1410 try:
1411 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1412 except OSError as e:
1413 # Test that the child process exec failure actually makes
1414 # it up to the parent process as the correct exception.
1415 self.assertEqual(desired_exception.errno, e.errno)
1416 self.assertEqual(desired_exception.strerror, e.strerror)
1417 else:
1418 self.fail("Expected OSError: %s" % desired_exception)
1419
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001420 def test_restore_signals(self):
1421 # Code coverage for both values of restore_signals to make sure it
1422 # at least does not blow up.
1423 # A test for behavior would be complex. Contributions welcome.
1424 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1425 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1426
1427 def test_start_new_session(self):
1428 # For code coverage of calling setsid(). We don't care if we get an
1429 # EPERM error from it depending on the test execution environment, that
1430 # still indicates that it was called.
1431 try:
1432 output = subprocess.check_output(
1433 [sys.executable, "-c",
1434 "import os; print(os.getpgid(os.getpid()))"],
1435 start_new_session=True)
1436 except OSError as e:
1437 if e.errno != errno.EPERM:
1438 raise
1439 else:
1440 parent_pgid = os.getpgid(os.getpid())
1441 child_pgid = int(output)
1442 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001443
1444 def test_run_abort(self):
1445 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001446 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001447 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001448 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001449 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001450 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001451
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001452 def test_CalledProcessError_str_signal(self):
1453 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1454 error_string = str(err)
1455 # We're relying on the repr() of the signal.Signals intenum to provide
1456 # the word signal, the signal name and the numeric value.
1457 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001458 # We're not being specific about the signal name as some signals have
1459 # multiple names and which name is revealed can vary.
1460 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001461 self.assertIn(str(signal.SIGABRT), error_string)
1462
1463 def test_CalledProcessError_str_unknown_signal(self):
1464 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1465 error_string = str(err)
1466 self.assertIn("unknown signal 9876543.", error_string)
1467
1468 def test_CalledProcessError_str_non_zero(self):
1469 err = subprocess.CalledProcessError(2, "fake cmd")
1470 error_string = str(err)
1471 self.assertIn("non-zero exit status 2.", error_string)
1472
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001473 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001474 # DISCLAIMER: Setting environment variables is *not* a good use
1475 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001476 p = subprocess.Popen([sys.executable, "-c",
1477 'import sys,os;'
1478 'sys.stdout.write(os.getenv("FRUIT"))'],
1479 stdout=subprocess.PIPE,
1480 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001481 with p:
1482 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001483
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001484 def test_preexec_exception(self):
1485 def raise_it():
1486 raise ValueError("What if two swallows carried a coconut?")
1487 try:
1488 p = subprocess.Popen([sys.executable, "-c", ""],
1489 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001490 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001491 self.assertTrue(
1492 subprocess._posixsubprocess,
1493 "Expected a ValueError from the preexec_fn")
1494 except ValueError as e:
1495 self.assertIn("coconut", e.args[0])
1496 else:
1497 self.fail("Exception raised by preexec_fn did not make it "
1498 "to the parent process.")
1499
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001500 class _TestExecuteChildPopen(subprocess.Popen):
1501 """Used to test behavior at the end of _execute_child."""
1502 def __init__(self, testcase, *args, **kwargs):
1503 self._testcase = testcase
1504 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001505
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001506 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001507 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001508 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001509 finally:
1510 # Open a bunch of file descriptors and verify that
1511 # none of them are the same as the ones the Popen
1512 # instance is using for stdin/stdout/stderr.
1513 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1514 for _ in range(8)]
1515 try:
1516 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001517 self._testcase.assertNotIn(
1518 fd, (self.stdin.fileno(), self.stdout.fileno(),
1519 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001520 msg="At least one fd was closed early.")
1521 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001522 for fd in devzero_fds:
1523 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001524
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001525 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1526 def test_preexec_errpipe_does_not_double_close_pipes(self):
1527 """Issue16140: Don't double close pipes on preexec error."""
1528
1529 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001530 raise subprocess.SubprocessError(
1531 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001532
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001533 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001534 self._TestExecuteChildPopen(
1535 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001536 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1537 stderr=subprocess.PIPE, preexec_fn=raise_it)
1538
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001539 def test_preexec_gc_module_failure(self):
1540 # This tests the code that disables garbage collection if the child
1541 # process will execute any Python.
1542 def raise_runtime_error():
1543 raise RuntimeError("this shouldn't escape")
1544 enabled = gc.isenabled()
1545 orig_gc_disable = gc.disable
1546 orig_gc_isenabled = gc.isenabled
1547 try:
1548 gc.disable()
1549 self.assertFalse(gc.isenabled())
1550 subprocess.call([sys.executable, '-c', ''],
1551 preexec_fn=lambda: None)
1552 self.assertFalse(gc.isenabled(),
1553 "Popen enabled gc when it shouldn't.")
1554
1555 gc.enable()
1556 self.assertTrue(gc.isenabled())
1557 subprocess.call([sys.executable, '-c', ''],
1558 preexec_fn=lambda: None)
1559 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1560
1561 gc.disable = raise_runtime_error
1562 self.assertRaises(RuntimeError, subprocess.Popen,
1563 [sys.executable, '-c', ''],
1564 preexec_fn=lambda: None)
1565
1566 del gc.isenabled # force an AttributeError
1567 self.assertRaises(AttributeError, subprocess.Popen,
1568 [sys.executable, '-c', ''],
1569 preexec_fn=lambda: None)
1570 finally:
1571 gc.disable = orig_gc_disable
1572 gc.isenabled = orig_gc_isenabled
1573 if not enabled:
1574 gc.disable()
1575
Martin Panterf7fdbda2015-12-05 09:51:52 +00001576 @unittest.skipIf(
1577 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001578 def test_preexec_fork_failure(self):
1579 # The internal code did not preserve the previous exception when
1580 # re-enabling garbage collection
1581 try:
1582 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1583 except ImportError as err:
1584 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1585 limits = getrlimit(RLIMIT_NPROC)
1586 [_, hard] = limits
1587 setrlimit(RLIMIT_NPROC, (0, hard))
1588 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001589 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001590 subprocess.call([sys.executable, '-c', ''],
1591 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001592 except BlockingIOError:
1593 # Forking should raise EAGAIN, translated to BlockingIOError
1594 pass
1595 else:
1596 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001597
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001598 def test_args_string(self):
1599 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001600 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001601 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001602 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001603 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001604 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1605 sys.executable)
1606 os.chmod(fname, 0o700)
1607 p = subprocess.Popen(fname)
1608 p.wait()
1609 os.remove(fname)
1610 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001611
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001612 def test_invalid_args(self):
1613 # invalid arguments should raise ValueError
1614 self.assertRaises(ValueError, subprocess.call,
1615 [sys.executable, "-c",
1616 "import sys; sys.exit(47)"],
1617 startupinfo=47)
1618 self.assertRaises(ValueError, subprocess.call,
1619 [sys.executable, "-c",
1620 "import sys; sys.exit(47)"],
1621 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001622
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001623 def test_shell_sequence(self):
1624 # Run command through the shell (sequence)
1625 newenv = os.environ.copy()
1626 newenv["FRUIT"] = "apple"
1627 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1628 stdout=subprocess.PIPE,
1629 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001630 with p:
1631 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001632
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001633 def test_shell_string(self):
1634 # Run command through the shell (string)
1635 newenv = os.environ.copy()
1636 newenv["FRUIT"] = "apple"
1637 p = subprocess.Popen("echo $FRUIT", shell=1,
1638 stdout=subprocess.PIPE,
1639 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001640 with p:
1641 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001642
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001643 def test_call_string(self):
1644 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001645 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001646 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001647 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001648 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001649 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1650 sys.executable)
1651 os.chmod(fname, 0o700)
1652 rc = subprocess.call(fname)
1653 os.remove(fname)
1654 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001655
Stefan Krah9542cc62010-07-19 14:20:53 +00001656 def test_specific_shell(self):
1657 # Issue #9265: Incorrect name passed as arg[0].
1658 shells = []
1659 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1660 for name in ['bash', 'ksh']:
1661 sh = os.path.join(prefix, name)
1662 if os.path.isfile(sh):
1663 shells.append(sh)
1664 if not shells: # Will probably work for any shell but csh.
1665 self.skipTest("bash or ksh required for this test")
1666 sh = '/bin/sh'
1667 if os.path.isfile(sh) and not os.path.islink(sh):
1668 # Test will fail if /bin/sh is a symlink to csh.
1669 shells.append(sh)
1670 for sh in shells:
1671 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1672 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001673 with p:
1674 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001675
Florent Xicluna4886d242010-03-08 13:27:26 +00001676 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001677 # Do not inherit file handles from the parent.
1678 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001679 # Also set the SIGINT handler to the default to make sure it's not
1680 # being ignored (some tests rely on that.)
1681 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1682 try:
1683 p = subprocess.Popen([sys.executable, "-c", """if 1:
1684 import sys, time
1685 sys.stdout.write('x\\n')
1686 sys.stdout.flush()
1687 time.sleep(30)
1688 """],
1689 close_fds=True,
1690 stdin=subprocess.PIPE,
1691 stdout=subprocess.PIPE,
1692 stderr=subprocess.PIPE)
1693 finally:
1694 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001695 # Wait for the interpreter to be completely initialized before
1696 # sending any signal.
1697 p.stdout.read(1)
1698 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001699 return p
1700
Charles-François Natali53221e32013-01-12 16:52:20 +01001701 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1702 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001703 def _kill_dead_process(self, method, *args):
1704 # Do not inherit file handles from the parent.
1705 # It should fix failures on some platforms.
1706 p = subprocess.Popen([sys.executable, "-c", """if 1:
1707 import sys, time
1708 sys.stdout.write('x\\n')
1709 sys.stdout.flush()
1710 """],
1711 close_fds=True,
1712 stdin=subprocess.PIPE,
1713 stdout=subprocess.PIPE,
1714 stderr=subprocess.PIPE)
1715 # Wait for the interpreter to be completely initialized before
1716 # sending any signal.
1717 p.stdout.read(1)
1718 # The process should end after this
1719 time.sleep(1)
1720 # This shouldn't raise even though the child is now dead
1721 getattr(p, method)(*args)
1722 p.communicate()
1723
Florent Xicluna4886d242010-03-08 13:27:26 +00001724 def test_send_signal(self):
1725 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001726 _, stderr = p.communicate()
1727 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001728 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001729
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001730 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001731 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001732 _, stderr = p.communicate()
1733 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001734 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001735
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001736 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001737 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001738 _, stderr = p.communicate()
1739 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001740 self.assertEqual(p.wait(), -signal.SIGTERM)
1741
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001742 def test_send_signal_dead(self):
1743 # Sending a signal to a dead process
1744 self._kill_dead_process('send_signal', signal.SIGINT)
1745
1746 def test_kill_dead(self):
1747 # Killing a dead process
1748 self._kill_dead_process('kill')
1749
1750 def test_terminate_dead(self):
1751 # Terminating a dead process
1752 self._kill_dead_process('terminate')
1753
Victor Stinnerdaf45552013-08-28 00:53:59 +02001754 def _save_fds(self, save_fds):
1755 fds = []
1756 for fd in save_fds:
1757 inheritable = os.get_inheritable(fd)
1758 saved = os.dup(fd)
1759 fds.append((fd, saved, inheritable))
1760 return fds
1761
1762 def _restore_fds(self, fds):
1763 for fd, saved, inheritable in fds:
1764 os.dup2(saved, fd, inheritable=inheritable)
1765 os.close(saved)
1766
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001767 def check_close_std_fds(self, fds):
1768 # Issue #9905: test that subprocess pipes still work properly with
1769 # some standard fds closed
1770 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001771 saved_fds = self._save_fds(fds)
1772 for fd, saved, inheritable in saved_fds:
1773 if fd == 0:
1774 stdin = saved
1775 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001776 try:
1777 for fd in fds:
1778 os.close(fd)
1779 out, err = subprocess.Popen([sys.executable, "-c",
1780 'import sys;'
1781 'sys.stdout.write("apple");'
1782 'sys.stdout.flush();'
1783 'sys.stderr.write("orange")'],
1784 stdin=stdin,
1785 stdout=subprocess.PIPE,
1786 stderr=subprocess.PIPE).communicate()
1787 err = support.strip_python_stderr(err)
1788 self.assertEqual((out, err), (b'apple', b'orange'))
1789 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001790 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001791
1792 def test_close_fd_0(self):
1793 self.check_close_std_fds([0])
1794
1795 def test_close_fd_1(self):
1796 self.check_close_std_fds([1])
1797
1798 def test_close_fd_2(self):
1799 self.check_close_std_fds([2])
1800
1801 def test_close_fds_0_1(self):
1802 self.check_close_std_fds([0, 1])
1803
1804 def test_close_fds_0_2(self):
1805 self.check_close_std_fds([0, 2])
1806
1807 def test_close_fds_1_2(self):
1808 self.check_close_std_fds([1, 2])
1809
1810 def test_close_fds_0_1_2(self):
1811 # Issue #10806: test that subprocess pipes still work properly with
1812 # all standard fds closed.
1813 self.check_close_std_fds([0, 1, 2])
1814
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001815 def test_small_errpipe_write_fd(self):
1816 """Issue #15798: Popen should work when stdio fds are available."""
1817 new_stdin = os.dup(0)
1818 new_stdout = os.dup(1)
1819 try:
1820 os.close(0)
1821 os.close(1)
1822
1823 # Side test: if errpipe_write fails to have its CLOEXEC
1824 # flag set this should cause the parent to think the exec
1825 # failed. Extremely unlikely: everyone supports CLOEXEC.
1826 subprocess.Popen([
1827 sys.executable, "-c",
1828 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1829 finally:
1830 # Restore original stdin and stdout
1831 os.dup2(new_stdin, 0)
1832 os.dup2(new_stdout, 1)
1833 os.close(new_stdin)
1834 os.close(new_stdout)
1835
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001836 def test_remapping_std_fds(self):
1837 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001838 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001839 try:
1840 temp_fds = [fd for fd, fname in temps]
1841
1842 # unlink the files -- we won't need to reopen them
1843 for fd, fname in temps:
1844 os.unlink(fname)
1845
1846 # write some data to what will become stdin, and rewind
1847 os.write(temp_fds[1], b"STDIN")
1848 os.lseek(temp_fds[1], 0, 0)
1849
1850 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001851 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001852 try:
1853 # duplicate the file objects over the standard fd's
1854 for fd, temp_fd in enumerate(temp_fds):
1855 os.dup2(temp_fd, fd)
1856
1857 # now use those files in the "wrong" order, so that subprocess
1858 # has to rearrange them in the child
1859 p = subprocess.Popen([sys.executable, "-c",
1860 'import sys; got = sys.stdin.read();'
1861 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1862 stdin=temp_fds[1],
1863 stdout=temp_fds[2],
1864 stderr=temp_fds[0])
1865 p.wait()
1866 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001867 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001868
1869 for fd in temp_fds:
1870 os.lseek(fd, 0, 0)
1871
1872 out = os.read(temp_fds[2], 1024)
1873 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1874 self.assertEqual(out, b"got STDIN")
1875 self.assertEqual(err, b"err")
1876
1877 finally:
1878 for fd in temp_fds:
1879 os.close(fd)
1880
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001881 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1882 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001883 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001884 temp_fds = [fd for fd, fname in temps]
1885 try:
1886 # unlink the files -- we won't need to reopen them
1887 for fd, fname in temps:
1888 os.unlink(fname)
1889
1890 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001891 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001892 try:
1893 # duplicate the temp files over the standard fd's 0, 1, 2
1894 for fd, temp_fd in enumerate(temp_fds):
1895 os.dup2(temp_fd, fd)
1896
1897 # write some data to what will become stdin, and rewind
1898 os.write(stdin_no, b"STDIN")
1899 os.lseek(stdin_no, 0, 0)
1900
1901 # now use those files in the given order, so that subprocess
1902 # has to rearrange them in the child
1903 p = subprocess.Popen([sys.executable, "-c",
1904 'import sys; got = sys.stdin.read();'
1905 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1906 stdin=stdin_no,
1907 stdout=stdout_no,
1908 stderr=stderr_no)
1909 p.wait()
1910
1911 for fd in temp_fds:
1912 os.lseek(fd, 0, 0)
1913
1914 out = os.read(stdout_no, 1024)
1915 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1916 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001917 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001918
1919 self.assertEqual(out, b"got STDIN")
1920 self.assertEqual(err, b"err")
1921
1922 finally:
1923 for fd in temp_fds:
1924 os.close(fd)
1925
1926 # When duping fds, if there arises a situation where one of the fds is
1927 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1928 # This tests all combinations of this.
1929 def test_swap_fds(self):
1930 self.check_swap_fds(0, 1, 2)
1931 self.check_swap_fds(0, 2, 1)
1932 self.check_swap_fds(1, 0, 2)
1933 self.check_swap_fds(1, 2, 0)
1934 self.check_swap_fds(2, 0, 1)
1935 self.check_swap_fds(2, 1, 0)
1936
Victor Stinner13bb71c2010-04-23 21:41:56 +00001937 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001938 def prepare():
1939 raise ValueError("surrogate:\uDCff")
1940
1941 try:
1942 subprocess.call(
1943 [sys.executable, "-c", "pass"],
1944 preexec_fn=prepare)
1945 except ValueError as err:
1946 # Pure Python implementations keeps the message
1947 self.assertIsNone(subprocess._posixsubprocess)
1948 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001949 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001950 # _posixsubprocess uses a default message
1951 self.assertIsNotNone(subprocess._posixsubprocess)
1952 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1953 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001954 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001955
Victor Stinner13bb71c2010-04-23 21:41:56 +00001956 def test_undecodable_env(self):
1957 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01001958 encoded_value = value.encode("ascii", "surrogateescape")
1959
Victor Stinner13bb71c2010-04-23 21:41:56 +00001960 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001961 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001962 env = os.environ.copy()
1963 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01001964 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00001965 # surrogate-escaping of \xFF in the child process; otherwise it can
1966 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001967 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01001968 if sys.platform.startswith("aix"):
1969 # On AIX, the C locale uses the Latin1 encoding
1970 decoded_value = encoded_value.decode("latin1", "surrogateescape")
1971 else:
1972 # On other UNIXes, the C locale uses the ASCII encoding
1973 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001974 stdout = subprocess.check_output(
1975 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001976 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001977 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001978 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001979
1980 # test bytes
1981 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001982 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001983 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01001984 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001985 stdout = subprocess.check_output(
1986 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001987 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001988 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001989 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001990
Victor Stinnerb745a742010-05-18 17:17:23 +00001991 def test_bytes_program(self):
1992 abs_program = os.fsencode(sys.executable)
1993 path, program = os.path.split(sys.executable)
1994 program = os.fsencode(program)
1995
1996 # absolute bytes path
1997 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001998 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001999
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002000 # absolute bytes path as a string
2001 cmd = b"'" + abs_program + b"' -c pass"
2002 exitcode = subprocess.call(cmd, shell=True)
2003 self.assertEqual(exitcode, 0)
2004
Victor Stinnerb745a742010-05-18 17:17:23 +00002005 # bytes program, unicode PATH
2006 env = os.environ.copy()
2007 env["PATH"] = path
2008 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002009 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002010
2011 # bytes program, bytes PATH
2012 envb = os.environb.copy()
2013 envb[b"PATH"] = os.fsencode(path)
2014 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002015 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002016
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002017 def test_pipe_cloexec(self):
2018 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2019 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2020
2021 p1 = subprocess.Popen([sys.executable, sleeper],
2022 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2023 stderr=subprocess.PIPE, close_fds=False)
2024
2025 self.addCleanup(p1.communicate, b'')
2026
2027 p2 = subprocess.Popen([sys.executable, fd_status],
2028 stdout=subprocess.PIPE, close_fds=False)
2029
2030 output, error = p2.communicate()
2031 result_fds = set(map(int, output.split(b',')))
2032 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2033 p1.stderr.fileno()])
2034
2035 self.assertFalse(result_fds & unwanted_fds,
2036 "Expected no fds from %r to be open in child, "
2037 "found %r" %
2038 (unwanted_fds, result_fds & unwanted_fds))
2039
2040 def test_pipe_cloexec_real_tools(self):
2041 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2042 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2043
2044 subdata = b'zxcvbn'
2045 data = subdata * 4 + b'\n'
2046
2047 p1 = subprocess.Popen([sys.executable, qcat],
2048 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2049 close_fds=False)
2050
2051 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2052 stdin=p1.stdout, stdout=subprocess.PIPE,
2053 close_fds=False)
2054
2055 self.addCleanup(p1.wait)
2056 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002057 def kill_p1():
2058 try:
2059 p1.terminate()
2060 except ProcessLookupError:
2061 pass
2062 def kill_p2():
2063 try:
2064 p2.terminate()
2065 except ProcessLookupError:
2066 pass
2067 self.addCleanup(kill_p1)
2068 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002069
2070 p1.stdin.write(data)
2071 p1.stdin.close()
2072
2073 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2074
2075 self.assertTrue(readfiles, "The child hung")
2076 self.assertEqual(p2.stdout.read(), data)
2077
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002078 p1.stdout.close()
2079 p2.stdout.close()
2080
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002081 def test_close_fds(self):
2082 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2083
2084 fds = os.pipe()
2085 self.addCleanup(os.close, fds[0])
2086 self.addCleanup(os.close, fds[1])
2087
2088 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002089 # add a bunch more fds
2090 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002091 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002092 self.addCleanup(os.close, fd)
2093 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002094
Victor Stinnerdaf45552013-08-28 00:53:59 +02002095 for fd in open_fds:
2096 os.set_inheritable(fd, True)
2097
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002098 p = subprocess.Popen([sys.executable, fd_status],
2099 stdout=subprocess.PIPE, close_fds=False)
2100 output, ignored = p.communicate()
2101 remaining_fds = set(map(int, output.split(b',')))
2102
2103 self.assertEqual(remaining_fds & open_fds, open_fds,
2104 "Some fds were closed")
2105
2106 p = subprocess.Popen([sys.executable, fd_status],
2107 stdout=subprocess.PIPE, close_fds=True)
2108 output, ignored = p.communicate()
2109 remaining_fds = set(map(int, output.split(b',')))
2110
2111 self.assertFalse(remaining_fds & open_fds,
2112 "Some fds were left open")
2113 self.assertIn(1, remaining_fds, "Subprocess failed")
2114
Gregory P. Smith8facece2012-01-21 14:01:08 -08002115 # Keep some of the fd's we opened open in the subprocess.
2116 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2117 fds_to_keep = set(open_fds.pop() for _ in range(8))
2118 p = subprocess.Popen([sys.executable, fd_status],
2119 stdout=subprocess.PIPE, close_fds=True,
2120 pass_fds=())
2121 output, ignored = p.communicate()
2122 remaining_fds = set(map(int, output.split(b',')))
2123
2124 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2125 "Some fds not in pass_fds were left open")
2126 self.assertIn(1, remaining_fds, "Subprocess failed")
2127
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002128
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002129 @unittest.skipIf(sys.platform.startswith("freebsd") and
2130 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2131 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002132 def test_close_fds_when_max_fd_is_lowered(self):
2133 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2134 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2135
Gregory P. Smith634aa682014-06-15 17:51:04 -07002136 # This launches the meat of the test in a child process to
2137 # avoid messing with the larger unittest processes maximum
2138 # number of file descriptors.
2139 # This process launches:
2140 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2141 # a bunch of high open fds above the new lower rlimit.
2142 # Those are reported via stdout before launching a new
2143 # process with close_fds=False to run the actual test:
2144 # +--> The TEST: This one launches a fd_status.py
2145 # subprocess with close_fds=True so we can find out if
2146 # any of the fds above the lowered rlimit are still open.
2147 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2148 '''
2149 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002150 open_fds = set()
2151 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002152 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002153 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002154 open_fds.add(fd)
2155
2156 # Leave a two pairs of low ones available for use by the
2157 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002158 # We also leave 10 more open as some Python buildbots run into
2159 # "too many open files" errors during the test if we do not.
2160 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002161 os.close(fd)
2162 open_fds.remove(fd)
2163
2164 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002165 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002166 os.set_inheritable(fd, True)
2167
2168 max_fd_open = max(open_fds)
2169
Gregory P. Smith634aa682014-06-15 17:51:04 -07002170 # Communicate the open_fds to the parent unittest.TestCase process.
2171 print(','.join(map(str, sorted(open_fds))))
2172 sys.stdout.flush()
2173
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002174 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2175 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002176 # 29 is lower than the highest fds we are leaving open.
2177 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002178 # Launch a new Python interpreter with our low fd rlim_cur that
2179 # inherits open fds above that limit. It then uses subprocess
2180 # with close_fds=True to get a report of open fds in the child.
2181 # An explicit list of fds to check is passed to fd_status.py as
2182 # letting fd_status rely on its default logic would miss the
2183 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002184 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002185 [sys.executable, '-c',
2186 textwrap.dedent("""
2187 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002188 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002189 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002190 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002191 """.format(max_fd=max_fd_open+1))],
2192 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002193 finally:
2194 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002195 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002196
2197 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002198 output_lines = output.splitlines()
2199 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002200 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002201 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2202 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002203
Gregory P. Smith634aa682014-06-15 17:51:04 -07002204 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002205 msg="Some fds were left open.")
2206
2207
Victor Stinner88701e22011-06-01 13:13:04 +02002208 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2209 # descriptor of a pipe closed in the parent process is valid in the
2210 # child process according to fstat(), but the mode of the file
2211 # descriptor is invalid, and read or write raise an error.
2212 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002213 def test_pass_fds(self):
2214 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2215
2216 open_fds = set()
2217
2218 for x in range(5):
2219 fds = os.pipe()
2220 self.addCleanup(os.close, fds[0])
2221 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002222 os.set_inheritable(fds[0], True)
2223 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002224 open_fds.update(fds)
2225
2226 for fd in open_fds:
2227 p = subprocess.Popen([sys.executable, fd_status],
2228 stdout=subprocess.PIPE, close_fds=True,
2229 pass_fds=(fd, ))
2230 output, ignored = p.communicate()
2231
2232 remaining_fds = set(map(int, output.split(b',')))
2233 to_be_closed = open_fds - {fd}
2234
2235 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2236 self.assertFalse(remaining_fds & to_be_closed,
2237 "fd to be closed passed")
2238
2239 # pass_fds overrides close_fds with a warning.
2240 with self.assertWarns(RuntimeWarning) as context:
2241 self.assertFalse(subprocess.call(
2242 [sys.executable, "-c", "import sys; sys.exit(0)"],
2243 close_fds=False, pass_fds=(fd, )))
2244 self.assertIn('overriding close_fds', str(context.warning))
2245
Victor Stinnerdaf45552013-08-28 00:53:59 +02002246 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002247 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002248
2249 inheritable, non_inheritable = os.pipe()
2250 self.addCleanup(os.close, inheritable)
2251 self.addCleanup(os.close, non_inheritable)
2252 os.set_inheritable(inheritable, True)
2253 os.set_inheritable(non_inheritable, False)
2254 pass_fds = (inheritable, non_inheritable)
2255 args = [sys.executable, script]
2256 args += list(map(str, pass_fds))
2257
2258 p = subprocess.Popen(args,
2259 stdout=subprocess.PIPE, close_fds=True,
2260 pass_fds=pass_fds)
2261 output, ignored = p.communicate()
2262 fds = set(map(int, output.split(b',')))
2263
2264 # the inheritable file descriptor must be inherited, so its inheritable
2265 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002266 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002267
2268 # inheritable flag must not be changed in the parent process
2269 self.assertEqual(os.get_inheritable(inheritable), True)
2270 self.assertEqual(os.get_inheritable(non_inheritable), False)
2271
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002272 def test_stdout_stdin_are_single_inout_fd(self):
2273 with io.open(os.devnull, "r+") as inout:
2274 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2275 stdout=inout, stdin=inout)
2276 p.wait()
2277
2278 def test_stdout_stderr_are_single_inout_fd(self):
2279 with io.open(os.devnull, "r+") as inout:
2280 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2281 stdout=inout, stderr=inout)
2282 p.wait()
2283
2284 def test_stderr_stdin_are_single_inout_fd(self):
2285 with io.open(os.devnull, "r+") as inout:
2286 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2287 stderr=inout, stdin=inout)
2288 p.wait()
2289
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002290 def test_wait_when_sigchild_ignored(self):
2291 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2292 sigchild_ignore = support.findfile("sigchild_ignore.py",
2293 subdir="subprocessdata")
2294 p = subprocess.Popen([sys.executable, sigchild_ignore],
2295 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2296 stdout, stderr = p.communicate()
2297 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002298 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002299 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002300
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002301 def test_select_unbuffered(self):
2302 # Issue #11459: bufsize=0 should really set the pipes as
2303 # unbuffered (and therefore let select() work properly).
2304 select = support.import_module("select")
2305 p = subprocess.Popen([sys.executable, "-c",
2306 'import sys;'
2307 'sys.stdout.write("apple")'],
2308 stdout=subprocess.PIPE,
2309 bufsize=0)
2310 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002311 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002312 try:
2313 self.assertEqual(f.read(4), b"appl")
2314 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2315 finally:
2316 p.wait()
2317
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002318 def test_zombie_fast_process_del(self):
2319 # Issue #12650: on Unix, if Popen.__del__() was called before the
2320 # process exited, it wouldn't be added to subprocess._active, and would
2321 # remain a zombie.
2322 # spawn a Popen, and delete its reference before it exits
2323 p = subprocess.Popen([sys.executable, "-c",
2324 'import sys, time;'
2325 'time.sleep(0.2)'],
2326 stdout=subprocess.PIPE,
2327 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002328 self.addCleanup(p.stdout.close)
2329 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002330 ident = id(p)
2331 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002332 with support.check_warnings(('', ResourceWarning)):
2333 p = None
2334
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002335 # check that p is in the active processes list
2336 self.assertIn(ident, [id(o) for o in subprocess._active])
2337
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002338 def test_leak_fast_process_del_killed(self):
2339 # Issue #12650: on Unix, if Popen.__del__() was called before the
2340 # process exited, and the process got killed by a signal, it would never
2341 # be removed from subprocess._active, which triggered a FD and memory
2342 # leak.
2343 # spawn a Popen, delete its reference and kill it
2344 p = subprocess.Popen([sys.executable, "-c",
2345 'import time;'
2346 'time.sleep(3)'],
2347 stdout=subprocess.PIPE,
2348 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002349 self.addCleanup(p.stdout.close)
2350 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002351 ident = id(p)
2352 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002353 with support.check_warnings(('', ResourceWarning)):
2354 p = None
2355
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002356 os.kill(pid, signal.SIGKILL)
2357 # check that p is in the active processes list
2358 self.assertIn(ident, [id(o) for o in subprocess._active])
2359
2360 # let some time for the process to exit, and create a new Popen: this
2361 # should trigger the wait() of p
2362 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002363 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002364 with subprocess.Popen(['nonexisting_i_hope'],
2365 stdout=subprocess.PIPE,
2366 stderr=subprocess.PIPE) as proc:
2367 pass
2368 # p should have been wait()ed on, and removed from the _active list
2369 self.assertRaises(OSError, os.waitpid, pid, 0)
2370 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2371
Charles-François Natali249cdc32013-08-25 18:24:45 +02002372 def test_close_fds_after_preexec(self):
2373 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2374
2375 # this FD is used as dup2() target by preexec_fn, and should be closed
2376 # in the child process
2377 fd = os.dup(1)
2378 self.addCleanup(os.close, fd)
2379
2380 p = subprocess.Popen([sys.executable, fd_status],
2381 stdout=subprocess.PIPE, close_fds=True,
2382 preexec_fn=lambda: os.dup2(1, fd))
2383 output, ignored = p.communicate()
2384
2385 remaining_fds = set(map(int, output.split(b',')))
2386
2387 self.assertNotIn(fd, remaining_fds)
2388
Victor Stinner8f437aa2014-10-05 17:25:19 +02002389 @support.cpython_only
2390 def test_fork_exec(self):
2391 # Issue #22290: fork_exec() must not crash on memory allocation failure
2392 # or other errors
2393 import _posixsubprocess
2394 gc_enabled = gc.isenabled()
2395 try:
2396 # Use a preexec function and enable the garbage collector
2397 # to force fork_exec() to re-enable the garbage collector
2398 # on error.
2399 func = lambda: None
2400 gc.enable()
2401
Victor Stinner8f437aa2014-10-05 17:25:19 +02002402 for args, exe_list, cwd, env_list in (
2403 (123, [b"exe"], None, [b"env"]),
2404 ([b"arg"], 123, None, [b"env"]),
2405 ([b"arg"], [b"exe"], 123, [b"env"]),
2406 ([b"arg"], [b"exe"], None, 123),
2407 ):
2408 with self.assertRaises(TypeError):
2409 _posixsubprocess.fork_exec(
2410 args, exe_list,
2411 True, [], cwd, env_list,
2412 -1, -1, -1, -1,
2413 1, 2, 3, 4,
2414 True, True, func)
2415 finally:
2416 if not gc_enabled:
2417 gc.disable()
2418
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002419 @support.cpython_only
2420 def test_fork_exec_sorted_fd_sanity_check(self):
2421 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2422 import _posixsubprocess
2423 gc_enabled = gc.isenabled()
2424 try:
2425 gc.enable()
2426
2427 for fds_to_keep in (
2428 (-1, 2, 3, 4, 5), # Negative number.
2429 ('str', 4), # Not an int.
2430 (18, 23, 42, 2**63), # Out of range.
2431 (5, 4), # Not sorted.
2432 (6, 7, 7, 8), # Duplicate.
2433 ):
2434 with self.assertRaises(
2435 ValueError,
2436 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2437 _posixsubprocess.fork_exec(
2438 [b"false"], [b"false"],
2439 True, fds_to_keep, None, [b"env"],
2440 -1, -1, -1, -1,
2441 1, 2, 3, 4,
2442 True, True, None)
2443 self.assertIn('fds_to_keep', str(c.exception))
2444 finally:
2445 if not gc_enabled:
2446 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002447
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002448 def test_communicate_BrokenPipeError_stdin_close(self):
2449 # By not setting stdout or stderr or a timeout we force the fast path
2450 # that just calls _stdin_write() internally due to our mock.
2451 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2452 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2453 mock_proc_stdin.close.side_effect = BrokenPipeError
2454 proc.communicate() # Should swallow BrokenPipeError from close.
2455 mock_proc_stdin.close.assert_called_with()
2456
2457 def test_communicate_BrokenPipeError_stdin_write(self):
2458 # By not setting stdout or stderr or a timeout we force the fast path
2459 # that just calls _stdin_write() internally due to our mock.
2460 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2461 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2462 mock_proc_stdin.write.side_effect = BrokenPipeError
2463 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2464 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2465 mock_proc_stdin.close.assert_called_once_with()
2466
2467 def test_communicate_BrokenPipeError_stdin_flush(self):
2468 # Setting stdin and stdout forces the ._communicate() code path.
2469 # python -h exits faster than python -c pass (but spams stdout).
2470 proc = subprocess.Popen([sys.executable, '-h'],
2471 stdin=subprocess.PIPE,
2472 stdout=subprocess.PIPE)
2473 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2474 open(os.devnull, 'wb') as dev_null:
2475 mock_proc_stdin.flush.side_effect = BrokenPipeError
2476 # because _communicate registers a selector using proc.stdin...
2477 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2478 # _communicate() should swallow BrokenPipeError from flush.
2479 proc.communicate(b'stuff')
2480 mock_proc_stdin.flush.assert_called_once_with()
2481
2482 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2483 # Setting stdin and stdout forces the ._communicate() code path.
2484 # python -h exits faster than python -c pass (but spams stdout).
2485 proc = subprocess.Popen([sys.executable, '-h'],
2486 stdin=subprocess.PIPE,
2487 stdout=subprocess.PIPE)
2488 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2489 mock_proc_stdin.close.side_effect = BrokenPipeError
2490 # _communicate() should swallow BrokenPipeError from close.
2491 proc.communicate(timeout=999)
2492 mock_proc_stdin.close.assert_called_once_with()
2493
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002494 _libc_file_extensions = {
2495 'Linux': 'so.6',
Gregory P. Smith21d333b2017-01-22 20:54:42 -08002496 'Darwin': 'dylib',
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002497 }
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -08002498 @unittest.skipIf(not ctypes, 'ctypes module required.')
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002499 @unittest.skipIf(platform.uname()[0] not in _libc_file_extensions,
2500 'Test requires a libc this code can load with ctypes.')
2501 @unittest.skipIf(not sys.executable, 'Test requires sys.executable.')
2502 def test_child_terminated_in_stopped_state(self):
2503 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
2504 PTRACE_TRACEME = 0 # From glibc and MacOS (PT_TRACE_ME).
2505 libc_name = 'libc.' + self._libc_file_extensions[platform.uname()[0]]
2506 libc = ctypes.CDLL(libc_name)
2507 if not hasattr(libc, 'ptrace'):
2508 raise unittest.SkipTest('ptrace() required.')
2509 test_ptrace = subprocess.Popen(
2510 [sys.executable, '-c', """if True:
2511 import ctypes
2512 libc = ctypes.CDLL({libc_name!r})
2513 libc.ptrace({PTRACE_TRACEME}, 0, 0)
2514 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
2515 ])
2516 if test_ptrace.wait() != 0:
2517 raise unittest.SkipTest('ptrace() failed - unable to test.')
2518 child = subprocess.Popen(
2519 [sys.executable, '-c', """if True:
2520 import ctypes
2521 libc = ctypes.CDLL({libc_name!r})
2522 libc.ptrace({PTRACE_TRACEME}, 0, 0)
2523 libc.printf(ctypes.c_char_p(0xdeadbeef)) # Crash the process.
2524 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
2525 ])
2526 try:
2527 returncode = child.wait()
2528 except Exception as e:
2529 child.kill() # Clean up the hung stopped process.
2530 raise e
2531 self.assertNotEqual(0, returncode)
2532 self.assertLess(returncode, 0) # signal death, likely SIGSEGV.
2533
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002534
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002535@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002536class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002537
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002538 def test_startupinfo(self):
2539 # startupinfo argument
2540 # We uses hardcoded constants, because we do not want to
2541 # depend on win32all.
2542 STARTF_USESHOWWINDOW = 1
2543 SW_MAXIMIZE = 3
2544 startupinfo = subprocess.STARTUPINFO()
2545 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2546 startupinfo.wShowWindow = SW_MAXIMIZE
2547 # Since Python is a console process, it won't be affected
2548 # by wShowWindow, but the argument should be silently
2549 # ignored
2550 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002551 startupinfo=startupinfo)
2552
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002553 def test_creationflags(self):
2554 # creationflags argument
2555 CREATE_NEW_CONSOLE = 16
2556 sys.stderr.write(" a DOS box should flash briefly ...\n")
2557 subprocess.call(sys.executable +
2558 ' -c "import time; time.sleep(0.25)"',
2559 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002560
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002561 def test_invalid_args(self):
2562 # invalid arguments should raise ValueError
2563 self.assertRaises(ValueError, subprocess.call,
2564 [sys.executable, "-c",
2565 "import sys; sys.exit(47)"],
2566 preexec_fn=lambda: 1)
2567 self.assertRaises(ValueError, subprocess.call,
2568 [sys.executable, "-c",
2569 "import sys; sys.exit(47)"],
2570 stdout=subprocess.PIPE,
2571 close_fds=True)
2572
2573 def test_close_fds(self):
2574 # close file descriptors
2575 rc = subprocess.call([sys.executable, "-c",
2576 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002577 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002578 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002579
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002580 def test_shell_sequence(self):
2581 # Run command through the shell (sequence)
2582 newenv = os.environ.copy()
2583 newenv["FRUIT"] = "physalis"
2584 p = subprocess.Popen(["set"], shell=1,
2585 stdout=subprocess.PIPE,
2586 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002587 with p:
2588 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002589
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002590 def test_shell_string(self):
2591 # Run command through the shell (string)
2592 newenv = os.environ.copy()
2593 newenv["FRUIT"] = "physalis"
2594 p = subprocess.Popen("set", shell=1,
2595 stdout=subprocess.PIPE,
2596 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002597 with p:
2598 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002599
Steve Dower050acae2016-09-06 20:16:17 -07002600 def test_shell_encodings(self):
2601 # Run command through the shell (string)
2602 for enc in ['ansi', 'oem']:
2603 newenv = os.environ.copy()
2604 newenv["FRUIT"] = "physalis"
2605 p = subprocess.Popen("set", shell=1,
2606 stdout=subprocess.PIPE,
2607 env=newenv,
2608 encoding=enc)
2609 with p:
2610 self.assertIn("physalis", p.stdout.read(), enc)
2611
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002612 def test_call_string(self):
2613 # call() function with string argument on Windows
2614 rc = subprocess.call(sys.executable +
2615 ' -c "import sys; sys.exit(47)"')
2616 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002617
Florent Xicluna4886d242010-03-08 13:27:26 +00002618 def _kill_process(self, method, *args):
2619 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002620 p = subprocess.Popen([sys.executable, "-c", """if 1:
2621 import sys, time
2622 sys.stdout.write('x\\n')
2623 sys.stdout.flush()
2624 time.sleep(30)
2625 """],
2626 stdin=subprocess.PIPE,
2627 stdout=subprocess.PIPE,
2628 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002629 with p:
2630 # Wait for the interpreter to be completely initialized before
2631 # sending any signal.
2632 p.stdout.read(1)
2633 getattr(p, method)(*args)
2634 _, stderr = p.communicate()
2635 self.assertStderrEqual(stderr, b'')
2636 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002637 self.assertNotEqual(returncode, 0)
2638
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002639 def _kill_dead_process(self, method, *args):
2640 p = subprocess.Popen([sys.executable, "-c", """if 1:
2641 import sys, time
2642 sys.stdout.write('x\\n')
2643 sys.stdout.flush()
2644 sys.exit(42)
2645 """],
2646 stdin=subprocess.PIPE,
2647 stdout=subprocess.PIPE,
2648 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002649 with p:
2650 # Wait for the interpreter to be completely initialized before
2651 # sending any signal.
2652 p.stdout.read(1)
2653 # The process should end after this
2654 time.sleep(1)
2655 # This shouldn't raise even though the child is now dead
2656 getattr(p, method)(*args)
2657 _, stderr = p.communicate()
2658 self.assertStderrEqual(stderr, b'')
2659 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002660 self.assertEqual(rc, 42)
2661
Florent Xicluna4886d242010-03-08 13:27:26 +00002662 def test_send_signal(self):
2663 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002664
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002665 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002666 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002667
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002668 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002669 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002670
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002671 def test_send_signal_dead(self):
2672 self._kill_dead_process('send_signal', signal.SIGTERM)
2673
2674 def test_kill_dead(self):
2675 self._kill_dead_process('kill')
2676
2677 def test_terminate_dead(self):
2678 self._kill_dead_process('terminate')
2679
Martin Panter23172bd2016-04-16 11:28:10 +00002680class MiscTests(unittest.TestCase):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002681 def test_getoutput(self):
2682 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2683 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2684 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002685
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002686 # we use mkdtemp in the next line to create an empty directory
2687 # under our exclusive control; from that, we can invent a pathname
2688 # that we _know_ won't exist. This is guaranteed to fail.
2689 dir = None
2690 try:
2691 dir = tempfile.mkdtemp()
2692 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002693 status, output = subprocess.getstatusoutput(
2694 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002695 self.assertNotEqual(status, 0)
2696 finally:
2697 if dir is not None:
2698 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002699
Gregory P. Smithace55862015-04-07 15:57:54 -07002700 def test__all__(self):
2701 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00002702 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07002703 exported = set(subprocess.__all__)
2704 possible_exports = set()
2705 import types
2706 for name, value in subprocess.__dict__.items():
2707 if name.startswith('_'):
2708 continue
2709 if isinstance(value, (types.ModuleType,)):
2710 continue
2711 possible_exports.add(name)
2712 self.assertEqual(exported, possible_exports - intentionally_excluded)
2713
2714
Martin Panter23172bd2016-04-16 11:28:10 +00002715@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2716 "Test needs selectors.PollSelector")
2717class ProcessTestCaseNoPoll(ProcessTestCase):
2718 def setUp(self):
2719 self.orig_selector = subprocess._PopenSelector
2720 subprocess._PopenSelector = selectors.SelectSelector
2721 ProcessTestCase.setUp(self)
2722
2723 def tearDown(self):
2724 subprocess._PopenSelector = self.orig_selector
2725 ProcessTestCase.tearDown(self)
2726
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002727
Tim Golden126c2962010-08-11 14:20:40 +00002728@unittest.skipUnless(mswindows, "Windows-specific tests")
2729class CommandsWithSpaces (BaseTestCase):
2730
2731 def setUp(self):
2732 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002733 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002734 self.fname = fname.lower ()
2735 os.write(f, b"import sys;"
2736 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2737 )
2738 os.close(f)
2739
2740 def tearDown(self):
2741 os.remove(self.fname)
2742 super().tearDown()
2743
2744 def with_spaces(self, *args, **kwargs):
2745 kwargs['stdout'] = subprocess.PIPE
2746 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02002747 with p:
2748 self.assertEqual(
2749 p.stdout.read ().decode("mbcs"),
2750 "2 [%r, 'ab cd']" % self.fname
2751 )
Tim Golden126c2962010-08-11 14:20:40 +00002752
2753 def test_shell_string_with_spaces(self):
2754 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002755 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2756 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002757
2758 def test_shell_sequence_with_spaces(self):
2759 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002760 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002761
2762 def test_noshell_string_with_spaces(self):
2763 # call() function with string argument with spaces on Windows
2764 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2765 "ab cd"))
2766
2767 def test_noshell_sequence_with_spaces(self):
2768 # call() function with sequence argument with spaces on Windows
2769 self.with_spaces([sys.executable, self.fname, "ab cd"])
2770
Brian Curtin79cdb662010-12-03 02:46:02 +00002771
Georg Brandla86b2622012-02-20 21:34:57 +01002772class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002773
2774 def test_pipe(self):
2775 with subprocess.Popen([sys.executable, "-c",
2776 "import sys;"
2777 "sys.stdout.write('stdout');"
2778 "sys.stderr.write('stderr');"],
2779 stdout=subprocess.PIPE,
2780 stderr=subprocess.PIPE) as proc:
2781 self.assertEqual(proc.stdout.read(), b"stdout")
2782 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2783
2784 self.assertTrue(proc.stdout.closed)
2785 self.assertTrue(proc.stderr.closed)
2786
2787 def test_returncode(self):
2788 with subprocess.Popen([sys.executable, "-c",
2789 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002790 pass
2791 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002792 self.assertEqual(proc.returncode, 100)
2793
2794 def test_communicate_stdin(self):
2795 with subprocess.Popen([sys.executable, "-c",
2796 "import sys;"
2797 "sys.exit(sys.stdin.read() == 'context')"],
2798 stdin=subprocess.PIPE) as proc:
2799 proc.communicate(b"context")
2800 self.assertEqual(proc.returncode, 1)
2801
2802 def test_invalid_args(self):
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +01002803 with self.assertRaises((FileNotFoundError, PermissionError)) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002804 with subprocess.Popen(['nonexisting_i_hope'],
2805 stdout=subprocess.PIPE,
2806 stderr=subprocess.PIPE) as proc:
2807 pass
2808
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002809 def test_broken_pipe_cleanup(self):
2810 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002811 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002812 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002813 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002814 proc = proc.__enter__()
2815 # Prepare to send enough data to overflow any OS pipe buffering and
2816 # guarantee a broken pipe error. Data is held in BufferedWriter
2817 # buffer until closed.
2818 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002819 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002820 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002821 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002822 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002823 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002824
Brian Curtin79cdb662010-12-03 02:46:02 +00002825
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002826if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002827 unittest.main()