blob: 2ce59517a796477283b8ce42a751d9c7338b6073 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Chris Jerdonekec3ea942012-09-30 00:10:28 -07002from test import script_helper
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
6import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04007import io
Andrew Svetlov82860712012-08-19 22:13:41 +03008import locale
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
Tim Peters3761e8d2004-10-13 04:07:12 +000013import re
Charles-François Natali3a4586a2013-11-08 19:56:59 +010014import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000015import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000016import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000017import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040018import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050019import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030020import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050021
22try:
Antoine Pitroua8392712013-08-30 23:38:13 +020023 import threading
24except ImportError:
25 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050026
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000027mswindows = (sys.platform == "win32")
28
29#
30# Depends on the following external programs: Python
31#
32
33if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000034 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
35 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000036else:
37 SETBINARY = ''
38
Florent Xiclunab1e94e82010-02-27 22:12:37 +000039
Florent Xiclunac049d872010-03-27 22:47:23 +000040class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000041 def setUp(self):
42 # Try to minimize the number of children we have so this test
43 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000044 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000046 def tearDown(self):
47 for inst in subprocess._active:
48 inst.wait()
49 subprocess._cleanup()
50 self.assertFalse(subprocess._active, "subprocess._active not empty")
51
Florent Xiclunab1e94e82010-02-27 22:12:37 +000052 def assertStderrEqual(self, stderr, expected, msg=None):
53 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
54 # shutdown time. That frustrates tests trying to check stderr produced
55 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000056 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040057 # strip_python_stderr also strips whitespace, so we do too.
58 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000059 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000060
Florent Xiclunac049d872010-03-27 22:47:23 +000061
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080062class PopenTestException(Exception):
63 pass
64
65
66class PopenExecuteChildRaises(subprocess.Popen):
67 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
68 _execute_child fails.
69 """
70 def _execute_child(self, *args, **kwargs):
71 raise PopenTestException("Forced Exception for Test")
72
73
Florent Xiclunac049d872010-03-27 22:47:23 +000074class ProcessTestCase(BaseTestCase):
75
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070076 def test_io_buffered_by_default(self):
77 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
78 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
79 stderr=subprocess.PIPE)
80 try:
81 self.assertIsInstance(p.stdin, io.BufferedIOBase)
82 self.assertIsInstance(p.stdout, io.BufferedIOBase)
83 self.assertIsInstance(p.stderr, io.BufferedIOBase)
84 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070085 p.stdin.close()
86 p.stdout.close()
87 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070088 p.wait()
89
90 def test_io_unbuffered_works(self):
91 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
92 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
93 stderr=subprocess.PIPE, bufsize=0)
94 try:
95 self.assertIsInstance(p.stdin, io.RawIOBase)
96 self.assertIsInstance(p.stdout, io.RawIOBase)
97 self.assertIsInstance(p.stderr, io.RawIOBase)
98 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070099 p.stdin.close()
100 p.stdout.close()
101 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700102 p.wait()
103
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000104 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000105 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000106 rc = subprocess.call([sys.executable, "-c",
107 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000108 self.assertEqual(rc, 47)
109
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400110 def test_call_timeout(self):
111 # call() function with timeout argument; we want to test that the child
112 # process gets killed when the timeout expires. If the child isn't
113 # killed, this call will deadlock since subprocess.call waits for the
114 # child.
115 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
116 [sys.executable, "-c", "while True: pass"],
117 timeout=0.1)
118
Peter Astrand454f7672005-01-01 09:36:35 +0000119 def test_check_call_zero(self):
120 # check_call() function with zero return code
121 rc = subprocess.check_call([sys.executable, "-c",
122 "import sys; sys.exit(0)"])
123 self.assertEqual(rc, 0)
124
125 def test_check_call_nonzero(self):
126 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000127 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000128 subprocess.check_call([sys.executable, "-c",
129 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000130 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000131
Georg Brandlf9734072008-12-07 15:30:06 +0000132 def test_check_output(self):
133 # check_output() function with zero return code
134 output = subprocess.check_output(
135 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000136 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000137
138 def test_check_output_nonzero(self):
139 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000140 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000141 subprocess.check_output(
142 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000143 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000144
145 def test_check_output_stderr(self):
146 # check_output() function stderr redirected to stdout
147 output = subprocess.check_output(
148 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
149 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000150 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000151
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300152 def test_check_output_stdin_arg(self):
153 # check_output() can be called with stdin set to a file
154 tf = tempfile.TemporaryFile()
155 self.addCleanup(tf.close)
156 tf.write(b'pear')
157 tf.seek(0)
158 output = subprocess.check_output(
159 [sys.executable, "-c",
160 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
161 stdin=tf)
162 self.assertIn(b'PEAR', output)
163
164 def test_check_output_input_arg(self):
165 # check_output() can be called with input set to a string
166 output = subprocess.check_output(
167 [sys.executable, "-c",
168 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
169 input=b'pear')
170 self.assertIn(b'PEAR', output)
171
Georg Brandlf9734072008-12-07 15:30:06 +0000172 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300173 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000174 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000175 output = subprocess.check_output(
176 [sys.executable, "-c", "print('will not be run')"],
177 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000178 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000179 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000180
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300181 def test_check_output_stdin_with_input_arg(self):
182 # check_output() refuses to accept 'stdin' with 'input'
183 tf = tempfile.TemporaryFile()
184 self.addCleanup(tf.close)
185 tf.write(b'pear')
186 tf.seek(0)
187 with self.assertRaises(ValueError) as c:
188 output = subprocess.check_output(
189 [sys.executable, "-c", "print('will not be run')"],
190 stdin=tf, input=b'hare')
191 self.fail("Expected ValueError when stdin and input args supplied.")
192 self.assertIn('stdin', c.exception.args[0])
193 self.assertIn('input', c.exception.args[0])
194
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400195 def test_check_output_timeout(self):
196 # check_output() function with timeout arg
197 with self.assertRaises(subprocess.TimeoutExpired) as c:
198 output = subprocess.check_output(
199 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200200 "import sys, time\n"
201 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400202 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200203 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400204 # Some heavily loaded buildbots (sparc Debian 3.x) require
205 # this much time to start and print.
206 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400207 self.fail("Expected TimeoutExpired.")
208 self.assertEqual(c.exception.output, b'BDFL')
209
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000211 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000212 newenv = os.environ.copy()
213 newenv["FRUIT"] = "banana"
214 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000215 'import sys, os;'
216 'sys.exit(os.getenv("FRUIT")=="banana")'],
217 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000218 self.assertEqual(rc, 1)
219
Victor Stinner87b9bc32011-06-01 00:57:47 +0200220 def test_invalid_args(self):
221 # Popen() called with invalid arguments should raise TypeError
222 # but Popen.__del__ should not complain (issue #12085)
223 with support.captured_stderr() as s:
224 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
225 argcount = subprocess.Popen.__init__.__code__.co_argcount
226 too_many_args = [0] * (argcount + 1)
227 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
228 self.assertEqual(s.getvalue(), '')
229
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000230 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000231 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000232 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000234 self.addCleanup(p.stdout.close)
235 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236 p.wait()
237 self.assertEqual(p.stdin, None)
238
239 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200240 # .stdout is None when not redirected, and the child's stdout will
241 # be inherited from the parent. In order to test this we run a
242 # subprocess in a subprocess:
243 # this_test
244 # \-- subprocess created by this test (parent)
245 # \-- subprocess created by the parent subprocess (child)
246 # The parent doesn't specify stdout, so the child will use the
247 # parent's stdout. This test checks that the message printed by the
248 # child goes to the parent stdout. The parent also checks that the
249 # child's stdout is None. See #11963.
250 code = ('import sys; from subprocess import Popen, PIPE;'
251 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
252 ' stdin=PIPE, stderr=PIPE);'
253 'p.wait(); assert p.stdout is None;')
254 p = subprocess.Popen([sys.executable, "-c", code],
255 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
256 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000257 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200258 out, err = p.communicate()
259 self.assertEqual(p.returncode, 0, err)
260 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000261
262 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000263 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000264 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000266 self.addCleanup(p.stdout.close)
267 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268 p.wait()
269 self.assertEqual(p.stderr, None)
270
Chris Jerdonek776cb192012-10-08 15:56:43 -0700271 def _assert_python(self, pre_args, **kwargs):
272 # We include sys.exit() to prevent the test runner from hanging
273 # whenever python is found.
274 args = pre_args + ["import sys; sys.exit(47)"]
275 p = subprocess.Popen(args, **kwargs)
276 p.wait()
277 self.assertEqual(47, p.returncode)
278
279 def test_executable(self):
280 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700281 #
282 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
283 # determine where its standard library is, so we need the directory
284 # of args[0] to be valid for the Popen() call to Python to succeed.
285 # See also issue #16170 and issue #7774.
286 doesnotexist = os.path.join(os.path.dirname(sys.executable),
287 "doesnotexist")
288 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700289
290 def test_executable_takes_precedence(self):
291 # Check that the executable argument takes precedence over args[0].
292 #
293 # Verify first that the call succeeds without the executable arg.
294 pre_args = [sys.executable, "-c"]
295 self._assert_python(pre_args)
296 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
297 executable="doesnotexist")
298
299 @unittest.skipIf(mswindows, "executable argument replaces shell")
300 def test_executable_replaces_shell(self):
301 # Check that the executable argument replaces the default shell
302 # when shell=True.
303 self._assert_python([], executable=sys.executable, shell=True)
304
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700305 # For use in the test_cwd* tests below.
306 def _normalize_cwd(self, cwd):
307 # Normalize an expected cwd (for Tru64 support).
308 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
309 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300310 with support.change_cwd(cwd):
311 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700312
313 # For use in the test_cwd* tests below.
314 def _split_python_path(self):
315 # Return normalized (python_dir, python_base).
316 python_path = os.path.realpath(sys.executable)
317 return os.path.split(python_path)
318
319 # For use in the test_cwd* tests below.
320 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
321 # Invoke Python via Popen, and assert that (1) the call succeeds,
322 # and that (2) the current working directory of the child process
323 # matches *expected_cwd*.
324 p = subprocess.Popen([python_arg, "-c",
325 "import os, sys; "
326 "sys.stdout.write(os.getcwd()); "
327 "sys.exit(47)"],
328 stdout=subprocess.PIPE,
329 **kwargs)
330 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000331 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700332 self.assertEqual(47, p.returncode)
333 normcase = os.path.normcase
334 self.assertEqual(normcase(expected_cwd),
335 normcase(p.stdout.read().decode("utf-8")))
336
337 def test_cwd(self):
338 # Check that cwd changes the cwd for the child process.
339 temp_dir = tempfile.gettempdir()
340 temp_dir = self._normalize_cwd(temp_dir)
341 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
342
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700343 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700344 def test_cwd_with_relative_arg(self):
345 # Check that Popen looks for args[0] relative to cwd if args[0]
346 # is relative.
347 python_dir, python_base = self._split_python_path()
348 rel_python = os.path.join(os.curdir, python_base)
349 with support.temp_cwd() as wrong_dir:
350 # Before calling with the correct cwd, confirm that the call fails
351 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700352 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700353 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700354 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700355 [rel_python], cwd=wrong_dir)
356 python_dir = self._normalize_cwd(python_dir)
357 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
358
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700359 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700360 def test_cwd_with_relative_executable(self):
361 # Check that Popen looks for executable relative to cwd if executable
362 # is relative (and that executable takes precedence over args[0]).
363 python_dir, python_base = self._split_python_path()
364 rel_python = os.path.join(os.curdir, python_base)
365 doesntexist = "somethingyoudonthave"
366 with support.temp_cwd() as wrong_dir:
367 # Before calling with the correct cwd, confirm that the call fails
368 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700369 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700370 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700371 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700372 [doesntexist], executable=rel_python,
373 cwd=wrong_dir)
374 python_dir = self._normalize_cwd(python_dir)
375 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
376 cwd=python_dir)
377
378 def test_cwd_with_absolute_arg(self):
379 # Check that Popen can find the executable when the cwd is wrong
380 # if args[0] is an absolute path.
381 python_dir, python_base = self._split_python_path()
382 abs_python = os.path.join(python_dir, python_base)
383 rel_python = os.path.join(os.curdir, python_base)
384 with script_helper.temp_dir() as wrong_dir:
385 # Before calling with an absolute path, confirm that using a
386 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700387 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700388 [rel_python], cwd=wrong_dir)
389 wrong_dir = self._normalize_cwd(wrong_dir)
390 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
391
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100392 @unittest.skipIf(sys.base_prefix != sys.prefix,
393 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000394 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700395 python_dir, python_base = self._split_python_path()
396 python_dir = self._normalize_cwd(python_dir)
397 self._assert_cwd(python_dir, "somethingyoudonthave",
398 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000399
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100400 @unittest.skipIf(sys.base_prefix != sys.prefix,
401 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000402 @unittest.skipIf(sysconfig.is_python_build(),
403 "need an installed Python. See #7774")
404 def test_executable_without_cwd(self):
405 # For a normal installation, it should work without 'cwd'
406 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700407 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
408 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000409
410 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000411 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000412 p = subprocess.Popen([sys.executable, "-c",
413 'import sys; sys.exit(sys.stdin.read() == "pear")'],
414 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000415 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416 p.stdin.close()
417 p.wait()
418 self.assertEqual(p.returncode, 1)
419
420 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000421 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000422 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000423 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000425 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426 os.lseek(d, 0, 0)
427 p = subprocess.Popen([sys.executable, "-c",
428 'import sys; sys.exit(sys.stdin.read() == "pear")'],
429 stdin=d)
430 p.wait()
431 self.assertEqual(p.returncode, 1)
432
433 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000434 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000436 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000437 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438 tf.seek(0)
439 p = subprocess.Popen([sys.executable, "-c",
440 'import sys; sys.exit(sys.stdin.read() == "pear")'],
441 stdin=tf)
442 p.wait()
443 self.assertEqual(p.returncode, 1)
444
445 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000446 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000447 p = subprocess.Popen([sys.executable, "-c",
448 'import sys; sys.stdout.write("orange")'],
449 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000450 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000451 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452
453 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000454 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000455 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000456 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000457 d = tf.fileno()
458 p = subprocess.Popen([sys.executable, "-c",
459 'import sys; sys.stdout.write("orange")'],
460 stdout=d)
461 p.wait()
462 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000463 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464
465 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000466 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000467 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000468 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000469 p = subprocess.Popen([sys.executable, "-c",
470 'import sys; sys.stdout.write("orange")'],
471 stdout=tf)
472 p.wait()
473 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000474 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000475
476 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000477 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478 p = subprocess.Popen([sys.executable, "-c",
479 'import sys; sys.stderr.write("strawberry")'],
480 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000481 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000482 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483
484 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000485 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000486 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000487 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488 d = tf.fileno()
489 p = subprocess.Popen([sys.executable, "-c",
490 'import sys; sys.stderr.write("strawberry")'],
491 stderr=d)
492 p.wait()
493 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000494 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495
496 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000497 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000498 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000499 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500 p = subprocess.Popen([sys.executable, "-c",
501 'import sys; sys.stderr.write("strawberry")'],
502 stderr=tf)
503 p.wait()
504 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000505 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000506
507 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000508 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000509 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000510 'import sys;'
511 'sys.stdout.write("apple");'
512 'sys.stdout.flush();'
513 'sys.stderr.write("orange")'],
514 stdout=subprocess.PIPE,
515 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000516 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000517 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518
519 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000520 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000521 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000522 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000524 'import sys;'
525 'sys.stdout.write("apple");'
526 'sys.stdout.flush();'
527 'sys.stderr.write("orange")'],
528 stdout=tf,
529 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530 p.wait()
531 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000532 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000533
Thomas Wouters89f507f2006-12-13 04:49:30 +0000534 def test_stdout_filedes_of_stdout(self):
535 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200536 # To avoid printing the text on stdout, we do something similar to
537 # test_stdout_none (see above). The parent subprocess calls the child
538 # subprocess passing stdout=1, and this test uses stdout=PIPE in
539 # order to capture and check the output of the parent. See #11963.
540 code = ('import sys, subprocess; '
541 'rc = subprocess.call([sys.executable, "-c", '
542 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
543 'b\'test with stdout=1\'))"], stdout=1); '
544 'assert rc == 18')
545 p = subprocess.Popen([sys.executable, "-c", code],
546 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
547 self.addCleanup(p.stdout.close)
548 self.addCleanup(p.stderr.close)
549 out, err = p.communicate()
550 self.assertEqual(p.returncode, 0, err)
551 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000552
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200553 def test_stdout_devnull(self):
554 p = subprocess.Popen([sys.executable, "-c",
555 'for i in range(10240):'
556 'print("x" * 1024)'],
557 stdout=subprocess.DEVNULL)
558 p.wait()
559 self.assertEqual(p.stdout, None)
560
561 def test_stderr_devnull(self):
562 p = subprocess.Popen([sys.executable, "-c",
563 'import sys\n'
564 'for i in range(10240):'
565 'sys.stderr.write("x" * 1024)'],
566 stderr=subprocess.DEVNULL)
567 p.wait()
568 self.assertEqual(p.stderr, None)
569
570 def test_stdin_devnull(self):
571 p = subprocess.Popen([sys.executable, "-c",
572 'import sys;'
573 'sys.stdin.read(1)'],
574 stdin=subprocess.DEVNULL)
575 p.wait()
576 self.assertEqual(p.stdin, None)
577
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000579 newenv = os.environ.copy()
580 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200581 with subprocess.Popen([sys.executable, "-c",
582 'import sys,os;'
583 'sys.stdout.write(os.getenv("FRUIT"))'],
584 stdout=subprocess.PIPE,
585 env=newenv) as p:
586 stdout, stderr = p.communicate()
587 self.assertEqual(stdout, b"orange")
588
Victor Stinner62d51182011-06-23 01:02:25 +0200589 # Windows requires at least the SYSTEMROOT environment variable to start
590 # Python
591 @unittest.skipIf(sys.platform == 'win32',
592 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200593 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200594 'the python library cannot be loaded '
595 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200596 def test_empty_env(self):
597 with subprocess.Popen([sys.executable, "-c",
598 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200599 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200600 stdout=subprocess.PIPE,
601 env={}) as p:
602 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200603 self.assertIn(stdout.strip(),
604 (b"[]",
605 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
606 # environment
607 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000608
Peter Astrandcbac93c2005-03-03 20:24:28 +0000609 def test_communicate_stdin(self):
610 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000611 'import sys;'
612 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000613 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000614 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000615 self.assertEqual(p.returncode, 1)
616
617 def test_communicate_stdout(self):
618 p = subprocess.Popen([sys.executable, "-c",
619 'import sys; sys.stdout.write("pineapple")'],
620 stdout=subprocess.PIPE)
621 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000622 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000623 self.assertEqual(stderr, None)
624
625 def test_communicate_stderr(self):
626 p = subprocess.Popen([sys.executable, "-c",
627 'import sys; sys.stderr.write("pineapple")'],
628 stderr=subprocess.PIPE)
629 (stdout, stderr) = p.communicate()
630 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000631 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000632
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000633 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000634 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000635 'import sys,os;'
636 'sys.stderr.write("pineapple");'
637 'sys.stdout.write(sys.stdin.read())'],
638 stdin=subprocess.PIPE,
639 stdout=subprocess.PIPE,
640 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000641 self.addCleanup(p.stdout.close)
642 self.addCleanup(p.stderr.close)
643 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000644 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000645 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000646 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400648 def test_communicate_timeout(self):
649 p = subprocess.Popen([sys.executable, "-c",
650 'import sys,os,time;'
651 'sys.stderr.write("pineapple\\n");'
652 'time.sleep(1);'
653 'sys.stderr.write("pear\\n");'
654 'sys.stdout.write(sys.stdin.read())'],
655 universal_newlines=True,
656 stdin=subprocess.PIPE,
657 stdout=subprocess.PIPE,
658 stderr=subprocess.PIPE)
659 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
660 timeout=0.3)
661 # Make sure we can keep waiting for it, and that we get the whole output
662 # after it completes.
663 (stdout, stderr) = p.communicate()
664 self.assertEqual(stdout, "banana")
665 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
666
667 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200668 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400669 p = subprocess.Popen([sys.executable, "-c",
670 'import sys,os,time;'
671 'sys.stdout.write("a" * (64 * 1024));'
672 'time.sleep(0.2);'
673 'sys.stdout.write("a" * (64 * 1024));'
674 'time.sleep(0.2);'
675 'sys.stdout.write("a" * (64 * 1024));'
676 'time.sleep(0.2);'
677 'sys.stdout.write("a" * (64 * 1024));'],
678 stdout=subprocess.PIPE)
679 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
680 (stdout, _) = p.communicate()
681 self.assertEqual(len(stdout), 4 * 64 * 1024)
682
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000683 # Test for the fd leak reported in http://bugs.python.org/issue2791.
684 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000685 for stdin_pipe in (False, True):
686 for stdout_pipe in (False, True):
687 for stderr_pipe in (False, True):
688 options = {}
689 if stdin_pipe:
690 options['stdin'] = subprocess.PIPE
691 if stdout_pipe:
692 options['stdout'] = subprocess.PIPE
693 if stderr_pipe:
694 options['stderr'] = subprocess.PIPE
695 if not options:
696 continue
697 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
698 p.communicate()
699 if p.stdin is not None:
700 self.assertTrue(p.stdin.closed)
701 if p.stdout is not None:
702 self.assertTrue(p.stdout.closed)
703 if p.stderr is not None:
704 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000705
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000706 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000707 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000708 p = subprocess.Popen([sys.executable, "-c",
709 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000710 (stdout, stderr) = p.communicate()
711 self.assertEqual(stdout, None)
712 self.assertEqual(stderr, None)
713
714 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000715 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000716 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000717 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000718 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000719 os.close(x)
720 os.close(y)
721 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000722 'import sys,os;'
723 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200724 'sys.stderr.write("x" * %d);'
725 'sys.stdout.write(sys.stdin.read())' %
726 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000727 stdin=subprocess.PIPE,
728 stdout=subprocess.PIPE,
729 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000730 self.addCleanup(p.stdout.close)
731 self.addCleanup(p.stderr.close)
732 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200733 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734 (stdout, stderr) = p.communicate(string_to_write)
735 self.assertEqual(stdout, string_to_write)
736
737 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000738 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000739 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000740 'import sys,os;'
741 'sys.stdout.write(sys.stdin.read())'],
742 stdin=subprocess.PIPE,
743 stdout=subprocess.PIPE,
744 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000745 self.addCleanup(p.stdout.close)
746 self.addCleanup(p.stderr.close)
747 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000748 p.stdin.write(b"banana")
749 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000750 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000751 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000752
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000753 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000754 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000755 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200756 'buf = sys.stdout.buffer;'
757 'buf.write(sys.stdin.readline().encode());'
758 'buf.flush();'
759 'buf.write(b"line2\\n");'
760 'buf.flush();'
761 'buf.write(sys.stdin.read().encode());'
762 'buf.flush();'
763 'buf.write(b"line4\\n");'
764 'buf.flush();'
765 'buf.write(b"line5\\r\\n");'
766 'buf.flush();'
767 'buf.write(b"line6\\r");'
768 'buf.flush();'
769 'buf.write(b"\\nline7");'
770 'buf.flush();'
771 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200772 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000773 stdout=subprocess.PIPE,
774 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200775 p.stdin.write("line1\n")
Antoine Pitrouc644e7c2014-05-09 00:24:50 +0200776 p.stdin.flush()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200777 self.assertEqual(p.stdout.readline(), "line1\n")
778 p.stdin.write("line3\n")
779 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000780 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200781 self.assertEqual(p.stdout.readline(),
782 "line2\n")
783 self.assertEqual(p.stdout.read(6),
784 "line3\n")
785 self.assertEqual(p.stdout.read(),
786 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000787
788 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000789 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000790 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000791 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200792 'buf = sys.stdout.buffer;'
793 'buf.write(b"line2\\n");'
794 'buf.flush();'
795 'buf.write(b"line4\\n");'
796 'buf.flush();'
797 'buf.write(b"line5\\r\\n");'
798 'buf.flush();'
799 'buf.write(b"line6\\r");'
800 'buf.flush();'
801 'buf.write(b"\\nline7");'
802 'buf.flush();'
803 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200804 stderr=subprocess.PIPE,
805 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000806 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000807 self.addCleanup(p.stdout.close)
808 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000809 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200810 self.assertEqual(stdout,
811 "line2\nline4\nline5\nline6\nline7\nline8")
812
813 def test_universal_newlines_communicate_stdin(self):
814 # universal newlines through communicate(), with only stdin
815 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300816 'import sys,os;' + SETBINARY + textwrap.dedent('''
817 s = sys.stdin.readline()
818 assert s == "line1\\n", repr(s)
819 s = sys.stdin.read()
820 assert s == "line3\\n", repr(s)
821 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200822 stdin=subprocess.PIPE,
823 universal_newlines=1)
824 (stdout, stderr) = p.communicate("line1\nline3\n")
825 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000826
Andrew Svetlovf3765072012-08-14 18:35:17 +0300827 def test_universal_newlines_communicate_input_none(self):
828 # Test communicate(input=None) with universal newlines.
829 #
830 # We set stdout to PIPE because, as of this writing, a different
831 # code path is tested when the number of pipes is zero or one.
832 p = subprocess.Popen([sys.executable, "-c", "pass"],
833 stdin=subprocess.PIPE,
834 stdout=subprocess.PIPE,
835 universal_newlines=True)
836 p.communicate()
837 self.assertEqual(p.returncode, 0)
838
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300839 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300840 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300841 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300842 'import sys,os;' + SETBINARY + textwrap.dedent('''
843 s = sys.stdin.buffer.readline()
844 sys.stdout.buffer.write(s)
845 sys.stdout.buffer.write(b"line2\\r")
846 sys.stderr.buffer.write(b"eline2\\n")
847 s = sys.stdin.buffer.read()
848 sys.stdout.buffer.write(s)
849 sys.stdout.buffer.write(b"line4\\n")
850 sys.stdout.buffer.write(b"line5\\r\\n")
851 sys.stderr.buffer.write(b"eline6\\r")
852 sys.stderr.buffer.write(b"eline7\\r\\nz")
853 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300854 stdin=subprocess.PIPE,
855 stderr=subprocess.PIPE,
856 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300857 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300858 self.addCleanup(p.stdout.close)
859 self.addCleanup(p.stderr.close)
860 (stdout, stderr) = p.communicate("line1\nline3\n")
861 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300862 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300863 # Python debug build push something like "[42442 refs]\n"
864 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300865 # Don't use assertStderrEqual because it strips CR and LF from output.
866 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300867
Andrew Svetlov82860712012-08-19 22:13:41 +0300868 def test_universal_newlines_communicate_encodings(self):
869 # Check that universal newlines mode works for various encodings,
870 # in particular for encodings in the UTF-16 and UTF-32 families.
871 # See issue #15595.
872 #
873 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
874 # without, and UTF-16 and UTF-32.
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200875 import _bootlocale
Andrew Svetlov82860712012-08-19 22:13:41 +0300876 for encoding in ['utf-16', 'utf-32-be']:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200877 old_getpreferredencoding = _bootlocale.getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300878 # Indirectly via io.TextIOWrapper, Popen() defaults to
879 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
880 # locale.getpreferredencoding().
881 def getpreferredencoding(do_setlocale=True):
882 return encoding
883 code = ("import sys; "
884 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
885 encoding)
886 args = [sys.executable, '-c', code]
887 try:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200888 _bootlocale.getpreferredencoding = getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300889 # We set stdin to be non-None because, as of this writing,
890 # a different code path is used when the number of pipes is
891 # zero or one.
892 popen = subprocess.Popen(args, universal_newlines=True,
893 stdin=subprocess.PIPE,
894 stdout=subprocess.PIPE)
895 stdout, stderr = popen.communicate(input='')
896 finally:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200897 _bootlocale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300898 self.assertEqual(stdout, '1\n2\n3\n4')
899
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000900 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000901 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000902 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000903 max_handles = 1026 # too much for most UNIX systems
904 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000905 max_handles = 2050 # too much for (at least some) Windows setups
906 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400907 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000908 try:
909 for i in range(max_handles):
910 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400911 tmpfile = os.path.join(tmpdir, support.TESTFN)
912 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000913 except OSError as e:
914 if e.errno != errno.EMFILE:
915 raise
916 break
917 else:
918 self.skipTest("failed to reach the file descriptor limit "
919 "(tried %d)" % max_handles)
920 # Close a couple of them (should be enough for a subprocess)
921 for i in range(10):
922 os.close(handles.pop())
923 # Loop creating some subprocesses. If one of them leaks some fds,
924 # the next loop iteration will fail by reaching the max fd limit.
925 for i in range(15):
926 p = subprocess.Popen([sys.executable, "-c",
927 "import sys;"
928 "sys.stdout.write(sys.stdin.read())"],
929 stdin=subprocess.PIPE,
930 stdout=subprocess.PIPE,
931 stderr=subprocess.PIPE)
932 data = p.communicate(b"lime")[0]
933 self.assertEqual(data, b"lime")
934 finally:
935 for h in handles:
936 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400937 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000938
939 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
941 '"a b c" d e')
942 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
943 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000944 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
945 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000946 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
947 'a\\\\\\b "de fg" h')
948 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
949 'a\\\\\\"b c d')
950 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
951 '"a\\\\b c" d e')
952 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
953 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000954 self.assertEqual(subprocess.list2cmdline(['ab', '']),
955 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000956
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000957 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200958 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200959 "import os; os.read(0, 1)"],
960 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200961 self.addCleanup(p.stdin.close)
962 self.assertIsNone(p.poll())
963 os.write(p.stdin.fileno(), b'A')
964 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000965 # Subsequent invocations should just return the returncode
966 self.assertEqual(p.poll(), 0)
967
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000968 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200969 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000970 self.assertEqual(p.wait(), 0)
971 # Subsequent invocations should just return the returncode
972 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000973
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400974 def test_wait_timeout(self):
975 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200976 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400977 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200978 p.wait(timeout=0.0001)
979 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400980 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
981 # time to start.
982 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400983
Peter Astrand738131d2004-11-30 21:04:45 +0000984 def test_invalid_bufsize(self):
985 # an invalid type of the bufsize argument should raise
986 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000987 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000988 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000989
Guido van Rossum46a05a72007-06-07 21:56:45 +0000990 def test_bufsize_is_none(self):
991 # bufsize=None should be the same as bufsize=0.
992 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
993 self.assertEqual(p.wait(), 0)
994 # Again with keyword arg
995 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
996 self.assertEqual(p.wait(), 0)
997
Antoine Pitrouafe8d062014-09-21 21:10:56 +0200998 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
999 # subprocess may deadlock with bufsize=1, see issue #21332
1000 with subprocess.Popen([sys.executable, "-c", "import sys;"
1001 "sys.stdout.write(sys.stdin.readline());"
1002 "sys.stdout.flush()"],
1003 stdin=subprocess.PIPE,
1004 stdout=subprocess.PIPE,
1005 stderr=subprocess.DEVNULL,
1006 bufsize=1,
1007 universal_newlines=universal_newlines) as p:
1008 p.stdin.write(line) # expect that it flushes the line in text mode
1009 os.close(p.stdin.fileno()) # close it without flushing the buffer
1010 read_line = p.stdout.readline()
1011 try:
1012 p.stdin.close()
1013 except OSError:
1014 pass
1015 p.stdin = None
1016 self.assertEqual(p.returncode, 0)
1017 self.assertEqual(read_line, expected)
1018
1019 def test_bufsize_equal_one_text_mode(self):
1020 # line is flushed in text mode with bufsize=1.
1021 # we should get the full line in return
1022 line = "line\n"
1023 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1024
1025 def test_bufsize_equal_one_binary_mode(self):
1026 # line is not flushed in binary mode with bufsize=1.
1027 # we should get empty response
1028 line = b'line' + os.linesep.encode() # assume ascii-based locale
1029 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1030
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001031 def test_leaking_fds_on_error(self):
1032 # see bug #5179: Popen leaks file descriptors to PIPEs if
1033 # the child fails to execute; this will eventually exhaust
1034 # the maximum number of open fds. 1024 seems a very common
1035 # value for that limit, but Windows has 2048, so we loop
1036 # 1024 times (each call leaked two fds).
1037 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001038 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001039 subprocess.Popen(['nonexisting_i_hope'],
1040 stdout=subprocess.PIPE,
1041 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001042 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001043 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001044 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001045
Antoine Pitroua8392712013-08-30 23:38:13 +02001046 @unittest.skipIf(threading is None, "threading required")
1047 def test_double_close_on_error(self):
1048 # Issue #18851
1049 fds = []
1050 def open_fds():
1051 for i in range(20):
1052 fds.extend(os.pipe())
1053 time.sleep(0.001)
1054 t = threading.Thread(target=open_fds)
1055 t.start()
1056 try:
1057 with self.assertRaises(EnvironmentError):
1058 subprocess.Popen(['nonexisting_i_hope'],
1059 stdin=subprocess.PIPE,
1060 stdout=subprocess.PIPE,
1061 stderr=subprocess.PIPE)
1062 finally:
1063 t.join()
1064 exc = None
1065 for fd in fds:
1066 # If a double close occurred, some of those fds will
1067 # already have been closed by mistake, and os.close()
1068 # here will raise.
1069 try:
1070 os.close(fd)
1071 except OSError as e:
1072 exc = e
1073 if exc is not None:
1074 raise exc
1075
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001076 @unittest.skipIf(threading is None, "threading required")
1077 def test_threadsafe_wait(self):
1078 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1079 proc = subprocess.Popen([sys.executable, '-c',
1080 'import time; time.sleep(12)'])
1081 self.assertEqual(proc.returncode, None)
1082 results = []
1083
1084 def kill_proc_timer_thread():
1085 results.append(('thread-start-poll-result', proc.poll()))
1086 # terminate it from the thread and wait for the result.
1087 proc.kill()
1088 proc.wait()
1089 results.append(('thread-after-kill-and-wait', proc.returncode))
1090 # this wait should be a no-op given the above.
1091 proc.wait()
1092 results.append(('thread-after-second-wait', proc.returncode))
1093
1094 # This is a timing sensitive test, the failure mode is
1095 # triggered when both the main thread and this thread are in
1096 # the wait() call at once. The delay here is to allow the
1097 # main thread to most likely be blocked in its wait() call.
1098 t = threading.Timer(0.2, kill_proc_timer_thread)
1099 t.start()
1100
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001101 if mswindows:
1102 expected_errorcode = 1
1103 else:
1104 # Should be -9 because of the proc.kill() from the thread.
1105 expected_errorcode = -9
1106
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001107 # Wait for the process to finish; the thread should kill it
1108 # long before it finishes on its own. Supplying a timeout
1109 # triggers a different code path for better coverage.
1110 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001111 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001112 msg="unexpected result in wait from main thread")
1113
1114 # This should be a no-op with no change in returncode.
1115 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001116 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001117 msg="unexpected result in second main wait.")
1118
1119 t.join()
1120 # Ensure that all of the thread results are as expected.
1121 # When a race condition occurs in wait(), the returncode could
1122 # be set by the wrong thread that doesn't actually have it
1123 # leading to an incorrect value.
1124 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001125 ('thread-after-kill-and-wait', expected_errorcode),
1126 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001127 results)
1128
Victor Stinnerb3693582010-05-21 20:13:12 +00001129 def test_issue8780(self):
1130 # Ensure that stdout is inherited from the parent
1131 # if stdout=PIPE is not used
1132 code = ';'.join((
1133 'import subprocess, sys',
1134 'retcode = subprocess.call('
1135 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1136 'assert retcode == 0'))
1137 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001138 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001139
Tim Goldenaf5ac392010-08-06 13:03:56 +00001140 def test_handles_closed_on_exception(self):
1141 # If CreateProcess exits with an error, ensure the
1142 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001143 ifhandle, ifname = tempfile.mkstemp()
1144 ofhandle, ofname = tempfile.mkstemp()
1145 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001146 try:
1147 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1148 stderr=efhandle)
1149 except OSError:
1150 os.close(ifhandle)
1151 os.remove(ifname)
1152 os.close(ofhandle)
1153 os.remove(ofname)
1154 os.close(efhandle)
1155 os.remove(efname)
1156 self.assertFalse(os.path.exists(ifname))
1157 self.assertFalse(os.path.exists(ofname))
1158 self.assertFalse(os.path.exists(efname))
1159
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001160 def test_communicate_epipe(self):
1161 # Issue 10963: communicate() should hide EPIPE
1162 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1163 stdin=subprocess.PIPE,
1164 stdout=subprocess.PIPE,
1165 stderr=subprocess.PIPE)
1166 self.addCleanup(p.stdout.close)
1167 self.addCleanup(p.stderr.close)
1168 self.addCleanup(p.stdin.close)
1169 p.communicate(b"x" * 2**20)
1170
1171 def test_communicate_epipe_only_stdin(self):
1172 # Issue 10963: communicate() should hide EPIPE
1173 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1174 stdin=subprocess.PIPE)
1175 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001176 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001177 p.communicate(b"x" * 2**20)
1178
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001179 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1180 "Requires signal.SIGUSR1")
1181 @unittest.skipUnless(hasattr(os, 'kill'),
1182 "Requires os.kill")
1183 @unittest.skipUnless(hasattr(os, 'getppid'),
1184 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001185 def test_communicate_eintr(self):
1186 # Issue #12493: communicate() should handle EINTR
1187 def handler(signum, frame):
1188 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001189 old_handler = signal.signal(signal.SIGUSR1, handler)
1190 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001191
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001192 args = [sys.executable, "-c",
1193 'import os, signal;'
1194 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001195 for stream in ('stdout', 'stderr'):
1196 kw = {stream: subprocess.PIPE}
1197 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001198 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001199 process.communicate()
1200
Tim Peterse718f612004-10-12 21:51:32 +00001201
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001202 # This test is Linux-ish specific for simplicity to at least have
1203 # some coverage. It is not a platform specific bug.
1204 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1205 "Linux specific")
1206 def test_failed_child_execute_fd_leak(self):
1207 """Test for the fork() failure fd leak reported in issue16327."""
1208 fd_directory = '/proc/%d/fd' % os.getpid()
1209 fds_before_popen = os.listdir(fd_directory)
1210 with self.assertRaises(PopenTestException):
1211 PopenExecuteChildRaises(
1212 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1213 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1214
1215 # NOTE: This test doesn't verify that the real _execute_child
1216 # does not close the file descriptors itself on the way out
1217 # during an exception. Code inspection has confirmed that.
1218
1219 fds_after_exception = os.listdir(fd_directory)
1220 self.assertEqual(fds_before_popen, fds_after_exception)
1221
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001222@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001223class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001224
Gregory P. Smith5591b022012-10-10 03:34:47 -07001225 def setUp(self):
1226 super().setUp()
1227 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1228
1229 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001230 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001231 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001232 except OSError as e:
1233 # This avoids hard coding the errno value or the OS perror()
1234 # string and instead capture the exception that we want to see
1235 # below for comparison.
1236 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001237 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001238 else:
1239 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001240 self._nonexistent_dir)
1241 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001242
Gregory P. Smith5591b022012-10-10 03:34:47 -07001243 def test_exception_cwd(self):
1244 """Test error in the child raised in the parent for a bad cwd."""
1245 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001246 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001247 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001248 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001249 except OSError as e:
1250 # Test that the child process chdir failure actually makes
1251 # it up to the parent process as the correct exception.
1252 self.assertEqual(desired_exception.errno, e.errno)
1253 self.assertEqual(desired_exception.strerror, e.strerror)
1254 else:
1255 self.fail("Expected OSError: %s" % desired_exception)
1256
Gregory P. Smith5591b022012-10-10 03:34:47 -07001257 def test_exception_bad_executable(self):
1258 """Test error in the child raised in the parent for a bad executable."""
1259 desired_exception = self._get_chdir_exception()
1260 try:
1261 p = subprocess.Popen([sys.executable, "-c", ""],
1262 executable=self._nonexistent_dir)
1263 except OSError as e:
1264 # Test that the child process exec failure actually makes
1265 # it up to the parent process as the correct exception.
1266 self.assertEqual(desired_exception.errno, e.errno)
1267 self.assertEqual(desired_exception.strerror, e.strerror)
1268 else:
1269 self.fail("Expected OSError: %s" % desired_exception)
1270
1271 def test_exception_bad_args_0(self):
1272 """Test error in the child raised in the parent for a bad args[0]."""
1273 desired_exception = self._get_chdir_exception()
1274 try:
1275 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1276 except OSError as e:
1277 # Test that the child process exec failure actually makes
1278 # it up to the parent process as the correct exception.
1279 self.assertEqual(desired_exception.errno, e.errno)
1280 self.assertEqual(desired_exception.strerror, e.strerror)
1281 else:
1282 self.fail("Expected OSError: %s" % desired_exception)
1283
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001284 def test_restore_signals(self):
1285 # Code coverage for both values of restore_signals to make sure it
1286 # at least does not blow up.
1287 # A test for behavior would be complex. Contributions welcome.
1288 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1289 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1290
1291 def test_start_new_session(self):
1292 # For code coverage of calling setsid(). We don't care if we get an
1293 # EPERM error from it depending on the test execution environment, that
1294 # still indicates that it was called.
1295 try:
1296 output = subprocess.check_output(
1297 [sys.executable, "-c",
1298 "import os; print(os.getpgid(os.getpid()))"],
1299 start_new_session=True)
1300 except OSError as e:
1301 if e.errno != errno.EPERM:
1302 raise
1303 else:
1304 parent_pgid = os.getpgid(os.getpid())
1305 child_pgid = int(output)
1306 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001307
1308 def test_run_abort(self):
1309 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001310 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001311 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001312 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001313 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001314 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001315
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001316 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001317 # DISCLAIMER: Setting environment variables is *not* a good use
1318 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001319 p = subprocess.Popen([sys.executable, "-c",
1320 'import sys,os;'
1321 'sys.stdout.write(os.getenv("FRUIT"))'],
1322 stdout=subprocess.PIPE,
1323 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001324 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001325 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001326
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001327 def test_preexec_exception(self):
1328 def raise_it():
1329 raise ValueError("What if two swallows carried a coconut?")
1330 try:
1331 p = subprocess.Popen([sys.executable, "-c", ""],
1332 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001333 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001334 self.assertTrue(
1335 subprocess._posixsubprocess,
1336 "Expected a ValueError from the preexec_fn")
1337 except ValueError as e:
1338 self.assertIn("coconut", e.args[0])
1339 else:
1340 self.fail("Exception raised by preexec_fn did not make it "
1341 "to the parent process.")
1342
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001343 class _TestExecuteChildPopen(subprocess.Popen):
1344 """Used to test behavior at the end of _execute_child."""
1345 def __init__(self, testcase, *args, **kwargs):
1346 self._testcase = testcase
1347 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001348
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001349 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001350 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001351 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001352 finally:
1353 # Open a bunch of file descriptors and verify that
1354 # none of them are the same as the ones the Popen
1355 # instance is using for stdin/stdout/stderr.
1356 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1357 for _ in range(8)]
1358 try:
1359 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001360 self._testcase.assertNotIn(
1361 fd, (self.stdin.fileno(), self.stdout.fileno(),
1362 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001363 msg="At least one fd was closed early.")
1364 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001365 for fd in devzero_fds:
1366 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001367
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001368 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1369 def test_preexec_errpipe_does_not_double_close_pipes(self):
1370 """Issue16140: Don't double close pipes on preexec error."""
1371
1372 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001373 raise subprocess.SubprocessError(
1374 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001375
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001376 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001377 self._TestExecuteChildPopen(
1378 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001379 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1380 stderr=subprocess.PIPE, preexec_fn=raise_it)
1381
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001382 def test_preexec_gc_module_failure(self):
1383 # This tests the code that disables garbage collection if the child
1384 # process will execute any Python.
1385 def raise_runtime_error():
1386 raise RuntimeError("this shouldn't escape")
1387 enabled = gc.isenabled()
1388 orig_gc_disable = gc.disable
1389 orig_gc_isenabled = gc.isenabled
1390 try:
1391 gc.disable()
1392 self.assertFalse(gc.isenabled())
1393 subprocess.call([sys.executable, '-c', ''],
1394 preexec_fn=lambda: None)
1395 self.assertFalse(gc.isenabled(),
1396 "Popen enabled gc when it shouldn't.")
1397
1398 gc.enable()
1399 self.assertTrue(gc.isenabled())
1400 subprocess.call([sys.executable, '-c', ''],
1401 preexec_fn=lambda: None)
1402 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1403
1404 gc.disable = raise_runtime_error
1405 self.assertRaises(RuntimeError, subprocess.Popen,
1406 [sys.executable, '-c', ''],
1407 preexec_fn=lambda: None)
1408
1409 del gc.isenabled # force an AttributeError
1410 self.assertRaises(AttributeError, subprocess.Popen,
1411 [sys.executable, '-c', ''],
1412 preexec_fn=lambda: None)
1413 finally:
1414 gc.disable = orig_gc_disable
1415 gc.isenabled = orig_gc_isenabled
1416 if not enabled:
1417 gc.disable()
1418
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001419 def test_args_string(self):
1420 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001421 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001422 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001423 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001424 fobj.write("#!/bin/sh\n")
1425 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1426 sys.executable)
1427 os.chmod(fname, 0o700)
1428 p = subprocess.Popen(fname)
1429 p.wait()
1430 os.remove(fname)
1431 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001432
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001433 def test_invalid_args(self):
1434 # invalid arguments should raise ValueError
1435 self.assertRaises(ValueError, subprocess.call,
1436 [sys.executable, "-c",
1437 "import sys; sys.exit(47)"],
1438 startupinfo=47)
1439 self.assertRaises(ValueError, subprocess.call,
1440 [sys.executable, "-c",
1441 "import sys; sys.exit(47)"],
1442 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001443
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001444 def test_shell_sequence(self):
1445 # Run command through the shell (sequence)
1446 newenv = os.environ.copy()
1447 newenv["FRUIT"] = "apple"
1448 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1449 stdout=subprocess.PIPE,
1450 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001451 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001452 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001453
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001454 def test_shell_string(self):
1455 # Run command through the shell (string)
1456 newenv = os.environ.copy()
1457 newenv["FRUIT"] = "apple"
1458 p = subprocess.Popen("echo $FRUIT", shell=1,
1459 stdout=subprocess.PIPE,
1460 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001461 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001462 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001463
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001464 def test_call_string(self):
1465 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001466 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001467 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001468 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001469 fobj.write("#!/bin/sh\n")
1470 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1471 sys.executable)
1472 os.chmod(fname, 0o700)
1473 rc = subprocess.call(fname)
1474 os.remove(fname)
1475 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001476
Stefan Krah9542cc62010-07-19 14:20:53 +00001477 def test_specific_shell(self):
1478 # Issue #9265: Incorrect name passed as arg[0].
1479 shells = []
1480 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1481 for name in ['bash', 'ksh']:
1482 sh = os.path.join(prefix, name)
1483 if os.path.isfile(sh):
1484 shells.append(sh)
1485 if not shells: # Will probably work for any shell but csh.
1486 self.skipTest("bash or ksh required for this test")
1487 sh = '/bin/sh'
1488 if os.path.isfile(sh) and not os.path.islink(sh):
1489 # Test will fail if /bin/sh is a symlink to csh.
1490 shells.append(sh)
1491 for sh in shells:
1492 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1493 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001494 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001495 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1496
Florent Xicluna4886d242010-03-08 13:27:26 +00001497 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001498 # Do not inherit file handles from the parent.
1499 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001500 # Also set the SIGINT handler to the default to make sure it's not
1501 # being ignored (some tests rely on that.)
1502 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1503 try:
1504 p = subprocess.Popen([sys.executable, "-c", """if 1:
1505 import sys, time
1506 sys.stdout.write('x\\n')
1507 sys.stdout.flush()
1508 time.sleep(30)
1509 """],
1510 close_fds=True,
1511 stdin=subprocess.PIPE,
1512 stdout=subprocess.PIPE,
1513 stderr=subprocess.PIPE)
1514 finally:
1515 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001516 # Wait for the interpreter to be completely initialized before
1517 # sending any signal.
1518 p.stdout.read(1)
1519 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001520 return p
1521
Charles-François Natali53221e32013-01-12 16:52:20 +01001522 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1523 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001524 def _kill_dead_process(self, method, *args):
1525 # Do not inherit file handles from the parent.
1526 # It should fix failures on some platforms.
1527 p = subprocess.Popen([sys.executable, "-c", """if 1:
1528 import sys, time
1529 sys.stdout.write('x\\n')
1530 sys.stdout.flush()
1531 """],
1532 close_fds=True,
1533 stdin=subprocess.PIPE,
1534 stdout=subprocess.PIPE,
1535 stderr=subprocess.PIPE)
1536 # Wait for the interpreter to be completely initialized before
1537 # sending any signal.
1538 p.stdout.read(1)
1539 # The process should end after this
1540 time.sleep(1)
1541 # This shouldn't raise even though the child is now dead
1542 getattr(p, method)(*args)
1543 p.communicate()
1544
Florent Xicluna4886d242010-03-08 13:27:26 +00001545 def test_send_signal(self):
1546 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001547 _, stderr = p.communicate()
1548 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001549 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001550
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001551 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001552 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001553 _, stderr = p.communicate()
1554 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001555 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001556
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001557 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001558 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001559 _, stderr = p.communicate()
1560 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001561 self.assertEqual(p.wait(), -signal.SIGTERM)
1562
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001563 def test_send_signal_dead(self):
1564 # Sending a signal to a dead process
1565 self._kill_dead_process('send_signal', signal.SIGINT)
1566
1567 def test_kill_dead(self):
1568 # Killing a dead process
1569 self._kill_dead_process('kill')
1570
1571 def test_terminate_dead(self):
1572 # Terminating a dead process
1573 self._kill_dead_process('terminate')
1574
Victor Stinnerdaf45552013-08-28 00:53:59 +02001575 def _save_fds(self, save_fds):
1576 fds = []
1577 for fd in save_fds:
1578 inheritable = os.get_inheritable(fd)
1579 saved = os.dup(fd)
1580 fds.append((fd, saved, inheritable))
1581 return fds
1582
1583 def _restore_fds(self, fds):
1584 for fd, saved, inheritable in fds:
1585 os.dup2(saved, fd, inheritable=inheritable)
1586 os.close(saved)
1587
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001588 def check_close_std_fds(self, fds):
1589 # Issue #9905: test that subprocess pipes still work properly with
1590 # some standard fds closed
1591 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001592 saved_fds = self._save_fds(fds)
1593 for fd, saved, inheritable in saved_fds:
1594 if fd == 0:
1595 stdin = saved
1596 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001597 try:
1598 for fd in fds:
1599 os.close(fd)
1600 out, err = subprocess.Popen([sys.executable, "-c",
1601 'import sys;'
1602 'sys.stdout.write("apple");'
1603 'sys.stdout.flush();'
1604 'sys.stderr.write("orange")'],
1605 stdin=stdin,
1606 stdout=subprocess.PIPE,
1607 stderr=subprocess.PIPE).communicate()
1608 err = support.strip_python_stderr(err)
1609 self.assertEqual((out, err), (b'apple', b'orange'))
1610 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001611 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001612
1613 def test_close_fd_0(self):
1614 self.check_close_std_fds([0])
1615
1616 def test_close_fd_1(self):
1617 self.check_close_std_fds([1])
1618
1619 def test_close_fd_2(self):
1620 self.check_close_std_fds([2])
1621
1622 def test_close_fds_0_1(self):
1623 self.check_close_std_fds([0, 1])
1624
1625 def test_close_fds_0_2(self):
1626 self.check_close_std_fds([0, 2])
1627
1628 def test_close_fds_1_2(self):
1629 self.check_close_std_fds([1, 2])
1630
1631 def test_close_fds_0_1_2(self):
1632 # Issue #10806: test that subprocess pipes still work properly with
1633 # all standard fds closed.
1634 self.check_close_std_fds([0, 1, 2])
1635
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001636 def test_small_errpipe_write_fd(self):
1637 """Issue #15798: Popen should work when stdio fds are available."""
1638 new_stdin = os.dup(0)
1639 new_stdout = os.dup(1)
1640 try:
1641 os.close(0)
1642 os.close(1)
1643
1644 # Side test: if errpipe_write fails to have its CLOEXEC
1645 # flag set this should cause the parent to think the exec
1646 # failed. Extremely unlikely: everyone supports CLOEXEC.
1647 subprocess.Popen([
1648 sys.executable, "-c",
1649 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1650 finally:
1651 # Restore original stdin and stdout
1652 os.dup2(new_stdin, 0)
1653 os.dup2(new_stdout, 1)
1654 os.close(new_stdin)
1655 os.close(new_stdout)
1656
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001657 def test_remapping_std_fds(self):
1658 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001659 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001660 try:
1661 temp_fds = [fd for fd, fname in temps]
1662
1663 # unlink the files -- we won't need to reopen them
1664 for fd, fname in temps:
1665 os.unlink(fname)
1666
1667 # write some data to what will become stdin, and rewind
1668 os.write(temp_fds[1], b"STDIN")
1669 os.lseek(temp_fds[1], 0, 0)
1670
1671 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001672 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001673 try:
1674 # duplicate the file objects over the standard fd's
1675 for fd, temp_fd in enumerate(temp_fds):
1676 os.dup2(temp_fd, fd)
1677
1678 # now use those files in the "wrong" order, so that subprocess
1679 # has to rearrange them in the child
1680 p = subprocess.Popen([sys.executable, "-c",
1681 'import sys; got = sys.stdin.read();'
1682 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1683 stdin=temp_fds[1],
1684 stdout=temp_fds[2],
1685 stderr=temp_fds[0])
1686 p.wait()
1687 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001688 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001689
1690 for fd in temp_fds:
1691 os.lseek(fd, 0, 0)
1692
1693 out = os.read(temp_fds[2], 1024)
1694 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1695 self.assertEqual(out, b"got STDIN")
1696 self.assertEqual(err, b"err")
1697
1698 finally:
1699 for fd in temp_fds:
1700 os.close(fd)
1701
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001702 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1703 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001704 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001705 temp_fds = [fd for fd, fname in temps]
1706 try:
1707 # unlink the files -- we won't need to reopen them
1708 for fd, fname in temps:
1709 os.unlink(fname)
1710
1711 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001712 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001713 try:
1714 # duplicate the temp files over the standard fd's 0, 1, 2
1715 for fd, temp_fd in enumerate(temp_fds):
1716 os.dup2(temp_fd, fd)
1717
1718 # write some data to what will become stdin, and rewind
1719 os.write(stdin_no, b"STDIN")
1720 os.lseek(stdin_no, 0, 0)
1721
1722 # now use those files in the given order, so that subprocess
1723 # has to rearrange them in the child
1724 p = subprocess.Popen([sys.executable, "-c",
1725 'import sys; got = sys.stdin.read();'
1726 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1727 stdin=stdin_no,
1728 stdout=stdout_no,
1729 stderr=stderr_no)
1730 p.wait()
1731
1732 for fd in temp_fds:
1733 os.lseek(fd, 0, 0)
1734
1735 out = os.read(stdout_no, 1024)
1736 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1737 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001738 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001739
1740 self.assertEqual(out, b"got STDIN")
1741 self.assertEqual(err, b"err")
1742
1743 finally:
1744 for fd in temp_fds:
1745 os.close(fd)
1746
1747 # When duping fds, if there arises a situation where one of the fds is
1748 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1749 # This tests all combinations of this.
1750 def test_swap_fds(self):
1751 self.check_swap_fds(0, 1, 2)
1752 self.check_swap_fds(0, 2, 1)
1753 self.check_swap_fds(1, 0, 2)
1754 self.check_swap_fds(1, 2, 0)
1755 self.check_swap_fds(2, 0, 1)
1756 self.check_swap_fds(2, 1, 0)
1757
Victor Stinner13bb71c2010-04-23 21:41:56 +00001758 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001759 def prepare():
1760 raise ValueError("surrogate:\uDCff")
1761
1762 try:
1763 subprocess.call(
1764 [sys.executable, "-c", "pass"],
1765 preexec_fn=prepare)
1766 except ValueError as err:
1767 # Pure Python implementations keeps the message
1768 self.assertIsNone(subprocess._posixsubprocess)
1769 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001770 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001771 # _posixsubprocess uses a default message
1772 self.assertIsNotNone(subprocess._posixsubprocess)
1773 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1774 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001775 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001776
Victor Stinner13bb71c2010-04-23 21:41:56 +00001777 def test_undecodable_env(self):
1778 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01001779 encoded_value = value.encode("ascii", "surrogateescape")
1780
Victor Stinner13bb71c2010-04-23 21:41:56 +00001781 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001782 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001783 env = os.environ.copy()
1784 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01001785 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00001786 # surrogate-escaping of \xFF in the child process; otherwise it can
1787 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001788 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01001789 if sys.platform.startswith("aix"):
1790 # On AIX, the C locale uses the Latin1 encoding
1791 decoded_value = encoded_value.decode("latin1", "surrogateescape")
1792 else:
1793 # On other UNIXes, the C locale uses the ASCII encoding
1794 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001795 stdout = subprocess.check_output(
1796 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001797 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001798 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001799 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001800
1801 # test bytes
1802 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001803 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001804 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01001805 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001806 stdout = subprocess.check_output(
1807 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001808 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001809 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001810 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001811
Victor Stinnerb745a742010-05-18 17:17:23 +00001812 def test_bytes_program(self):
1813 abs_program = os.fsencode(sys.executable)
1814 path, program = os.path.split(sys.executable)
1815 program = os.fsencode(program)
1816
1817 # absolute bytes path
1818 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001819 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001820
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001821 # absolute bytes path as a string
1822 cmd = b"'" + abs_program + b"' -c pass"
1823 exitcode = subprocess.call(cmd, shell=True)
1824 self.assertEqual(exitcode, 0)
1825
Victor Stinnerb745a742010-05-18 17:17:23 +00001826 # bytes program, unicode PATH
1827 env = os.environ.copy()
1828 env["PATH"] = path
1829 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001830 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001831
1832 # bytes program, bytes PATH
1833 envb = os.environb.copy()
1834 envb[b"PATH"] = os.fsencode(path)
1835 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001836 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001837
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001838 def test_pipe_cloexec(self):
1839 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1840 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1841
1842 p1 = subprocess.Popen([sys.executable, sleeper],
1843 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1844 stderr=subprocess.PIPE, close_fds=False)
1845
1846 self.addCleanup(p1.communicate, b'')
1847
1848 p2 = subprocess.Popen([sys.executable, fd_status],
1849 stdout=subprocess.PIPE, close_fds=False)
1850
1851 output, error = p2.communicate()
1852 result_fds = set(map(int, output.split(b',')))
1853 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1854 p1.stderr.fileno()])
1855
1856 self.assertFalse(result_fds & unwanted_fds,
1857 "Expected no fds from %r to be open in child, "
1858 "found %r" %
1859 (unwanted_fds, result_fds & unwanted_fds))
1860
1861 def test_pipe_cloexec_real_tools(self):
1862 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1863 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1864
1865 subdata = b'zxcvbn'
1866 data = subdata * 4 + b'\n'
1867
1868 p1 = subprocess.Popen([sys.executable, qcat],
1869 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1870 close_fds=False)
1871
1872 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1873 stdin=p1.stdout, stdout=subprocess.PIPE,
1874 close_fds=False)
1875
1876 self.addCleanup(p1.wait)
1877 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001878 def kill_p1():
1879 try:
1880 p1.terminate()
1881 except ProcessLookupError:
1882 pass
1883 def kill_p2():
1884 try:
1885 p2.terminate()
1886 except ProcessLookupError:
1887 pass
1888 self.addCleanup(kill_p1)
1889 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001890
1891 p1.stdin.write(data)
1892 p1.stdin.close()
1893
1894 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1895
1896 self.assertTrue(readfiles, "The child hung")
1897 self.assertEqual(p2.stdout.read(), data)
1898
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001899 p1.stdout.close()
1900 p2.stdout.close()
1901
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001902 def test_close_fds(self):
1903 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1904
1905 fds = os.pipe()
1906 self.addCleanup(os.close, fds[0])
1907 self.addCleanup(os.close, fds[1])
1908
1909 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001910 # add a bunch more fds
1911 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02001912 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001913 self.addCleanup(os.close, fd)
1914 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001915
Victor Stinnerdaf45552013-08-28 00:53:59 +02001916 for fd in open_fds:
1917 os.set_inheritable(fd, True)
1918
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001919 p = subprocess.Popen([sys.executable, fd_status],
1920 stdout=subprocess.PIPE, close_fds=False)
1921 output, ignored = p.communicate()
1922 remaining_fds = set(map(int, output.split(b',')))
1923
1924 self.assertEqual(remaining_fds & open_fds, open_fds,
1925 "Some fds were closed")
1926
1927 p = subprocess.Popen([sys.executable, fd_status],
1928 stdout=subprocess.PIPE, close_fds=True)
1929 output, ignored = p.communicate()
1930 remaining_fds = set(map(int, output.split(b',')))
1931
1932 self.assertFalse(remaining_fds & open_fds,
1933 "Some fds were left open")
1934 self.assertIn(1, remaining_fds, "Subprocess failed")
1935
Gregory P. Smith8facece2012-01-21 14:01:08 -08001936 # Keep some of the fd's we opened open in the subprocess.
1937 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1938 fds_to_keep = set(open_fds.pop() for _ in range(8))
1939 p = subprocess.Popen([sys.executable, fd_status],
1940 stdout=subprocess.PIPE, close_fds=True,
1941 pass_fds=())
1942 output, ignored = p.communicate()
1943 remaining_fds = set(map(int, output.split(b',')))
1944
1945 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1946 "Some fds not in pass_fds were left open")
1947 self.assertIn(1, remaining_fds, "Subprocess failed")
1948
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07001949
Gregory P. Smithd04f6992014-06-01 15:27:28 -07001950 @unittest.skipIf(sys.platform.startswith("freebsd") and
1951 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
1952 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07001953 def test_close_fds_when_max_fd_is_lowered(self):
1954 """Confirm that issue21618 is fixed (may fail under valgrind)."""
1955 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1956
Gregory P. Smith634aa682014-06-15 17:51:04 -07001957 # This launches the meat of the test in a child process to
1958 # avoid messing with the larger unittest processes maximum
1959 # number of file descriptors.
1960 # This process launches:
1961 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
1962 # a bunch of high open fds above the new lower rlimit.
1963 # Those are reported via stdout before launching a new
1964 # process with close_fds=False to run the actual test:
1965 # +--> The TEST: This one launches a fd_status.py
1966 # subprocess with close_fds=True so we can find out if
1967 # any of the fds above the lowered rlimit are still open.
1968 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
1969 '''
1970 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07001971 open_fds = set()
1972 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07001973 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02001974 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07001975 open_fds.add(fd)
1976
1977 # Leave a two pairs of low ones available for use by the
1978 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07001979 # We also leave 10 more open as some Python buildbots run into
1980 # "too many open files" errors during the test if we do not.
1981 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07001982 os.close(fd)
1983 open_fds.remove(fd)
1984
1985 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07001986 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07001987 os.set_inheritable(fd, True)
1988
1989 max_fd_open = max(open_fds)
1990
Gregory P. Smith634aa682014-06-15 17:51:04 -07001991 # Communicate the open_fds to the parent unittest.TestCase process.
1992 print(','.join(map(str, sorted(open_fds))))
1993 sys.stdout.flush()
1994
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07001995 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
1996 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07001997 # 29 is lower than the highest fds we are leaving open.
1998 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07001999 # Launch a new Python interpreter with our low fd rlim_cur that
2000 # inherits open fds above that limit. It then uses subprocess
2001 # with close_fds=True to get a report of open fds in the child.
2002 # An explicit list of fds to check is passed to fd_status.py as
2003 # letting fd_status rely on its default logic would miss the
2004 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002005 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002006 [sys.executable, '-c',
2007 textwrap.dedent("""
2008 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002009 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002010 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002011 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002012 """.format(max_fd=max_fd_open+1))],
2013 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002014 finally:
2015 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002016 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002017
2018 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002019 output_lines = output.splitlines()
2020 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002021 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002022 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2023 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002024
Gregory P. Smith634aa682014-06-15 17:51:04 -07002025 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002026 msg="Some fds were left open.")
2027
2028
Victor Stinner88701e22011-06-01 13:13:04 +02002029 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2030 # descriptor of a pipe closed in the parent process is valid in the
2031 # child process according to fstat(), but the mode of the file
2032 # descriptor is invalid, and read or write raise an error.
2033 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002034 def test_pass_fds(self):
2035 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2036
2037 open_fds = set()
2038
2039 for x in range(5):
2040 fds = os.pipe()
2041 self.addCleanup(os.close, fds[0])
2042 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002043 os.set_inheritable(fds[0], True)
2044 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002045 open_fds.update(fds)
2046
2047 for fd in open_fds:
2048 p = subprocess.Popen([sys.executable, fd_status],
2049 stdout=subprocess.PIPE, close_fds=True,
2050 pass_fds=(fd, ))
2051 output, ignored = p.communicate()
2052
2053 remaining_fds = set(map(int, output.split(b',')))
2054 to_be_closed = open_fds - {fd}
2055
2056 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2057 self.assertFalse(remaining_fds & to_be_closed,
2058 "fd to be closed passed")
2059
2060 # pass_fds overrides close_fds with a warning.
2061 with self.assertWarns(RuntimeWarning) as context:
2062 self.assertFalse(subprocess.call(
2063 [sys.executable, "-c", "import sys; sys.exit(0)"],
2064 close_fds=False, pass_fds=(fd, )))
2065 self.assertIn('overriding close_fds', str(context.warning))
2066
Victor Stinnerdaf45552013-08-28 00:53:59 +02002067 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002068 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002069
2070 inheritable, non_inheritable = os.pipe()
2071 self.addCleanup(os.close, inheritable)
2072 self.addCleanup(os.close, non_inheritable)
2073 os.set_inheritable(inheritable, True)
2074 os.set_inheritable(non_inheritable, False)
2075 pass_fds = (inheritable, non_inheritable)
2076 args = [sys.executable, script]
2077 args += list(map(str, pass_fds))
2078
2079 p = subprocess.Popen(args,
2080 stdout=subprocess.PIPE, close_fds=True,
2081 pass_fds=pass_fds)
2082 output, ignored = p.communicate()
2083 fds = set(map(int, output.split(b',')))
2084
2085 # the inheritable file descriptor must be inherited, so its inheritable
2086 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002087 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002088
2089 # inheritable flag must not be changed in the parent process
2090 self.assertEqual(os.get_inheritable(inheritable), True)
2091 self.assertEqual(os.get_inheritable(non_inheritable), False)
2092
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002093 def test_stdout_stdin_are_single_inout_fd(self):
2094 with io.open(os.devnull, "r+") as inout:
2095 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2096 stdout=inout, stdin=inout)
2097 p.wait()
2098
2099 def test_stdout_stderr_are_single_inout_fd(self):
2100 with io.open(os.devnull, "r+") as inout:
2101 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2102 stdout=inout, stderr=inout)
2103 p.wait()
2104
2105 def test_stderr_stdin_are_single_inout_fd(self):
2106 with io.open(os.devnull, "r+") as inout:
2107 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2108 stderr=inout, stdin=inout)
2109 p.wait()
2110
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002111 def test_wait_when_sigchild_ignored(self):
2112 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2113 sigchild_ignore = support.findfile("sigchild_ignore.py",
2114 subdir="subprocessdata")
2115 p = subprocess.Popen([sys.executable, sigchild_ignore],
2116 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2117 stdout, stderr = p.communicate()
2118 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002119 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002120 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002121
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002122 def test_select_unbuffered(self):
2123 # Issue #11459: bufsize=0 should really set the pipes as
2124 # unbuffered (and therefore let select() work properly).
2125 select = support.import_module("select")
2126 p = subprocess.Popen([sys.executable, "-c",
2127 'import sys;'
2128 'sys.stdout.write("apple")'],
2129 stdout=subprocess.PIPE,
2130 bufsize=0)
2131 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002132 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002133 try:
2134 self.assertEqual(f.read(4), b"appl")
2135 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2136 finally:
2137 p.wait()
2138
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002139 def test_zombie_fast_process_del(self):
2140 # Issue #12650: on Unix, if Popen.__del__() was called before the
2141 # process exited, it wouldn't be added to subprocess._active, and would
2142 # remain a zombie.
2143 # spawn a Popen, and delete its reference before it exits
2144 p = subprocess.Popen([sys.executable, "-c",
2145 'import sys, time;'
2146 'time.sleep(0.2)'],
2147 stdout=subprocess.PIPE,
2148 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002149 self.addCleanup(p.stdout.close)
2150 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002151 ident = id(p)
2152 pid = p.pid
2153 del p
2154 # check that p is in the active processes list
2155 self.assertIn(ident, [id(o) for o in subprocess._active])
2156
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002157 def test_leak_fast_process_del_killed(self):
2158 # Issue #12650: on Unix, if Popen.__del__() was called before the
2159 # process exited, and the process got killed by a signal, it would never
2160 # be removed from subprocess._active, which triggered a FD and memory
2161 # leak.
2162 # spawn a Popen, delete its reference and kill it
2163 p = subprocess.Popen([sys.executable, "-c",
2164 'import time;'
2165 'time.sleep(3)'],
2166 stdout=subprocess.PIPE,
2167 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002168 self.addCleanup(p.stdout.close)
2169 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002170 ident = id(p)
2171 pid = p.pid
2172 del p
2173 os.kill(pid, signal.SIGKILL)
2174 # check that p is in the active processes list
2175 self.assertIn(ident, [id(o) for o in subprocess._active])
2176
2177 # let some time for the process to exit, and create a new Popen: this
2178 # should trigger the wait() of p
2179 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002180 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002181 with subprocess.Popen(['nonexisting_i_hope'],
2182 stdout=subprocess.PIPE,
2183 stderr=subprocess.PIPE) as proc:
2184 pass
2185 # p should have been wait()ed on, and removed from the _active list
2186 self.assertRaises(OSError, os.waitpid, pid, 0)
2187 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2188
Charles-François Natali249cdc32013-08-25 18:24:45 +02002189 def test_close_fds_after_preexec(self):
2190 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2191
2192 # this FD is used as dup2() target by preexec_fn, and should be closed
2193 # in the child process
2194 fd = os.dup(1)
2195 self.addCleanup(os.close, fd)
2196
2197 p = subprocess.Popen([sys.executable, fd_status],
2198 stdout=subprocess.PIPE, close_fds=True,
2199 preexec_fn=lambda: os.dup2(1, fd))
2200 output, ignored = p.communicate()
2201
2202 remaining_fds = set(map(int, output.split(b',')))
2203
2204 self.assertNotIn(fd, remaining_fds)
2205
Victor Stinner8f437aa2014-10-05 17:25:19 +02002206 @support.cpython_only
2207 def test_fork_exec(self):
2208 # Issue #22290: fork_exec() must not crash on memory allocation failure
2209 # or other errors
2210 import _posixsubprocess
2211 gc_enabled = gc.isenabled()
2212 try:
2213 # Use a preexec function and enable the garbage collector
2214 # to force fork_exec() to re-enable the garbage collector
2215 # on error.
2216 func = lambda: None
2217 gc.enable()
2218
2219 executable_list = "exec" # error: must be a sequence
2220
2221 for args, exe_list, cwd, env_list in (
2222 (123, [b"exe"], None, [b"env"]),
2223 ([b"arg"], 123, None, [b"env"]),
2224 ([b"arg"], [b"exe"], 123, [b"env"]),
2225 ([b"arg"], [b"exe"], None, 123),
2226 ):
2227 with self.assertRaises(TypeError):
2228 _posixsubprocess.fork_exec(
2229 args, exe_list,
2230 True, [], cwd, env_list,
2231 -1, -1, -1, -1,
2232 1, 2, 3, 4,
2233 True, True, func)
2234 finally:
2235 if not gc_enabled:
2236 gc.disable()
2237
2238
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002239
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002240@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002241class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002242
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002243 def test_startupinfo(self):
2244 # startupinfo argument
2245 # We uses hardcoded constants, because we do not want to
2246 # depend on win32all.
2247 STARTF_USESHOWWINDOW = 1
2248 SW_MAXIMIZE = 3
2249 startupinfo = subprocess.STARTUPINFO()
2250 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2251 startupinfo.wShowWindow = SW_MAXIMIZE
2252 # Since Python is a console process, it won't be affected
2253 # by wShowWindow, but the argument should be silently
2254 # ignored
2255 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002256 startupinfo=startupinfo)
2257
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002258 def test_creationflags(self):
2259 # creationflags argument
2260 CREATE_NEW_CONSOLE = 16
2261 sys.stderr.write(" a DOS box should flash briefly ...\n")
2262 subprocess.call(sys.executable +
2263 ' -c "import time; time.sleep(0.25)"',
2264 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002265
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002266 def test_invalid_args(self):
2267 # invalid arguments should raise ValueError
2268 self.assertRaises(ValueError, subprocess.call,
2269 [sys.executable, "-c",
2270 "import sys; sys.exit(47)"],
2271 preexec_fn=lambda: 1)
2272 self.assertRaises(ValueError, subprocess.call,
2273 [sys.executable, "-c",
2274 "import sys; sys.exit(47)"],
2275 stdout=subprocess.PIPE,
2276 close_fds=True)
2277
2278 def test_close_fds(self):
2279 # close file descriptors
2280 rc = subprocess.call([sys.executable, "-c",
2281 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002282 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002283 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002284
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002285 def test_shell_sequence(self):
2286 # Run command through the shell (sequence)
2287 newenv = os.environ.copy()
2288 newenv["FRUIT"] = "physalis"
2289 p = subprocess.Popen(["set"], shell=1,
2290 stdout=subprocess.PIPE,
2291 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002292 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002293 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002294
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002295 def test_shell_string(self):
2296 # Run command through the shell (string)
2297 newenv = os.environ.copy()
2298 newenv["FRUIT"] = "physalis"
2299 p = subprocess.Popen("set", shell=1,
2300 stdout=subprocess.PIPE,
2301 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002302 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002303 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002304
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002305 def test_call_string(self):
2306 # call() function with string argument on Windows
2307 rc = subprocess.call(sys.executable +
2308 ' -c "import sys; sys.exit(47)"')
2309 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002310
Florent Xicluna4886d242010-03-08 13:27:26 +00002311 def _kill_process(self, method, *args):
2312 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002313 p = subprocess.Popen([sys.executable, "-c", """if 1:
2314 import sys, time
2315 sys.stdout.write('x\\n')
2316 sys.stdout.flush()
2317 time.sleep(30)
2318 """],
2319 stdin=subprocess.PIPE,
2320 stdout=subprocess.PIPE,
2321 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00002322 self.addCleanup(p.stdout.close)
2323 self.addCleanup(p.stderr.close)
2324 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00002325 # Wait for the interpreter to be completely initialized before
2326 # sending any signal.
2327 p.stdout.read(1)
2328 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00002329 _, stderr = p.communicate()
2330 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00002331 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002332 self.assertNotEqual(returncode, 0)
2333
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002334 def _kill_dead_process(self, method, *args):
2335 p = subprocess.Popen([sys.executable, "-c", """if 1:
2336 import sys, time
2337 sys.stdout.write('x\\n')
2338 sys.stdout.flush()
2339 sys.exit(42)
2340 """],
2341 stdin=subprocess.PIPE,
2342 stdout=subprocess.PIPE,
2343 stderr=subprocess.PIPE)
2344 self.addCleanup(p.stdout.close)
2345 self.addCleanup(p.stderr.close)
2346 self.addCleanup(p.stdin.close)
2347 # Wait for the interpreter to be completely initialized before
2348 # sending any signal.
2349 p.stdout.read(1)
2350 # The process should end after this
2351 time.sleep(1)
2352 # This shouldn't raise even though the child is now dead
2353 getattr(p, method)(*args)
2354 _, stderr = p.communicate()
2355 self.assertStderrEqual(stderr, b'')
2356 rc = p.wait()
2357 self.assertEqual(rc, 42)
2358
Florent Xicluna4886d242010-03-08 13:27:26 +00002359 def test_send_signal(self):
2360 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002361
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002362 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002363 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002364
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002365 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002366 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002367
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002368 def test_send_signal_dead(self):
2369 self._kill_dead_process('send_signal', signal.SIGTERM)
2370
2371 def test_kill_dead(self):
2372 self._kill_dead_process('kill')
2373
2374 def test_terminate_dead(self):
2375 self._kill_dead_process('terminate')
2376
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002377class CommandTests(unittest.TestCase):
2378 def test_getoutput(self):
2379 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2380 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2381 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002382
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002383 # we use mkdtemp in the next line to create an empty directory
2384 # under our exclusive control; from that, we can invent a pathname
2385 # that we _know_ won't exist. This is guaranteed to fail.
2386 dir = None
2387 try:
2388 dir = tempfile.mkdtemp()
2389 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002390 status, output = subprocess.getstatusoutput(
2391 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002392 self.assertNotEqual(status, 0)
2393 finally:
2394 if dir is not None:
2395 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002396
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002397
Charles-François Natali3a4586a2013-11-08 19:56:59 +01002398@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2399 "Test needs selectors.PollSelector")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002400class ProcessTestCaseNoPoll(ProcessTestCase):
2401 def setUp(self):
Charles-François Natali3a4586a2013-11-08 19:56:59 +01002402 self.orig_selector = subprocess._PopenSelector
2403 subprocess._PopenSelector = selectors.SelectSelector
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002404 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002405
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002406 def tearDown(self):
Charles-François Natali3a4586a2013-11-08 19:56:59 +01002407 subprocess._PopenSelector = self.orig_selector
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002408 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002409
2410
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002411class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00002412 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002413 def test_eintr_retry_call(self):
2414 record_calls = []
2415 def fake_os_func(*args):
2416 record_calls.append(args)
2417 if len(record_calls) == 2:
2418 raise OSError(errno.EINTR, "fake interrupted system call")
2419 return tuple(reversed(args))
2420
2421 self.assertEqual((999, 256),
2422 subprocess._eintr_retry_call(fake_os_func, 256, 999))
2423 self.assertEqual([(256, 999)], record_calls)
2424 # This time there will be an EINTR so it will loop once.
2425 self.assertEqual((666,),
2426 subprocess._eintr_retry_call(fake_os_func, 666))
2427 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
2428
2429
Tim Golden126c2962010-08-11 14:20:40 +00002430@unittest.skipUnless(mswindows, "Windows-specific tests")
2431class CommandsWithSpaces (BaseTestCase):
2432
2433 def setUp(self):
2434 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002435 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002436 self.fname = fname.lower ()
2437 os.write(f, b"import sys;"
2438 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2439 )
2440 os.close(f)
2441
2442 def tearDown(self):
2443 os.remove(self.fname)
2444 super().tearDown()
2445
2446 def with_spaces(self, *args, **kwargs):
2447 kwargs['stdout'] = subprocess.PIPE
2448 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002449 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002450 self.assertEqual(
2451 p.stdout.read ().decode("mbcs"),
2452 "2 [%r, 'ab cd']" % self.fname
2453 )
2454
2455 def test_shell_string_with_spaces(self):
2456 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002457 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2458 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002459
2460 def test_shell_sequence_with_spaces(self):
2461 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002462 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002463
2464 def test_noshell_string_with_spaces(self):
2465 # call() function with string argument with spaces on Windows
2466 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2467 "ab cd"))
2468
2469 def test_noshell_sequence_with_spaces(self):
2470 # call() function with sequence argument with spaces on Windows
2471 self.with_spaces([sys.executable, self.fname, "ab cd"])
2472
Brian Curtin79cdb662010-12-03 02:46:02 +00002473
Georg Brandla86b2622012-02-20 21:34:57 +01002474class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002475
2476 def test_pipe(self):
2477 with subprocess.Popen([sys.executable, "-c",
2478 "import sys;"
2479 "sys.stdout.write('stdout');"
2480 "sys.stderr.write('stderr');"],
2481 stdout=subprocess.PIPE,
2482 stderr=subprocess.PIPE) as proc:
2483 self.assertEqual(proc.stdout.read(), b"stdout")
2484 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2485
2486 self.assertTrue(proc.stdout.closed)
2487 self.assertTrue(proc.stderr.closed)
2488
2489 def test_returncode(self):
2490 with subprocess.Popen([sys.executable, "-c",
2491 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002492 pass
2493 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002494 self.assertEqual(proc.returncode, 100)
2495
2496 def test_communicate_stdin(self):
2497 with subprocess.Popen([sys.executable, "-c",
2498 "import sys;"
2499 "sys.exit(sys.stdin.read() == 'context')"],
2500 stdin=subprocess.PIPE) as proc:
2501 proc.communicate(b"context")
2502 self.assertEqual(proc.returncode, 1)
2503
2504 def test_invalid_args(self):
Andrew Svetlovb1726972012-12-26 23:34:54 +02002505 with self.assertRaises(FileNotFoundError) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002506 with subprocess.Popen(['nonexisting_i_hope'],
2507 stdout=subprocess.PIPE,
2508 stderr=subprocess.PIPE) as proc:
2509 pass
2510
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002511 def test_broken_pipe_cleanup(self):
2512 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002513 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002514 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002515 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002516 proc = proc.__enter__()
2517 # Prepare to send enough data to overflow any OS pipe buffering and
2518 # guarantee a broken pipe error. Data is held in BufferedWriter
2519 # buffer until closed.
2520 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002521 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002522 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002523 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002524 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002525 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002526
Brian Curtin79cdb662010-12-03 02:46:02 +00002527
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002528def test_main():
2529 unit_tests = (ProcessTestCase,
2530 POSIXProcessTestCase,
2531 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002532 CommandTests,
2533 ProcessTestCaseNoPoll,
2534 HelperFunctionTests,
2535 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002536 ContextManagerTests,
2537 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002538
2539 support.run_unittest(*unit_tests)
2540 support.reap_children()
2541
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002542if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002543 unittest.main()