blob: 05957c9afa753ea3f88e1b9d44a853de0afdb30d [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:
22 import resource
23except ImportError:
24 resource = None
25
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
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000085 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000086 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000087 rc = subprocess.call([sys.executable, "-c",
88 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000089 self.assertEqual(rc, 47)
90
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040091 def test_call_timeout(self):
92 # call() function with timeout argument; we want to test that the child
93 # process gets killed when the timeout expires. If the child isn't
94 # killed, this call will deadlock since subprocess.call waits for the
95 # child.
96 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
97 [sys.executable, "-c", "while True: pass"],
98 timeout=0.1)
99
Peter Astrand454f7672005-01-01 09:36:35 +0000100 def test_check_call_zero(self):
101 # check_call() function with zero return code
102 rc = subprocess.check_call([sys.executable, "-c",
103 "import sys; sys.exit(0)"])
104 self.assertEqual(rc, 0)
105
106 def test_check_call_nonzero(self):
107 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000108 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000109 subprocess.check_call([sys.executable, "-c",
110 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000111 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000112
Georg Brandlf9734072008-12-07 15:30:06 +0000113 def test_check_output(self):
114 # check_output() function with zero return code
115 output = subprocess.check_output(
116 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000117 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000118
119 def test_check_output_nonzero(self):
120 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000121 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000122 subprocess.check_output(
123 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000124 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000125
126 def test_check_output_stderr(self):
127 # check_output() function stderr redirected to stdout
128 output = subprocess.check_output(
129 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
130 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000131 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000132
133 def test_check_output_stdout_arg(self):
134 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000135 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000136 output = subprocess.check_output(
137 [sys.executable, "-c", "print('will not be run')"],
138 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000139 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000140 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000141
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400142 def test_check_output_timeout(self):
143 # check_output() function with timeout arg
144 with self.assertRaises(subprocess.TimeoutExpired) as c:
145 output = subprocess.check_output(
146 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200147 "import sys, time\n"
148 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400149 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200150 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400151 # Some heavily loaded buildbots (sparc Debian 3.x) require
152 # this much time to start and print.
153 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400154 self.fail("Expected TimeoutExpired.")
155 self.assertEqual(c.exception.output, b'BDFL')
156
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000157 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000158 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000159 newenv = os.environ.copy()
160 newenv["FRUIT"] = "banana"
161 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000162 'import sys, os;'
163 'sys.exit(os.getenv("FRUIT")=="banana")'],
164 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165 self.assertEqual(rc, 1)
166
Victor Stinner87b9bc32011-06-01 00:57:47 +0200167 def test_invalid_args(self):
168 # Popen() called with invalid arguments should raise TypeError
169 # but Popen.__del__ should not complain (issue #12085)
170 with support.captured_stderr() as s:
171 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
172 argcount = subprocess.Popen.__init__.__code__.co_argcount
173 too_many_args = [0] * (argcount + 1)
174 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
175 self.assertEqual(s.getvalue(), '')
176
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000177 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000178 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000179 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000180 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000181 self.addCleanup(p.stdout.close)
182 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000183 p.wait()
184 self.assertEqual(p.stdin, None)
185
186 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200187 # .stdout is None when not redirected, and the child's stdout will
188 # be inherited from the parent. In order to test this we run a
189 # subprocess in a subprocess:
190 # this_test
191 # \-- subprocess created by this test (parent)
192 # \-- subprocess created by the parent subprocess (child)
193 # The parent doesn't specify stdout, so the child will use the
194 # parent's stdout. This test checks that the message printed by the
195 # child goes to the parent stdout. The parent also checks that the
196 # child's stdout is None. See #11963.
197 code = ('import sys; from subprocess import Popen, PIPE;'
198 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
199 ' stdin=PIPE, stderr=PIPE);'
200 'p.wait(); assert p.stdout is None;')
201 p = subprocess.Popen([sys.executable, "-c", code],
202 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
203 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000204 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200205 out, err = p.communicate()
206 self.assertEqual(p.returncode, 0, err)
207 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000208
209 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000210 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000211 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000212 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000213 self.addCleanup(p.stdout.close)
214 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000215 p.wait()
216 self.assertEqual(p.stderr, None)
217
Chris Jerdonek776cb192012-10-08 15:56:43 -0700218 def _assert_python(self, pre_args, **kwargs):
219 # We include sys.exit() to prevent the test runner from hanging
220 # whenever python is found.
221 args = pre_args + ["import sys; sys.exit(47)"]
222 p = subprocess.Popen(args, **kwargs)
223 p.wait()
224 self.assertEqual(47, p.returncode)
225
226 def test_executable(self):
227 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700228 #
229 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
230 # determine where its standard library is, so we need the directory
231 # of args[0] to be valid for the Popen() call to Python to succeed.
232 # See also issue #16170 and issue #7774.
233 doesnotexist = os.path.join(os.path.dirname(sys.executable),
234 "doesnotexist")
235 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700236
237 def test_executable_takes_precedence(self):
238 # Check that the executable argument takes precedence over args[0].
239 #
240 # Verify first that the call succeeds without the executable arg.
241 pre_args = [sys.executable, "-c"]
242 self._assert_python(pre_args)
243 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
244 executable="doesnotexist")
245
246 @unittest.skipIf(mswindows, "executable argument replaces shell")
247 def test_executable_replaces_shell(self):
248 # Check that the executable argument replaces the default shell
249 # when shell=True.
250 self._assert_python([], executable=sys.executable, shell=True)
251
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700252 # For use in the test_cwd* tests below.
253 def _normalize_cwd(self, cwd):
254 # Normalize an expected cwd (for Tru64 support).
255 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
256 # strings. See bug #1063571.
257 original_cwd = os.getcwd()
258 os.chdir(cwd)
259 cwd = os.getcwd()
260 os.chdir(original_cwd)
261 return cwd
262
263 # For use in the test_cwd* tests below.
264 def _split_python_path(self):
265 # Return normalized (python_dir, python_base).
266 python_path = os.path.realpath(sys.executable)
267 return os.path.split(python_path)
268
269 # For use in the test_cwd* tests below.
270 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
271 # Invoke Python via Popen, and assert that (1) the call succeeds,
272 # and that (2) the current working directory of the child process
273 # matches *expected_cwd*.
274 p = subprocess.Popen([python_arg, "-c",
275 "import os, sys; "
276 "sys.stdout.write(os.getcwd()); "
277 "sys.exit(47)"],
278 stdout=subprocess.PIPE,
279 **kwargs)
280 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000281 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700282 self.assertEqual(47, p.returncode)
283 normcase = os.path.normcase
284 self.assertEqual(normcase(expected_cwd),
285 normcase(p.stdout.read().decode("utf-8")))
286
287 def test_cwd(self):
288 # Check that cwd changes the cwd for the child process.
289 temp_dir = tempfile.gettempdir()
290 temp_dir = self._normalize_cwd(temp_dir)
291 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
292
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700293 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700294 def test_cwd_with_relative_arg(self):
295 # Check that Popen looks for args[0] relative to cwd if args[0]
296 # is relative.
297 python_dir, python_base = self._split_python_path()
298 rel_python = os.path.join(os.curdir, python_base)
299 with support.temp_cwd() as wrong_dir:
300 # Before calling with the correct cwd, confirm that the call fails
301 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700302 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700303 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700304 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700305 [rel_python], cwd=wrong_dir)
306 python_dir = self._normalize_cwd(python_dir)
307 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
308
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700309 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700310 def test_cwd_with_relative_executable(self):
311 # Check that Popen looks for executable relative to cwd if executable
312 # is relative (and that executable takes precedence over args[0]).
313 python_dir, python_base = self._split_python_path()
314 rel_python = os.path.join(os.curdir, python_base)
315 doesntexist = "somethingyoudonthave"
316 with support.temp_cwd() as wrong_dir:
317 # Before calling with the correct cwd, confirm that the call fails
318 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700319 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700320 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700321 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700322 [doesntexist], executable=rel_python,
323 cwd=wrong_dir)
324 python_dir = self._normalize_cwd(python_dir)
325 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
326 cwd=python_dir)
327
328 def test_cwd_with_absolute_arg(self):
329 # Check that Popen can find the executable when the cwd is wrong
330 # if args[0] is an absolute path.
331 python_dir, python_base = self._split_python_path()
332 abs_python = os.path.join(python_dir, python_base)
333 rel_python = os.path.join(os.curdir, python_base)
334 with script_helper.temp_dir() as wrong_dir:
335 # Before calling with an absolute path, confirm that using a
336 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700337 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700338 [rel_python], cwd=wrong_dir)
339 wrong_dir = self._normalize_cwd(wrong_dir)
340 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
341
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100342 @unittest.skipIf(sys.base_prefix != sys.prefix,
343 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000344 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700345 python_dir, python_base = self._split_python_path()
346 python_dir = self._normalize_cwd(python_dir)
347 self._assert_cwd(python_dir, "somethingyoudonthave",
348 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000349
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100350 @unittest.skipIf(sys.base_prefix != sys.prefix,
351 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000352 @unittest.skipIf(sysconfig.is_python_build(),
353 "need an installed Python. See #7774")
354 def test_executable_without_cwd(self):
355 # For a normal installation, it should work without 'cwd'
356 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700357 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000358
359 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000360 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361 p = subprocess.Popen([sys.executable, "-c",
362 'import sys; sys.exit(sys.stdin.read() == "pear")'],
363 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000364 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000365 p.stdin.close()
366 p.wait()
367 self.assertEqual(p.returncode, 1)
368
369 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000370 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000371 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000372 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000373 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000374 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000375 os.lseek(d, 0, 0)
376 p = subprocess.Popen([sys.executable, "-c",
377 'import sys; sys.exit(sys.stdin.read() == "pear")'],
378 stdin=d)
379 p.wait()
380 self.assertEqual(p.returncode, 1)
381
382 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000383 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000384 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000385 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000386 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000387 tf.seek(0)
388 p = subprocess.Popen([sys.executable, "-c",
389 'import sys; sys.exit(sys.stdin.read() == "pear")'],
390 stdin=tf)
391 p.wait()
392 self.assertEqual(p.returncode, 1)
393
394 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000395 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000396 p = subprocess.Popen([sys.executable, "-c",
397 'import sys; sys.stdout.write("orange")'],
398 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000399 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000400 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000401
402 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000403 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000404 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000405 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000406 d = tf.fileno()
407 p = subprocess.Popen([sys.executable, "-c",
408 'import sys; sys.stdout.write("orange")'],
409 stdout=d)
410 p.wait()
411 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000412 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413
414 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000415 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000416 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000417 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000418 p = subprocess.Popen([sys.executable, "-c",
419 'import sys; sys.stdout.write("orange")'],
420 stdout=tf)
421 p.wait()
422 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000423 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424
425 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000426 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000427 p = subprocess.Popen([sys.executable, "-c",
428 'import sys; sys.stderr.write("strawberry")'],
429 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000430 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000431 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000432
433 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000434 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000435 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000436 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000437 d = tf.fileno()
438 p = subprocess.Popen([sys.executable, "-c",
439 'import sys; sys.stderr.write("strawberry")'],
440 stderr=d)
441 p.wait()
442 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000443 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444
445 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000446 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000447 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000448 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449 p = subprocess.Popen([sys.executable, "-c",
450 'import sys; sys.stderr.write("strawberry")'],
451 stderr=tf)
452 p.wait()
453 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000454 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000455
456 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000457 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000458 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000459 'import sys;'
460 'sys.stdout.write("apple");'
461 'sys.stdout.flush();'
462 'sys.stderr.write("orange")'],
463 stdout=subprocess.PIPE,
464 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000465 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000466 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000467
468 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000469 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000471 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000472 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000473 'import sys;'
474 'sys.stdout.write("apple");'
475 'sys.stdout.flush();'
476 'sys.stderr.write("orange")'],
477 stdout=tf,
478 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479 p.wait()
480 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000481 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482
Thomas Wouters89f507f2006-12-13 04:49:30 +0000483 def test_stdout_filedes_of_stdout(self):
484 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200485 # To avoid printing the text on stdout, we do something similar to
486 # test_stdout_none (see above). The parent subprocess calls the child
487 # subprocess passing stdout=1, and this test uses stdout=PIPE in
488 # order to capture and check the output of the parent. See #11963.
489 code = ('import sys, subprocess; '
490 'rc = subprocess.call([sys.executable, "-c", '
491 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
492 'b\'test with stdout=1\'))"], stdout=1); '
493 'assert rc == 18')
494 p = subprocess.Popen([sys.executable, "-c", code],
495 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
496 self.addCleanup(p.stdout.close)
497 self.addCleanup(p.stderr.close)
498 out, err = p.communicate()
499 self.assertEqual(p.returncode, 0, err)
500 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000501
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200502 def test_stdout_devnull(self):
503 p = subprocess.Popen([sys.executable, "-c",
504 'for i in range(10240):'
505 'print("x" * 1024)'],
506 stdout=subprocess.DEVNULL)
507 p.wait()
508 self.assertEqual(p.stdout, None)
509
510 def test_stderr_devnull(self):
511 p = subprocess.Popen([sys.executable, "-c",
512 'import sys\n'
513 'for i in range(10240):'
514 'sys.stderr.write("x" * 1024)'],
515 stderr=subprocess.DEVNULL)
516 p.wait()
517 self.assertEqual(p.stderr, None)
518
519 def test_stdin_devnull(self):
520 p = subprocess.Popen([sys.executable, "-c",
521 'import sys;'
522 'sys.stdin.read(1)'],
523 stdin=subprocess.DEVNULL)
524 p.wait()
525 self.assertEqual(p.stdin, None)
526
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 newenv = os.environ.copy()
529 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200530 with subprocess.Popen([sys.executable, "-c",
531 'import sys,os;'
532 'sys.stdout.write(os.getenv("FRUIT"))'],
533 stdout=subprocess.PIPE,
534 env=newenv) as p:
535 stdout, stderr = p.communicate()
536 self.assertEqual(stdout, b"orange")
537
Victor Stinner62d51182011-06-23 01:02:25 +0200538 # Windows requires at least the SYSTEMROOT environment variable to start
539 # Python
540 @unittest.skipIf(sys.platform == 'win32',
541 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200542 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200543 'the python library cannot be loaded '
544 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200545 def test_empty_env(self):
546 with subprocess.Popen([sys.executable, "-c",
547 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200548 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200549 stdout=subprocess.PIPE,
550 env={}) as p:
551 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200552 self.assertIn(stdout.strip(),
553 (b"[]",
554 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
555 # environment
556 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000557
Peter Astrandcbac93c2005-03-03 20:24:28 +0000558 def test_communicate_stdin(self):
559 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000560 'import sys;'
561 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000562 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000563 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000564 self.assertEqual(p.returncode, 1)
565
566 def test_communicate_stdout(self):
567 p = subprocess.Popen([sys.executable, "-c",
568 'import sys; sys.stdout.write("pineapple")'],
569 stdout=subprocess.PIPE)
570 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000571 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000572 self.assertEqual(stderr, None)
573
574 def test_communicate_stderr(self):
575 p = subprocess.Popen([sys.executable, "-c",
576 'import sys; sys.stderr.write("pineapple")'],
577 stderr=subprocess.PIPE)
578 (stdout, stderr) = p.communicate()
579 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000580 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000581
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000582 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000583 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000584 'import sys,os;'
585 'sys.stderr.write("pineapple");'
586 'sys.stdout.write(sys.stdin.read())'],
587 stdin=subprocess.PIPE,
588 stdout=subprocess.PIPE,
589 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000590 self.addCleanup(p.stdout.close)
591 self.addCleanup(p.stderr.close)
592 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000593 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000594 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000595 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400597 def test_communicate_timeout(self):
598 p = subprocess.Popen([sys.executable, "-c",
599 'import sys,os,time;'
600 'sys.stderr.write("pineapple\\n");'
601 'time.sleep(1);'
602 'sys.stderr.write("pear\\n");'
603 'sys.stdout.write(sys.stdin.read())'],
604 universal_newlines=True,
605 stdin=subprocess.PIPE,
606 stdout=subprocess.PIPE,
607 stderr=subprocess.PIPE)
608 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
609 timeout=0.3)
610 # Make sure we can keep waiting for it, and that we get the whole output
611 # after it completes.
612 (stdout, stderr) = p.communicate()
613 self.assertEqual(stdout, "banana")
614 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
615
616 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200617 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400618 p = subprocess.Popen([sys.executable, "-c",
619 'import sys,os,time;'
620 'sys.stdout.write("a" * (64 * 1024));'
621 'time.sleep(0.2);'
622 'sys.stdout.write("a" * (64 * 1024));'
623 'time.sleep(0.2);'
624 'sys.stdout.write("a" * (64 * 1024));'
625 'time.sleep(0.2);'
626 'sys.stdout.write("a" * (64 * 1024));'],
627 stdout=subprocess.PIPE)
628 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
629 (stdout, _) = p.communicate()
630 self.assertEqual(len(stdout), 4 * 64 * 1024)
631
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000632 # Test for the fd leak reported in http://bugs.python.org/issue2791.
633 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000634 for stdin_pipe in (False, True):
635 for stdout_pipe in (False, True):
636 for stderr_pipe in (False, True):
637 options = {}
638 if stdin_pipe:
639 options['stdin'] = subprocess.PIPE
640 if stdout_pipe:
641 options['stdout'] = subprocess.PIPE
642 if stderr_pipe:
643 options['stderr'] = subprocess.PIPE
644 if not options:
645 continue
646 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
647 p.communicate()
648 if p.stdin is not None:
649 self.assertTrue(p.stdin.closed)
650 if p.stdout is not None:
651 self.assertTrue(p.stdout.closed)
652 if p.stderr is not None:
653 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000654
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000655 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000656 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000657 p = subprocess.Popen([sys.executable, "-c",
658 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659 (stdout, stderr) = p.communicate()
660 self.assertEqual(stdout, None)
661 self.assertEqual(stderr, None)
662
663 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000664 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000665 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000666 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000667 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000668 os.close(x)
669 os.close(y)
670 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000671 'import sys,os;'
672 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200673 'sys.stderr.write("x" * %d);'
674 'sys.stdout.write(sys.stdin.read())' %
675 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000676 stdin=subprocess.PIPE,
677 stdout=subprocess.PIPE,
678 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000679 self.addCleanup(p.stdout.close)
680 self.addCleanup(p.stderr.close)
681 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200682 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000683 (stdout, stderr) = p.communicate(string_to_write)
684 self.assertEqual(stdout, string_to_write)
685
686 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000687 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000688 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000689 'import sys,os;'
690 'sys.stdout.write(sys.stdin.read())'],
691 stdin=subprocess.PIPE,
692 stdout=subprocess.PIPE,
693 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000694 self.addCleanup(p.stdout.close)
695 self.addCleanup(p.stderr.close)
696 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000697 p.stdin.write(b"banana")
698 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000699 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000700 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000701
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000702 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000703 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000704 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200705 'buf = sys.stdout.buffer;'
706 'buf.write(sys.stdin.readline().encode());'
707 'buf.flush();'
708 'buf.write(b"line2\\n");'
709 'buf.flush();'
710 'buf.write(sys.stdin.read().encode());'
711 'buf.flush();'
712 'buf.write(b"line4\\n");'
713 'buf.flush();'
714 'buf.write(b"line5\\r\\n");'
715 'buf.flush();'
716 'buf.write(b"line6\\r");'
717 'buf.flush();'
718 'buf.write(b"\\nline7");'
719 'buf.flush();'
720 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200721 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000722 stdout=subprocess.PIPE,
723 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200724 p.stdin.write("line1\n")
725 self.assertEqual(p.stdout.readline(), "line1\n")
726 p.stdin.write("line3\n")
727 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000728 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200729 self.assertEqual(p.stdout.readline(),
730 "line2\n")
731 self.assertEqual(p.stdout.read(6),
732 "line3\n")
733 self.assertEqual(p.stdout.read(),
734 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000735
736 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000737 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000739 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200740 'buf = sys.stdout.buffer;'
741 'buf.write(b"line2\\n");'
742 'buf.flush();'
743 'buf.write(b"line4\\n");'
744 'buf.flush();'
745 'buf.write(b"line5\\r\\n");'
746 'buf.flush();'
747 'buf.write(b"line6\\r");'
748 'buf.flush();'
749 'buf.write(b"\\nline7");'
750 'buf.flush();'
751 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200752 stderr=subprocess.PIPE,
753 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000754 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000755 self.addCleanup(p.stdout.close)
756 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000757 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200758 self.assertEqual(stdout,
759 "line2\nline4\nline5\nline6\nline7\nline8")
760
761 def test_universal_newlines_communicate_stdin(self):
762 # universal newlines through communicate(), with only stdin
763 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300764 'import sys,os;' + SETBINARY + textwrap.dedent('''
765 s = sys.stdin.readline()
766 assert s == "line1\\n", repr(s)
767 s = sys.stdin.read()
768 assert s == "line3\\n", repr(s)
769 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200770 stdin=subprocess.PIPE,
771 universal_newlines=1)
772 (stdout, stderr) = p.communicate("line1\nline3\n")
773 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000774
Andrew Svetlovf3765072012-08-14 18:35:17 +0300775 def test_universal_newlines_communicate_input_none(self):
776 # Test communicate(input=None) with universal newlines.
777 #
778 # We set stdout to PIPE because, as of this writing, a different
779 # code path is tested when the number of pipes is zero or one.
780 p = subprocess.Popen([sys.executable, "-c", "pass"],
781 stdin=subprocess.PIPE,
782 stdout=subprocess.PIPE,
783 universal_newlines=True)
784 p.communicate()
785 self.assertEqual(p.returncode, 0)
786
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300787 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300788 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300789 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300790 'import sys,os;' + SETBINARY + textwrap.dedent('''
791 s = sys.stdin.buffer.readline()
792 sys.stdout.buffer.write(s)
793 sys.stdout.buffer.write(b"line2\\r")
794 sys.stderr.buffer.write(b"eline2\\n")
795 s = sys.stdin.buffer.read()
796 sys.stdout.buffer.write(s)
797 sys.stdout.buffer.write(b"line4\\n")
798 sys.stdout.buffer.write(b"line5\\r\\n")
799 sys.stderr.buffer.write(b"eline6\\r")
800 sys.stderr.buffer.write(b"eline7\\r\\nz")
801 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300802 stdin=subprocess.PIPE,
803 stderr=subprocess.PIPE,
804 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300805 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300806 self.addCleanup(p.stdout.close)
807 self.addCleanup(p.stderr.close)
808 (stdout, stderr) = p.communicate("line1\nline3\n")
809 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300810 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300811 # Python debug build push something like "[42442 refs]\n"
812 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300813 # Don't use assertStderrEqual because it strips CR and LF from output.
814 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300815
Andrew Svetlov82860712012-08-19 22:13:41 +0300816 def test_universal_newlines_communicate_encodings(self):
817 # Check that universal newlines mode works for various encodings,
818 # in particular for encodings in the UTF-16 and UTF-32 families.
819 # See issue #15595.
820 #
821 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
822 # without, and UTF-16 and UTF-32.
823 for encoding in ['utf-16', 'utf-32-be']:
824 old_getpreferredencoding = locale.getpreferredencoding
825 # Indirectly via io.TextIOWrapper, Popen() defaults to
826 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
827 # locale.getpreferredencoding().
828 def getpreferredencoding(do_setlocale=True):
829 return encoding
830 code = ("import sys; "
831 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
832 encoding)
833 args = [sys.executable, '-c', code]
834 try:
835 locale.getpreferredencoding = getpreferredencoding
836 # We set stdin to be non-None because, as of this writing,
837 # a different code path is used when the number of pipes is
838 # zero or one.
839 popen = subprocess.Popen(args, universal_newlines=True,
840 stdin=subprocess.PIPE,
841 stdout=subprocess.PIPE)
842 stdout, stderr = popen.communicate(input='')
843 finally:
844 locale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300845 self.assertEqual(stdout, '1\n2\n3\n4')
846
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000848 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000849 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000850 max_handles = 1026 # too much for most UNIX systems
851 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000852 max_handles = 2050 # too much for (at least some) Windows setups
853 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400854 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000855 try:
856 for i in range(max_handles):
857 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400858 tmpfile = os.path.join(tmpdir, support.TESTFN)
859 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000860 except OSError as e:
861 if e.errno != errno.EMFILE:
862 raise
863 break
864 else:
865 self.skipTest("failed to reach the file descriptor limit "
866 "(tried %d)" % max_handles)
867 # Close a couple of them (should be enough for a subprocess)
868 for i in range(10):
869 os.close(handles.pop())
870 # Loop creating some subprocesses. If one of them leaks some fds,
871 # the next loop iteration will fail by reaching the max fd limit.
872 for i in range(15):
873 p = subprocess.Popen([sys.executable, "-c",
874 "import sys;"
875 "sys.stdout.write(sys.stdin.read())"],
876 stdin=subprocess.PIPE,
877 stdout=subprocess.PIPE,
878 stderr=subprocess.PIPE)
879 data = p.communicate(b"lime")[0]
880 self.assertEqual(data, b"lime")
881 finally:
882 for h in handles:
883 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400884 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000885
886 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000887 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
888 '"a b c" d e')
889 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
890 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000891 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
892 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000893 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
894 'a\\\\\\b "de fg" h')
895 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
896 'a\\\\\\"b c d')
897 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
898 '"a\\\\b c" d e')
899 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
900 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000901 self.assertEqual(subprocess.list2cmdline(['ab', '']),
902 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000903
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000904 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200905 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200906 "import os; os.read(0, 1)"],
907 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200908 self.addCleanup(p.stdin.close)
909 self.assertIsNone(p.poll())
910 os.write(p.stdin.fileno(), b'A')
911 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000912 # Subsequent invocations should just return the returncode
913 self.assertEqual(p.poll(), 0)
914
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000915 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200916 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000917 self.assertEqual(p.wait(), 0)
918 # Subsequent invocations should just return the returncode
919 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000920
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400921 def test_wait_timeout(self):
922 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400923 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400924 with self.assertRaises(subprocess.TimeoutExpired) as c:
925 p.wait(timeout=0.01)
926 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400927 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
928 # time to start.
929 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400930
Peter Astrand738131d2004-11-30 21:04:45 +0000931 def test_invalid_bufsize(self):
932 # an invalid type of the bufsize argument should raise
933 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000934 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000935 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000936
Guido van Rossum46a05a72007-06-07 21:56:45 +0000937 def test_bufsize_is_none(self):
938 # bufsize=None should be the same as bufsize=0.
939 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
940 self.assertEqual(p.wait(), 0)
941 # Again with keyword arg
942 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
943 self.assertEqual(p.wait(), 0)
944
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000945 def test_leaking_fds_on_error(self):
946 # see bug #5179: Popen leaks file descriptors to PIPEs if
947 # the child fails to execute; this will eventually exhaust
948 # the maximum number of open fds. 1024 seems a very common
949 # value for that limit, but Windows has 2048, so we loop
950 # 1024 times (each call leaked two fds).
951 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200952 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000953 subprocess.Popen(['nonexisting_i_hope'],
954 stdout=subprocess.PIPE,
955 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400956 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400957 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000958 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000959
Victor Stinnerb3693582010-05-21 20:13:12 +0000960 def test_issue8780(self):
961 # Ensure that stdout is inherited from the parent
962 # if stdout=PIPE is not used
963 code = ';'.join((
964 'import subprocess, sys',
965 'retcode = subprocess.call('
966 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
967 'assert retcode == 0'))
968 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000969 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000970
Tim Goldenaf5ac392010-08-06 13:03:56 +0000971 def test_handles_closed_on_exception(self):
972 # If CreateProcess exits with an error, ensure the
973 # duplicate output handles are released
974 ifhandle, ifname = mkstemp()
975 ofhandle, ofname = mkstemp()
976 efhandle, efname = mkstemp()
977 try:
978 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
979 stderr=efhandle)
980 except OSError:
981 os.close(ifhandle)
982 os.remove(ifname)
983 os.close(ofhandle)
984 os.remove(ofname)
985 os.close(efhandle)
986 os.remove(efname)
987 self.assertFalse(os.path.exists(ifname))
988 self.assertFalse(os.path.exists(ofname))
989 self.assertFalse(os.path.exists(efname))
990
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200991 def test_communicate_epipe(self):
992 # Issue 10963: communicate() should hide EPIPE
993 p = subprocess.Popen([sys.executable, "-c", 'pass'],
994 stdin=subprocess.PIPE,
995 stdout=subprocess.PIPE,
996 stderr=subprocess.PIPE)
997 self.addCleanup(p.stdout.close)
998 self.addCleanup(p.stderr.close)
999 self.addCleanup(p.stdin.close)
1000 p.communicate(b"x" * 2**20)
1001
1002 def test_communicate_epipe_only_stdin(self):
1003 # Issue 10963: communicate() should hide EPIPE
1004 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1005 stdin=subprocess.PIPE)
1006 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001007 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001008 p.communicate(b"x" * 2**20)
1009
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001010 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1011 "Requires signal.SIGUSR1")
1012 @unittest.skipUnless(hasattr(os, 'kill'),
1013 "Requires os.kill")
1014 @unittest.skipUnless(hasattr(os, 'getppid'),
1015 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001016 def test_communicate_eintr(self):
1017 # Issue #12493: communicate() should handle EINTR
1018 def handler(signum, frame):
1019 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001020 old_handler = signal.signal(signal.SIGUSR1, handler)
1021 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001022
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001023 args = [sys.executable, "-c",
1024 'import os, signal;'
1025 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001026 for stream in ('stdout', 'stderr'):
1027 kw = {stream: subprocess.PIPE}
1028 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001029 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001030 process.communicate()
1031
Tim Peterse718f612004-10-12 21:51:32 +00001032
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001033 # This test is Linux-ish specific for simplicity to at least have
1034 # some coverage. It is not a platform specific bug.
1035 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1036 "Linux specific")
1037 def test_failed_child_execute_fd_leak(self):
1038 """Test for the fork() failure fd leak reported in issue16327."""
1039 fd_directory = '/proc/%d/fd' % os.getpid()
1040 fds_before_popen = os.listdir(fd_directory)
1041 with self.assertRaises(PopenTestException):
1042 PopenExecuteChildRaises(
1043 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1044 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1045
1046 # NOTE: This test doesn't verify that the real _execute_child
1047 # does not close the file descriptors itself on the way out
1048 # during an exception. Code inspection has confirmed that.
1049
1050 fds_after_exception = os.listdir(fd_directory)
1051 self.assertEqual(fds_before_popen, fds_after_exception)
1052
1053
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001054# context manager
1055class _SuppressCoreFiles(object):
1056 """Try to prevent core files from being created."""
1057 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001058
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001059 def __enter__(self):
1060 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -05001061 if resource is not None:
1062 try:
1063 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
1064 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
1065 except (ValueError, resource.error):
1066 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001067
Ronald Oussoren102d11a2010-07-23 09:50:05 +00001068 if sys.platform == 'darwin':
1069 # Check if the 'Crash Reporter' on OSX was configured
1070 # in 'Developer' mode and warn that it will get triggered
1071 # when it is.
1072 #
1073 # This assumes that this context manager is used in tests
1074 # that might trigger the next manager.
1075 value = subprocess.Popen(['/usr/bin/defaults', 'read',
1076 'com.apple.CrashReporter', 'DialogType'],
1077 stdout=subprocess.PIPE).communicate()[0]
1078 if value.strip() == b'developer':
1079 print("this tests triggers the Crash Reporter, "
1080 "that is intentional", end='')
1081 sys.stdout.flush()
1082
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001083 def __exit__(self, *args):
1084 """Return core file behavior to default."""
1085 if self.old_limit is None:
1086 return
Benjamin Peterson964561b2011-12-10 12:31:42 -05001087 if resource is not None:
1088 try:
1089 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
1090 except (ValueError, resource.error):
1091 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001092
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001093
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001094@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001095class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001096
Gregory P. Smith5591b022012-10-10 03:34:47 -07001097 def setUp(self):
1098 super().setUp()
1099 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1100
1101 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001102 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001103 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001104 except OSError as e:
1105 # This avoids hard coding the errno value or the OS perror()
1106 # string and instead capture the exception that we want to see
1107 # below for comparison.
1108 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001109 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001110 else:
1111 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001112 self._nonexistent_dir)
1113 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001114
Gregory P. Smith5591b022012-10-10 03:34:47 -07001115 def test_exception_cwd(self):
1116 """Test error in the child raised in the parent for a bad cwd."""
1117 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001118 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001119 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001120 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001121 except OSError as e:
1122 # Test that the child process chdir failure actually makes
1123 # it up to the parent process as the correct exception.
1124 self.assertEqual(desired_exception.errno, e.errno)
1125 self.assertEqual(desired_exception.strerror, e.strerror)
1126 else:
1127 self.fail("Expected OSError: %s" % desired_exception)
1128
Gregory P. Smith5591b022012-10-10 03:34:47 -07001129 def test_exception_bad_executable(self):
1130 """Test error in the child raised in the parent for a bad executable."""
1131 desired_exception = self._get_chdir_exception()
1132 try:
1133 p = subprocess.Popen([sys.executable, "-c", ""],
1134 executable=self._nonexistent_dir)
1135 except OSError as e:
1136 # Test that the child process exec failure actually makes
1137 # it up to the parent process as the correct exception.
1138 self.assertEqual(desired_exception.errno, e.errno)
1139 self.assertEqual(desired_exception.strerror, e.strerror)
1140 else:
1141 self.fail("Expected OSError: %s" % desired_exception)
1142
1143 def test_exception_bad_args_0(self):
1144 """Test error in the child raised in the parent for a bad args[0]."""
1145 desired_exception = self._get_chdir_exception()
1146 try:
1147 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1148 except OSError as e:
1149 # Test that the child process exec failure actually makes
1150 # it up to the parent process as the correct exception.
1151 self.assertEqual(desired_exception.errno, e.errno)
1152 self.assertEqual(desired_exception.strerror, e.strerror)
1153 else:
1154 self.fail("Expected OSError: %s" % desired_exception)
1155
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001156 def test_restore_signals(self):
1157 # Code coverage for both values of restore_signals to make sure it
1158 # at least does not blow up.
1159 # A test for behavior would be complex. Contributions welcome.
1160 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1161 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1162
1163 def test_start_new_session(self):
1164 # For code coverage of calling setsid(). We don't care if we get an
1165 # EPERM error from it depending on the test execution environment, that
1166 # still indicates that it was called.
1167 try:
1168 output = subprocess.check_output(
1169 [sys.executable, "-c",
1170 "import os; print(os.getpgid(os.getpid()))"],
1171 start_new_session=True)
1172 except OSError as e:
1173 if e.errno != errno.EPERM:
1174 raise
1175 else:
1176 parent_pgid = os.getpgid(os.getpid())
1177 child_pgid = int(output)
1178 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001179
1180 def test_run_abort(self):
1181 # returncode handles signal termination
1182 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001183 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001184 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001185 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001186 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001187
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001188 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001189 # DISCLAIMER: Setting environment variables is *not* a good use
1190 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001191 p = subprocess.Popen([sys.executable, "-c",
1192 'import sys,os;'
1193 'sys.stdout.write(os.getenv("FRUIT"))'],
1194 stdout=subprocess.PIPE,
1195 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001196 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001197 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001198
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001199 def test_preexec_exception(self):
1200 def raise_it():
1201 raise ValueError("What if two swallows carried a coconut?")
1202 try:
1203 p = subprocess.Popen([sys.executable, "-c", ""],
1204 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001205 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001206 self.assertTrue(
1207 subprocess._posixsubprocess,
1208 "Expected a ValueError from the preexec_fn")
1209 except ValueError as e:
1210 self.assertIn("coconut", e.args[0])
1211 else:
1212 self.fail("Exception raised by preexec_fn did not make it "
1213 "to the parent process.")
1214
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001215 class _TestExecuteChildPopen(subprocess.Popen):
1216 """Used to test behavior at the end of _execute_child."""
1217 def __init__(self, testcase, *args, **kwargs):
1218 self._testcase = testcase
1219 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001220
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001221 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001222 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001223 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001224 finally:
1225 # Open a bunch of file descriptors and verify that
1226 # none of them are the same as the ones the Popen
1227 # instance is using for stdin/stdout/stderr.
1228 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1229 for _ in range(8)]
1230 try:
1231 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001232 self._testcase.assertNotIn(
1233 fd, (self.stdin.fileno(), self.stdout.fileno(),
1234 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001235 msg="At least one fd was closed early.")
1236 finally:
1237 map(os.close, devzero_fds)
1238
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001239 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1240 def test_preexec_errpipe_does_not_double_close_pipes(self):
1241 """Issue16140: Don't double close pipes on preexec error."""
1242
1243 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001244 raise subprocess.SubprocessError(
1245 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001246
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001247 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001248 self._TestExecuteChildPopen(
1249 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001250 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1251 stderr=subprocess.PIPE, preexec_fn=raise_it)
1252
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001253 def test_preexec_gc_module_failure(self):
1254 # This tests the code that disables garbage collection if the child
1255 # process will execute any Python.
1256 def raise_runtime_error():
1257 raise RuntimeError("this shouldn't escape")
1258 enabled = gc.isenabled()
1259 orig_gc_disable = gc.disable
1260 orig_gc_isenabled = gc.isenabled
1261 try:
1262 gc.disable()
1263 self.assertFalse(gc.isenabled())
1264 subprocess.call([sys.executable, '-c', ''],
1265 preexec_fn=lambda: None)
1266 self.assertFalse(gc.isenabled(),
1267 "Popen enabled gc when it shouldn't.")
1268
1269 gc.enable()
1270 self.assertTrue(gc.isenabled())
1271 subprocess.call([sys.executable, '-c', ''],
1272 preexec_fn=lambda: None)
1273 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1274
1275 gc.disable = raise_runtime_error
1276 self.assertRaises(RuntimeError, subprocess.Popen,
1277 [sys.executable, '-c', ''],
1278 preexec_fn=lambda: None)
1279
1280 del gc.isenabled # force an AttributeError
1281 self.assertRaises(AttributeError, subprocess.Popen,
1282 [sys.executable, '-c', ''],
1283 preexec_fn=lambda: None)
1284 finally:
1285 gc.disable = orig_gc_disable
1286 gc.isenabled = orig_gc_isenabled
1287 if not enabled:
1288 gc.disable()
1289
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001290 def test_args_string(self):
1291 # args is a string
1292 fd, fname = mkstemp()
1293 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001294 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001295 fobj.write("#!/bin/sh\n")
1296 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1297 sys.executable)
1298 os.chmod(fname, 0o700)
1299 p = subprocess.Popen(fname)
1300 p.wait()
1301 os.remove(fname)
1302 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001303
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001304 def test_invalid_args(self):
1305 # invalid arguments should raise ValueError
1306 self.assertRaises(ValueError, subprocess.call,
1307 [sys.executable, "-c",
1308 "import sys; sys.exit(47)"],
1309 startupinfo=47)
1310 self.assertRaises(ValueError, subprocess.call,
1311 [sys.executable, "-c",
1312 "import sys; sys.exit(47)"],
1313 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001314
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001315 def test_shell_sequence(self):
1316 # Run command through the shell (sequence)
1317 newenv = os.environ.copy()
1318 newenv["FRUIT"] = "apple"
1319 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1320 stdout=subprocess.PIPE,
1321 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001322 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001323 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001324
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001325 def test_shell_string(self):
1326 # Run command through the shell (string)
1327 newenv = os.environ.copy()
1328 newenv["FRUIT"] = "apple"
1329 p = subprocess.Popen("echo $FRUIT", shell=1,
1330 stdout=subprocess.PIPE,
1331 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001332 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001333 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001334
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001335 def test_call_string(self):
1336 # call() function with string argument on UNIX
1337 fd, fname = mkstemp()
1338 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001339 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001340 fobj.write("#!/bin/sh\n")
1341 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1342 sys.executable)
1343 os.chmod(fname, 0o700)
1344 rc = subprocess.call(fname)
1345 os.remove(fname)
1346 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001347
Stefan Krah9542cc62010-07-19 14:20:53 +00001348 def test_specific_shell(self):
1349 # Issue #9265: Incorrect name passed as arg[0].
1350 shells = []
1351 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1352 for name in ['bash', 'ksh']:
1353 sh = os.path.join(prefix, name)
1354 if os.path.isfile(sh):
1355 shells.append(sh)
1356 if not shells: # Will probably work for any shell but csh.
1357 self.skipTest("bash or ksh required for this test")
1358 sh = '/bin/sh'
1359 if os.path.isfile(sh) and not os.path.islink(sh):
1360 # Test will fail if /bin/sh is a symlink to csh.
1361 shells.append(sh)
1362 for sh in shells:
1363 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1364 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001365 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001366 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1367
Florent Xicluna4886d242010-03-08 13:27:26 +00001368 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001369 # Do not inherit file handles from the parent.
1370 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001371 p = subprocess.Popen([sys.executable, "-c", """if 1:
1372 import sys, time
1373 sys.stdout.write('x\\n')
1374 sys.stdout.flush()
1375 time.sleep(30)
1376 """],
1377 close_fds=True,
1378 stdin=subprocess.PIPE,
1379 stdout=subprocess.PIPE,
1380 stderr=subprocess.PIPE)
1381 # Wait for the interpreter to be completely initialized before
1382 # sending any signal.
1383 p.stdout.read(1)
1384 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001385 return p
1386
Charles-François Natali53221e32013-01-12 16:52:20 +01001387 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1388 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001389 def _kill_dead_process(self, method, *args):
1390 # Do not inherit file handles from the parent.
1391 # It should fix failures on some platforms.
1392 p = subprocess.Popen([sys.executable, "-c", """if 1:
1393 import sys, time
1394 sys.stdout.write('x\\n')
1395 sys.stdout.flush()
1396 """],
1397 close_fds=True,
1398 stdin=subprocess.PIPE,
1399 stdout=subprocess.PIPE,
1400 stderr=subprocess.PIPE)
1401 # Wait for the interpreter to be completely initialized before
1402 # sending any signal.
1403 p.stdout.read(1)
1404 # The process should end after this
1405 time.sleep(1)
1406 # This shouldn't raise even though the child is now dead
1407 getattr(p, method)(*args)
1408 p.communicate()
1409
Florent Xicluna4886d242010-03-08 13:27:26 +00001410 def test_send_signal(self):
1411 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001412 _, stderr = p.communicate()
1413 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001414 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001415
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001416 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001417 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001418 _, stderr = p.communicate()
1419 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001420 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001421
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001422 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001423 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001424 _, stderr = p.communicate()
1425 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001426 self.assertEqual(p.wait(), -signal.SIGTERM)
1427
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001428 def test_send_signal_dead(self):
1429 # Sending a signal to a dead process
1430 self._kill_dead_process('send_signal', signal.SIGINT)
1431
1432 def test_kill_dead(self):
1433 # Killing a dead process
1434 self._kill_dead_process('kill')
1435
1436 def test_terminate_dead(self):
1437 # Terminating a dead process
1438 self._kill_dead_process('terminate')
1439
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001440 def check_close_std_fds(self, fds):
1441 # Issue #9905: test that subprocess pipes still work properly with
1442 # some standard fds closed
1443 stdin = 0
1444 newfds = []
1445 for a in fds:
1446 b = os.dup(a)
1447 newfds.append(b)
1448 if a == 0:
1449 stdin = b
1450 try:
1451 for fd in fds:
1452 os.close(fd)
1453 out, err = subprocess.Popen([sys.executable, "-c",
1454 'import sys;'
1455 'sys.stdout.write("apple");'
1456 'sys.stdout.flush();'
1457 'sys.stderr.write("orange")'],
1458 stdin=stdin,
1459 stdout=subprocess.PIPE,
1460 stderr=subprocess.PIPE).communicate()
1461 err = support.strip_python_stderr(err)
1462 self.assertEqual((out, err), (b'apple', b'orange'))
1463 finally:
1464 for b, a in zip(newfds, fds):
1465 os.dup2(b, a)
1466 for b in newfds:
1467 os.close(b)
1468
1469 def test_close_fd_0(self):
1470 self.check_close_std_fds([0])
1471
1472 def test_close_fd_1(self):
1473 self.check_close_std_fds([1])
1474
1475 def test_close_fd_2(self):
1476 self.check_close_std_fds([2])
1477
1478 def test_close_fds_0_1(self):
1479 self.check_close_std_fds([0, 1])
1480
1481 def test_close_fds_0_2(self):
1482 self.check_close_std_fds([0, 2])
1483
1484 def test_close_fds_1_2(self):
1485 self.check_close_std_fds([1, 2])
1486
1487 def test_close_fds_0_1_2(self):
1488 # Issue #10806: test that subprocess pipes still work properly with
1489 # all standard fds closed.
1490 self.check_close_std_fds([0, 1, 2])
1491
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001492 def test_remapping_std_fds(self):
1493 # open up some temporary files
1494 temps = [mkstemp() for i in range(3)]
1495 try:
1496 temp_fds = [fd for fd, fname in temps]
1497
1498 # unlink the files -- we won't need to reopen them
1499 for fd, fname in temps:
1500 os.unlink(fname)
1501
1502 # write some data to what will become stdin, and rewind
1503 os.write(temp_fds[1], b"STDIN")
1504 os.lseek(temp_fds[1], 0, 0)
1505
1506 # move the standard file descriptors out of the way
1507 saved_fds = [os.dup(fd) for fd in range(3)]
1508 try:
1509 # duplicate the file objects over the standard fd's
1510 for fd, temp_fd in enumerate(temp_fds):
1511 os.dup2(temp_fd, fd)
1512
1513 # now use those files in the "wrong" order, so that subprocess
1514 # has to rearrange them in the child
1515 p = subprocess.Popen([sys.executable, "-c",
1516 'import sys; got = sys.stdin.read();'
1517 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1518 stdin=temp_fds[1],
1519 stdout=temp_fds[2],
1520 stderr=temp_fds[0])
1521 p.wait()
1522 finally:
1523 # restore the original fd's underneath sys.stdin, etc.
1524 for std, saved in enumerate(saved_fds):
1525 os.dup2(saved, std)
1526 os.close(saved)
1527
1528 for fd in temp_fds:
1529 os.lseek(fd, 0, 0)
1530
1531 out = os.read(temp_fds[2], 1024)
1532 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1533 self.assertEqual(out, b"got STDIN")
1534 self.assertEqual(err, b"err")
1535
1536 finally:
1537 for fd in temp_fds:
1538 os.close(fd)
1539
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001540 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1541 # open up some temporary files
1542 temps = [mkstemp() for i in range(3)]
1543 temp_fds = [fd for fd, fname in temps]
1544 try:
1545 # unlink the files -- we won't need to reopen them
1546 for fd, fname in temps:
1547 os.unlink(fname)
1548
1549 # save a copy of the standard file descriptors
1550 saved_fds = [os.dup(fd) for fd in range(3)]
1551 try:
1552 # duplicate the temp files over the standard fd's 0, 1, 2
1553 for fd, temp_fd in enumerate(temp_fds):
1554 os.dup2(temp_fd, fd)
1555
1556 # write some data to what will become stdin, and rewind
1557 os.write(stdin_no, b"STDIN")
1558 os.lseek(stdin_no, 0, 0)
1559
1560 # now use those files in the given order, so that subprocess
1561 # has to rearrange them in the child
1562 p = subprocess.Popen([sys.executable, "-c",
1563 'import sys; got = sys.stdin.read();'
1564 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1565 stdin=stdin_no,
1566 stdout=stdout_no,
1567 stderr=stderr_no)
1568 p.wait()
1569
1570 for fd in temp_fds:
1571 os.lseek(fd, 0, 0)
1572
1573 out = os.read(stdout_no, 1024)
1574 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1575 finally:
1576 for std, saved in enumerate(saved_fds):
1577 os.dup2(saved, std)
1578 os.close(saved)
1579
1580 self.assertEqual(out, b"got STDIN")
1581 self.assertEqual(err, b"err")
1582
1583 finally:
1584 for fd in temp_fds:
1585 os.close(fd)
1586
1587 # When duping fds, if there arises a situation where one of the fds is
1588 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1589 # This tests all combinations of this.
1590 def test_swap_fds(self):
1591 self.check_swap_fds(0, 1, 2)
1592 self.check_swap_fds(0, 2, 1)
1593 self.check_swap_fds(1, 0, 2)
1594 self.check_swap_fds(1, 2, 0)
1595 self.check_swap_fds(2, 0, 1)
1596 self.check_swap_fds(2, 1, 0)
1597
Victor Stinner13bb71c2010-04-23 21:41:56 +00001598 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001599 def prepare():
1600 raise ValueError("surrogate:\uDCff")
1601
1602 try:
1603 subprocess.call(
1604 [sys.executable, "-c", "pass"],
1605 preexec_fn=prepare)
1606 except ValueError as err:
1607 # Pure Python implementations keeps the message
1608 self.assertIsNone(subprocess._posixsubprocess)
1609 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001610 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001611 # _posixsubprocess uses a default message
1612 self.assertIsNotNone(subprocess._posixsubprocess)
1613 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1614 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001615 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001616
Victor Stinner13bb71c2010-04-23 21:41:56 +00001617 def test_undecodable_env(self):
1618 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001619 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001620 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001621 env = os.environ.copy()
1622 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001623 # Use C locale to get ascii for the locale encoding to force
1624 # surrogate-escaping of \xFF in the child process; otherwise it can
1625 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001626 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001627 stdout = subprocess.check_output(
1628 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001629 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001630 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001631 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001632
1633 # test bytes
1634 key = key.encode("ascii", "surrogateescape")
1635 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001636 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001637 env = os.environ.copy()
1638 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001639 stdout = subprocess.check_output(
1640 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001641 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001642 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001643 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001644
Victor Stinnerb745a742010-05-18 17:17:23 +00001645 def test_bytes_program(self):
1646 abs_program = os.fsencode(sys.executable)
1647 path, program = os.path.split(sys.executable)
1648 program = os.fsencode(program)
1649
1650 # absolute bytes path
1651 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001652 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001653
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001654 # absolute bytes path as a string
1655 cmd = b"'" + abs_program + b"' -c pass"
1656 exitcode = subprocess.call(cmd, shell=True)
1657 self.assertEqual(exitcode, 0)
1658
Victor Stinnerb745a742010-05-18 17:17:23 +00001659 # bytes program, unicode PATH
1660 env = os.environ.copy()
1661 env["PATH"] = path
1662 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001663 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001664
1665 # bytes program, bytes PATH
1666 envb = os.environb.copy()
1667 envb[b"PATH"] = os.fsencode(path)
1668 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001669 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001670
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001671 def test_pipe_cloexec(self):
1672 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1673 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1674
1675 p1 = subprocess.Popen([sys.executable, sleeper],
1676 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1677 stderr=subprocess.PIPE, close_fds=False)
1678
1679 self.addCleanup(p1.communicate, b'')
1680
1681 p2 = subprocess.Popen([sys.executable, fd_status],
1682 stdout=subprocess.PIPE, close_fds=False)
1683
1684 output, error = p2.communicate()
1685 result_fds = set(map(int, output.split(b',')))
1686 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1687 p1.stderr.fileno()])
1688
1689 self.assertFalse(result_fds & unwanted_fds,
1690 "Expected no fds from %r to be open in child, "
1691 "found %r" %
1692 (unwanted_fds, result_fds & unwanted_fds))
1693
1694 def test_pipe_cloexec_real_tools(self):
1695 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1696 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1697
1698 subdata = b'zxcvbn'
1699 data = subdata * 4 + b'\n'
1700
1701 p1 = subprocess.Popen([sys.executable, qcat],
1702 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1703 close_fds=False)
1704
1705 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1706 stdin=p1.stdout, stdout=subprocess.PIPE,
1707 close_fds=False)
1708
1709 self.addCleanup(p1.wait)
1710 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001711 def kill_p1():
1712 try:
1713 p1.terminate()
1714 except ProcessLookupError:
1715 pass
1716 def kill_p2():
1717 try:
1718 p2.terminate()
1719 except ProcessLookupError:
1720 pass
1721 self.addCleanup(kill_p1)
1722 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001723
1724 p1.stdin.write(data)
1725 p1.stdin.close()
1726
1727 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1728
1729 self.assertTrue(readfiles, "The child hung")
1730 self.assertEqual(p2.stdout.read(), data)
1731
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001732 p1.stdout.close()
1733 p2.stdout.close()
1734
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001735 def test_close_fds(self):
1736 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1737
1738 fds = os.pipe()
1739 self.addCleanup(os.close, fds[0])
1740 self.addCleanup(os.close, fds[1])
1741
1742 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001743 # add a bunch more fds
1744 for _ in range(9):
1745 fd = os.open("/dev/null", os.O_RDONLY)
1746 self.addCleanup(os.close, fd)
1747 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001748
1749 p = subprocess.Popen([sys.executable, fd_status],
1750 stdout=subprocess.PIPE, close_fds=False)
1751 output, ignored = p.communicate()
1752 remaining_fds = set(map(int, output.split(b',')))
1753
1754 self.assertEqual(remaining_fds & open_fds, open_fds,
1755 "Some fds were closed")
1756
1757 p = subprocess.Popen([sys.executable, fd_status],
1758 stdout=subprocess.PIPE, close_fds=True)
1759 output, ignored = p.communicate()
1760 remaining_fds = set(map(int, output.split(b',')))
1761
1762 self.assertFalse(remaining_fds & open_fds,
1763 "Some fds were left open")
1764 self.assertIn(1, remaining_fds, "Subprocess failed")
1765
Gregory P. Smith8facece2012-01-21 14:01:08 -08001766 # Keep some of the fd's we opened open in the subprocess.
1767 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1768 fds_to_keep = set(open_fds.pop() for _ in range(8))
1769 p = subprocess.Popen([sys.executable, fd_status],
1770 stdout=subprocess.PIPE, close_fds=True,
1771 pass_fds=())
1772 output, ignored = p.communicate()
1773 remaining_fds = set(map(int, output.split(b',')))
1774
1775 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1776 "Some fds not in pass_fds were left open")
1777 self.assertIn(1, remaining_fds, "Subprocess failed")
1778
Victor Stinner88701e22011-06-01 13:13:04 +02001779 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1780 # descriptor of a pipe closed in the parent process is valid in the
1781 # child process according to fstat(), but the mode of the file
1782 # descriptor is invalid, and read or write raise an error.
1783 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001784 def test_pass_fds(self):
1785 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1786
1787 open_fds = set()
1788
1789 for x in range(5):
1790 fds = os.pipe()
1791 self.addCleanup(os.close, fds[0])
1792 self.addCleanup(os.close, fds[1])
1793 open_fds.update(fds)
1794
1795 for fd in open_fds:
1796 p = subprocess.Popen([sys.executable, fd_status],
1797 stdout=subprocess.PIPE, close_fds=True,
1798 pass_fds=(fd, ))
1799 output, ignored = p.communicate()
1800
1801 remaining_fds = set(map(int, output.split(b',')))
1802 to_be_closed = open_fds - {fd}
1803
1804 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1805 self.assertFalse(remaining_fds & to_be_closed,
1806 "fd to be closed passed")
1807
1808 # pass_fds overrides close_fds with a warning.
1809 with self.assertWarns(RuntimeWarning) as context:
1810 self.assertFalse(subprocess.call(
1811 [sys.executable, "-c", "import sys; sys.exit(0)"],
1812 close_fds=False, pass_fds=(fd, )))
1813 self.assertIn('overriding close_fds', str(context.warning))
1814
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001815 def test_stdout_stdin_are_single_inout_fd(self):
1816 with io.open(os.devnull, "r+") as inout:
1817 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1818 stdout=inout, stdin=inout)
1819 p.wait()
1820
1821 def test_stdout_stderr_are_single_inout_fd(self):
1822 with io.open(os.devnull, "r+") as inout:
1823 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1824 stdout=inout, stderr=inout)
1825 p.wait()
1826
1827 def test_stderr_stdin_are_single_inout_fd(self):
1828 with io.open(os.devnull, "r+") as inout:
1829 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1830 stderr=inout, stdin=inout)
1831 p.wait()
1832
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001833 def test_wait_when_sigchild_ignored(self):
1834 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1835 sigchild_ignore = support.findfile("sigchild_ignore.py",
1836 subdir="subprocessdata")
1837 p = subprocess.Popen([sys.executable, sigchild_ignore],
1838 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1839 stdout, stderr = p.communicate()
1840 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001841 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001842 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001843
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001844 def test_select_unbuffered(self):
1845 # Issue #11459: bufsize=0 should really set the pipes as
1846 # unbuffered (and therefore let select() work properly).
1847 select = support.import_module("select")
1848 p = subprocess.Popen([sys.executable, "-c",
1849 'import sys;'
1850 'sys.stdout.write("apple")'],
1851 stdout=subprocess.PIPE,
1852 bufsize=0)
1853 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001854 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001855 try:
1856 self.assertEqual(f.read(4), b"appl")
1857 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1858 finally:
1859 p.wait()
1860
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001861 def test_zombie_fast_process_del(self):
1862 # Issue #12650: on Unix, if Popen.__del__() was called before the
1863 # process exited, it wouldn't be added to subprocess._active, and would
1864 # remain a zombie.
1865 # spawn a Popen, and delete its reference before it exits
1866 p = subprocess.Popen([sys.executable, "-c",
1867 'import sys, time;'
1868 'time.sleep(0.2)'],
1869 stdout=subprocess.PIPE,
1870 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001871 self.addCleanup(p.stdout.close)
1872 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001873 ident = id(p)
1874 pid = p.pid
1875 del p
1876 # check that p is in the active processes list
1877 self.assertIn(ident, [id(o) for o in subprocess._active])
1878
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001879 def test_leak_fast_process_del_killed(self):
1880 # Issue #12650: on Unix, if Popen.__del__() was called before the
1881 # process exited, and the process got killed by a signal, it would never
1882 # be removed from subprocess._active, which triggered a FD and memory
1883 # leak.
1884 # spawn a Popen, delete its reference and kill it
1885 p = subprocess.Popen([sys.executable, "-c",
1886 'import time;'
1887 'time.sleep(3)'],
1888 stdout=subprocess.PIPE,
1889 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001890 self.addCleanup(p.stdout.close)
1891 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001892 ident = id(p)
1893 pid = p.pid
1894 del p
1895 os.kill(pid, signal.SIGKILL)
1896 # check that p is in the active processes list
1897 self.assertIn(ident, [id(o) for o in subprocess._active])
1898
1899 # let some time for the process to exit, and create a new Popen: this
1900 # should trigger the wait() of p
1901 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001902 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001903 with subprocess.Popen(['nonexisting_i_hope'],
1904 stdout=subprocess.PIPE,
1905 stderr=subprocess.PIPE) as proc:
1906 pass
1907 # p should have been wait()ed on, and removed from the _active list
1908 self.assertRaises(OSError, os.waitpid, pid, 0)
1909 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1910
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001911
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001912@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001913class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001914
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001915 def test_startupinfo(self):
1916 # startupinfo argument
1917 # We uses hardcoded constants, because we do not want to
1918 # depend on win32all.
1919 STARTF_USESHOWWINDOW = 1
1920 SW_MAXIMIZE = 3
1921 startupinfo = subprocess.STARTUPINFO()
1922 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1923 startupinfo.wShowWindow = SW_MAXIMIZE
1924 # Since Python is a console process, it won't be affected
1925 # by wShowWindow, but the argument should be silently
1926 # ignored
1927 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001928 startupinfo=startupinfo)
1929
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001930 def test_creationflags(self):
1931 # creationflags argument
1932 CREATE_NEW_CONSOLE = 16
1933 sys.stderr.write(" a DOS box should flash briefly ...\n")
1934 subprocess.call(sys.executable +
1935 ' -c "import time; time.sleep(0.25)"',
1936 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001937
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001938 def test_invalid_args(self):
1939 # invalid arguments should raise ValueError
1940 self.assertRaises(ValueError, subprocess.call,
1941 [sys.executable, "-c",
1942 "import sys; sys.exit(47)"],
1943 preexec_fn=lambda: 1)
1944 self.assertRaises(ValueError, subprocess.call,
1945 [sys.executable, "-c",
1946 "import sys; sys.exit(47)"],
1947 stdout=subprocess.PIPE,
1948 close_fds=True)
1949
1950 def test_close_fds(self):
1951 # close file descriptors
1952 rc = subprocess.call([sys.executable, "-c",
1953 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001954 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001955 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001956
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001957 def test_shell_sequence(self):
1958 # Run command through the shell (sequence)
1959 newenv = os.environ.copy()
1960 newenv["FRUIT"] = "physalis"
1961 p = subprocess.Popen(["set"], shell=1,
1962 stdout=subprocess.PIPE,
1963 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001964 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001965 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001966
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001967 def test_shell_string(self):
1968 # Run command through the shell (string)
1969 newenv = os.environ.copy()
1970 newenv["FRUIT"] = "physalis"
1971 p = subprocess.Popen("set", shell=1,
1972 stdout=subprocess.PIPE,
1973 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001974 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001975 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001976
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001977 def test_call_string(self):
1978 # call() function with string argument on Windows
1979 rc = subprocess.call(sys.executable +
1980 ' -c "import sys; sys.exit(47)"')
1981 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001982
Florent Xicluna4886d242010-03-08 13:27:26 +00001983 def _kill_process(self, method, *args):
1984 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001985 p = subprocess.Popen([sys.executable, "-c", """if 1:
1986 import sys, time
1987 sys.stdout.write('x\\n')
1988 sys.stdout.flush()
1989 time.sleep(30)
1990 """],
1991 stdin=subprocess.PIPE,
1992 stdout=subprocess.PIPE,
1993 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001994 self.addCleanup(p.stdout.close)
1995 self.addCleanup(p.stderr.close)
1996 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001997 # Wait for the interpreter to be completely initialized before
1998 # sending any signal.
1999 p.stdout.read(1)
2000 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00002001 _, stderr = p.communicate()
2002 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00002003 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002004 self.assertNotEqual(returncode, 0)
2005
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002006 def _kill_dead_process(self, method, *args):
2007 p = subprocess.Popen([sys.executable, "-c", """if 1:
2008 import sys, time
2009 sys.stdout.write('x\\n')
2010 sys.stdout.flush()
2011 sys.exit(42)
2012 """],
2013 stdin=subprocess.PIPE,
2014 stdout=subprocess.PIPE,
2015 stderr=subprocess.PIPE)
2016 self.addCleanup(p.stdout.close)
2017 self.addCleanup(p.stderr.close)
2018 self.addCleanup(p.stdin.close)
2019 # Wait for the interpreter to be completely initialized before
2020 # sending any signal.
2021 p.stdout.read(1)
2022 # The process should end after this
2023 time.sleep(1)
2024 # This shouldn't raise even though the child is now dead
2025 getattr(p, method)(*args)
2026 _, stderr = p.communicate()
2027 self.assertStderrEqual(stderr, b'')
2028 rc = p.wait()
2029 self.assertEqual(rc, 42)
2030
Florent Xicluna4886d242010-03-08 13:27:26 +00002031 def test_send_signal(self):
2032 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002033
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002034 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002035 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002036
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002037 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002038 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002039
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002040 def test_send_signal_dead(self):
2041 self._kill_dead_process('send_signal', signal.SIGTERM)
2042
2043 def test_kill_dead(self):
2044 self._kill_dead_process('kill')
2045
2046 def test_terminate_dead(self):
2047 self._kill_dead_process('terminate')
2048
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002049
Brett Cannona23810f2008-05-26 19:04:21 +00002050# The module says:
2051# "NB This only works (and is only relevant) for UNIX."
2052#
2053# Actually, getoutput should work on any platform with an os.popen, but
2054# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002055@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002056class CommandTests(unittest.TestCase):
2057 def test_getoutput(self):
2058 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2059 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2060 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002061
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002062 # we use mkdtemp in the next line to create an empty directory
2063 # under our exclusive control; from that, we can invent a pathname
2064 # that we _know_ won't exist. This is guaranteed to fail.
2065 dir = None
2066 try:
2067 dir = tempfile.mkdtemp()
2068 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00002069
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002070 status, output = subprocess.getstatusoutput('cat ' + name)
2071 self.assertNotEqual(status, 0)
2072 finally:
2073 if dir is not None:
2074 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002075
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002076
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002077@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
2078 "poll system call not supported")
2079class ProcessTestCaseNoPoll(ProcessTestCase):
2080 def setUp(self):
2081 subprocess._has_poll = False
2082 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002083
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002084 def tearDown(self):
2085 subprocess._has_poll = True
2086 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002087
2088
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002089class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00002090 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002091 def test_eintr_retry_call(self):
2092 record_calls = []
2093 def fake_os_func(*args):
2094 record_calls.append(args)
2095 if len(record_calls) == 2:
2096 raise OSError(errno.EINTR, "fake interrupted system call")
2097 return tuple(reversed(args))
2098
2099 self.assertEqual((999, 256),
2100 subprocess._eintr_retry_call(fake_os_func, 256, 999))
2101 self.assertEqual([(256, 999)], record_calls)
2102 # This time there will be an EINTR so it will loop once.
2103 self.assertEqual((666,),
2104 subprocess._eintr_retry_call(fake_os_func, 666))
2105 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
2106
2107
Tim Golden126c2962010-08-11 14:20:40 +00002108@unittest.skipUnless(mswindows, "Windows-specific tests")
2109class CommandsWithSpaces (BaseTestCase):
2110
2111 def setUp(self):
2112 super().setUp()
2113 f, fname = mkstemp(".py", "te st")
2114 self.fname = fname.lower ()
2115 os.write(f, b"import sys;"
2116 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2117 )
2118 os.close(f)
2119
2120 def tearDown(self):
2121 os.remove(self.fname)
2122 super().tearDown()
2123
2124 def with_spaces(self, *args, **kwargs):
2125 kwargs['stdout'] = subprocess.PIPE
2126 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002127 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002128 self.assertEqual(
2129 p.stdout.read ().decode("mbcs"),
2130 "2 [%r, 'ab cd']" % self.fname
2131 )
2132
2133 def test_shell_string_with_spaces(self):
2134 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002135 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2136 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002137
2138 def test_shell_sequence_with_spaces(self):
2139 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002140 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002141
2142 def test_noshell_string_with_spaces(self):
2143 # call() function with string argument with spaces on Windows
2144 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2145 "ab cd"))
2146
2147 def test_noshell_sequence_with_spaces(self):
2148 # call() function with sequence argument with spaces on Windows
2149 self.with_spaces([sys.executable, self.fname, "ab cd"])
2150
Brian Curtin79cdb662010-12-03 02:46:02 +00002151
Georg Brandla86b2622012-02-20 21:34:57 +01002152class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002153
2154 def test_pipe(self):
2155 with subprocess.Popen([sys.executable, "-c",
2156 "import sys;"
2157 "sys.stdout.write('stdout');"
2158 "sys.stderr.write('stderr');"],
2159 stdout=subprocess.PIPE,
2160 stderr=subprocess.PIPE) as proc:
2161 self.assertEqual(proc.stdout.read(), b"stdout")
2162 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2163
2164 self.assertTrue(proc.stdout.closed)
2165 self.assertTrue(proc.stderr.closed)
2166
2167 def test_returncode(self):
2168 with subprocess.Popen([sys.executable, "-c",
2169 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002170 pass
2171 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002172 self.assertEqual(proc.returncode, 100)
2173
2174 def test_communicate_stdin(self):
2175 with subprocess.Popen([sys.executable, "-c",
2176 "import sys;"
2177 "sys.exit(sys.stdin.read() == 'context')"],
2178 stdin=subprocess.PIPE) as proc:
2179 proc.communicate(b"context")
2180 self.assertEqual(proc.returncode, 1)
2181
2182 def test_invalid_args(self):
Andrew Svetlovb1726972012-12-26 23:34:54 +02002183 with self.assertRaises(FileNotFoundError) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002184 with subprocess.Popen(['nonexisting_i_hope'],
2185 stdout=subprocess.PIPE,
2186 stderr=subprocess.PIPE) as proc:
2187 pass
2188
Brian Curtin79cdb662010-12-03 02:46:02 +00002189
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002190def test_main():
2191 unit_tests = (ProcessTestCase,
2192 POSIXProcessTestCase,
2193 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002194 CommandTests,
2195 ProcessTestCaseNoPoll,
2196 HelperFunctionTests,
2197 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002198 ContextManagerTests,
2199 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002200
2201 support.run_unittest(*unit_tests)
2202 support.reap_children()
2203
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002204if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002205 unittest.main()