blob: ff74e87433e53e09ff22604c47ee08f9507e6972 [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):
Tim Peters7b759da2004-10-12 22:29:54 +0000187 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000188 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000189 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000190 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000191 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000192 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000193 self.addCleanup(p.stdin.close)
194 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000195 p.wait()
196 self.assertEqual(p.stdout, None)
197
198 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000199 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000200 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000201 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000202 self.addCleanup(p.stdout.close)
203 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000204 p.wait()
205 self.assertEqual(p.stderr, None)
206
Chris Jerdonek776cb192012-10-08 15:56:43 -0700207 def _assert_python(self, pre_args, **kwargs):
208 # We include sys.exit() to prevent the test runner from hanging
209 # whenever python is found.
210 args = pre_args + ["import sys; sys.exit(47)"]
211 p = subprocess.Popen(args, **kwargs)
212 p.wait()
213 self.assertEqual(47, p.returncode)
214
215 def test_executable(self):
216 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700217 #
218 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
219 # determine where its standard library is, so we need the directory
220 # of args[0] to be valid for the Popen() call to Python to succeed.
221 # See also issue #16170 and issue #7774.
222 doesnotexist = os.path.join(os.path.dirname(sys.executable),
223 "doesnotexist")
224 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700225
226 def test_executable_takes_precedence(self):
227 # Check that the executable argument takes precedence over args[0].
228 #
229 # Verify first that the call succeeds without the executable arg.
230 pre_args = [sys.executable, "-c"]
231 self._assert_python(pre_args)
232 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
233 executable="doesnotexist")
234
235 @unittest.skipIf(mswindows, "executable argument replaces shell")
236 def test_executable_replaces_shell(self):
237 # Check that the executable argument replaces the default shell
238 # when shell=True.
239 self._assert_python([], executable=sys.executable, shell=True)
240
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700241 # For use in the test_cwd* tests below.
242 def _normalize_cwd(self, cwd):
243 # Normalize an expected cwd (for Tru64 support).
244 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
245 # strings. See bug #1063571.
246 original_cwd = os.getcwd()
247 os.chdir(cwd)
248 cwd = os.getcwd()
249 os.chdir(original_cwd)
250 return cwd
251
252 # For use in the test_cwd* tests below.
253 def _split_python_path(self):
254 # Return normalized (python_dir, python_base).
255 python_path = os.path.realpath(sys.executable)
256 return os.path.split(python_path)
257
258 # For use in the test_cwd* tests below.
259 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
260 # Invoke Python via Popen, and assert that (1) the call succeeds,
261 # and that (2) the current working directory of the child process
262 # matches *expected_cwd*.
263 p = subprocess.Popen([python_arg, "-c",
264 "import os, sys; "
265 "sys.stdout.write(os.getcwd()); "
266 "sys.exit(47)"],
267 stdout=subprocess.PIPE,
268 **kwargs)
269 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000270 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700271 self.assertEqual(47, p.returncode)
272 normcase = os.path.normcase
273 self.assertEqual(normcase(expected_cwd),
274 normcase(p.stdout.read().decode("utf-8")))
275
276 def test_cwd(self):
277 # Check that cwd changes the cwd for the child process.
278 temp_dir = tempfile.gettempdir()
279 temp_dir = self._normalize_cwd(temp_dir)
280 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
281
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700282 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700283 def test_cwd_with_relative_arg(self):
284 # Check that Popen looks for args[0] relative to cwd if args[0]
285 # is relative.
286 python_dir, python_base = self._split_python_path()
287 rel_python = os.path.join(os.curdir, python_base)
288 with support.temp_cwd() as wrong_dir:
289 # Before calling with the correct cwd, confirm that the call fails
290 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700291 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700292 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700293 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700294 [rel_python], cwd=wrong_dir)
295 python_dir = self._normalize_cwd(python_dir)
296 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
297
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700298 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700299 def test_cwd_with_relative_executable(self):
300 # Check that Popen looks for executable relative to cwd if executable
301 # is relative (and that executable takes precedence over args[0]).
302 python_dir, python_base = self._split_python_path()
303 rel_python = os.path.join(os.curdir, python_base)
304 doesntexist = "somethingyoudonthave"
305 with support.temp_cwd() as wrong_dir:
306 # Before calling with the correct cwd, confirm that the call fails
307 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700308 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700309 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700310 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700311 [doesntexist], executable=rel_python,
312 cwd=wrong_dir)
313 python_dir = self._normalize_cwd(python_dir)
314 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
315 cwd=python_dir)
316
317 def test_cwd_with_absolute_arg(self):
318 # Check that Popen can find the executable when the cwd is wrong
319 # if args[0] is an absolute path.
320 python_dir, python_base = self._split_python_path()
321 abs_python = os.path.join(python_dir, python_base)
322 rel_python = os.path.join(os.curdir, python_base)
323 with script_helper.temp_dir() as wrong_dir:
324 # Before calling with an absolute path, confirm that using a
325 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700326 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700327 [rel_python], cwd=wrong_dir)
328 wrong_dir = self._normalize_cwd(wrong_dir)
329 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
330
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100331 @unittest.skipIf(sys.base_prefix != sys.prefix,
332 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000333 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700334 python_dir, python_base = self._split_python_path()
335 python_dir = self._normalize_cwd(python_dir)
336 self._assert_cwd(python_dir, "somethingyoudonthave",
337 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000338
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100339 @unittest.skipIf(sys.base_prefix != sys.prefix,
340 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000341 @unittest.skipIf(sysconfig.is_python_build(),
342 "need an installed Python. See #7774")
343 def test_executable_without_cwd(self):
344 # For a normal installation, it should work without 'cwd'
345 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700346 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000347
348 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000349 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000350 p = subprocess.Popen([sys.executable, "-c",
351 'import sys; sys.exit(sys.stdin.read() == "pear")'],
352 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000353 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354 p.stdin.close()
355 p.wait()
356 self.assertEqual(p.returncode, 1)
357
358 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000359 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000360 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000361 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000363 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000364 os.lseek(d, 0, 0)
365 p = subprocess.Popen([sys.executable, "-c",
366 'import sys; sys.exit(sys.stdin.read() == "pear")'],
367 stdin=d)
368 p.wait()
369 self.assertEqual(p.returncode, 1)
370
371 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000372 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000373 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000374 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000375 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000376 tf.seek(0)
377 p = subprocess.Popen([sys.executable, "-c",
378 'import sys; sys.exit(sys.stdin.read() == "pear")'],
379 stdin=tf)
380 p.wait()
381 self.assertEqual(p.returncode, 1)
382
383 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000384 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000385 p = subprocess.Popen([sys.executable, "-c",
386 'import sys; sys.stdout.write("orange")'],
387 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000388 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000389 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390
391 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000392 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000393 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000394 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000395 d = tf.fileno()
396 p = subprocess.Popen([sys.executable, "-c",
397 'import sys; sys.stdout.write("orange")'],
398 stdout=d)
399 p.wait()
400 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000401 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000402
403 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000404 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000405 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000406 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000407 p = subprocess.Popen([sys.executable, "-c",
408 'import sys; sys.stdout.write("orange")'],
409 stdout=tf)
410 p.wait()
411 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000412 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413
414 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000415 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416 p = subprocess.Popen([sys.executable, "-c",
417 'import sys; sys.stderr.write("strawberry")'],
418 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000419 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000420 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000421
422 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000423 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000424 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000425 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426 d = tf.fileno()
427 p = subprocess.Popen([sys.executable, "-c",
428 'import sys; sys.stderr.write("strawberry")'],
429 stderr=d)
430 p.wait()
431 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000432 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433
434 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000435 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000436 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000437 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438 p = subprocess.Popen([sys.executable, "-c",
439 'import sys; sys.stderr.write("strawberry")'],
440 stderr=tf)
441 p.wait()
442 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000443 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444
445 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000446 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000447 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000448 'import sys;'
449 'sys.stdout.write("apple");'
450 'sys.stdout.flush();'
451 'sys.stderr.write("orange")'],
452 stdout=subprocess.PIPE,
453 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000454 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000455 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000456
457 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000458 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000460 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000461 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000462 'import sys;'
463 'sys.stdout.write("apple");'
464 'sys.stdout.flush();'
465 'sys.stderr.write("orange")'],
466 stdout=tf,
467 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468 p.wait()
469 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000470 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471
Thomas Wouters89f507f2006-12-13 04:49:30 +0000472 def test_stdout_filedes_of_stdout(self):
473 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000474 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000475 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000476 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000477
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200478 def test_stdout_devnull(self):
479 p = subprocess.Popen([sys.executable, "-c",
480 'for i in range(10240):'
481 'print("x" * 1024)'],
482 stdout=subprocess.DEVNULL)
483 p.wait()
484 self.assertEqual(p.stdout, None)
485
486 def test_stderr_devnull(self):
487 p = subprocess.Popen([sys.executable, "-c",
488 'import sys\n'
489 'for i in range(10240):'
490 'sys.stderr.write("x" * 1024)'],
491 stderr=subprocess.DEVNULL)
492 p.wait()
493 self.assertEqual(p.stderr, None)
494
495 def test_stdin_devnull(self):
496 p = subprocess.Popen([sys.executable, "-c",
497 'import sys;'
498 'sys.stdin.read(1)'],
499 stdin=subprocess.DEVNULL)
500 p.wait()
501 self.assertEqual(p.stdin, None)
502
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000503 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504 newenv = os.environ.copy()
505 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200506 with subprocess.Popen([sys.executable, "-c",
507 'import sys,os;'
508 'sys.stdout.write(os.getenv("FRUIT"))'],
509 stdout=subprocess.PIPE,
510 env=newenv) as p:
511 stdout, stderr = p.communicate()
512 self.assertEqual(stdout, b"orange")
513
Victor Stinner62d51182011-06-23 01:02:25 +0200514 # Windows requires at least the SYSTEMROOT environment variable to start
515 # Python
516 @unittest.skipIf(sys.platform == 'win32',
517 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200518 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200519 'the python library cannot be loaded '
520 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200521 def test_empty_env(self):
522 with subprocess.Popen([sys.executable, "-c",
523 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200524 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200525 stdout=subprocess.PIPE,
526 env={}) as p:
527 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200528 self.assertIn(stdout.strip(),
529 (b"[]",
530 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
531 # environment
532 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000533
Peter Astrandcbac93c2005-03-03 20:24:28 +0000534 def test_communicate_stdin(self):
535 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000536 'import sys;'
537 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000538 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000539 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000540 self.assertEqual(p.returncode, 1)
541
542 def test_communicate_stdout(self):
543 p = subprocess.Popen([sys.executable, "-c",
544 'import sys; sys.stdout.write("pineapple")'],
545 stdout=subprocess.PIPE)
546 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000547 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000548 self.assertEqual(stderr, None)
549
550 def test_communicate_stderr(self):
551 p = subprocess.Popen([sys.executable, "-c",
552 'import sys; sys.stderr.write("pineapple")'],
553 stderr=subprocess.PIPE)
554 (stdout, stderr) = p.communicate()
555 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000556 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000557
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000560 'import sys,os;'
561 'sys.stderr.write("pineapple");'
562 'sys.stdout.write(sys.stdin.read())'],
563 stdin=subprocess.PIPE,
564 stdout=subprocess.PIPE,
565 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000566 self.addCleanup(p.stdout.close)
567 self.addCleanup(p.stderr.close)
568 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000569 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000570 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000571 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000572
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400573 def test_communicate_timeout(self):
574 p = subprocess.Popen([sys.executable, "-c",
575 'import sys,os,time;'
576 'sys.stderr.write("pineapple\\n");'
577 'time.sleep(1);'
578 'sys.stderr.write("pear\\n");'
579 'sys.stdout.write(sys.stdin.read())'],
580 universal_newlines=True,
581 stdin=subprocess.PIPE,
582 stdout=subprocess.PIPE,
583 stderr=subprocess.PIPE)
584 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
585 timeout=0.3)
586 # Make sure we can keep waiting for it, and that we get the whole output
587 # after it completes.
588 (stdout, stderr) = p.communicate()
589 self.assertEqual(stdout, "banana")
590 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
591
592 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200593 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400594 p = subprocess.Popen([sys.executable, "-c",
595 'import sys,os,time;'
596 'sys.stdout.write("a" * (64 * 1024));'
597 'time.sleep(0.2);'
598 'sys.stdout.write("a" * (64 * 1024));'
599 'time.sleep(0.2);'
600 'sys.stdout.write("a" * (64 * 1024));'
601 'time.sleep(0.2);'
602 'sys.stdout.write("a" * (64 * 1024));'],
603 stdout=subprocess.PIPE)
604 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
605 (stdout, _) = p.communicate()
606 self.assertEqual(len(stdout), 4 * 64 * 1024)
607
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000608 # Test for the fd leak reported in http://bugs.python.org/issue2791.
609 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000610 for stdin_pipe in (False, True):
611 for stdout_pipe in (False, True):
612 for stderr_pipe in (False, True):
613 options = {}
614 if stdin_pipe:
615 options['stdin'] = subprocess.PIPE
616 if stdout_pipe:
617 options['stdout'] = subprocess.PIPE
618 if stderr_pipe:
619 options['stderr'] = subprocess.PIPE
620 if not options:
621 continue
622 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
623 p.communicate()
624 if p.stdin is not None:
625 self.assertTrue(p.stdin.closed)
626 if p.stdout is not None:
627 self.assertTrue(p.stdout.closed)
628 if p.stderr is not None:
629 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000630
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000632 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000633 p = subprocess.Popen([sys.executable, "-c",
634 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000635 (stdout, stderr) = p.communicate()
636 self.assertEqual(stdout, None)
637 self.assertEqual(stderr, None)
638
639 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000640 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000641 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000642 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000644 os.close(x)
645 os.close(y)
646 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000647 'import sys,os;'
648 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200649 'sys.stderr.write("x" * %d);'
650 'sys.stdout.write(sys.stdin.read())' %
651 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000652 stdin=subprocess.PIPE,
653 stdout=subprocess.PIPE,
654 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000655 self.addCleanup(p.stdout.close)
656 self.addCleanup(p.stderr.close)
657 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200658 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659 (stdout, stderr) = p.communicate(string_to_write)
660 self.assertEqual(stdout, string_to_write)
661
662 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000663 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000664 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000665 'import sys,os;'
666 'sys.stdout.write(sys.stdin.read())'],
667 stdin=subprocess.PIPE,
668 stdout=subprocess.PIPE,
669 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000670 self.addCleanup(p.stdout.close)
671 self.addCleanup(p.stderr.close)
672 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000673 p.stdin.write(b"banana")
674 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000675 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000676 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000677
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000678 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000679 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000680 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200681 'buf = sys.stdout.buffer;'
682 'buf.write(sys.stdin.readline().encode());'
683 'buf.flush();'
684 'buf.write(b"line2\\n");'
685 'buf.flush();'
686 'buf.write(sys.stdin.read().encode());'
687 'buf.flush();'
688 'buf.write(b"line4\\n");'
689 'buf.flush();'
690 'buf.write(b"line5\\r\\n");'
691 'buf.flush();'
692 'buf.write(b"line6\\r");'
693 'buf.flush();'
694 'buf.write(b"\\nline7");'
695 'buf.flush();'
696 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200697 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000698 stdout=subprocess.PIPE,
699 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200700 p.stdin.write("line1\n")
701 self.assertEqual(p.stdout.readline(), "line1\n")
702 p.stdin.write("line3\n")
703 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000704 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200705 self.assertEqual(p.stdout.readline(),
706 "line2\n")
707 self.assertEqual(p.stdout.read(6),
708 "line3\n")
709 self.assertEqual(p.stdout.read(),
710 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000711
712 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000713 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000714 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000715 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200716 'buf = sys.stdout.buffer;'
717 'buf.write(b"line2\\n");'
718 'buf.flush();'
719 'buf.write(b"line4\\n");'
720 'buf.flush();'
721 'buf.write(b"line5\\r\\n");'
722 'buf.flush();'
723 'buf.write(b"line6\\r");'
724 'buf.flush();'
725 'buf.write(b"\\nline7");'
726 'buf.flush();'
727 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200728 stderr=subprocess.PIPE,
729 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000730 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000731 self.addCleanup(p.stdout.close)
732 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000733 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200734 self.assertEqual(stdout,
735 "line2\nline4\nline5\nline6\nline7\nline8")
736
737 def test_universal_newlines_communicate_stdin(self):
738 # universal newlines through communicate(), with only stdin
739 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300740 'import sys,os;' + SETBINARY + textwrap.dedent('''
741 s = sys.stdin.readline()
742 assert s == "line1\\n", repr(s)
743 s = sys.stdin.read()
744 assert s == "line3\\n", repr(s)
745 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200746 stdin=subprocess.PIPE,
747 universal_newlines=1)
748 (stdout, stderr) = p.communicate("line1\nline3\n")
749 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000750
Andrew Svetlovf3765072012-08-14 18:35:17 +0300751 def test_universal_newlines_communicate_input_none(self):
752 # Test communicate(input=None) with universal newlines.
753 #
754 # We set stdout to PIPE because, as of this writing, a different
755 # code path is tested when the number of pipes is zero or one.
756 p = subprocess.Popen([sys.executable, "-c", "pass"],
757 stdin=subprocess.PIPE,
758 stdout=subprocess.PIPE,
759 universal_newlines=True)
760 p.communicate()
761 self.assertEqual(p.returncode, 0)
762
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300763 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300764 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300765 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300766 'import sys,os;' + SETBINARY + textwrap.dedent('''
767 s = sys.stdin.buffer.readline()
768 sys.stdout.buffer.write(s)
769 sys.stdout.buffer.write(b"line2\\r")
770 sys.stderr.buffer.write(b"eline2\\n")
771 s = sys.stdin.buffer.read()
772 sys.stdout.buffer.write(s)
773 sys.stdout.buffer.write(b"line4\\n")
774 sys.stdout.buffer.write(b"line5\\r\\n")
775 sys.stderr.buffer.write(b"eline6\\r")
776 sys.stderr.buffer.write(b"eline7\\r\\nz")
777 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300778 stdin=subprocess.PIPE,
779 stderr=subprocess.PIPE,
780 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300781 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300782 self.addCleanup(p.stdout.close)
783 self.addCleanup(p.stderr.close)
784 (stdout, stderr) = p.communicate("line1\nline3\n")
785 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300786 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300787 # Python debug build push something like "[42442 refs]\n"
788 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300789 # Don't use assertStderrEqual because it strips CR and LF from output.
790 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300791
Andrew Svetlov82860712012-08-19 22:13:41 +0300792 def test_universal_newlines_communicate_encodings(self):
793 # Check that universal newlines mode works for various encodings,
794 # in particular for encodings in the UTF-16 and UTF-32 families.
795 # See issue #15595.
796 #
797 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
798 # without, and UTF-16 and UTF-32.
799 for encoding in ['utf-16', 'utf-32-be']:
800 old_getpreferredencoding = locale.getpreferredencoding
801 # Indirectly via io.TextIOWrapper, Popen() defaults to
802 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
803 # locale.getpreferredencoding().
804 def getpreferredencoding(do_setlocale=True):
805 return encoding
806 code = ("import sys; "
807 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
808 encoding)
809 args = [sys.executable, '-c', code]
810 try:
811 locale.getpreferredencoding = getpreferredencoding
812 # We set stdin to be non-None because, as of this writing,
813 # a different code path is used when the number of pipes is
814 # zero or one.
815 popen = subprocess.Popen(args, universal_newlines=True,
816 stdin=subprocess.PIPE,
817 stdout=subprocess.PIPE)
818 stdout, stderr = popen.communicate(input='')
819 finally:
820 locale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300821 self.assertEqual(stdout, '1\n2\n3\n4')
822
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000823 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000824 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000825 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000826 max_handles = 1026 # too much for most UNIX systems
827 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000828 max_handles = 2050 # too much for (at least some) Windows setups
829 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400830 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000831 try:
832 for i in range(max_handles):
833 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400834 tmpfile = os.path.join(tmpdir, support.TESTFN)
835 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000836 except OSError as e:
837 if e.errno != errno.EMFILE:
838 raise
839 break
840 else:
841 self.skipTest("failed to reach the file descriptor limit "
842 "(tried %d)" % max_handles)
843 # Close a couple of them (should be enough for a subprocess)
844 for i in range(10):
845 os.close(handles.pop())
846 # Loop creating some subprocesses. If one of them leaks some fds,
847 # the next loop iteration will fail by reaching the max fd limit.
848 for i in range(15):
849 p = subprocess.Popen([sys.executable, "-c",
850 "import sys;"
851 "sys.stdout.write(sys.stdin.read())"],
852 stdin=subprocess.PIPE,
853 stdout=subprocess.PIPE,
854 stderr=subprocess.PIPE)
855 data = p.communicate(b"lime")[0]
856 self.assertEqual(data, b"lime")
857 finally:
858 for h in handles:
859 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400860 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000861
862 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000863 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
864 '"a b c" d e')
865 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
866 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000867 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
868 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000869 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
870 'a\\\\\\b "de fg" h')
871 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
872 'a\\\\\\"b c d')
873 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
874 '"a\\\\b c" d e')
875 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
876 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000877 self.assertEqual(subprocess.list2cmdline(['ab', '']),
878 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000879
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000880 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200881 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200882 "import os; os.read(0, 1)"],
883 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200884 self.addCleanup(p.stdin.close)
885 self.assertIsNone(p.poll())
886 os.write(p.stdin.fileno(), b'A')
887 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000888 # Subsequent invocations should just return the returncode
889 self.assertEqual(p.poll(), 0)
890
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000891 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200892 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000893 self.assertEqual(p.wait(), 0)
894 # Subsequent invocations should just return the returncode
895 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000896
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400897 def test_wait_timeout(self):
898 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400899 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400900 with self.assertRaises(subprocess.TimeoutExpired) as c:
901 p.wait(timeout=0.01)
902 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400903 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
904 # time to start.
905 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400906
Peter Astrand738131d2004-11-30 21:04:45 +0000907 def test_invalid_bufsize(self):
908 # an invalid type of the bufsize argument should raise
909 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000910 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000911 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000912
Guido van Rossum46a05a72007-06-07 21:56:45 +0000913 def test_bufsize_is_none(self):
914 # bufsize=None should be the same as bufsize=0.
915 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
916 self.assertEqual(p.wait(), 0)
917 # Again with keyword arg
918 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
919 self.assertEqual(p.wait(), 0)
920
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000921 def test_leaking_fds_on_error(self):
922 # see bug #5179: Popen leaks file descriptors to PIPEs if
923 # the child fails to execute; this will eventually exhaust
924 # the maximum number of open fds. 1024 seems a very common
925 # value for that limit, but Windows has 2048, so we loop
926 # 1024 times (each call leaked two fds).
927 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000928 # Windows raises IOError. Others raise OSError.
929 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000930 subprocess.Popen(['nonexisting_i_hope'],
931 stdout=subprocess.PIPE,
932 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400933 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400934 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000935 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000936
Victor Stinnerb3693582010-05-21 20:13:12 +0000937 def test_issue8780(self):
938 # Ensure that stdout is inherited from the parent
939 # if stdout=PIPE is not used
940 code = ';'.join((
941 'import subprocess, sys',
942 'retcode = subprocess.call('
943 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
944 'assert retcode == 0'))
945 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000946 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000947
Tim Goldenaf5ac392010-08-06 13:03:56 +0000948 def test_handles_closed_on_exception(self):
949 # If CreateProcess exits with an error, ensure the
950 # duplicate output handles are released
951 ifhandle, ifname = mkstemp()
952 ofhandle, ofname = mkstemp()
953 efhandle, efname = mkstemp()
954 try:
955 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
956 stderr=efhandle)
957 except OSError:
958 os.close(ifhandle)
959 os.remove(ifname)
960 os.close(ofhandle)
961 os.remove(ofname)
962 os.close(efhandle)
963 os.remove(efname)
964 self.assertFalse(os.path.exists(ifname))
965 self.assertFalse(os.path.exists(ofname))
966 self.assertFalse(os.path.exists(efname))
967
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200968 def test_communicate_epipe(self):
969 # Issue 10963: communicate() should hide EPIPE
970 p = subprocess.Popen([sys.executable, "-c", 'pass'],
971 stdin=subprocess.PIPE,
972 stdout=subprocess.PIPE,
973 stderr=subprocess.PIPE)
974 self.addCleanup(p.stdout.close)
975 self.addCleanup(p.stderr.close)
976 self.addCleanup(p.stdin.close)
977 p.communicate(b"x" * 2**20)
978
979 def test_communicate_epipe_only_stdin(self):
980 # Issue 10963: communicate() should hide EPIPE
981 p = subprocess.Popen([sys.executable, "-c", 'pass'],
982 stdin=subprocess.PIPE)
983 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200984 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200985 p.communicate(b"x" * 2**20)
986
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200987 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
988 "Requires signal.SIGUSR1")
989 @unittest.skipUnless(hasattr(os, 'kill'),
990 "Requires os.kill")
991 @unittest.skipUnless(hasattr(os, 'getppid'),
992 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200993 def test_communicate_eintr(self):
994 # Issue #12493: communicate() should handle EINTR
995 def handler(signum, frame):
996 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200997 old_handler = signal.signal(signal.SIGUSR1, handler)
998 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200999
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001000 args = [sys.executable, "-c",
1001 'import os, signal;'
1002 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001003 for stream in ('stdout', 'stderr'):
1004 kw = {stream: subprocess.PIPE}
1005 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001006 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001007 process.communicate()
1008
Tim Peterse718f612004-10-12 21:51:32 +00001009
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001010 # This test is Linux-ish specific for simplicity to at least have
1011 # some coverage. It is not a platform specific bug.
1012 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1013 "Linux specific")
1014 def test_failed_child_execute_fd_leak(self):
1015 """Test for the fork() failure fd leak reported in issue16327."""
1016 fd_directory = '/proc/%d/fd' % os.getpid()
1017 fds_before_popen = os.listdir(fd_directory)
1018 with self.assertRaises(PopenTestException):
1019 PopenExecuteChildRaises(
1020 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1021 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1022
1023 # NOTE: This test doesn't verify that the real _execute_child
1024 # does not close the file descriptors itself on the way out
1025 # during an exception. Code inspection has confirmed that.
1026
1027 fds_after_exception = os.listdir(fd_directory)
1028 self.assertEqual(fds_before_popen, fds_after_exception)
1029
1030
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001031# context manager
1032class _SuppressCoreFiles(object):
1033 """Try to prevent core files from being created."""
1034 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001035
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001036 def __enter__(self):
1037 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -05001038 if resource is not None:
1039 try:
1040 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
1041 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
1042 except (ValueError, resource.error):
1043 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001044
Ronald Oussoren102d11a2010-07-23 09:50:05 +00001045 if sys.platform == 'darwin':
1046 # Check if the 'Crash Reporter' on OSX was configured
1047 # in 'Developer' mode and warn that it will get triggered
1048 # when it is.
1049 #
1050 # This assumes that this context manager is used in tests
1051 # that might trigger the next manager.
1052 value = subprocess.Popen(['/usr/bin/defaults', 'read',
1053 'com.apple.CrashReporter', 'DialogType'],
1054 stdout=subprocess.PIPE).communicate()[0]
1055 if value.strip() == b'developer':
1056 print("this tests triggers the Crash Reporter, "
1057 "that is intentional", end='')
1058 sys.stdout.flush()
1059
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001060 def __exit__(self, *args):
1061 """Return core file behavior to default."""
1062 if self.old_limit is None:
1063 return
Benjamin Peterson964561b2011-12-10 12:31:42 -05001064 if resource is not None:
1065 try:
1066 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
1067 except (ValueError, resource.error):
1068 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001069
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001070
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001071@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001072class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001073
Gregory P. Smith5591b022012-10-10 03:34:47 -07001074 def setUp(self):
1075 super().setUp()
1076 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1077
1078 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001079 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001080 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001081 except OSError as e:
1082 # This avoids hard coding the errno value or the OS perror()
1083 # string and instead capture the exception that we want to see
1084 # below for comparison.
1085 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001086 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001087 else:
1088 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001089 self._nonexistent_dir)
1090 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001091
Gregory P. Smith5591b022012-10-10 03:34:47 -07001092 def test_exception_cwd(self):
1093 """Test error in the child raised in the parent for a bad cwd."""
1094 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001095 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001096 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001097 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001098 except OSError as e:
1099 # Test that the child process chdir failure actually makes
1100 # it up to the parent process as the correct exception.
1101 self.assertEqual(desired_exception.errno, e.errno)
1102 self.assertEqual(desired_exception.strerror, e.strerror)
1103 else:
1104 self.fail("Expected OSError: %s" % desired_exception)
1105
Gregory P. Smith5591b022012-10-10 03:34:47 -07001106 def test_exception_bad_executable(self):
1107 """Test error in the child raised in the parent for a bad executable."""
1108 desired_exception = self._get_chdir_exception()
1109 try:
1110 p = subprocess.Popen([sys.executable, "-c", ""],
1111 executable=self._nonexistent_dir)
1112 except OSError as e:
1113 # Test that the child process exec failure actually makes
1114 # it up to the parent process as the correct exception.
1115 self.assertEqual(desired_exception.errno, e.errno)
1116 self.assertEqual(desired_exception.strerror, e.strerror)
1117 else:
1118 self.fail("Expected OSError: %s" % desired_exception)
1119
1120 def test_exception_bad_args_0(self):
1121 """Test error in the child raised in the parent for a bad args[0]."""
1122 desired_exception = self._get_chdir_exception()
1123 try:
1124 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1125 except OSError as e:
1126 # Test that the child process exec failure actually makes
1127 # it up to the parent process as the correct exception.
1128 self.assertEqual(desired_exception.errno, e.errno)
1129 self.assertEqual(desired_exception.strerror, e.strerror)
1130 else:
1131 self.fail("Expected OSError: %s" % desired_exception)
1132
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001133 def test_restore_signals(self):
1134 # Code coverage for both values of restore_signals to make sure it
1135 # at least does not blow up.
1136 # A test for behavior would be complex. Contributions welcome.
1137 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1138 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1139
1140 def test_start_new_session(self):
1141 # For code coverage of calling setsid(). We don't care if we get an
1142 # EPERM error from it depending on the test execution environment, that
1143 # still indicates that it was called.
1144 try:
1145 output = subprocess.check_output(
1146 [sys.executable, "-c",
1147 "import os; print(os.getpgid(os.getpid()))"],
1148 start_new_session=True)
1149 except OSError as e:
1150 if e.errno != errno.EPERM:
1151 raise
1152 else:
1153 parent_pgid = os.getpgid(os.getpid())
1154 child_pgid = int(output)
1155 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001156
1157 def test_run_abort(self):
1158 # returncode handles signal termination
1159 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001160 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001161 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001162 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001163 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001164
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001165 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001166 # DISCLAIMER: Setting environment variables is *not* a good use
1167 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001168 p = subprocess.Popen([sys.executable, "-c",
1169 'import sys,os;'
1170 'sys.stdout.write(os.getenv("FRUIT"))'],
1171 stdout=subprocess.PIPE,
1172 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001173 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001174 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001175
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001176 def test_preexec_exception(self):
1177 def raise_it():
1178 raise ValueError("What if two swallows carried a coconut?")
1179 try:
1180 p = subprocess.Popen([sys.executable, "-c", ""],
1181 preexec_fn=raise_it)
1182 except RuntimeError as e:
1183 self.assertTrue(
1184 subprocess._posixsubprocess,
1185 "Expected a ValueError from the preexec_fn")
1186 except ValueError as e:
1187 self.assertIn("coconut", e.args[0])
1188 else:
1189 self.fail("Exception raised by preexec_fn did not make it "
1190 "to the parent process.")
1191
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001192 class _TestExecuteChildPopen(subprocess.Popen):
1193 """Used to test behavior at the end of _execute_child."""
1194 def __init__(self, testcase, *args, **kwargs):
1195 self._testcase = testcase
1196 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001197
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001198 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001199 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001200 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001201 finally:
1202 # Open a bunch of file descriptors and verify that
1203 # none of them are the same as the ones the Popen
1204 # instance is using for stdin/stdout/stderr.
1205 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1206 for _ in range(8)]
1207 try:
1208 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001209 self._testcase.assertNotIn(
1210 fd, (self.stdin.fileno(), self.stdout.fileno(),
1211 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001212 msg="At least one fd was closed early.")
1213 finally:
1214 map(os.close, devzero_fds)
1215
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001216 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1217 def test_preexec_errpipe_does_not_double_close_pipes(self):
1218 """Issue16140: Don't double close pipes on preexec error."""
1219
1220 def raise_it():
1221 raise RuntimeError("force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001222
1223 with self.assertRaises(RuntimeError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001224 self._TestExecuteChildPopen(
1225 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001226 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1227 stderr=subprocess.PIPE, preexec_fn=raise_it)
1228
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001229 def test_preexec_gc_module_failure(self):
1230 # This tests the code that disables garbage collection if the child
1231 # process will execute any Python.
1232 def raise_runtime_error():
1233 raise RuntimeError("this shouldn't escape")
1234 enabled = gc.isenabled()
1235 orig_gc_disable = gc.disable
1236 orig_gc_isenabled = gc.isenabled
1237 try:
1238 gc.disable()
1239 self.assertFalse(gc.isenabled())
1240 subprocess.call([sys.executable, '-c', ''],
1241 preexec_fn=lambda: None)
1242 self.assertFalse(gc.isenabled(),
1243 "Popen enabled gc when it shouldn't.")
1244
1245 gc.enable()
1246 self.assertTrue(gc.isenabled())
1247 subprocess.call([sys.executable, '-c', ''],
1248 preexec_fn=lambda: None)
1249 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1250
1251 gc.disable = raise_runtime_error
1252 self.assertRaises(RuntimeError, subprocess.Popen,
1253 [sys.executable, '-c', ''],
1254 preexec_fn=lambda: None)
1255
1256 del gc.isenabled # force an AttributeError
1257 self.assertRaises(AttributeError, subprocess.Popen,
1258 [sys.executable, '-c', ''],
1259 preexec_fn=lambda: None)
1260 finally:
1261 gc.disable = orig_gc_disable
1262 gc.isenabled = orig_gc_isenabled
1263 if not enabled:
1264 gc.disable()
1265
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001266 def test_args_string(self):
1267 # args is a string
1268 fd, fname = mkstemp()
1269 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001270 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001271 fobj.write("#!/bin/sh\n")
1272 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1273 sys.executable)
1274 os.chmod(fname, 0o700)
1275 p = subprocess.Popen(fname)
1276 p.wait()
1277 os.remove(fname)
1278 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001279
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001280 def test_invalid_args(self):
1281 # invalid arguments should raise ValueError
1282 self.assertRaises(ValueError, subprocess.call,
1283 [sys.executable, "-c",
1284 "import sys; sys.exit(47)"],
1285 startupinfo=47)
1286 self.assertRaises(ValueError, subprocess.call,
1287 [sys.executable, "-c",
1288 "import sys; sys.exit(47)"],
1289 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001290
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001291 def test_shell_sequence(self):
1292 # Run command through the shell (sequence)
1293 newenv = os.environ.copy()
1294 newenv["FRUIT"] = "apple"
1295 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1296 stdout=subprocess.PIPE,
1297 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001298 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001299 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001300
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001301 def test_shell_string(self):
1302 # Run command through the shell (string)
1303 newenv = os.environ.copy()
1304 newenv["FRUIT"] = "apple"
1305 p = subprocess.Popen("echo $FRUIT", shell=1,
1306 stdout=subprocess.PIPE,
1307 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001308 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001309 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001310
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001311 def test_call_string(self):
1312 # call() function with string argument on UNIX
1313 fd, fname = mkstemp()
1314 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001315 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001316 fobj.write("#!/bin/sh\n")
1317 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1318 sys.executable)
1319 os.chmod(fname, 0o700)
1320 rc = subprocess.call(fname)
1321 os.remove(fname)
1322 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001323
Stefan Krah9542cc62010-07-19 14:20:53 +00001324 def test_specific_shell(self):
1325 # Issue #9265: Incorrect name passed as arg[0].
1326 shells = []
1327 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1328 for name in ['bash', 'ksh']:
1329 sh = os.path.join(prefix, name)
1330 if os.path.isfile(sh):
1331 shells.append(sh)
1332 if not shells: # Will probably work for any shell but csh.
1333 self.skipTest("bash or ksh required for this test")
1334 sh = '/bin/sh'
1335 if os.path.isfile(sh) and not os.path.islink(sh):
1336 # Test will fail if /bin/sh is a symlink to csh.
1337 shells.append(sh)
1338 for sh in shells:
1339 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1340 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001341 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001342 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1343
Florent Xicluna4886d242010-03-08 13:27:26 +00001344 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001345 # Do not inherit file handles from the parent.
1346 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001347 p = subprocess.Popen([sys.executable, "-c", """if 1:
1348 import sys, time
1349 sys.stdout.write('x\\n')
1350 sys.stdout.flush()
1351 time.sleep(30)
1352 """],
1353 close_fds=True,
1354 stdin=subprocess.PIPE,
1355 stdout=subprocess.PIPE,
1356 stderr=subprocess.PIPE)
1357 # Wait for the interpreter to be completely initialized before
1358 # sending any signal.
1359 p.stdout.read(1)
1360 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001361 return p
1362
Charles-François Natali53221e32013-01-12 16:52:20 +01001363 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1364 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001365 def _kill_dead_process(self, method, *args):
1366 # Do not inherit file handles from the parent.
1367 # It should fix failures on some platforms.
1368 p = subprocess.Popen([sys.executable, "-c", """if 1:
1369 import sys, time
1370 sys.stdout.write('x\\n')
1371 sys.stdout.flush()
1372 """],
1373 close_fds=True,
1374 stdin=subprocess.PIPE,
1375 stdout=subprocess.PIPE,
1376 stderr=subprocess.PIPE)
1377 # Wait for the interpreter to be completely initialized before
1378 # sending any signal.
1379 p.stdout.read(1)
1380 # The process should end after this
1381 time.sleep(1)
1382 # This shouldn't raise even though the child is now dead
1383 getattr(p, method)(*args)
1384 p.communicate()
1385
Florent Xicluna4886d242010-03-08 13:27:26 +00001386 def test_send_signal(self):
1387 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001388 _, stderr = p.communicate()
1389 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001390 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001391
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001392 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001393 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001394 _, stderr = p.communicate()
1395 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001396 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001397
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001398 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001399 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001400 _, stderr = p.communicate()
1401 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001402 self.assertEqual(p.wait(), -signal.SIGTERM)
1403
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001404 def test_send_signal_dead(self):
1405 # Sending a signal to a dead process
1406 self._kill_dead_process('send_signal', signal.SIGINT)
1407
1408 def test_kill_dead(self):
1409 # Killing a dead process
1410 self._kill_dead_process('kill')
1411
1412 def test_terminate_dead(self):
1413 # Terminating a dead process
1414 self._kill_dead_process('terminate')
1415
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001416 def check_close_std_fds(self, fds):
1417 # Issue #9905: test that subprocess pipes still work properly with
1418 # some standard fds closed
1419 stdin = 0
1420 newfds = []
1421 for a in fds:
1422 b = os.dup(a)
1423 newfds.append(b)
1424 if a == 0:
1425 stdin = b
1426 try:
1427 for fd in fds:
1428 os.close(fd)
1429 out, err = subprocess.Popen([sys.executable, "-c",
1430 'import sys;'
1431 'sys.stdout.write("apple");'
1432 'sys.stdout.flush();'
1433 'sys.stderr.write("orange")'],
1434 stdin=stdin,
1435 stdout=subprocess.PIPE,
1436 stderr=subprocess.PIPE).communicate()
1437 err = support.strip_python_stderr(err)
1438 self.assertEqual((out, err), (b'apple', b'orange'))
1439 finally:
1440 for b, a in zip(newfds, fds):
1441 os.dup2(b, a)
1442 for b in newfds:
1443 os.close(b)
1444
1445 def test_close_fd_0(self):
1446 self.check_close_std_fds([0])
1447
1448 def test_close_fd_1(self):
1449 self.check_close_std_fds([1])
1450
1451 def test_close_fd_2(self):
1452 self.check_close_std_fds([2])
1453
1454 def test_close_fds_0_1(self):
1455 self.check_close_std_fds([0, 1])
1456
1457 def test_close_fds_0_2(self):
1458 self.check_close_std_fds([0, 2])
1459
1460 def test_close_fds_1_2(self):
1461 self.check_close_std_fds([1, 2])
1462
1463 def test_close_fds_0_1_2(self):
1464 # Issue #10806: test that subprocess pipes still work properly with
1465 # all standard fds closed.
1466 self.check_close_std_fds([0, 1, 2])
1467
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001468 def test_remapping_std_fds(self):
1469 # open up some temporary files
1470 temps = [mkstemp() for i in range(3)]
1471 try:
1472 temp_fds = [fd for fd, fname in temps]
1473
1474 # unlink the files -- we won't need to reopen them
1475 for fd, fname in temps:
1476 os.unlink(fname)
1477
1478 # write some data to what will become stdin, and rewind
1479 os.write(temp_fds[1], b"STDIN")
1480 os.lseek(temp_fds[1], 0, 0)
1481
1482 # move the standard file descriptors out of the way
1483 saved_fds = [os.dup(fd) for fd in range(3)]
1484 try:
1485 # duplicate the file objects over the standard fd's
1486 for fd, temp_fd in enumerate(temp_fds):
1487 os.dup2(temp_fd, fd)
1488
1489 # now use those files in the "wrong" order, so that subprocess
1490 # has to rearrange them in the child
1491 p = subprocess.Popen([sys.executable, "-c",
1492 'import sys; got = sys.stdin.read();'
1493 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1494 stdin=temp_fds[1],
1495 stdout=temp_fds[2],
1496 stderr=temp_fds[0])
1497 p.wait()
1498 finally:
1499 # restore the original fd's underneath sys.stdin, etc.
1500 for std, saved in enumerate(saved_fds):
1501 os.dup2(saved, std)
1502 os.close(saved)
1503
1504 for fd in temp_fds:
1505 os.lseek(fd, 0, 0)
1506
1507 out = os.read(temp_fds[2], 1024)
1508 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1509 self.assertEqual(out, b"got STDIN")
1510 self.assertEqual(err, b"err")
1511
1512 finally:
1513 for fd in temp_fds:
1514 os.close(fd)
1515
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001516 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1517 # open up some temporary files
1518 temps = [mkstemp() for i in range(3)]
1519 temp_fds = [fd for fd, fname in temps]
1520 try:
1521 # unlink the files -- we won't need to reopen them
1522 for fd, fname in temps:
1523 os.unlink(fname)
1524
1525 # save a copy of the standard file descriptors
1526 saved_fds = [os.dup(fd) for fd in range(3)]
1527 try:
1528 # duplicate the temp files over the standard fd's 0, 1, 2
1529 for fd, temp_fd in enumerate(temp_fds):
1530 os.dup2(temp_fd, fd)
1531
1532 # write some data to what will become stdin, and rewind
1533 os.write(stdin_no, b"STDIN")
1534 os.lseek(stdin_no, 0, 0)
1535
1536 # now use those files in the given order, so that subprocess
1537 # has to rearrange them in the child
1538 p = subprocess.Popen([sys.executable, "-c",
1539 'import sys; got = sys.stdin.read();'
1540 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1541 stdin=stdin_no,
1542 stdout=stdout_no,
1543 stderr=stderr_no)
1544 p.wait()
1545
1546 for fd in temp_fds:
1547 os.lseek(fd, 0, 0)
1548
1549 out = os.read(stdout_no, 1024)
1550 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1551 finally:
1552 for std, saved in enumerate(saved_fds):
1553 os.dup2(saved, std)
1554 os.close(saved)
1555
1556 self.assertEqual(out, b"got STDIN")
1557 self.assertEqual(err, b"err")
1558
1559 finally:
1560 for fd in temp_fds:
1561 os.close(fd)
1562
1563 # When duping fds, if there arises a situation where one of the fds is
1564 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1565 # This tests all combinations of this.
1566 def test_swap_fds(self):
1567 self.check_swap_fds(0, 1, 2)
1568 self.check_swap_fds(0, 2, 1)
1569 self.check_swap_fds(1, 0, 2)
1570 self.check_swap_fds(1, 2, 0)
1571 self.check_swap_fds(2, 0, 1)
1572 self.check_swap_fds(2, 1, 0)
1573
Victor Stinner13bb71c2010-04-23 21:41:56 +00001574 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001575 def prepare():
1576 raise ValueError("surrogate:\uDCff")
1577
1578 try:
1579 subprocess.call(
1580 [sys.executable, "-c", "pass"],
1581 preexec_fn=prepare)
1582 except ValueError as err:
1583 # Pure Python implementations keeps the message
1584 self.assertIsNone(subprocess._posixsubprocess)
1585 self.assertEqual(str(err), "surrogate:\uDCff")
1586 except RuntimeError as err:
1587 # _posixsubprocess uses a default message
1588 self.assertIsNotNone(subprocess._posixsubprocess)
1589 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1590 else:
1591 self.fail("Expected ValueError or RuntimeError")
1592
Victor Stinner13bb71c2010-04-23 21:41:56 +00001593 def test_undecodable_env(self):
1594 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001595 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001596 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001597 env = os.environ.copy()
1598 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001599 # Use C locale to get ascii for the locale encoding to force
1600 # surrogate-escaping of \xFF in the child process; otherwise it can
1601 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001602 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001603 stdout = subprocess.check_output(
1604 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001605 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001606 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001607 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001608
1609 # test bytes
1610 key = key.encode("ascii", "surrogateescape")
1611 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001612 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001613 env = os.environ.copy()
1614 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001615 stdout = subprocess.check_output(
1616 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001617 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001618 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001619 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001620
Victor Stinnerb745a742010-05-18 17:17:23 +00001621 def test_bytes_program(self):
1622 abs_program = os.fsencode(sys.executable)
1623 path, program = os.path.split(sys.executable)
1624 program = os.fsencode(program)
1625
1626 # absolute bytes path
1627 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001628 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001629
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001630 # absolute bytes path as a string
1631 cmd = b"'" + abs_program + b"' -c pass"
1632 exitcode = subprocess.call(cmd, shell=True)
1633 self.assertEqual(exitcode, 0)
1634
Victor Stinnerb745a742010-05-18 17:17:23 +00001635 # bytes program, unicode PATH
1636 env = os.environ.copy()
1637 env["PATH"] = path
1638 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001639 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001640
1641 # bytes program, bytes PATH
1642 envb = os.environb.copy()
1643 envb[b"PATH"] = os.fsencode(path)
1644 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001645 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001646
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001647 def test_pipe_cloexec(self):
1648 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1649 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1650
1651 p1 = subprocess.Popen([sys.executable, sleeper],
1652 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1653 stderr=subprocess.PIPE, close_fds=False)
1654
1655 self.addCleanup(p1.communicate, b'')
1656
1657 p2 = subprocess.Popen([sys.executable, fd_status],
1658 stdout=subprocess.PIPE, close_fds=False)
1659
1660 output, error = p2.communicate()
1661 result_fds = set(map(int, output.split(b',')))
1662 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1663 p1.stderr.fileno()])
1664
1665 self.assertFalse(result_fds & unwanted_fds,
1666 "Expected no fds from %r to be open in child, "
1667 "found %r" %
1668 (unwanted_fds, result_fds & unwanted_fds))
1669
1670 def test_pipe_cloexec_real_tools(self):
1671 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1672 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1673
1674 subdata = b'zxcvbn'
1675 data = subdata * 4 + b'\n'
1676
1677 p1 = subprocess.Popen([sys.executable, qcat],
1678 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1679 close_fds=False)
1680
1681 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1682 stdin=p1.stdout, stdout=subprocess.PIPE,
1683 close_fds=False)
1684
1685 self.addCleanup(p1.wait)
1686 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001687 def kill_p1():
1688 try:
1689 p1.terminate()
1690 except ProcessLookupError:
1691 pass
1692 def kill_p2():
1693 try:
1694 p2.terminate()
1695 except ProcessLookupError:
1696 pass
1697 self.addCleanup(kill_p1)
1698 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001699
1700 p1.stdin.write(data)
1701 p1.stdin.close()
1702
1703 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1704
1705 self.assertTrue(readfiles, "The child hung")
1706 self.assertEqual(p2.stdout.read(), data)
1707
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001708 p1.stdout.close()
1709 p2.stdout.close()
1710
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001711 def test_close_fds(self):
1712 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1713
1714 fds = os.pipe()
1715 self.addCleanup(os.close, fds[0])
1716 self.addCleanup(os.close, fds[1])
1717
1718 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001719 # add a bunch more fds
1720 for _ in range(9):
1721 fd = os.open("/dev/null", os.O_RDONLY)
1722 self.addCleanup(os.close, fd)
1723 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001724
1725 p = subprocess.Popen([sys.executable, fd_status],
1726 stdout=subprocess.PIPE, close_fds=False)
1727 output, ignored = p.communicate()
1728 remaining_fds = set(map(int, output.split(b',')))
1729
1730 self.assertEqual(remaining_fds & open_fds, open_fds,
1731 "Some fds were closed")
1732
1733 p = subprocess.Popen([sys.executable, fd_status],
1734 stdout=subprocess.PIPE, close_fds=True)
1735 output, ignored = p.communicate()
1736 remaining_fds = set(map(int, output.split(b',')))
1737
1738 self.assertFalse(remaining_fds & open_fds,
1739 "Some fds were left open")
1740 self.assertIn(1, remaining_fds, "Subprocess failed")
1741
Gregory P. Smith8facece2012-01-21 14:01:08 -08001742 # Keep some of the fd's we opened open in the subprocess.
1743 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1744 fds_to_keep = set(open_fds.pop() for _ in range(8))
1745 p = subprocess.Popen([sys.executable, fd_status],
1746 stdout=subprocess.PIPE, close_fds=True,
1747 pass_fds=())
1748 output, ignored = p.communicate()
1749 remaining_fds = set(map(int, output.split(b',')))
1750
1751 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1752 "Some fds not in pass_fds were left open")
1753 self.assertIn(1, remaining_fds, "Subprocess failed")
1754
Victor Stinner88701e22011-06-01 13:13:04 +02001755 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1756 # descriptor of a pipe closed in the parent process is valid in the
1757 # child process according to fstat(), but the mode of the file
1758 # descriptor is invalid, and read or write raise an error.
1759 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001760 def test_pass_fds(self):
1761 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1762
1763 open_fds = set()
1764
1765 for x in range(5):
1766 fds = os.pipe()
1767 self.addCleanup(os.close, fds[0])
1768 self.addCleanup(os.close, fds[1])
1769 open_fds.update(fds)
1770
1771 for fd in open_fds:
1772 p = subprocess.Popen([sys.executable, fd_status],
1773 stdout=subprocess.PIPE, close_fds=True,
1774 pass_fds=(fd, ))
1775 output, ignored = p.communicate()
1776
1777 remaining_fds = set(map(int, output.split(b',')))
1778 to_be_closed = open_fds - {fd}
1779
1780 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1781 self.assertFalse(remaining_fds & to_be_closed,
1782 "fd to be closed passed")
1783
1784 # pass_fds overrides close_fds with a warning.
1785 with self.assertWarns(RuntimeWarning) as context:
1786 self.assertFalse(subprocess.call(
1787 [sys.executable, "-c", "import sys; sys.exit(0)"],
1788 close_fds=False, pass_fds=(fd, )))
1789 self.assertIn('overriding close_fds', str(context.warning))
1790
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001791 def test_stdout_stdin_are_single_inout_fd(self):
1792 with io.open(os.devnull, "r+") as inout:
1793 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1794 stdout=inout, stdin=inout)
1795 p.wait()
1796
1797 def test_stdout_stderr_are_single_inout_fd(self):
1798 with io.open(os.devnull, "r+") as inout:
1799 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1800 stdout=inout, stderr=inout)
1801 p.wait()
1802
1803 def test_stderr_stdin_are_single_inout_fd(self):
1804 with io.open(os.devnull, "r+") as inout:
1805 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1806 stderr=inout, stdin=inout)
1807 p.wait()
1808
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001809 def test_wait_when_sigchild_ignored(self):
1810 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1811 sigchild_ignore = support.findfile("sigchild_ignore.py",
1812 subdir="subprocessdata")
1813 p = subprocess.Popen([sys.executable, sigchild_ignore],
1814 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1815 stdout, stderr = p.communicate()
1816 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001817 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001818 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001819
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001820 def test_select_unbuffered(self):
1821 # Issue #11459: bufsize=0 should really set the pipes as
1822 # unbuffered (and therefore let select() work properly).
1823 select = support.import_module("select")
1824 p = subprocess.Popen([sys.executable, "-c",
1825 'import sys;'
1826 'sys.stdout.write("apple")'],
1827 stdout=subprocess.PIPE,
1828 bufsize=0)
1829 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001830 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001831 try:
1832 self.assertEqual(f.read(4), b"appl")
1833 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1834 finally:
1835 p.wait()
1836
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001837 def test_zombie_fast_process_del(self):
1838 # Issue #12650: on Unix, if Popen.__del__() was called before the
1839 # process exited, it wouldn't be added to subprocess._active, and would
1840 # remain a zombie.
1841 # spawn a Popen, and delete its reference before it exits
1842 p = subprocess.Popen([sys.executable, "-c",
1843 'import sys, time;'
1844 'time.sleep(0.2)'],
1845 stdout=subprocess.PIPE,
1846 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001847 self.addCleanup(p.stdout.close)
1848 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001849 ident = id(p)
1850 pid = p.pid
1851 del p
1852 # check that p is in the active processes list
1853 self.assertIn(ident, [id(o) for o in subprocess._active])
1854
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001855 def test_leak_fast_process_del_killed(self):
1856 # Issue #12650: on Unix, if Popen.__del__() was called before the
1857 # process exited, and the process got killed by a signal, it would never
1858 # be removed from subprocess._active, which triggered a FD and memory
1859 # leak.
1860 # spawn a Popen, delete its reference and kill it
1861 p = subprocess.Popen([sys.executable, "-c",
1862 'import time;'
1863 'time.sleep(3)'],
1864 stdout=subprocess.PIPE,
1865 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001866 self.addCleanup(p.stdout.close)
1867 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001868 ident = id(p)
1869 pid = p.pid
1870 del p
1871 os.kill(pid, signal.SIGKILL)
1872 # check that p is in the active processes list
1873 self.assertIn(ident, [id(o) for o in subprocess._active])
1874
1875 # let some time for the process to exit, and create a new Popen: this
1876 # should trigger the wait() of p
1877 time.sleep(0.2)
1878 with self.assertRaises(EnvironmentError) as c:
1879 with subprocess.Popen(['nonexisting_i_hope'],
1880 stdout=subprocess.PIPE,
1881 stderr=subprocess.PIPE) as proc:
1882 pass
1883 # p should have been wait()ed on, and removed from the _active list
1884 self.assertRaises(OSError, os.waitpid, pid, 0)
1885 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1886
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001887
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001888@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001889class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001890
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001891 def test_startupinfo(self):
1892 # startupinfo argument
1893 # We uses hardcoded constants, because we do not want to
1894 # depend on win32all.
1895 STARTF_USESHOWWINDOW = 1
1896 SW_MAXIMIZE = 3
1897 startupinfo = subprocess.STARTUPINFO()
1898 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1899 startupinfo.wShowWindow = SW_MAXIMIZE
1900 # Since Python is a console process, it won't be affected
1901 # by wShowWindow, but the argument should be silently
1902 # ignored
1903 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001904 startupinfo=startupinfo)
1905
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001906 def test_creationflags(self):
1907 # creationflags argument
1908 CREATE_NEW_CONSOLE = 16
1909 sys.stderr.write(" a DOS box should flash briefly ...\n")
1910 subprocess.call(sys.executable +
1911 ' -c "import time; time.sleep(0.25)"',
1912 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001913
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001914 def test_invalid_args(self):
1915 # invalid arguments should raise ValueError
1916 self.assertRaises(ValueError, subprocess.call,
1917 [sys.executable, "-c",
1918 "import sys; sys.exit(47)"],
1919 preexec_fn=lambda: 1)
1920 self.assertRaises(ValueError, subprocess.call,
1921 [sys.executable, "-c",
1922 "import sys; sys.exit(47)"],
1923 stdout=subprocess.PIPE,
1924 close_fds=True)
1925
1926 def test_close_fds(self):
1927 # close file descriptors
1928 rc = subprocess.call([sys.executable, "-c",
1929 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001930 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001931 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001932
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001933 def test_shell_sequence(self):
1934 # Run command through the shell (sequence)
1935 newenv = os.environ.copy()
1936 newenv["FRUIT"] = "physalis"
1937 p = subprocess.Popen(["set"], shell=1,
1938 stdout=subprocess.PIPE,
1939 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001940 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001941 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001942
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001943 def test_shell_string(self):
1944 # Run command through the shell (string)
1945 newenv = os.environ.copy()
1946 newenv["FRUIT"] = "physalis"
1947 p = subprocess.Popen("set", shell=1,
1948 stdout=subprocess.PIPE,
1949 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001950 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001951 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001952
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001953 def test_call_string(self):
1954 # call() function with string argument on Windows
1955 rc = subprocess.call(sys.executable +
1956 ' -c "import sys; sys.exit(47)"')
1957 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001958
Florent Xicluna4886d242010-03-08 13:27:26 +00001959 def _kill_process(self, method, *args):
1960 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001961 p = subprocess.Popen([sys.executable, "-c", """if 1:
1962 import sys, time
1963 sys.stdout.write('x\\n')
1964 sys.stdout.flush()
1965 time.sleep(30)
1966 """],
1967 stdin=subprocess.PIPE,
1968 stdout=subprocess.PIPE,
1969 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001970 self.addCleanup(p.stdout.close)
1971 self.addCleanup(p.stderr.close)
1972 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001973 # Wait for the interpreter to be completely initialized before
1974 # sending any signal.
1975 p.stdout.read(1)
1976 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001977 _, stderr = p.communicate()
1978 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001979 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001980 self.assertNotEqual(returncode, 0)
1981
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001982 def _kill_dead_process(self, method, *args):
1983 p = subprocess.Popen([sys.executable, "-c", """if 1:
1984 import sys, time
1985 sys.stdout.write('x\\n')
1986 sys.stdout.flush()
1987 sys.exit(42)
1988 """],
1989 stdin=subprocess.PIPE,
1990 stdout=subprocess.PIPE,
1991 stderr=subprocess.PIPE)
1992 self.addCleanup(p.stdout.close)
1993 self.addCleanup(p.stderr.close)
1994 self.addCleanup(p.stdin.close)
1995 # Wait for the interpreter to be completely initialized before
1996 # sending any signal.
1997 p.stdout.read(1)
1998 # The process should end after this
1999 time.sleep(1)
2000 # This shouldn't raise even though the child is now dead
2001 getattr(p, method)(*args)
2002 _, stderr = p.communicate()
2003 self.assertStderrEqual(stderr, b'')
2004 rc = p.wait()
2005 self.assertEqual(rc, 42)
2006
Florent Xicluna4886d242010-03-08 13:27:26 +00002007 def test_send_signal(self):
2008 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002009
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002010 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002011 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002012
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002013 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002014 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002015
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002016 def test_send_signal_dead(self):
2017 self._kill_dead_process('send_signal', signal.SIGTERM)
2018
2019 def test_kill_dead(self):
2020 self._kill_dead_process('kill')
2021
2022 def test_terminate_dead(self):
2023 self._kill_dead_process('terminate')
2024
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002025
Brett Cannona23810f2008-05-26 19:04:21 +00002026# The module says:
2027# "NB This only works (and is only relevant) for UNIX."
2028#
2029# Actually, getoutput should work on any platform with an os.popen, but
2030# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002031@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002032class CommandTests(unittest.TestCase):
2033 def test_getoutput(self):
2034 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2035 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2036 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002037
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002038 # we use mkdtemp in the next line to create an empty directory
2039 # under our exclusive control; from that, we can invent a pathname
2040 # that we _know_ won't exist. This is guaranteed to fail.
2041 dir = None
2042 try:
2043 dir = tempfile.mkdtemp()
2044 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00002045
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002046 status, output = subprocess.getstatusoutput('cat ' + name)
2047 self.assertNotEqual(status, 0)
2048 finally:
2049 if dir is not None:
2050 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002051
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002052
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002053@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
2054 "poll system call not supported")
2055class ProcessTestCaseNoPoll(ProcessTestCase):
2056 def setUp(self):
2057 subprocess._has_poll = False
2058 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002059
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002060 def tearDown(self):
2061 subprocess._has_poll = True
2062 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002063
2064
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002065class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00002066 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002067 def test_eintr_retry_call(self):
2068 record_calls = []
2069 def fake_os_func(*args):
2070 record_calls.append(args)
2071 if len(record_calls) == 2:
2072 raise OSError(errno.EINTR, "fake interrupted system call")
2073 return tuple(reversed(args))
2074
2075 self.assertEqual((999, 256),
2076 subprocess._eintr_retry_call(fake_os_func, 256, 999))
2077 self.assertEqual([(256, 999)], record_calls)
2078 # This time there will be an EINTR so it will loop once.
2079 self.assertEqual((666,),
2080 subprocess._eintr_retry_call(fake_os_func, 666))
2081 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
2082
2083
Tim Golden126c2962010-08-11 14:20:40 +00002084@unittest.skipUnless(mswindows, "Windows-specific tests")
2085class CommandsWithSpaces (BaseTestCase):
2086
2087 def setUp(self):
2088 super().setUp()
2089 f, fname = mkstemp(".py", "te st")
2090 self.fname = fname.lower ()
2091 os.write(f, b"import sys;"
2092 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2093 )
2094 os.close(f)
2095
2096 def tearDown(self):
2097 os.remove(self.fname)
2098 super().tearDown()
2099
2100 def with_spaces(self, *args, **kwargs):
2101 kwargs['stdout'] = subprocess.PIPE
2102 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002103 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002104 self.assertEqual(
2105 p.stdout.read ().decode("mbcs"),
2106 "2 [%r, 'ab cd']" % self.fname
2107 )
2108
2109 def test_shell_string_with_spaces(self):
2110 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002111 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2112 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002113
2114 def test_shell_sequence_with_spaces(self):
2115 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002116 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002117
2118 def test_noshell_string_with_spaces(self):
2119 # call() function with string argument with spaces on Windows
2120 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2121 "ab cd"))
2122
2123 def test_noshell_sequence_with_spaces(self):
2124 # call() function with sequence argument with spaces on Windows
2125 self.with_spaces([sys.executable, self.fname, "ab cd"])
2126
Brian Curtin79cdb662010-12-03 02:46:02 +00002127
Georg Brandla86b2622012-02-20 21:34:57 +01002128class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002129
2130 def test_pipe(self):
2131 with subprocess.Popen([sys.executable, "-c",
2132 "import sys;"
2133 "sys.stdout.write('stdout');"
2134 "sys.stderr.write('stderr');"],
2135 stdout=subprocess.PIPE,
2136 stderr=subprocess.PIPE) as proc:
2137 self.assertEqual(proc.stdout.read(), b"stdout")
2138 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2139
2140 self.assertTrue(proc.stdout.closed)
2141 self.assertTrue(proc.stderr.closed)
2142
2143 def test_returncode(self):
2144 with subprocess.Popen([sys.executable, "-c",
2145 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002146 pass
2147 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002148 self.assertEqual(proc.returncode, 100)
2149
2150 def test_communicate_stdin(self):
2151 with subprocess.Popen([sys.executable, "-c",
2152 "import sys;"
2153 "sys.exit(sys.stdin.read() == 'context')"],
2154 stdin=subprocess.PIPE) as proc:
2155 proc.communicate(b"context")
2156 self.assertEqual(proc.returncode, 1)
2157
2158 def test_invalid_args(self):
Andrew Svetlovb1726972012-12-26 23:34:54 +02002159 with self.assertRaises(FileNotFoundError) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002160 with subprocess.Popen(['nonexisting_i_hope'],
2161 stdout=subprocess.PIPE,
2162 stderr=subprocess.PIPE) as proc:
2163 pass
2164
Brian Curtin79cdb662010-12-03 02:46:02 +00002165
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002166def test_main():
2167 unit_tests = (ProcessTestCase,
2168 POSIXProcessTestCase,
2169 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002170 CommandTests,
2171 ProcessTestCaseNoPoll,
2172 HelperFunctionTests,
2173 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002174 ContextManagerTests,
2175 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002176
2177 support.run_unittest(*unit_tests)
2178 support.reap_children()
2179
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002180if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002181 unittest.main()