blob: b0cd63c8f2508eab17c25f5b9bb2222282028514 [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
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001363 def _kill_dead_process(self, method, *args):
1364 # Do not inherit file handles from the parent.
1365 # It should fix failures on some platforms.
1366 p = subprocess.Popen([sys.executable, "-c", """if 1:
1367 import sys, time
1368 sys.stdout.write('x\\n')
1369 sys.stdout.flush()
1370 """],
1371 close_fds=True,
1372 stdin=subprocess.PIPE,
1373 stdout=subprocess.PIPE,
1374 stderr=subprocess.PIPE)
1375 # Wait for the interpreter to be completely initialized before
1376 # sending any signal.
1377 p.stdout.read(1)
1378 # The process should end after this
1379 time.sleep(1)
1380 # This shouldn't raise even though the child is now dead
1381 getattr(p, method)(*args)
1382 p.communicate()
1383
Florent Xicluna4886d242010-03-08 13:27:26 +00001384 def test_send_signal(self):
1385 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001386 _, stderr = p.communicate()
1387 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001388 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001389
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001390 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001391 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001392 _, stderr = p.communicate()
1393 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001394 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001395
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001396 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001397 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001398 _, stderr = p.communicate()
1399 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001400 self.assertEqual(p.wait(), -signal.SIGTERM)
1401
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001402 def test_send_signal_dead(self):
1403 # Sending a signal to a dead process
1404 self._kill_dead_process('send_signal', signal.SIGINT)
1405
1406 def test_kill_dead(self):
1407 # Killing a dead process
1408 self._kill_dead_process('kill')
1409
1410 def test_terminate_dead(self):
1411 # Terminating a dead process
1412 self._kill_dead_process('terminate')
1413
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001414 def check_close_std_fds(self, fds):
1415 # Issue #9905: test that subprocess pipes still work properly with
1416 # some standard fds closed
1417 stdin = 0
1418 newfds = []
1419 for a in fds:
1420 b = os.dup(a)
1421 newfds.append(b)
1422 if a == 0:
1423 stdin = b
1424 try:
1425 for fd in fds:
1426 os.close(fd)
1427 out, err = subprocess.Popen([sys.executable, "-c",
1428 'import sys;'
1429 'sys.stdout.write("apple");'
1430 'sys.stdout.flush();'
1431 'sys.stderr.write("orange")'],
1432 stdin=stdin,
1433 stdout=subprocess.PIPE,
1434 stderr=subprocess.PIPE).communicate()
1435 err = support.strip_python_stderr(err)
1436 self.assertEqual((out, err), (b'apple', b'orange'))
1437 finally:
1438 for b, a in zip(newfds, fds):
1439 os.dup2(b, a)
1440 for b in newfds:
1441 os.close(b)
1442
1443 def test_close_fd_0(self):
1444 self.check_close_std_fds([0])
1445
1446 def test_close_fd_1(self):
1447 self.check_close_std_fds([1])
1448
1449 def test_close_fd_2(self):
1450 self.check_close_std_fds([2])
1451
1452 def test_close_fds_0_1(self):
1453 self.check_close_std_fds([0, 1])
1454
1455 def test_close_fds_0_2(self):
1456 self.check_close_std_fds([0, 2])
1457
1458 def test_close_fds_1_2(self):
1459 self.check_close_std_fds([1, 2])
1460
1461 def test_close_fds_0_1_2(self):
1462 # Issue #10806: test that subprocess pipes still work properly with
1463 # all standard fds closed.
1464 self.check_close_std_fds([0, 1, 2])
1465
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001466 def test_remapping_std_fds(self):
1467 # open up some temporary files
1468 temps = [mkstemp() for i in range(3)]
1469 try:
1470 temp_fds = [fd for fd, fname in temps]
1471
1472 # unlink the files -- we won't need to reopen them
1473 for fd, fname in temps:
1474 os.unlink(fname)
1475
1476 # write some data to what will become stdin, and rewind
1477 os.write(temp_fds[1], b"STDIN")
1478 os.lseek(temp_fds[1], 0, 0)
1479
1480 # move the standard file descriptors out of the way
1481 saved_fds = [os.dup(fd) for fd in range(3)]
1482 try:
1483 # duplicate the file objects over the standard fd's
1484 for fd, temp_fd in enumerate(temp_fds):
1485 os.dup2(temp_fd, fd)
1486
1487 # now use those files in the "wrong" order, so that subprocess
1488 # has to rearrange them in the child
1489 p = subprocess.Popen([sys.executable, "-c",
1490 'import sys; got = sys.stdin.read();'
1491 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1492 stdin=temp_fds[1],
1493 stdout=temp_fds[2],
1494 stderr=temp_fds[0])
1495 p.wait()
1496 finally:
1497 # restore the original fd's underneath sys.stdin, etc.
1498 for std, saved in enumerate(saved_fds):
1499 os.dup2(saved, std)
1500 os.close(saved)
1501
1502 for fd in temp_fds:
1503 os.lseek(fd, 0, 0)
1504
1505 out = os.read(temp_fds[2], 1024)
1506 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1507 self.assertEqual(out, b"got STDIN")
1508 self.assertEqual(err, b"err")
1509
1510 finally:
1511 for fd in temp_fds:
1512 os.close(fd)
1513
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001514 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1515 # open up some temporary files
1516 temps = [mkstemp() for i in range(3)]
1517 temp_fds = [fd for fd, fname in temps]
1518 try:
1519 # unlink the files -- we won't need to reopen them
1520 for fd, fname in temps:
1521 os.unlink(fname)
1522
1523 # save a copy of the standard file descriptors
1524 saved_fds = [os.dup(fd) for fd in range(3)]
1525 try:
1526 # duplicate the temp files over the standard fd's 0, 1, 2
1527 for fd, temp_fd in enumerate(temp_fds):
1528 os.dup2(temp_fd, fd)
1529
1530 # write some data to what will become stdin, and rewind
1531 os.write(stdin_no, b"STDIN")
1532 os.lseek(stdin_no, 0, 0)
1533
1534 # now use those files in the given order, so that subprocess
1535 # has to rearrange them in the child
1536 p = subprocess.Popen([sys.executable, "-c",
1537 'import sys; got = sys.stdin.read();'
1538 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1539 stdin=stdin_no,
1540 stdout=stdout_no,
1541 stderr=stderr_no)
1542 p.wait()
1543
1544 for fd in temp_fds:
1545 os.lseek(fd, 0, 0)
1546
1547 out = os.read(stdout_no, 1024)
1548 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1549 finally:
1550 for std, saved in enumerate(saved_fds):
1551 os.dup2(saved, std)
1552 os.close(saved)
1553
1554 self.assertEqual(out, b"got STDIN")
1555 self.assertEqual(err, b"err")
1556
1557 finally:
1558 for fd in temp_fds:
1559 os.close(fd)
1560
1561 # When duping fds, if there arises a situation where one of the fds is
1562 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1563 # This tests all combinations of this.
1564 def test_swap_fds(self):
1565 self.check_swap_fds(0, 1, 2)
1566 self.check_swap_fds(0, 2, 1)
1567 self.check_swap_fds(1, 0, 2)
1568 self.check_swap_fds(1, 2, 0)
1569 self.check_swap_fds(2, 0, 1)
1570 self.check_swap_fds(2, 1, 0)
1571
Victor Stinner13bb71c2010-04-23 21:41:56 +00001572 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001573 def prepare():
1574 raise ValueError("surrogate:\uDCff")
1575
1576 try:
1577 subprocess.call(
1578 [sys.executable, "-c", "pass"],
1579 preexec_fn=prepare)
1580 except ValueError as err:
1581 # Pure Python implementations keeps the message
1582 self.assertIsNone(subprocess._posixsubprocess)
1583 self.assertEqual(str(err), "surrogate:\uDCff")
1584 except RuntimeError as err:
1585 # _posixsubprocess uses a default message
1586 self.assertIsNotNone(subprocess._posixsubprocess)
1587 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1588 else:
1589 self.fail("Expected ValueError or RuntimeError")
1590
Victor Stinner13bb71c2010-04-23 21:41:56 +00001591 def test_undecodable_env(self):
1592 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001593 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001594 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001595 env = os.environ.copy()
1596 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001597 # Use C locale to get ascii for the locale encoding to force
1598 # surrogate-escaping of \xFF in the child process; otherwise it can
1599 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001600 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001601 stdout = subprocess.check_output(
1602 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001603 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001604 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001605 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001606
1607 # test bytes
1608 key = key.encode("ascii", "surrogateescape")
1609 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001610 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001611 env = os.environ.copy()
1612 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001613 stdout = subprocess.check_output(
1614 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001615 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001616 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001617 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001618
Victor Stinnerb745a742010-05-18 17:17:23 +00001619 def test_bytes_program(self):
1620 abs_program = os.fsencode(sys.executable)
1621 path, program = os.path.split(sys.executable)
1622 program = os.fsencode(program)
1623
1624 # absolute bytes path
1625 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001626 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001627
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001628 # absolute bytes path as a string
1629 cmd = b"'" + abs_program + b"' -c pass"
1630 exitcode = subprocess.call(cmd, shell=True)
1631 self.assertEqual(exitcode, 0)
1632
Victor Stinnerb745a742010-05-18 17:17:23 +00001633 # bytes program, unicode PATH
1634 env = os.environ.copy()
1635 env["PATH"] = path
1636 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001637 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001638
1639 # bytes program, bytes PATH
1640 envb = os.environb.copy()
1641 envb[b"PATH"] = os.fsencode(path)
1642 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001643 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001644
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001645 def test_pipe_cloexec(self):
1646 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1647 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1648
1649 p1 = subprocess.Popen([sys.executable, sleeper],
1650 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1651 stderr=subprocess.PIPE, close_fds=False)
1652
1653 self.addCleanup(p1.communicate, b'')
1654
1655 p2 = subprocess.Popen([sys.executable, fd_status],
1656 stdout=subprocess.PIPE, close_fds=False)
1657
1658 output, error = p2.communicate()
1659 result_fds = set(map(int, output.split(b',')))
1660 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1661 p1.stderr.fileno()])
1662
1663 self.assertFalse(result_fds & unwanted_fds,
1664 "Expected no fds from %r to be open in child, "
1665 "found %r" %
1666 (unwanted_fds, result_fds & unwanted_fds))
1667
1668 def test_pipe_cloexec_real_tools(self):
1669 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1670 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1671
1672 subdata = b'zxcvbn'
1673 data = subdata * 4 + b'\n'
1674
1675 p1 = subprocess.Popen([sys.executable, qcat],
1676 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1677 close_fds=False)
1678
1679 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1680 stdin=p1.stdout, stdout=subprocess.PIPE,
1681 close_fds=False)
1682
1683 self.addCleanup(p1.wait)
1684 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001685 def kill_p1():
1686 try:
1687 p1.terminate()
1688 except ProcessLookupError:
1689 pass
1690 def kill_p2():
1691 try:
1692 p2.terminate()
1693 except ProcessLookupError:
1694 pass
1695 self.addCleanup(kill_p1)
1696 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001697
1698 p1.stdin.write(data)
1699 p1.stdin.close()
1700
1701 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1702
1703 self.assertTrue(readfiles, "The child hung")
1704 self.assertEqual(p2.stdout.read(), data)
1705
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001706 p1.stdout.close()
1707 p2.stdout.close()
1708
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001709 def test_close_fds(self):
1710 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1711
1712 fds = os.pipe()
1713 self.addCleanup(os.close, fds[0])
1714 self.addCleanup(os.close, fds[1])
1715
1716 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001717 # add a bunch more fds
1718 for _ in range(9):
1719 fd = os.open("/dev/null", os.O_RDONLY)
1720 self.addCleanup(os.close, fd)
1721 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001722
1723 p = subprocess.Popen([sys.executable, fd_status],
1724 stdout=subprocess.PIPE, close_fds=False)
1725 output, ignored = p.communicate()
1726 remaining_fds = set(map(int, output.split(b',')))
1727
1728 self.assertEqual(remaining_fds & open_fds, open_fds,
1729 "Some fds were closed")
1730
1731 p = subprocess.Popen([sys.executable, fd_status],
1732 stdout=subprocess.PIPE, close_fds=True)
1733 output, ignored = p.communicate()
1734 remaining_fds = set(map(int, output.split(b',')))
1735
1736 self.assertFalse(remaining_fds & open_fds,
1737 "Some fds were left open")
1738 self.assertIn(1, remaining_fds, "Subprocess failed")
1739
Gregory P. Smith8facece2012-01-21 14:01:08 -08001740 # Keep some of the fd's we opened open in the subprocess.
1741 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1742 fds_to_keep = set(open_fds.pop() for _ in range(8))
1743 p = subprocess.Popen([sys.executable, fd_status],
1744 stdout=subprocess.PIPE, close_fds=True,
1745 pass_fds=())
1746 output, ignored = p.communicate()
1747 remaining_fds = set(map(int, output.split(b',')))
1748
1749 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1750 "Some fds not in pass_fds were left open")
1751 self.assertIn(1, remaining_fds, "Subprocess failed")
1752
Victor Stinner88701e22011-06-01 13:13:04 +02001753 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1754 # descriptor of a pipe closed in the parent process is valid in the
1755 # child process according to fstat(), but the mode of the file
1756 # descriptor is invalid, and read or write raise an error.
1757 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001758 def test_pass_fds(self):
1759 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1760
1761 open_fds = set()
1762
1763 for x in range(5):
1764 fds = os.pipe()
1765 self.addCleanup(os.close, fds[0])
1766 self.addCleanup(os.close, fds[1])
1767 open_fds.update(fds)
1768
1769 for fd in open_fds:
1770 p = subprocess.Popen([sys.executable, fd_status],
1771 stdout=subprocess.PIPE, close_fds=True,
1772 pass_fds=(fd, ))
1773 output, ignored = p.communicate()
1774
1775 remaining_fds = set(map(int, output.split(b',')))
1776 to_be_closed = open_fds - {fd}
1777
1778 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1779 self.assertFalse(remaining_fds & to_be_closed,
1780 "fd to be closed passed")
1781
1782 # pass_fds overrides close_fds with a warning.
1783 with self.assertWarns(RuntimeWarning) as context:
1784 self.assertFalse(subprocess.call(
1785 [sys.executable, "-c", "import sys; sys.exit(0)"],
1786 close_fds=False, pass_fds=(fd, )))
1787 self.assertIn('overriding close_fds', str(context.warning))
1788
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001789 def test_stdout_stdin_are_single_inout_fd(self):
1790 with io.open(os.devnull, "r+") as inout:
1791 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1792 stdout=inout, stdin=inout)
1793 p.wait()
1794
1795 def test_stdout_stderr_are_single_inout_fd(self):
1796 with io.open(os.devnull, "r+") as inout:
1797 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1798 stdout=inout, stderr=inout)
1799 p.wait()
1800
1801 def test_stderr_stdin_are_single_inout_fd(self):
1802 with io.open(os.devnull, "r+") as inout:
1803 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1804 stderr=inout, stdin=inout)
1805 p.wait()
1806
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001807 def test_wait_when_sigchild_ignored(self):
1808 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1809 sigchild_ignore = support.findfile("sigchild_ignore.py",
1810 subdir="subprocessdata")
1811 p = subprocess.Popen([sys.executable, sigchild_ignore],
1812 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1813 stdout, stderr = p.communicate()
1814 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001815 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001816 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001817
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001818 def test_select_unbuffered(self):
1819 # Issue #11459: bufsize=0 should really set the pipes as
1820 # unbuffered (and therefore let select() work properly).
1821 select = support.import_module("select")
1822 p = subprocess.Popen([sys.executable, "-c",
1823 'import sys;'
1824 'sys.stdout.write("apple")'],
1825 stdout=subprocess.PIPE,
1826 bufsize=0)
1827 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001828 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001829 try:
1830 self.assertEqual(f.read(4), b"appl")
1831 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1832 finally:
1833 p.wait()
1834
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001835 def test_zombie_fast_process_del(self):
1836 # Issue #12650: on Unix, if Popen.__del__() was called before the
1837 # process exited, it wouldn't be added to subprocess._active, and would
1838 # remain a zombie.
1839 # spawn a Popen, and delete its reference before it exits
1840 p = subprocess.Popen([sys.executable, "-c",
1841 'import sys, time;'
1842 'time.sleep(0.2)'],
1843 stdout=subprocess.PIPE,
1844 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001845 self.addCleanup(p.stdout.close)
1846 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001847 ident = id(p)
1848 pid = p.pid
1849 del p
1850 # check that p is in the active processes list
1851 self.assertIn(ident, [id(o) for o in subprocess._active])
1852
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001853 def test_leak_fast_process_del_killed(self):
1854 # Issue #12650: on Unix, if Popen.__del__() was called before the
1855 # process exited, and the process got killed by a signal, it would never
1856 # be removed from subprocess._active, which triggered a FD and memory
1857 # leak.
1858 # spawn a Popen, delete its reference and kill it
1859 p = subprocess.Popen([sys.executable, "-c",
1860 'import time;'
1861 'time.sleep(3)'],
1862 stdout=subprocess.PIPE,
1863 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001864 self.addCleanup(p.stdout.close)
1865 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001866 ident = id(p)
1867 pid = p.pid
1868 del p
1869 os.kill(pid, signal.SIGKILL)
1870 # check that p is in the active processes list
1871 self.assertIn(ident, [id(o) for o in subprocess._active])
1872
1873 # let some time for the process to exit, and create a new Popen: this
1874 # should trigger the wait() of p
1875 time.sleep(0.2)
1876 with self.assertRaises(EnvironmentError) as c:
1877 with subprocess.Popen(['nonexisting_i_hope'],
1878 stdout=subprocess.PIPE,
1879 stderr=subprocess.PIPE) as proc:
1880 pass
1881 # p should have been wait()ed on, and removed from the _active list
1882 self.assertRaises(OSError, os.waitpid, pid, 0)
1883 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1884
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001885
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001886@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001887class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001888
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001889 def test_startupinfo(self):
1890 # startupinfo argument
1891 # We uses hardcoded constants, because we do not want to
1892 # depend on win32all.
1893 STARTF_USESHOWWINDOW = 1
1894 SW_MAXIMIZE = 3
1895 startupinfo = subprocess.STARTUPINFO()
1896 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1897 startupinfo.wShowWindow = SW_MAXIMIZE
1898 # Since Python is a console process, it won't be affected
1899 # by wShowWindow, but the argument should be silently
1900 # ignored
1901 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001902 startupinfo=startupinfo)
1903
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001904 def test_creationflags(self):
1905 # creationflags argument
1906 CREATE_NEW_CONSOLE = 16
1907 sys.stderr.write(" a DOS box should flash briefly ...\n")
1908 subprocess.call(sys.executable +
1909 ' -c "import time; time.sleep(0.25)"',
1910 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001911
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001912 def test_invalid_args(self):
1913 # invalid arguments should raise ValueError
1914 self.assertRaises(ValueError, subprocess.call,
1915 [sys.executable, "-c",
1916 "import sys; sys.exit(47)"],
1917 preexec_fn=lambda: 1)
1918 self.assertRaises(ValueError, subprocess.call,
1919 [sys.executable, "-c",
1920 "import sys; sys.exit(47)"],
1921 stdout=subprocess.PIPE,
1922 close_fds=True)
1923
1924 def test_close_fds(self):
1925 # close file descriptors
1926 rc = subprocess.call([sys.executable, "-c",
1927 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001928 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001929 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001930
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001931 def test_shell_sequence(self):
1932 # Run command through the shell (sequence)
1933 newenv = os.environ.copy()
1934 newenv["FRUIT"] = "physalis"
1935 p = subprocess.Popen(["set"], shell=1,
1936 stdout=subprocess.PIPE,
1937 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001938 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001939 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001940
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001941 def test_shell_string(self):
1942 # Run command through the shell (string)
1943 newenv = os.environ.copy()
1944 newenv["FRUIT"] = "physalis"
1945 p = subprocess.Popen("set", shell=1,
1946 stdout=subprocess.PIPE,
1947 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001948 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001949 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001950
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001951 def test_call_string(self):
1952 # call() function with string argument on Windows
1953 rc = subprocess.call(sys.executable +
1954 ' -c "import sys; sys.exit(47)"')
1955 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001956
Florent Xicluna4886d242010-03-08 13:27:26 +00001957 def _kill_process(self, method, *args):
1958 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001959 p = subprocess.Popen([sys.executable, "-c", """if 1:
1960 import sys, time
1961 sys.stdout.write('x\\n')
1962 sys.stdout.flush()
1963 time.sleep(30)
1964 """],
1965 stdin=subprocess.PIPE,
1966 stdout=subprocess.PIPE,
1967 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001968 self.addCleanup(p.stdout.close)
1969 self.addCleanup(p.stderr.close)
1970 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001971 # Wait for the interpreter to be completely initialized before
1972 # sending any signal.
1973 p.stdout.read(1)
1974 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001975 _, stderr = p.communicate()
1976 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001977 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001978 self.assertNotEqual(returncode, 0)
1979
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001980 def _kill_dead_process(self, method, *args):
1981 p = subprocess.Popen([sys.executable, "-c", """if 1:
1982 import sys, time
1983 sys.stdout.write('x\\n')
1984 sys.stdout.flush()
1985 sys.exit(42)
1986 """],
1987 stdin=subprocess.PIPE,
1988 stdout=subprocess.PIPE,
1989 stderr=subprocess.PIPE)
1990 self.addCleanup(p.stdout.close)
1991 self.addCleanup(p.stderr.close)
1992 self.addCleanup(p.stdin.close)
1993 # Wait for the interpreter to be completely initialized before
1994 # sending any signal.
1995 p.stdout.read(1)
1996 # The process should end after this
1997 time.sleep(1)
1998 # This shouldn't raise even though the child is now dead
1999 getattr(p, method)(*args)
2000 _, stderr = p.communicate()
2001 self.assertStderrEqual(stderr, b'')
2002 rc = p.wait()
2003 self.assertEqual(rc, 42)
2004
Florent Xicluna4886d242010-03-08 13:27:26 +00002005 def test_send_signal(self):
2006 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002007
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002008 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002009 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002010
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002011 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002012 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002013
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002014 def test_send_signal_dead(self):
2015 self._kill_dead_process('send_signal', signal.SIGTERM)
2016
2017 def test_kill_dead(self):
2018 self._kill_dead_process('kill')
2019
2020 def test_terminate_dead(self):
2021 self._kill_dead_process('terminate')
2022
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002023
Brett Cannona23810f2008-05-26 19:04:21 +00002024# The module says:
2025# "NB This only works (and is only relevant) for UNIX."
2026#
2027# Actually, getoutput should work on any platform with an os.popen, but
2028# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002029@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002030class CommandTests(unittest.TestCase):
2031 def test_getoutput(self):
2032 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2033 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2034 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002035
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002036 # we use mkdtemp in the next line to create an empty directory
2037 # under our exclusive control; from that, we can invent a pathname
2038 # that we _know_ won't exist. This is guaranteed to fail.
2039 dir = None
2040 try:
2041 dir = tempfile.mkdtemp()
2042 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00002043
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002044 status, output = subprocess.getstatusoutput('cat ' + name)
2045 self.assertNotEqual(status, 0)
2046 finally:
2047 if dir is not None:
2048 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002049
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002050
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002051@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
2052 "poll system call not supported")
2053class ProcessTestCaseNoPoll(ProcessTestCase):
2054 def setUp(self):
2055 subprocess._has_poll = False
2056 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002057
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002058 def tearDown(self):
2059 subprocess._has_poll = True
2060 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002061
2062
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002063class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00002064 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002065 def test_eintr_retry_call(self):
2066 record_calls = []
2067 def fake_os_func(*args):
2068 record_calls.append(args)
2069 if len(record_calls) == 2:
2070 raise OSError(errno.EINTR, "fake interrupted system call")
2071 return tuple(reversed(args))
2072
2073 self.assertEqual((999, 256),
2074 subprocess._eintr_retry_call(fake_os_func, 256, 999))
2075 self.assertEqual([(256, 999)], record_calls)
2076 # This time there will be an EINTR so it will loop once.
2077 self.assertEqual((666,),
2078 subprocess._eintr_retry_call(fake_os_func, 666))
2079 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
2080
2081
Tim Golden126c2962010-08-11 14:20:40 +00002082@unittest.skipUnless(mswindows, "Windows-specific tests")
2083class CommandsWithSpaces (BaseTestCase):
2084
2085 def setUp(self):
2086 super().setUp()
2087 f, fname = mkstemp(".py", "te st")
2088 self.fname = fname.lower ()
2089 os.write(f, b"import sys;"
2090 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2091 )
2092 os.close(f)
2093
2094 def tearDown(self):
2095 os.remove(self.fname)
2096 super().tearDown()
2097
2098 def with_spaces(self, *args, **kwargs):
2099 kwargs['stdout'] = subprocess.PIPE
2100 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002101 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002102 self.assertEqual(
2103 p.stdout.read ().decode("mbcs"),
2104 "2 [%r, 'ab cd']" % self.fname
2105 )
2106
2107 def test_shell_string_with_spaces(self):
2108 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002109 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2110 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002111
2112 def test_shell_sequence_with_spaces(self):
2113 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002114 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002115
2116 def test_noshell_string_with_spaces(self):
2117 # call() function with string argument with spaces on Windows
2118 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2119 "ab cd"))
2120
2121 def test_noshell_sequence_with_spaces(self):
2122 # call() function with sequence argument with spaces on Windows
2123 self.with_spaces([sys.executable, self.fname, "ab cd"])
2124
Brian Curtin79cdb662010-12-03 02:46:02 +00002125
Georg Brandla86b2622012-02-20 21:34:57 +01002126class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002127
2128 def test_pipe(self):
2129 with subprocess.Popen([sys.executable, "-c",
2130 "import sys;"
2131 "sys.stdout.write('stdout');"
2132 "sys.stderr.write('stderr');"],
2133 stdout=subprocess.PIPE,
2134 stderr=subprocess.PIPE) as proc:
2135 self.assertEqual(proc.stdout.read(), b"stdout")
2136 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2137
2138 self.assertTrue(proc.stdout.closed)
2139 self.assertTrue(proc.stderr.closed)
2140
2141 def test_returncode(self):
2142 with subprocess.Popen([sys.executable, "-c",
2143 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002144 pass
2145 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002146 self.assertEqual(proc.returncode, 100)
2147
2148 def test_communicate_stdin(self):
2149 with subprocess.Popen([sys.executable, "-c",
2150 "import sys;"
2151 "sys.exit(sys.stdin.read() == 'context')"],
2152 stdin=subprocess.PIPE) as proc:
2153 proc.communicate(b"context")
2154 self.assertEqual(proc.returncode, 1)
2155
2156 def test_invalid_args(self):
2157 with self.assertRaises(EnvironmentError) as c:
2158 with subprocess.Popen(['nonexisting_i_hope'],
2159 stdout=subprocess.PIPE,
2160 stderr=subprocess.PIPE) as proc:
2161 pass
2162
2163 if c.exception.errno != errno.ENOENT: # ignore "no such file"
2164 raise c.exception
2165
2166
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002167def test_main():
2168 unit_tests = (ProcessTestCase,
2169 POSIXProcessTestCase,
2170 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002171 CommandTests,
2172 ProcessTestCaseNoPoll,
2173 HelperFunctionTests,
2174 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002175 ContextManagerTests,
2176 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002177
2178 support.run_unittest(*unit_tests)
2179 support.reap_children()
2180
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002181if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002182 unittest.main()