blob: 840577dba1e390a97feb4c905121d0058cb3b38e [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
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000015import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000016import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040017import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050018import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030019import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050020
21try:
Antoine Pitroua8392712013-08-30 23:38:13 +020022 import threading
23except ImportError:
24 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050025
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000026mswindows = (sys.platform == "win32")
27
28#
29# Depends on the following external programs: Python
30#
31
32if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000033 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
34 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000035else:
36 SETBINARY = ''
37
Florent Xiclunab1e94e82010-02-27 22:12:37 +000038
39try:
40 mkstemp = tempfile.mkstemp
41except AttributeError:
42 # tempfile.mkstemp is not available
43 def mkstemp():
44 """Replacement for mkstemp, calling mktemp."""
45 fname = tempfile.mktemp()
46 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
47
Tim Peters3761e8d2004-10-13 04:07:12 +000048
Florent Xiclunac049d872010-03-27 22:47:23 +000049class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000050 def setUp(self):
51 # Try to minimize the number of children we have so this test
52 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000053 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000055 def tearDown(self):
56 for inst in subprocess._active:
57 inst.wait()
58 subprocess._cleanup()
59 self.assertFalse(subprocess._active, "subprocess._active not empty")
60
Florent Xiclunab1e94e82010-02-27 22:12:37 +000061 def assertStderrEqual(self, stderr, expected, msg=None):
62 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
63 # shutdown time. That frustrates tests trying to check stderr produced
64 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000065 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040066 # strip_python_stderr also strips whitespace, so we do too.
67 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000068 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069
Florent Xiclunac049d872010-03-27 22:47:23 +000070
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080071class PopenTestException(Exception):
72 pass
73
74
75class PopenExecuteChildRaises(subprocess.Popen):
76 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
77 _execute_child fails.
78 """
79 def _execute_child(self, *args, **kwargs):
80 raise PopenTestException("Forced Exception for Test")
81
82
Florent Xiclunac049d872010-03-27 22:47:23 +000083class ProcessTestCase(BaseTestCase):
84
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070085 def test_io_buffered_by_default(self):
86 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
87 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
88 stderr=subprocess.PIPE)
89 try:
90 self.assertIsInstance(p.stdin, io.BufferedIOBase)
91 self.assertIsInstance(p.stdout, io.BufferedIOBase)
92 self.assertIsInstance(p.stderr, io.BufferedIOBase)
93 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070094 p.stdin.close()
95 p.stdout.close()
96 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070097 p.wait()
98
99 def test_io_unbuffered_works(self):
100 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
101 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
102 stderr=subprocess.PIPE, bufsize=0)
103 try:
104 self.assertIsInstance(p.stdin, io.RawIOBase)
105 self.assertIsInstance(p.stdout, io.RawIOBase)
106 self.assertIsInstance(p.stderr, io.RawIOBase)
107 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700108 p.stdin.close()
109 p.stdout.close()
110 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700111 p.wait()
112
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000113 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000114 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000115 rc = subprocess.call([sys.executable, "-c",
116 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000117 self.assertEqual(rc, 47)
118
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400119 def test_call_timeout(self):
120 # call() function with timeout argument; we want to test that the child
121 # process gets killed when the timeout expires. If the child isn't
122 # killed, this call will deadlock since subprocess.call waits for the
123 # child.
124 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
125 [sys.executable, "-c", "while True: pass"],
126 timeout=0.1)
127
Peter Astrand454f7672005-01-01 09:36:35 +0000128 def test_check_call_zero(self):
129 # check_call() function with zero return code
130 rc = subprocess.check_call([sys.executable, "-c",
131 "import sys; sys.exit(0)"])
132 self.assertEqual(rc, 0)
133
134 def test_check_call_nonzero(self):
135 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000136 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000137 subprocess.check_call([sys.executable, "-c",
138 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000139 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000140
Georg Brandlf9734072008-12-07 15:30:06 +0000141 def test_check_output(self):
142 # check_output() function with zero return code
143 output = subprocess.check_output(
144 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000145 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000146
147 def test_check_output_nonzero(self):
148 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000149 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000150 subprocess.check_output(
151 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000152 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000153
154 def test_check_output_stderr(self):
155 # check_output() function stderr redirected to stdout
156 output = subprocess.check_output(
157 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
158 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000159 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000160
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300161 def test_check_output_stdin_arg(self):
162 # check_output() can be called with stdin set to a file
163 tf = tempfile.TemporaryFile()
164 self.addCleanup(tf.close)
165 tf.write(b'pear')
166 tf.seek(0)
167 output = subprocess.check_output(
168 [sys.executable, "-c",
169 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
170 stdin=tf)
171 self.assertIn(b'PEAR', output)
172
173 def test_check_output_input_arg(self):
174 # check_output() can be called with input set to a string
175 output = subprocess.check_output(
176 [sys.executable, "-c",
177 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
178 input=b'pear')
179 self.assertIn(b'PEAR', output)
180
Georg Brandlf9734072008-12-07 15:30:06 +0000181 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300182 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000183 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000184 output = subprocess.check_output(
185 [sys.executable, "-c", "print('will not be run')"],
186 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000187 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000188 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000189
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300190 def test_check_output_stdin_with_input_arg(self):
191 # check_output() refuses to accept 'stdin' with 'input'
192 tf = tempfile.TemporaryFile()
193 self.addCleanup(tf.close)
194 tf.write(b'pear')
195 tf.seek(0)
196 with self.assertRaises(ValueError) as c:
197 output = subprocess.check_output(
198 [sys.executable, "-c", "print('will not be run')"],
199 stdin=tf, input=b'hare')
200 self.fail("Expected ValueError when stdin and input args supplied.")
201 self.assertIn('stdin', c.exception.args[0])
202 self.assertIn('input', c.exception.args[0])
203
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400204 def test_check_output_timeout(self):
205 # check_output() function with timeout arg
206 with self.assertRaises(subprocess.TimeoutExpired) as c:
207 output = subprocess.check_output(
208 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200209 "import sys, time\n"
210 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400211 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200212 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400213 # Some heavily loaded buildbots (sparc Debian 3.x) require
214 # this much time to start and print.
215 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400216 self.fail("Expected TimeoutExpired.")
217 self.assertEqual(c.exception.output, b'BDFL')
218
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000219 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000220 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000221 newenv = os.environ.copy()
222 newenv["FRUIT"] = "banana"
223 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000224 'import sys, os;'
225 'sys.exit(os.getenv("FRUIT")=="banana")'],
226 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 self.assertEqual(rc, 1)
228
Victor Stinner87b9bc32011-06-01 00:57:47 +0200229 def test_invalid_args(self):
230 # Popen() called with invalid arguments should raise TypeError
231 # but Popen.__del__ should not complain (issue #12085)
232 with support.captured_stderr() as s:
233 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
234 argcount = subprocess.Popen.__init__.__code__.co_argcount
235 too_many_args = [0] * (argcount + 1)
236 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
237 self.assertEqual(s.getvalue(), '')
238
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000240 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000241 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000243 self.addCleanup(p.stdout.close)
244 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 p.wait()
246 self.assertEqual(p.stdin, None)
247
248 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200249 # .stdout is None when not redirected, and the child's stdout will
250 # be inherited from the parent. In order to test this we run a
251 # subprocess in a subprocess:
252 # this_test
253 # \-- subprocess created by this test (parent)
254 # \-- subprocess created by the parent subprocess (child)
255 # The parent doesn't specify stdout, so the child will use the
256 # parent's stdout. This test checks that the message printed by the
257 # child goes to the parent stdout. The parent also checks that the
258 # child's stdout is None. See #11963.
259 code = ('import sys; from subprocess import Popen, PIPE;'
260 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
261 ' stdin=PIPE, stderr=PIPE);'
262 'p.wait(); assert p.stdout is None;')
263 p = subprocess.Popen([sys.executable, "-c", code],
264 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
265 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000266 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200267 out, err = p.communicate()
268 self.assertEqual(p.returncode, 0, err)
269 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270
271 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000272 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000273 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000275 self.addCleanup(p.stdout.close)
276 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000277 p.wait()
278 self.assertEqual(p.stderr, None)
279
Chris Jerdonek776cb192012-10-08 15:56:43 -0700280 def _assert_python(self, pre_args, **kwargs):
281 # We include sys.exit() to prevent the test runner from hanging
282 # whenever python is found.
283 args = pre_args + ["import sys; sys.exit(47)"]
284 p = subprocess.Popen(args, **kwargs)
285 p.wait()
286 self.assertEqual(47, p.returncode)
287
288 def test_executable(self):
289 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700290 #
291 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
292 # determine where its standard library is, so we need the directory
293 # of args[0] to be valid for the Popen() call to Python to succeed.
294 # See also issue #16170 and issue #7774.
295 doesnotexist = os.path.join(os.path.dirname(sys.executable),
296 "doesnotexist")
297 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700298
299 def test_executable_takes_precedence(self):
300 # Check that the executable argument takes precedence over args[0].
301 #
302 # Verify first that the call succeeds without the executable arg.
303 pre_args = [sys.executable, "-c"]
304 self._assert_python(pre_args)
305 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
306 executable="doesnotexist")
307
308 @unittest.skipIf(mswindows, "executable argument replaces shell")
309 def test_executable_replaces_shell(self):
310 # Check that the executable argument replaces the default shell
311 # when shell=True.
312 self._assert_python([], executable=sys.executable, shell=True)
313
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700314 # For use in the test_cwd* tests below.
315 def _normalize_cwd(self, cwd):
316 # Normalize an expected cwd (for Tru64 support).
317 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
318 # strings. See bug #1063571.
319 original_cwd = os.getcwd()
320 os.chdir(cwd)
321 cwd = os.getcwd()
322 os.chdir(original_cwd)
323 return cwd
324
325 # For use in the test_cwd* tests below.
326 def _split_python_path(self):
327 # Return normalized (python_dir, python_base).
328 python_path = os.path.realpath(sys.executable)
329 return os.path.split(python_path)
330
331 # For use in the test_cwd* tests below.
332 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
333 # Invoke Python via Popen, and assert that (1) the call succeeds,
334 # and that (2) the current working directory of the child process
335 # matches *expected_cwd*.
336 p = subprocess.Popen([python_arg, "-c",
337 "import os, sys; "
338 "sys.stdout.write(os.getcwd()); "
339 "sys.exit(47)"],
340 stdout=subprocess.PIPE,
341 **kwargs)
342 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000343 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700344 self.assertEqual(47, p.returncode)
345 normcase = os.path.normcase
346 self.assertEqual(normcase(expected_cwd),
347 normcase(p.stdout.read().decode("utf-8")))
348
349 def test_cwd(self):
350 # Check that cwd changes the cwd for the child process.
351 temp_dir = tempfile.gettempdir()
352 temp_dir = self._normalize_cwd(temp_dir)
353 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
354
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700355 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700356 def test_cwd_with_relative_arg(self):
357 # Check that Popen looks for args[0] relative to cwd if args[0]
358 # is relative.
359 python_dir, python_base = self._split_python_path()
360 rel_python = os.path.join(os.curdir, python_base)
361 with support.temp_cwd() as wrong_dir:
362 # Before calling with the correct cwd, confirm that the call fails
363 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700364 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700365 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700366 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700367 [rel_python], cwd=wrong_dir)
368 python_dir = self._normalize_cwd(python_dir)
369 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
370
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700371 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700372 def test_cwd_with_relative_executable(self):
373 # Check that Popen looks for executable relative to cwd if executable
374 # is relative (and that executable takes precedence over args[0]).
375 python_dir, python_base = self._split_python_path()
376 rel_python = os.path.join(os.curdir, python_base)
377 doesntexist = "somethingyoudonthave"
378 with support.temp_cwd() as wrong_dir:
379 # Before calling with the correct cwd, confirm that the call fails
380 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700381 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700382 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700383 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700384 [doesntexist], executable=rel_python,
385 cwd=wrong_dir)
386 python_dir = self._normalize_cwd(python_dir)
387 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
388 cwd=python_dir)
389
390 def test_cwd_with_absolute_arg(self):
391 # Check that Popen can find the executable when the cwd is wrong
392 # if args[0] is an absolute path.
393 python_dir, python_base = self._split_python_path()
394 abs_python = os.path.join(python_dir, python_base)
395 rel_python = os.path.join(os.curdir, python_base)
396 with script_helper.temp_dir() as wrong_dir:
397 # Before calling with an absolute path, confirm that using a
398 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700399 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700400 [rel_python], cwd=wrong_dir)
401 wrong_dir = self._normalize_cwd(wrong_dir)
402 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
403
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100404 @unittest.skipIf(sys.base_prefix != sys.prefix,
405 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000406 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700407 python_dir, python_base = self._split_python_path()
408 python_dir = self._normalize_cwd(python_dir)
409 self._assert_cwd(python_dir, "somethingyoudonthave",
410 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000411
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100412 @unittest.skipIf(sys.base_prefix != sys.prefix,
413 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000414 @unittest.skipIf(sysconfig.is_python_build(),
415 "need an installed Python. See #7774")
416 def test_executable_without_cwd(self):
417 # For a normal installation, it should work without 'cwd'
418 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700419 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
420 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000421
422 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000423 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424 p = subprocess.Popen([sys.executable, "-c",
425 'import sys; sys.exit(sys.stdin.read() == "pear")'],
426 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000427 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000428 p.stdin.close()
429 p.wait()
430 self.assertEqual(p.returncode, 1)
431
432 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000433 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000434 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000435 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000436 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000437 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438 os.lseek(d, 0, 0)
439 p = subprocess.Popen([sys.executable, "-c",
440 'import sys; sys.exit(sys.stdin.read() == "pear")'],
441 stdin=d)
442 p.wait()
443 self.assertEqual(p.returncode, 1)
444
445 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000446 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000447 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000448 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000449 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000450 tf.seek(0)
451 p = subprocess.Popen([sys.executable, "-c",
452 'import sys; sys.exit(sys.stdin.read() == "pear")'],
453 stdin=tf)
454 p.wait()
455 self.assertEqual(p.returncode, 1)
456
457 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000458 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459 p = subprocess.Popen([sys.executable, "-c",
460 'import sys; sys.stdout.write("orange")'],
461 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000462 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000463 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464
465 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000466 # stdout is set to open file descriptor
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 d = tf.fileno()
470 p = subprocess.Popen([sys.executable, "-c",
471 'import sys; sys.stdout.write("orange")'],
472 stdout=d)
473 p.wait()
474 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000475 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476
477 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000478 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000479 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000480 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481 p = subprocess.Popen([sys.executable, "-c",
482 'import sys; sys.stdout.write("orange")'],
483 stdout=tf)
484 p.wait()
485 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000486 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000487
488 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000489 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490 p = subprocess.Popen([sys.executable, "-c",
491 'import sys; sys.stderr.write("strawberry")'],
492 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000493 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000494 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495
496 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000497 # stderr is set to open file descriptor
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 d = tf.fileno()
501 p = subprocess.Popen([sys.executable, "-c",
502 'import sys; sys.stderr.write("strawberry")'],
503 stderr=d)
504 p.wait()
505 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000506 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507
508 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000509 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000510 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000511 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 p = subprocess.Popen([sys.executable, "-c",
513 'import sys; sys.stderr.write("strawberry")'],
514 stderr=tf)
515 p.wait()
516 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000517 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518
519 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000520 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000521 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000522 'import sys;'
523 'sys.stdout.write("apple");'
524 'sys.stdout.flush();'
525 'sys.stderr.write("orange")'],
526 stdout=subprocess.PIPE,
527 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000528 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000529 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530
531 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000532 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000533 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000534 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000535 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000536 'import sys;'
537 'sys.stdout.write("apple");'
538 'sys.stdout.flush();'
539 'sys.stderr.write("orange")'],
540 stdout=tf,
541 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542 p.wait()
543 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000544 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545
Thomas Wouters89f507f2006-12-13 04:49:30 +0000546 def test_stdout_filedes_of_stdout(self):
547 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200548 # To avoid printing the text on stdout, we do something similar to
549 # test_stdout_none (see above). The parent subprocess calls the child
550 # subprocess passing stdout=1, and this test uses stdout=PIPE in
551 # order to capture and check the output of the parent. See #11963.
552 code = ('import sys, subprocess; '
553 'rc = subprocess.call([sys.executable, "-c", '
554 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
555 'b\'test with stdout=1\'))"], stdout=1); '
556 'assert rc == 18')
557 p = subprocess.Popen([sys.executable, "-c", code],
558 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
559 self.addCleanup(p.stdout.close)
560 self.addCleanup(p.stderr.close)
561 out, err = p.communicate()
562 self.assertEqual(p.returncode, 0, err)
563 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000564
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200565 def test_stdout_devnull(self):
566 p = subprocess.Popen([sys.executable, "-c",
567 'for i in range(10240):'
568 'print("x" * 1024)'],
569 stdout=subprocess.DEVNULL)
570 p.wait()
571 self.assertEqual(p.stdout, None)
572
573 def test_stderr_devnull(self):
574 p = subprocess.Popen([sys.executable, "-c",
575 'import sys\n'
576 'for i in range(10240):'
577 'sys.stderr.write("x" * 1024)'],
578 stderr=subprocess.DEVNULL)
579 p.wait()
580 self.assertEqual(p.stderr, None)
581
582 def test_stdin_devnull(self):
583 p = subprocess.Popen([sys.executable, "-c",
584 'import sys;'
585 'sys.stdin.read(1)'],
586 stdin=subprocess.DEVNULL)
587 p.wait()
588 self.assertEqual(p.stdin, None)
589
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000590 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000591 newenv = os.environ.copy()
592 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200593 with subprocess.Popen([sys.executable, "-c",
594 'import sys,os;'
595 'sys.stdout.write(os.getenv("FRUIT"))'],
596 stdout=subprocess.PIPE,
597 env=newenv) as p:
598 stdout, stderr = p.communicate()
599 self.assertEqual(stdout, b"orange")
600
Victor Stinner62d51182011-06-23 01:02:25 +0200601 # Windows requires at least the SYSTEMROOT environment variable to start
602 # Python
603 @unittest.skipIf(sys.platform == 'win32',
604 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200605 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200606 'the python library cannot be loaded '
607 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200608 def test_empty_env(self):
609 with subprocess.Popen([sys.executable, "-c",
610 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200611 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200612 stdout=subprocess.PIPE,
613 env={}) as p:
614 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200615 self.assertIn(stdout.strip(),
616 (b"[]",
617 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
618 # environment
619 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000620
Peter Astrandcbac93c2005-03-03 20:24:28 +0000621 def test_communicate_stdin(self):
622 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000623 'import sys;'
624 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000625 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000626 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000627 self.assertEqual(p.returncode, 1)
628
629 def test_communicate_stdout(self):
630 p = subprocess.Popen([sys.executable, "-c",
631 'import sys; sys.stdout.write("pineapple")'],
632 stdout=subprocess.PIPE)
633 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000634 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000635 self.assertEqual(stderr, None)
636
637 def test_communicate_stderr(self):
638 p = subprocess.Popen([sys.executable, "-c",
639 'import sys; sys.stderr.write("pineapple")'],
640 stderr=subprocess.PIPE)
641 (stdout, stderr) = p.communicate()
642 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000643 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000644
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000645 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000647 'import sys,os;'
648 'sys.stderr.write("pineapple");'
649 'sys.stdout.write(sys.stdin.read())'],
650 stdin=subprocess.PIPE,
651 stdout=subprocess.PIPE,
652 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000653 self.addCleanup(p.stdout.close)
654 self.addCleanup(p.stderr.close)
655 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000656 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000657 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000658 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400660 def test_communicate_timeout(self):
661 p = subprocess.Popen([sys.executable, "-c",
662 'import sys,os,time;'
663 'sys.stderr.write("pineapple\\n");'
664 'time.sleep(1);'
665 'sys.stderr.write("pear\\n");'
666 'sys.stdout.write(sys.stdin.read())'],
667 universal_newlines=True,
668 stdin=subprocess.PIPE,
669 stdout=subprocess.PIPE,
670 stderr=subprocess.PIPE)
671 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
672 timeout=0.3)
673 # Make sure we can keep waiting for it, and that we get the whole output
674 # after it completes.
675 (stdout, stderr) = p.communicate()
676 self.assertEqual(stdout, "banana")
677 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
678
679 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200680 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400681 p = subprocess.Popen([sys.executable, "-c",
682 'import sys,os,time;'
683 'sys.stdout.write("a" * (64 * 1024));'
684 'time.sleep(0.2);'
685 'sys.stdout.write("a" * (64 * 1024));'
686 'time.sleep(0.2);'
687 'sys.stdout.write("a" * (64 * 1024));'
688 'time.sleep(0.2);'
689 'sys.stdout.write("a" * (64 * 1024));'],
690 stdout=subprocess.PIPE)
691 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
692 (stdout, _) = p.communicate()
693 self.assertEqual(len(stdout), 4 * 64 * 1024)
694
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000695 # Test for the fd leak reported in http://bugs.python.org/issue2791.
696 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000697 for stdin_pipe in (False, True):
698 for stdout_pipe in (False, True):
699 for stderr_pipe in (False, True):
700 options = {}
701 if stdin_pipe:
702 options['stdin'] = subprocess.PIPE
703 if stdout_pipe:
704 options['stdout'] = subprocess.PIPE
705 if stderr_pipe:
706 options['stderr'] = subprocess.PIPE
707 if not options:
708 continue
709 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
710 p.communicate()
711 if p.stdin is not None:
712 self.assertTrue(p.stdin.closed)
713 if p.stdout is not None:
714 self.assertTrue(p.stdout.closed)
715 if p.stderr is not None:
716 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000717
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000718 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000719 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000720 p = subprocess.Popen([sys.executable, "-c",
721 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000722 (stdout, stderr) = p.communicate()
723 self.assertEqual(stdout, None)
724 self.assertEqual(stderr, None)
725
726 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000727 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000728 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000729 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 os.close(x)
732 os.close(y)
733 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000734 'import sys,os;'
735 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200736 'sys.stderr.write("x" * %d);'
737 'sys.stdout.write(sys.stdin.read())' %
738 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000739 stdin=subprocess.PIPE,
740 stdout=subprocess.PIPE,
741 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000742 self.addCleanup(p.stdout.close)
743 self.addCleanup(p.stderr.close)
744 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200745 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000746 (stdout, stderr) = p.communicate(string_to_write)
747 self.assertEqual(stdout, string_to_write)
748
749 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000750 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000751 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000752 'import sys,os;'
753 'sys.stdout.write(sys.stdin.read())'],
754 stdin=subprocess.PIPE,
755 stdout=subprocess.PIPE,
756 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000757 self.addCleanup(p.stdout.close)
758 self.addCleanup(p.stderr.close)
759 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000760 p.stdin.write(b"banana")
761 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000762 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000763 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000764
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000765 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000767 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200768 'buf = sys.stdout.buffer;'
769 'buf.write(sys.stdin.readline().encode());'
770 'buf.flush();'
771 'buf.write(b"line2\\n");'
772 'buf.flush();'
773 'buf.write(sys.stdin.read().encode());'
774 'buf.flush();'
775 'buf.write(b"line4\\n");'
776 'buf.flush();'
777 'buf.write(b"line5\\r\\n");'
778 'buf.flush();'
779 'buf.write(b"line6\\r");'
780 'buf.flush();'
781 'buf.write(b"\\nline7");'
782 'buf.flush();'
783 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200784 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000785 stdout=subprocess.PIPE,
786 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200787 p.stdin.write("line1\n")
788 self.assertEqual(p.stdout.readline(), "line1\n")
789 p.stdin.write("line3\n")
790 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000791 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200792 self.assertEqual(p.stdout.readline(),
793 "line2\n")
794 self.assertEqual(p.stdout.read(6),
795 "line3\n")
796 self.assertEqual(p.stdout.read(),
797 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000798
799 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000800 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000801 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000802 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200803 'buf = sys.stdout.buffer;'
804 'buf.write(b"line2\\n");'
805 'buf.flush();'
806 'buf.write(b"line4\\n");'
807 'buf.flush();'
808 'buf.write(b"line5\\r\\n");'
809 'buf.flush();'
810 'buf.write(b"line6\\r");'
811 'buf.flush();'
812 'buf.write(b"\\nline7");'
813 'buf.flush();'
814 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200815 stderr=subprocess.PIPE,
816 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000817 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000818 self.addCleanup(p.stdout.close)
819 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000820 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200821 self.assertEqual(stdout,
822 "line2\nline4\nline5\nline6\nline7\nline8")
823
824 def test_universal_newlines_communicate_stdin(self):
825 # universal newlines through communicate(), with only stdin
826 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300827 'import sys,os;' + SETBINARY + textwrap.dedent('''
828 s = sys.stdin.readline()
829 assert s == "line1\\n", repr(s)
830 s = sys.stdin.read()
831 assert s == "line3\\n", repr(s)
832 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200833 stdin=subprocess.PIPE,
834 universal_newlines=1)
835 (stdout, stderr) = p.communicate("line1\nline3\n")
836 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000837
Andrew Svetlovf3765072012-08-14 18:35:17 +0300838 def test_universal_newlines_communicate_input_none(self):
839 # Test communicate(input=None) with universal newlines.
840 #
841 # We set stdout to PIPE because, as of this writing, a different
842 # code path is tested when the number of pipes is zero or one.
843 p = subprocess.Popen([sys.executable, "-c", "pass"],
844 stdin=subprocess.PIPE,
845 stdout=subprocess.PIPE,
846 universal_newlines=True)
847 p.communicate()
848 self.assertEqual(p.returncode, 0)
849
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300850 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300851 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300852 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300853 'import sys,os;' + SETBINARY + textwrap.dedent('''
854 s = sys.stdin.buffer.readline()
855 sys.stdout.buffer.write(s)
856 sys.stdout.buffer.write(b"line2\\r")
857 sys.stderr.buffer.write(b"eline2\\n")
858 s = sys.stdin.buffer.read()
859 sys.stdout.buffer.write(s)
860 sys.stdout.buffer.write(b"line4\\n")
861 sys.stdout.buffer.write(b"line5\\r\\n")
862 sys.stderr.buffer.write(b"eline6\\r")
863 sys.stderr.buffer.write(b"eline7\\r\\nz")
864 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300865 stdin=subprocess.PIPE,
866 stderr=subprocess.PIPE,
867 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300868 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300869 self.addCleanup(p.stdout.close)
870 self.addCleanup(p.stderr.close)
871 (stdout, stderr) = p.communicate("line1\nline3\n")
872 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300873 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300874 # Python debug build push something like "[42442 refs]\n"
875 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300876 # Don't use assertStderrEqual because it strips CR and LF from output.
877 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300878
Andrew Svetlov82860712012-08-19 22:13:41 +0300879 def test_universal_newlines_communicate_encodings(self):
880 # Check that universal newlines mode works for various encodings,
881 # in particular for encodings in the UTF-16 and UTF-32 families.
882 # See issue #15595.
883 #
884 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
885 # without, and UTF-16 and UTF-32.
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200886 import _bootlocale
Andrew Svetlov82860712012-08-19 22:13:41 +0300887 for encoding in ['utf-16', 'utf-32-be']:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200888 old_getpreferredencoding = _bootlocale.getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300889 # Indirectly via io.TextIOWrapper, Popen() defaults to
890 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
891 # locale.getpreferredencoding().
892 def getpreferredencoding(do_setlocale=True):
893 return encoding
894 code = ("import sys; "
895 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
896 encoding)
897 args = [sys.executable, '-c', code]
898 try:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200899 _bootlocale.getpreferredencoding = getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300900 # We set stdin to be non-None because, as of this writing,
901 # a different code path is used when the number of pipes is
902 # zero or one.
903 popen = subprocess.Popen(args, universal_newlines=True,
904 stdin=subprocess.PIPE,
905 stdout=subprocess.PIPE)
906 stdout, stderr = popen.communicate(input='')
907 finally:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200908 _bootlocale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300909 self.assertEqual(stdout, '1\n2\n3\n4')
910
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000911 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000912 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000913 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000914 max_handles = 1026 # too much for most UNIX systems
915 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000916 max_handles = 2050 # too much for (at least some) Windows setups
917 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400918 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000919 try:
920 for i in range(max_handles):
921 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400922 tmpfile = os.path.join(tmpdir, support.TESTFN)
923 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000924 except OSError as e:
925 if e.errno != errno.EMFILE:
926 raise
927 break
928 else:
929 self.skipTest("failed to reach the file descriptor limit "
930 "(tried %d)" % max_handles)
931 # Close a couple of them (should be enough for a subprocess)
932 for i in range(10):
933 os.close(handles.pop())
934 # Loop creating some subprocesses. If one of them leaks some fds,
935 # the next loop iteration will fail by reaching the max fd limit.
936 for i in range(15):
937 p = subprocess.Popen([sys.executable, "-c",
938 "import sys;"
939 "sys.stdout.write(sys.stdin.read())"],
940 stdin=subprocess.PIPE,
941 stdout=subprocess.PIPE,
942 stderr=subprocess.PIPE)
943 data = p.communicate(b"lime")[0]
944 self.assertEqual(data, b"lime")
945 finally:
946 for h in handles:
947 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400948 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000949
950 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000951 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
952 '"a b c" d e')
953 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
954 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000955 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
956 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000957 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
958 'a\\\\\\b "de fg" h')
959 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
960 'a\\\\\\"b c d')
961 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
962 '"a\\\\b c" d e')
963 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
964 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000965 self.assertEqual(subprocess.list2cmdline(['ab', '']),
966 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000967
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000968 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200969 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200970 "import os; os.read(0, 1)"],
971 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200972 self.addCleanup(p.stdin.close)
973 self.assertIsNone(p.poll())
974 os.write(p.stdin.fileno(), b'A')
975 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000976 # Subsequent invocations should just return the returncode
977 self.assertEqual(p.poll(), 0)
978
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000979 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200980 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000981 self.assertEqual(p.wait(), 0)
982 # Subsequent invocations should just return the returncode
983 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000984
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400985 def test_wait_timeout(self):
986 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200987 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400988 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200989 p.wait(timeout=0.0001)
990 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400991 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
992 # time to start.
993 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400994
Peter Astrand738131d2004-11-30 21:04:45 +0000995 def test_invalid_bufsize(self):
996 # an invalid type of the bufsize argument should raise
997 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000998 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000999 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001000
Guido van Rossum46a05a72007-06-07 21:56:45 +00001001 def test_bufsize_is_none(self):
1002 # bufsize=None should be the same as bufsize=0.
1003 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1004 self.assertEqual(p.wait(), 0)
1005 # Again with keyword arg
1006 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1007 self.assertEqual(p.wait(), 0)
1008
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001009 def test_leaking_fds_on_error(self):
1010 # see bug #5179: Popen leaks file descriptors to PIPEs if
1011 # the child fails to execute; this will eventually exhaust
1012 # the maximum number of open fds. 1024 seems a very common
1013 # value for that limit, but Windows has 2048, so we loop
1014 # 1024 times (each call leaked two fds).
1015 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001016 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001017 subprocess.Popen(['nonexisting_i_hope'],
1018 stdout=subprocess.PIPE,
1019 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001020 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001021 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001022 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001023
Antoine Pitroua8392712013-08-30 23:38:13 +02001024 @unittest.skipIf(threading is None, "threading required")
1025 def test_double_close_on_error(self):
1026 # Issue #18851
1027 fds = []
1028 def open_fds():
1029 for i in range(20):
1030 fds.extend(os.pipe())
1031 time.sleep(0.001)
1032 t = threading.Thread(target=open_fds)
1033 t.start()
1034 try:
1035 with self.assertRaises(EnvironmentError):
1036 subprocess.Popen(['nonexisting_i_hope'],
1037 stdin=subprocess.PIPE,
1038 stdout=subprocess.PIPE,
1039 stderr=subprocess.PIPE)
1040 finally:
1041 t.join()
1042 exc = None
1043 for fd in fds:
1044 # If a double close occurred, some of those fds will
1045 # already have been closed by mistake, and os.close()
1046 # here will raise.
1047 try:
1048 os.close(fd)
1049 except OSError as e:
1050 exc = e
1051 if exc is not None:
1052 raise exc
1053
Victor Stinnerb3693582010-05-21 20:13:12 +00001054 def test_issue8780(self):
1055 # Ensure that stdout is inherited from the parent
1056 # if stdout=PIPE is not used
1057 code = ';'.join((
1058 'import subprocess, sys',
1059 'retcode = subprocess.call('
1060 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1061 'assert retcode == 0'))
1062 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001063 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001064
Tim Goldenaf5ac392010-08-06 13:03:56 +00001065 def test_handles_closed_on_exception(self):
1066 # If CreateProcess exits with an error, ensure the
1067 # duplicate output handles are released
1068 ifhandle, ifname = mkstemp()
1069 ofhandle, ofname = mkstemp()
1070 efhandle, efname = mkstemp()
1071 try:
1072 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1073 stderr=efhandle)
1074 except OSError:
1075 os.close(ifhandle)
1076 os.remove(ifname)
1077 os.close(ofhandle)
1078 os.remove(ofname)
1079 os.close(efhandle)
1080 os.remove(efname)
1081 self.assertFalse(os.path.exists(ifname))
1082 self.assertFalse(os.path.exists(ofname))
1083 self.assertFalse(os.path.exists(efname))
1084
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001085 def test_communicate_epipe(self):
1086 # Issue 10963: communicate() should hide EPIPE
1087 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1088 stdin=subprocess.PIPE,
1089 stdout=subprocess.PIPE,
1090 stderr=subprocess.PIPE)
1091 self.addCleanup(p.stdout.close)
1092 self.addCleanup(p.stderr.close)
1093 self.addCleanup(p.stdin.close)
1094 p.communicate(b"x" * 2**20)
1095
1096 def test_communicate_epipe_only_stdin(self):
1097 # Issue 10963: communicate() should hide EPIPE
1098 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1099 stdin=subprocess.PIPE)
1100 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001101 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001102 p.communicate(b"x" * 2**20)
1103
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001104 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1105 "Requires signal.SIGUSR1")
1106 @unittest.skipUnless(hasattr(os, 'kill'),
1107 "Requires os.kill")
1108 @unittest.skipUnless(hasattr(os, 'getppid'),
1109 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001110 def test_communicate_eintr(self):
1111 # Issue #12493: communicate() should handle EINTR
1112 def handler(signum, frame):
1113 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001114 old_handler = signal.signal(signal.SIGUSR1, handler)
1115 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001116
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001117 args = [sys.executable, "-c",
1118 'import os, signal;'
1119 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001120 for stream in ('stdout', 'stderr'):
1121 kw = {stream: subprocess.PIPE}
1122 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001123 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001124 process.communicate()
1125
Tim Peterse718f612004-10-12 21:51:32 +00001126
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001127 # This test is Linux-ish specific for simplicity to at least have
1128 # some coverage. It is not a platform specific bug.
1129 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1130 "Linux specific")
1131 def test_failed_child_execute_fd_leak(self):
1132 """Test for the fork() failure fd leak reported in issue16327."""
1133 fd_directory = '/proc/%d/fd' % os.getpid()
1134 fds_before_popen = os.listdir(fd_directory)
1135 with self.assertRaises(PopenTestException):
1136 PopenExecuteChildRaises(
1137 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1138 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1139
1140 # NOTE: This test doesn't verify that the real _execute_child
1141 # does not close the file descriptors itself on the way out
1142 # during an exception. Code inspection has confirmed that.
1143
1144 fds_after_exception = os.listdir(fd_directory)
1145 self.assertEqual(fds_before_popen, fds_after_exception)
1146
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001147@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001148class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001149
Gregory P. Smith5591b022012-10-10 03:34:47 -07001150 def setUp(self):
1151 super().setUp()
1152 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1153
1154 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001155 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001156 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001157 except OSError as e:
1158 # This avoids hard coding the errno value or the OS perror()
1159 # string and instead capture the exception that we want to see
1160 # below for comparison.
1161 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001162 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001163 else:
1164 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001165 self._nonexistent_dir)
1166 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001167
Gregory P. Smith5591b022012-10-10 03:34:47 -07001168 def test_exception_cwd(self):
1169 """Test error in the child raised in the parent for a bad cwd."""
1170 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001171 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001172 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001173 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001174 except OSError as e:
1175 # Test that the child process chdir failure actually makes
1176 # it up to the parent process as the correct exception.
1177 self.assertEqual(desired_exception.errno, e.errno)
1178 self.assertEqual(desired_exception.strerror, e.strerror)
1179 else:
1180 self.fail("Expected OSError: %s" % desired_exception)
1181
Gregory P. Smith5591b022012-10-10 03:34:47 -07001182 def test_exception_bad_executable(self):
1183 """Test error in the child raised in the parent for a bad executable."""
1184 desired_exception = self._get_chdir_exception()
1185 try:
1186 p = subprocess.Popen([sys.executable, "-c", ""],
1187 executable=self._nonexistent_dir)
1188 except OSError as e:
1189 # Test that the child process exec failure actually makes
1190 # it up to the parent process as the correct exception.
1191 self.assertEqual(desired_exception.errno, e.errno)
1192 self.assertEqual(desired_exception.strerror, e.strerror)
1193 else:
1194 self.fail("Expected OSError: %s" % desired_exception)
1195
1196 def test_exception_bad_args_0(self):
1197 """Test error in the child raised in the parent for a bad args[0]."""
1198 desired_exception = self._get_chdir_exception()
1199 try:
1200 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1201 except OSError as e:
1202 # Test that the child process exec failure actually makes
1203 # it up to the parent process as the correct exception.
1204 self.assertEqual(desired_exception.errno, e.errno)
1205 self.assertEqual(desired_exception.strerror, e.strerror)
1206 else:
1207 self.fail("Expected OSError: %s" % desired_exception)
1208
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001209 def test_restore_signals(self):
1210 # Code coverage for both values of restore_signals to make sure it
1211 # at least does not blow up.
1212 # A test for behavior would be complex. Contributions welcome.
1213 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1214 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1215
1216 def test_start_new_session(self):
1217 # For code coverage of calling setsid(). We don't care if we get an
1218 # EPERM error from it depending on the test execution environment, that
1219 # still indicates that it was called.
1220 try:
1221 output = subprocess.check_output(
1222 [sys.executable, "-c",
1223 "import os; print(os.getpgid(os.getpid()))"],
1224 start_new_session=True)
1225 except OSError as e:
1226 if e.errno != errno.EPERM:
1227 raise
1228 else:
1229 parent_pgid = os.getpgid(os.getpid())
1230 child_pgid = int(output)
1231 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001232
1233 def test_run_abort(self):
1234 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001235 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001236 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001237 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001238 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001239 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001240
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001241 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001242 # DISCLAIMER: Setting environment variables is *not* a good use
1243 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001244 p = subprocess.Popen([sys.executable, "-c",
1245 'import sys,os;'
1246 'sys.stdout.write(os.getenv("FRUIT"))'],
1247 stdout=subprocess.PIPE,
1248 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001249 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001250 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001251
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001252 def test_preexec_exception(self):
1253 def raise_it():
1254 raise ValueError("What if two swallows carried a coconut?")
1255 try:
1256 p = subprocess.Popen([sys.executable, "-c", ""],
1257 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001258 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001259 self.assertTrue(
1260 subprocess._posixsubprocess,
1261 "Expected a ValueError from the preexec_fn")
1262 except ValueError as e:
1263 self.assertIn("coconut", e.args[0])
1264 else:
1265 self.fail("Exception raised by preexec_fn did not make it "
1266 "to the parent process.")
1267
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001268 class _TestExecuteChildPopen(subprocess.Popen):
1269 """Used to test behavior at the end of _execute_child."""
1270 def __init__(self, testcase, *args, **kwargs):
1271 self._testcase = testcase
1272 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001273
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001274 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001275 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001276 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001277 finally:
1278 # Open a bunch of file descriptors and verify that
1279 # none of them are the same as the ones the Popen
1280 # instance is using for stdin/stdout/stderr.
1281 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1282 for _ in range(8)]
1283 try:
1284 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001285 self._testcase.assertNotIn(
1286 fd, (self.stdin.fileno(), self.stdout.fileno(),
1287 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001288 msg="At least one fd was closed early.")
1289 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001290 for fd in devzero_fds:
1291 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001292
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001293 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1294 def test_preexec_errpipe_does_not_double_close_pipes(self):
1295 """Issue16140: Don't double close pipes on preexec error."""
1296
1297 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001298 raise subprocess.SubprocessError(
1299 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001300
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001301 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001302 self._TestExecuteChildPopen(
1303 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001304 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1305 stderr=subprocess.PIPE, preexec_fn=raise_it)
1306
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001307 def test_preexec_gc_module_failure(self):
1308 # This tests the code that disables garbage collection if the child
1309 # process will execute any Python.
1310 def raise_runtime_error():
1311 raise RuntimeError("this shouldn't escape")
1312 enabled = gc.isenabled()
1313 orig_gc_disable = gc.disable
1314 orig_gc_isenabled = gc.isenabled
1315 try:
1316 gc.disable()
1317 self.assertFalse(gc.isenabled())
1318 subprocess.call([sys.executable, '-c', ''],
1319 preexec_fn=lambda: None)
1320 self.assertFalse(gc.isenabled(),
1321 "Popen enabled gc when it shouldn't.")
1322
1323 gc.enable()
1324 self.assertTrue(gc.isenabled())
1325 subprocess.call([sys.executable, '-c', ''],
1326 preexec_fn=lambda: None)
1327 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1328
1329 gc.disable = raise_runtime_error
1330 self.assertRaises(RuntimeError, subprocess.Popen,
1331 [sys.executable, '-c', ''],
1332 preexec_fn=lambda: None)
1333
1334 del gc.isenabled # force an AttributeError
1335 self.assertRaises(AttributeError, subprocess.Popen,
1336 [sys.executable, '-c', ''],
1337 preexec_fn=lambda: None)
1338 finally:
1339 gc.disable = orig_gc_disable
1340 gc.isenabled = orig_gc_isenabled
1341 if not enabled:
1342 gc.disable()
1343
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001344 def test_args_string(self):
1345 # args is a string
1346 fd, fname = mkstemp()
1347 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001348 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001349 fobj.write("#!/bin/sh\n")
1350 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1351 sys.executable)
1352 os.chmod(fname, 0o700)
1353 p = subprocess.Popen(fname)
1354 p.wait()
1355 os.remove(fname)
1356 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001357
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001358 def test_invalid_args(self):
1359 # invalid arguments should raise ValueError
1360 self.assertRaises(ValueError, subprocess.call,
1361 [sys.executable, "-c",
1362 "import sys; sys.exit(47)"],
1363 startupinfo=47)
1364 self.assertRaises(ValueError, subprocess.call,
1365 [sys.executable, "-c",
1366 "import sys; sys.exit(47)"],
1367 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001368
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001369 def test_shell_sequence(self):
1370 # Run command through the shell (sequence)
1371 newenv = os.environ.copy()
1372 newenv["FRUIT"] = "apple"
1373 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1374 stdout=subprocess.PIPE,
1375 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001376 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001377 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001378
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001379 def test_shell_string(self):
1380 # Run command through the shell (string)
1381 newenv = os.environ.copy()
1382 newenv["FRUIT"] = "apple"
1383 p = subprocess.Popen("echo $FRUIT", shell=1,
1384 stdout=subprocess.PIPE,
1385 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001386 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001387 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001388
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001389 def test_call_string(self):
1390 # call() function with string argument on UNIX
1391 fd, fname = mkstemp()
1392 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001393 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001394 fobj.write("#!/bin/sh\n")
1395 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1396 sys.executable)
1397 os.chmod(fname, 0o700)
1398 rc = subprocess.call(fname)
1399 os.remove(fname)
1400 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001401
Stefan Krah9542cc62010-07-19 14:20:53 +00001402 def test_specific_shell(self):
1403 # Issue #9265: Incorrect name passed as arg[0].
1404 shells = []
1405 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1406 for name in ['bash', 'ksh']:
1407 sh = os.path.join(prefix, name)
1408 if os.path.isfile(sh):
1409 shells.append(sh)
1410 if not shells: # Will probably work for any shell but csh.
1411 self.skipTest("bash or ksh required for this test")
1412 sh = '/bin/sh'
1413 if os.path.isfile(sh) and not os.path.islink(sh):
1414 # Test will fail if /bin/sh is a symlink to csh.
1415 shells.append(sh)
1416 for sh in shells:
1417 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1418 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001419 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001420 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1421
Florent Xicluna4886d242010-03-08 13:27:26 +00001422 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001423 # Do not inherit file handles from the parent.
1424 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001425 # Also set the SIGINT handler to the default to make sure it's not
1426 # being ignored (some tests rely on that.)
1427 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1428 try:
1429 p = subprocess.Popen([sys.executable, "-c", """if 1:
1430 import sys, time
1431 sys.stdout.write('x\\n')
1432 sys.stdout.flush()
1433 time.sleep(30)
1434 """],
1435 close_fds=True,
1436 stdin=subprocess.PIPE,
1437 stdout=subprocess.PIPE,
1438 stderr=subprocess.PIPE)
1439 finally:
1440 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001441 # Wait for the interpreter to be completely initialized before
1442 # sending any signal.
1443 p.stdout.read(1)
1444 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001445 return p
1446
Charles-François Natali53221e32013-01-12 16:52:20 +01001447 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1448 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001449 def _kill_dead_process(self, method, *args):
1450 # Do not inherit file handles from the parent.
1451 # It should fix failures on some platforms.
1452 p = subprocess.Popen([sys.executable, "-c", """if 1:
1453 import sys, time
1454 sys.stdout.write('x\\n')
1455 sys.stdout.flush()
1456 """],
1457 close_fds=True,
1458 stdin=subprocess.PIPE,
1459 stdout=subprocess.PIPE,
1460 stderr=subprocess.PIPE)
1461 # Wait for the interpreter to be completely initialized before
1462 # sending any signal.
1463 p.stdout.read(1)
1464 # The process should end after this
1465 time.sleep(1)
1466 # This shouldn't raise even though the child is now dead
1467 getattr(p, method)(*args)
1468 p.communicate()
1469
Florent Xicluna4886d242010-03-08 13:27:26 +00001470 def test_send_signal(self):
1471 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001472 _, stderr = p.communicate()
1473 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001474 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001475
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001476 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001477 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001478 _, stderr = p.communicate()
1479 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001480 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001481
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001482 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001483 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001484 _, stderr = p.communicate()
1485 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001486 self.assertEqual(p.wait(), -signal.SIGTERM)
1487
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001488 def test_send_signal_dead(self):
1489 # Sending a signal to a dead process
1490 self._kill_dead_process('send_signal', signal.SIGINT)
1491
1492 def test_kill_dead(self):
1493 # Killing a dead process
1494 self._kill_dead_process('kill')
1495
1496 def test_terminate_dead(self):
1497 # Terminating a dead process
1498 self._kill_dead_process('terminate')
1499
Victor Stinnerdaf45552013-08-28 00:53:59 +02001500 def _save_fds(self, save_fds):
1501 fds = []
1502 for fd in save_fds:
1503 inheritable = os.get_inheritable(fd)
1504 saved = os.dup(fd)
1505 fds.append((fd, saved, inheritable))
1506 return fds
1507
1508 def _restore_fds(self, fds):
1509 for fd, saved, inheritable in fds:
1510 os.dup2(saved, fd, inheritable=inheritable)
1511 os.close(saved)
1512
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001513 def check_close_std_fds(self, fds):
1514 # Issue #9905: test that subprocess pipes still work properly with
1515 # some standard fds closed
1516 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001517 saved_fds = self._save_fds(fds)
1518 for fd, saved, inheritable in saved_fds:
1519 if fd == 0:
1520 stdin = saved
1521 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001522 try:
1523 for fd in fds:
1524 os.close(fd)
1525 out, err = subprocess.Popen([sys.executable, "-c",
1526 'import sys;'
1527 'sys.stdout.write("apple");'
1528 'sys.stdout.flush();'
1529 'sys.stderr.write("orange")'],
1530 stdin=stdin,
1531 stdout=subprocess.PIPE,
1532 stderr=subprocess.PIPE).communicate()
1533 err = support.strip_python_stderr(err)
1534 self.assertEqual((out, err), (b'apple', b'orange'))
1535 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001536 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001537
1538 def test_close_fd_0(self):
1539 self.check_close_std_fds([0])
1540
1541 def test_close_fd_1(self):
1542 self.check_close_std_fds([1])
1543
1544 def test_close_fd_2(self):
1545 self.check_close_std_fds([2])
1546
1547 def test_close_fds_0_1(self):
1548 self.check_close_std_fds([0, 1])
1549
1550 def test_close_fds_0_2(self):
1551 self.check_close_std_fds([0, 2])
1552
1553 def test_close_fds_1_2(self):
1554 self.check_close_std_fds([1, 2])
1555
1556 def test_close_fds_0_1_2(self):
1557 # Issue #10806: test that subprocess pipes still work properly with
1558 # all standard fds closed.
1559 self.check_close_std_fds([0, 1, 2])
1560
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001561 def test_remapping_std_fds(self):
1562 # open up some temporary files
1563 temps = [mkstemp() for i in range(3)]
1564 try:
1565 temp_fds = [fd for fd, fname in temps]
1566
1567 # unlink the files -- we won't need to reopen them
1568 for fd, fname in temps:
1569 os.unlink(fname)
1570
1571 # write some data to what will become stdin, and rewind
1572 os.write(temp_fds[1], b"STDIN")
1573 os.lseek(temp_fds[1], 0, 0)
1574
1575 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001576 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001577 try:
1578 # duplicate the file objects over the standard fd's
1579 for fd, temp_fd in enumerate(temp_fds):
1580 os.dup2(temp_fd, fd)
1581
1582 # now use those files in the "wrong" order, so that subprocess
1583 # has to rearrange them in the child
1584 p = subprocess.Popen([sys.executable, "-c",
1585 'import sys; got = sys.stdin.read();'
1586 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1587 stdin=temp_fds[1],
1588 stdout=temp_fds[2],
1589 stderr=temp_fds[0])
1590 p.wait()
1591 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001592 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001593
1594 for fd in temp_fds:
1595 os.lseek(fd, 0, 0)
1596
1597 out = os.read(temp_fds[2], 1024)
1598 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1599 self.assertEqual(out, b"got STDIN")
1600 self.assertEqual(err, b"err")
1601
1602 finally:
1603 for fd in temp_fds:
1604 os.close(fd)
1605
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001606 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1607 # open up some temporary files
1608 temps = [mkstemp() for i in range(3)]
1609 temp_fds = [fd for fd, fname in temps]
1610 try:
1611 # unlink the files -- we won't need to reopen them
1612 for fd, fname in temps:
1613 os.unlink(fname)
1614
1615 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001616 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001617 try:
1618 # duplicate the temp files over the standard fd's 0, 1, 2
1619 for fd, temp_fd in enumerate(temp_fds):
1620 os.dup2(temp_fd, fd)
1621
1622 # write some data to what will become stdin, and rewind
1623 os.write(stdin_no, b"STDIN")
1624 os.lseek(stdin_no, 0, 0)
1625
1626 # now use those files in the given order, so that subprocess
1627 # has to rearrange them in the child
1628 p = subprocess.Popen([sys.executable, "-c",
1629 'import sys; got = sys.stdin.read();'
1630 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1631 stdin=stdin_no,
1632 stdout=stdout_no,
1633 stderr=stderr_no)
1634 p.wait()
1635
1636 for fd in temp_fds:
1637 os.lseek(fd, 0, 0)
1638
1639 out = os.read(stdout_no, 1024)
1640 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1641 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001642 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001643
1644 self.assertEqual(out, b"got STDIN")
1645 self.assertEqual(err, b"err")
1646
1647 finally:
1648 for fd in temp_fds:
1649 os.close(fd)
1650
1651 # When duping fds, if there arises a situation where one of the fds is
1652 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1653 # This tests all combinations of this.
1654 def test_swap_fds(self):
1655 self.check_swap_fds(0, 1, 2)
1656 self.check_swap_fds(0, 2, 1)
1657 self.check_swap_fds(1, 0, 2)
1658 self.check_swap_fds(1, 2, 0)
1659 self.check_swap_fds(2, 0, 1)
1660 self.check_swap_fds(2, 1, 0)
1661
Victor Stinner13bb71c2010-04-23 21:41:56 +00001662 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001663 def prepare():
1664 raise ValueError("surrogate:\uDCff")
1665
1666 try:
1667 subprocess.call(
1668 [sys.executable, "-c", "pass"],
1669 preexec_fn=prepare)
1670 except ValueError as err:
1671 # Pure Python implementations keeps the message
1672 self.assertIsNone(subprocess._posixsubprocess)
1673 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001674 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001675 # _posixsubprocess uses a default message
1676 self.assertIsNotNone(subprocess._posixsubprocess)
1677 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1678 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001679 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001680
Victor Stinner13bb71c2010-04-23 21:41:56 +00001681 def test_undecodable_env(self):
1682 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001683 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001684 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001685 env = os.environ.copy()
1686 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001687 # Use C locale to get ascii for the locale encoding to force
1688 # surrogate-escaping of \xFF in the child process; otherwise it can
1689 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001690 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001691 stdout = subprocess.check_output(
1692 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001693 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001694 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001695 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001696
1697 # test bytes
1698 key = key.encode("ascii", "surrogateescape")
1699 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001700 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001701 env = os.environ.copy()
1702 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001703 stdout = subprocess.check_output(
1704 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001705 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001706 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001707 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001708
Victor Stinnerb745a742010-05-18 17:17:23 +00001709 def test_bytes_program(self):
1710 abs_program = os.fsencode(sys.executable)
1711 path, program = os.path.split(sys.executable)
1712 program = os.fsencode(program)
1713
1714 # absolute bytes path
1715 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001716 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001717
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001718 # absolute bytes path as a string
1719 cmd = b"'" + abs_program + b"' -c pass"
1720 exitcode = subprocess.call(cmd, shell=True)
1721 self.assertEqual(exitcode, 0)
1722
Victor Stinnerb745a742010-05-18 17:17:23 +00001723 # bytes program, unicode PATH
1724 env = os.environ.copy()
1725 env["PATH"] = path
1726 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001727 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001728
1729 # bytes program, bytes PATH
1730 envb = os.environb.copy()
1731 envb[b"PATH"] = os.fsencode(path)
1732 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001733 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001734
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001735 def test_pipe_cloexec(self):
1736 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1737 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1738
1739 p1 = subprocess.Popen([sys.executable, sleeper],
1740 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1741 stderr=subprocess.PIPE, close_fds=False)
1742
1743 self.addCleanup(p1.communicate, b'')
1744
1745 p2 = subprocess.Popen([sys.executable, fd_status],
1746 stdout=subprocess.PIPE, close_fds=False)
1747
1748 output, error = p2.communicate()
1749 result_fds = set(map(int, output.split(b',')))
1750 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1751 p1.stderr.fileno()])
1752
1753 self.assertFalse(result_fds & unwanted_fds,
1754 "Expected no fds from %r to be open in child, "
1755 "found %r" %
1756 (unwanted_fds, result_fds & unwanted_fds))
1757
1758 def test_pipe_cloexec_real_tools(self):
1759 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1760 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1761
1762 subdata = b'zxcvbn'
1763 data = subdata * 4 + b'\n'
1764
1765 p1 = subprocess.Popen([sys.executable, qcat],
1766 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1767 close_fds=False)
1768
1769 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1770 stdin=p1.stdout, stdout=subprocess.PIPE,
1771 close_fds=False)
1772
1773 self.addCleanup(p1.wait)
1774 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001775 def kill_p1():
1776 try:
1777 p1.terminate()
1778 except ProcessLookupError:
1779 pass
1780 def kill_p2():
1781 try:
1782 p2.terminate()
1783 except ProcessLookupError:
1784 pass
1785 self.addCleanup(kill_p1)
1786 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001787
1788 p1.stdin.write(data)
1789 p1.stdin.close()
1790
1791 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1792
1793 self.assertTrue(readfiles, "The child hung")
1794 self.assertEqual(p2.stdout.read(), data)
1795
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001796 p1.stdout.close()
1797 p2.stdout.close()
1798
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001799 def test_close_fds(self):
1800 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1801
1802 fds = os.pipe()
1803 self.addCleanup(os.close, fds[0])
1804 self.addCleanup(os.close, fds[1])
1805
1806 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001807 # add a bunch more fds
1808 for _ in range(9):
1809 fd = os.open("/dev/null", os.O_RDONLY)
1810 self.addCleanup(os.close, fd)
1811 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001812
Victor Stinnerdaf45552013-08-28 00:53:59 +02001813 for fd in open_fds:
1814 os.set_inheritable(fd, True)
1815
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001816 p = subprocess.Popen([sys.executable, fd_status],
1817 stdout=subprocess.PIPE, close_fds=False)
1818 output, ignored = p.communicate()
1819 remaining_fds = set(map(int, output.split(b',')))
1820
1821 self.assertEqual(remaining_fds & open_fds, open_fds,
1822 "Some fds were closed")
1823
1824 p = subprocess.Popen([sys.executable, fd_status],
1825 stdout=subprocess.PIPE, close_fds=True)
1826 output, ignored = p.communicate()
1827 remaining_fds = set(map(int, output.split(b',')))
1828
1829 self.assertFalse(remaining_fds & open_fds,
1830 "Some fds were left open")
1831 self.assertIn(1, remaining_fds, "Subprocess failed")
1832
Gregory P. Smith8facece2012-01-21 14:01:08 -08001833 # Keep some of the fd's we opened open in the subprocess.
1834 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1835 fds_to_keep = set(open_fds.pop() for _ in range(8))
1836 p = subprocess.Popen([sys.executable, fd_status],
1837 stdout=subprocess.PIPE, close_fds=True,
1838 pass_fds=())
1839 output, ignored = p.communicate()
1840 remaining_fds = set(map(int, output.split(b',')))
1841
1842 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1843 "Some fds not in pass_fds were left open")
1844 self.assertIn(1, remaining_fds, "Subprocess failed")
1845
Victor Stinner88701e22011-06-01 13:13:04 +02001846 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1847 # descriptor of a pipe closed in the parent process is valid in the
1848 # child process according to fstat(), but the mode of the file
1849 # descriptor is invalid, and read or write raise an error.
1850 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001851 def test_pass_fds(self):
1852 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1853
1854 open_fds = set()
1855
1856 for x in range(5):
1857 fds = os.pipe()
1858 self.addCleanup(os.close, fds[0])
1859 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02001860 os.set_inheritable(fds[0], True)
1861 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001862 open_fds.update(fds)
1863
1864 for fd in open_fds:
1865 p = subprocess.Popen([sys.executable, fd_status],
1866 stdout=subprocess.PIPE, close_fds=True,
1867 pass_fds=(fd, ))
1868 output, ignored = p.communicate()
1869
1870 remaining_fds = set(map(int, output.split(b',')))
1871 to_be_closed = open_fds - {fd}
1872
1873 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1874 self.assertFalse(remaining_fds & to_be_closed,
1875 "fd to be closed passed")
1876
1877 # pass_fds overrides close_fds with a warning.
1878 with self.assertWarns(RuntimeWarning) as context:
1879 self.assertFalse(subprocess.call(
1880 [sys.executable, "-c", "import sys; sys.exit(0)"],
1881 close_fds=False, pass_fds=(fd, )))
1882 self.assertIn('overriding close_fds', str(context.warning))
1883
Victor Stinnerdaf45552013-08-28 00:53:59 +02001884 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02001885 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02001886
1887 inheritable, non_inheritable = os.pipe()
1888 self.addCleanup(os.close, inheritable)
1889 self.addCleanup(os.close, non_inheritable)
1890 os.set_inheritable(inheritable, True)
1891 os.set_inheritable(non_inheritable, False)
1892 pass_fds = (inheritable, non_inheritable)
1893 args = [sys.executable, script]
1894 args += list(map(str, pass_fds))
1895
1896 p = subprocess.Popen(args,
1897 stdout=subprocess.PIPE, close_fds=True,
1898 pass_fds=pass_fds)
1899 output, ignored = p.communicate()
1900 fds = set(map(int, output.split(b',')))
1901
1902 # the inheritable file descriptor must be inherited, so its inheritable
1903 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02001904 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02001905
1906 # inheritable flag must not be changed in the parent process
1907 self.assertEqual(os.get_inheritable(inheritable), True)
1908 self.assertEqual(os.get_inheritable(non_inheritable), False)
1909
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001910 def test_stdout_stdin_are_single_inout_fd(self):
1911 with io.open(os.devnull, "r+") as inout:
1912 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1913 stdout=inout, stdin=inout)
1914 p.wait()
1915
1916 def test_stdout_stderr_are_single_inout_fd(self):
1917 with io.open(os.devnull, "r+") as inout:
1918 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1919 stdout=inout, stderr=inout)
1920 p.wait()
1921
1922 def test_stderr_stdin_are_single_inout_fd(self):
1923 with io.open(os.devnull, "r+") as inout:
1924 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1925 stderr=inout, stdin=inout)
1926 p.wait()
1927
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001928 def test_wait_when_sigchild_ignored(self):
1929 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1930 sigchild_ignore = support.findfile("sigchild_ignore.py",
1931 subdir="subprocessdata")
1932 p = subprocess.Popen([sys.executable, sigchild_ignore],
1933 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1934 stdout, stderr = p.communicate()
1935 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001936 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001937 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001938
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001939 def test_select_unbuffered(self):
1940 # Issue #11459: bufsize=0 should really set the pipes as
1941 # unbuffered (and therefore let select() work properly).
1942 select = support.import_module("select")
1943 p = subprocess.Popen([sys.executable, "-c",
1944 'import sys;'
1945 'sys.stdout.write("apple")'],
1946 stdout=subprocess.PIPE,
1947 bufsize=0)
1948 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001949 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001950 try:
1951 self.assertEqual(f.read(4), b"appl")
1952 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1953 finally:
1954 p.wait()
1955
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001956 def test_zombie_fast_process_del(self):
1957 # Issue #12650: on Unix, if Popen.__del__() was called before the
1958 # process exited, it wouldn't be added to subprocess._active, and would
1959 # remain a zombie.
1960 # spawn a Popen, and delete its reference before it exits
1961 p = subprocess.Popen([sys.executable, "-c",
1962 'import sys, time;'
1963 'time.sleep(0.2)'],
1964 stdout=subprocess.PIPE,
1965 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001966 self.addCleanup(p.stdout.close)
1967 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001968 ident = id(p)
1969 pid = p.pid
1970 del p
1971 # check that p is in the active processes list
1972 self.assertIn(ident, [id(o) for o in subprocess._active])
1973
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001974 def test_leak_fast_process_del_killed(self):
1975 # Issue #12650: on Unix, if Popen.__del__() was called before the
1976 # process exited, and the process got killed by a signal, it would never
1977 # be removed from subprocess._active, which triggered a FD and memory
1978 # leak.
1979 # spawn a Popen, delete its reference and kill it
1980 p = subprocess.Popen([sys.executable, "-c",
1981 'import time;'
1982 'time.sleep(3)'],
1983 stdout=subprocess.PIPE,
1984 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001985 self.addCleanup(p.stdout.close)
1986 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001987 ident = id(p)
1988 pid = p.pid
1989 del p
1990 os.kill(pid, signal.SIGKILL)
1991 # check that p is in the active processes list
1992 self.assertIn(ident, [id(o) for o in subprocess._active])
1993
1994 # let some time for the process to exit, and create a new Popen: this
1995 # should trigger the wait() of p
1996 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001997 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001998 with subprocess.Popen(['nonexisting_i_hope'],
1999 stdout=subprocess.PIPE,
2000 stderr=subprocess.PIPE) as proc:
2001 pass
2002 # p should have been wait()ed on, and removed from the _active list
2003 self.assertRaises(OSError, os.waitpid, pid, 0)
2004 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2005
Charles-François Natali249cdc32013-08-25 18:24:45 +02002006 def test_close_fds_after_preexec(self):
2007 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2008
2009 # this FD is used as dup2() target by preexec_fn, and should be closed
2010 # in the child process
2011 fd = os.dup(1)
2012 self.addCleanup(os.close, fd)
2013
2014 p = subprocess.Popen([sys.executable, fd_status],
2015 stdout=subprocess.PIPE, close_fds=True,
2016 preexec_fn=lambda: os.dup2(1, fd))
2017 output, ignored = p.communicate()
2018
2019 remaining_fds = set(map(int, output.split(b',')))
2020
2021 self.assertNotIn(fd, remaining_fds)
2022
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002023
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002024@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002025class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002026
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002027 def test_startupinfo(self):
2028 # startupinfo argument
2029 # We uses hardcoded constants, because we do not want to
2030 # depend on win32all.
2031 STARTF_USESHOWWINDOW = 1
2032 SW_MAXIMIZE = 3
2033 startupinfo = subprocess.STARTUPINFO()
2034 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2035 startupinfo.wShowWindow = SW_MAXIMIZE
2036 # Since Python is a console process, it won't be affected
2037 # by wShowWindow, but the argument should be silently
2038 # ignored
2039 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002040 startupinfo=startupinfo)
2041
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002042 def test_creationflags(self):
2043 # creationflags argument
2044 CREATE_NEW_CONSOLE = 16
2045 sys.stderr.write(" a DOS box should flash briefly ...\n")
2046 subprocess.call(sys.executable +
2047 ' -c "import time; time.sleep(0.25)"',
2048 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002049
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002050 def test_invalid_args(self):
2051 # invalid arguments should raise ValueError
2052 self.assertRaises(ValueError, subprocess.call,
2053 [sys.executable, "-c",
2054 "import sys; sys.exit(47)"],
2055 preexec_fn=lambda: 1)
2056 self.assertRaises(ValueError, subprocess.call,
2057 [sys.executable, "-c",
2058 "import sys; sys.exit(47)"],
2059 stdout=subprocess.PIPE,
2060 close_fds=True)
2061
2062 def test_close_fds(self):
2063 # close file descriptors
2064 rc = subprocess.call([sys.executable, "-c",
2065 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002066 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002067 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002068
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002069 def test_shell_sequence(self):
2070 # Run command through the shell (sequence)
2071 newenv = os.environ.copy()
2072 newenv["FRUIT"] = "physalis"
2073 p = subprocess.Popen(["set"], shell=1,
2074 stdout=subprocess.PIPE,
2075 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002076 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002077 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002078
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002079 def test_shell_string(self):
2080 # Run command through the shell (string)
2081 newenv = os.environ.copy()
2082 newenv["FRUIT"] = "physalis"
2083 p = subprocess.Popen("set", shell=1,
2084 stdout=subprocess.PIPE,
2085 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002086 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002087 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002088
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002089 def test_call_string(self):
2090 # call() function with string argument on Windows
2091 rc = subprocess.call(sys.executable +
2092 ' -c "import sys; sys.exit(47)"')
2093 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002094
Florent Xicluna4886d242010-03-08 13:27:26 +00002095 def _kill_process(self, method, *args):
2096 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002097 p = subprocess.Popen([sys.executable, "-c", """if 1:
2098 import sys, time
2099 sys.stdout.write('x\\n')
2100 sys.stdout.flush()
2101 time.sleep(30)
2102 """],
2103 stdin=subprocess.PIPE,
2104 stdout=subprocess.PIPE,
2105 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00002106 self.addCleanup(p.stdout.close)
2107 self.addCleanup(p.stderr.close)
2108 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00002109 # Wait for the interpreter to be completely initialized before
2110 # sending any signal.
2111 p.stdout.read(1)
2112 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00002113 _, stderr = p.communicate()
2114 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00002115 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002116 self.assertNotEqual(returncode, 0)
2117
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002118 def _kill_dead_process(self, method, *args):
2119 p = subprocess.Popen([sys.executable, "-c", """if 1:
2120 import sys, time
2121 sys.stdout.write('x\\n')
2122 sys.stdout.flush()
2123 sys.exit(42)
2124 """],
2125 stdin=subprocess.PIPE,
2126 stdout=subprocess.PIPE,
2127 stderr=subprocess.PIPE)
2128 self.addCleanup(p.stdout.close)
2129 self.addCleanup(p.stderr.close)
2130 self.addCleanup(p.stdin.close)
2131 # Wait for the interpreter to be completely initialized before
2132 # sending any signal.
2133 p.stdout.read(1)
2134 # The process should end after this
2135 time.sleep(1)
2136 # This shouldn't raise even though the child is now dead
2137 getattr(p, method)(*args)
2138 _, stderr = p.communicate()
2139 self.assertStderrEqual(stderr, b'')
2140 rc = p.wait()
2141 self.assertEqual(rc, 42)
2142
Florent Xicluna4886d242010-03-08 13:27:26 +00002143 def test_send_signal(self):
2144 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002145
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002146 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002147 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002148
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002149 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002150 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002151
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002152 def test_send_signal_dead(self):
2153 self._kill_dead_process('send_signal', signal.SIGTERM)
2154
2155 def test_kill_dead(self):
2156 self._kill_dead_process('kill')
2157
2158 def test_terminate_dead(self):
2159 self._kill_dead_process('terminate')
2160
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002161
Brett Cannona23810f2008-05-26 19:04:21 +00002162# The module says:
2163# "NB This only works (and is only relevant) for UNIX."
2164#
2165# Actually, getoutput should work on any platform with an os.popen, but
2166# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002167@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002168class CommandTests(unittest.TestCase):
2169 def test_getoutput(self):
2170 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2171 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2172 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002173
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002174 # we use mkdtemp in the next line to create an empty directory
2175 # under our exclusive control; from that, we can invent a pathname
2176 # that we _know_ won't exist. This is guaranteed to fail.
2177 dir = None
2178 try:
2179 dir = tempfile.mkdtemp()
2180 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00002181
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002182 status, output = subprocess.getstatusoutput('cat ' + name)
2183 self.assertNotEqual(status, 0)
2184 finally:
2185 if dir is not None:
2186 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002187
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002188
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002189@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
2190 "poll system call not supported")
2191class ProcessTestCaseNoPoll(ProcessTestCase):
2192 def setUp(self):
2193 subprocess._has_poll = False
2194 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002195
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002196 def tearDown(self):
2197 subprocess._has_poll = True
2198 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002199
2200
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002201class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00002202 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002203 def test_eintr_retry_call(self):
2204 record_calls = []
2205 def fake_os_func(*args):
2206 record_calls.append(args)
2207 if len(record_calls) == 2:
2208 raise OSError(errno.EINTR, "fake interrupted system call")
2209 return tuple(reversed(args))
2210
2211 self.assertEqual((999, 256),
2212 subprocess._eintr_retry_call(fake_os_func, 256, 999))
2213 self.assertEqual([(256, 999)], record_calls)
2214 # This time there will be an EINTR so it will loop once.
2215 self.assertEqual((666,),
2216 subprocess._eintr_retry_call(fake_os_func, 666))
2217 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
2218
2219
Tim Golden126c2962010-08-11 14:20:40 +00002220@unittest.skipUnless(mswindows, "Windows-specific tests")
2221class CommandsWithSpaces (BaseTestCase):
2222
2223 def setUp(self):
2224 super().setUp()
2225 f, fname = mkstemp(".py", "te st")
2226 self.fname = fname.lower ()
2227 os.write(f, b"import sys;"
2228 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2229 )
2230 os.close(f)
2231
2232 def tearDown(self):
2233 os.remove(self.fname)
2234 super().tearDown()
2235
2236 def with_spaces(self, *args, **kwargs):
2237 kwargs['stdout'] = subprocess.PIPE
2238 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002239 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002240 self.assertEqual(
2241 p.stdout.read ().decode("mbcs"),
2242 "2 [%r, 'ab cd']" % self.fname
2243 )
2244
2245 def test_shell_string_with_spaces(self):
2246 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002247 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2248 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002249
2250 def test_shell_sequence_with_spaces(self):
2251 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002252 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002253
2254 def test_noshell_string_with_spaces(self):
2255 # call() function with string argument with spaces on Windows
2256 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2257 "ab cd"))
2258
2259 def test_noshell_sequence_with_spaces(self):
2260 # call() function with sequence argument with spaces on Windows
2261 self.with_spaces([sys.executable, self.fname, "ab cd"])
2262
Brian Curtin79cdb662010-12-03 02:46:02 +00002263
Georg Brandla86b2622012-02-20 21:34:57 +01002264class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002265
2266 def test_pipe(self):
2267 with subprocess.Popen([sys.executable, "-c",
2268 "import sys;"
2269 "sys.stdout.write('stdout');"
2270 "sys.stderr.write('stderr');"],
2271 stdout=subprocess.PIPE,
2272 stderr=subprocess.PIPE) as proc:
2273 self.assertEqual(proc.stdout.read(), b"stdout")
2274 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2275
2276 self.assertTrue(proc.stdout.closed)
2277 self.assertTrue(proc.stderr.closed)
2278
2279 def test_returncode(self):
2280 with subprocess.Popen([sys.executable, "-c",
2281 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002282 pass
2283 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002284 self.assertEqual(proc.returncode, 100)
2285
2286 def test_communicate_stdin(self):
2287 with subprocess.Popen([sys.executable, "-c",
2288 "import sys;"
2289 "sys.exit(sys.stdin.read() == 'context')"],
2290 stdin=subprocess.PIPE) as proc:
2291 proc.communicate(b"context")
2292 self.assertEqual(proc.returncode, 1)
2293
2294 def test_invalid_args(self):
Andrew Svetlovb1726972012-12-26 23:34:54 +02002295 with self.assertRaises(FileNotFoundError) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002296 with subprocess.Popen(['nonexisting_i_hope'],
2297 stdout=subprocess.PIPE,
2298 stderr=subprocess.PIPE) as proc:
2299 pass
2300
Brian Curtin79cdb662010-12-03 02:46:02 +00002301
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002302def test_main():
2303 unit_tests = (ProcessTestCase,
2304 POSIXProcessTestCase,
2305 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002306 CommandTests,
2307 ProcessTestCaseNoPoll,
2308 HelperFunctionTests,
2309 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002310 ContextManagerTests,
2311 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002312
2313 support.run_unittest(*unit_tests)
2314 support.reap_children()
2315
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002316if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002317 unittest.main()