blob: 627275891fb3b29b826bb159c32124362c451114 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
2from test import test_support
3import subprocess
4import sys
Gregory P. Smithf0739cb2017-01-22 22:38:28 -08005import platform
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00006import signal
7import os
Gregory P. Smithcce211f2010-03-01 00:05:08 +00008import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import tempfile
10import time
Tim Peters3761e8d2004-10-13 04:07:12 +000011import re
Ezio Melotti8f6a2872010-02-10 21:40:33 +000012import sysconfig
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000013
Benjamin Peterson8b59c232011-12-10 12:31:42 -050014try:
Gregory P. Smithf0739cb2017-01-22 22:38:28 -080015 import ctypes
16except ImportError:
17 ctypes = None
18
19try:
Benjamin Peterson8b59c232011-12-10 12:31:42 -050020 import resource
21except ImportError:
22 resource = None
Antoine Pitrou33fc7442013-08-30 23:38:13 +020023try:
24 import threading
25except ImportError:
26 threading = None
Benjamin Peterson8b59c232011-12-10 12:31:42 -050027
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000028mswindows = (sys.platform == "win32")
29
30#
31# Depends on the following external programs: Python
32#
33
34if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000035 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
36 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000037else:
38 SETBINARY = ''
39
Florent Xicluna98e3fc32010-02-27 19:20:50 +000040
Florent Xiclunafc4d6d72010-03-23 14:36:45 +000041class BaseTestCase(unittest.TestCase):
Neal Norwitzb15ac312006-06-29 04:10:08 +000042 def setUp(self):
Tim Peters38ff36c2006-06-30 06:18:39 +000043 # Try to minimize the number of children we have so this test
44 # doesn't crash on some buildbots (Alphas in particular).
Florent Xicluna98e3fc32010-02-27 19:20:50 +000045 test_support.reap_children()
Neal Norwitzb15ac312006-06-29 04:10:08 +000046
Florent Xiclunaab5e17f2010-03-04 21:31:58 +000047 def tearDown(self):
48 for inst in subprocess._active:
49 inst.wait()
50 subprocess._cleanup()
51 self.assertFalse(subprocess._active, "subprocess._active not empty")
52
Florent Xicluna98e3fc32010-02-27 19:20:50 +000053 def assertStderrEqual(self, stderr, expected, msg=None):
54 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
55 # shutdown time. That frustrates tests trying to check stderr produced
56 # from a spawned Python process.
57 actual = re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr)
58 self.assertEqual(actual, expected, msg)
Neal Norwitzb15ac312006-06-29 04:10:08 +000059
Florent Xiclunafc4d6d72010-03-23 14:36:45 +000060
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -080061class PopenTestException(Exception):
62 pass
63
64
65class PopenExecuteChildRaises(subprocess.Popen):
66 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
67 _execute_child fails.
68 """
69 def _execute_child(self, *args, **kwargs):
70 raise PopenTestException("Forced Exception for Test")
71
72
Florent Xiclunafc4d6d72010-03-23 14:36:45 +000073class ProcessTestCase(BaseTestCase):
74
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000075 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000076 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000077 rc = subprocess.call([sys.executable, "-c",
78 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000079 self.assertEqual(rc, 47)
80
Peter Astrand454f7672005-01-01 09:36:35 +000081 def test_check_call_zero(self):
82 # check_call() function with zero return code
83 rc = subprocess.check_call([sys.executable, "-c",
84 "import sys; sys.exit(0)"])
85 self.assertEqual(rc, 0)
86
87 def test_check_call_nonzero(self):
88 # check_call() function with non-zero return code
Florent Xicluna98e3fc32010-02-27 19:20:50 +000089 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000090 subprocess.check_call([sys.executable, "-c",
91 "import sys; sys.exit(47)"])
Florent Xicluna98e3fc32010-02-27 19:20:50 +000092 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000093
Gregory P. Smith26576802008-12-05 02:27:01 +000094 def test_check_output(self):
95 # check_output() function with zero return code
96 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +000097 [sys.executable, "-c", "print 'BDFL'"])
Ezio Melottiaa980582010-01-23 23:04:36 +000098 self.assertIn('BDFL', output)
Gregory P. Smith97f49f42008-12-04 20:21:09 +000099
Gregory P. Smith26576802008-12-05 02:27:01 +0000100 def test_check_output_nonzero(self):
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000101 # check_call() function with non-zero return code
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000102 with self.assertRaises(subprocess.CalledProcessError) as c:
Gregory P. Smith26576802008-12-05 02:27:01 +0000103 subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000104 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000105 self.assertEqual(c.exception.returncode, 5)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000106
Gregory P. Smith26576802008-12-05 02:27:01 +0000107 def test_check_output_stderr(self):
108 # check_output() function stderr redirected to stdout
109 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000110 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
111 stderr=subprocess.STDOUT)
Ezio Melottiaa980582010-01-23 23:04:36 +0000112 self.assertIn('BDFL', output)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000113
Gregory P. Smith26576802008-12-05 02:27:01 +0000114 def test_check_output_stdout_arg(self):
115 # check_output() function stderr redirected to stdout
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000116 with self.assertRaises(ValueError) as c:
Gregory P. Smith26576802008-12-05 02:27:01 +0000117 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000118 [sys.executable, "-c", "print 'will not be run'"],
119 stdout=sys.stdout)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000120 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000121 self.assertIn('stdout', c.exception.args[0])
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000122
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000123 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000124 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000125 newenv = os.environ.copy()
126 newenv["FRUIT"] = "banana"
127 rc = subprocess.call([sys.executable, "-c",
Florent Xiclunabab22a72010-03-04 19:40:48 +0000128 'import sys, os;'
129 'sys.exit(os.getenv("FRUIT")=="banana")'],
130 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000131 self.assertEqual(rc, 1)
132
Victor Stinner776e69b2011-06-01 01:03:00 +0200133 def test_invalid_args(self):
134 # Popen() called with invalid arguments should raise TypeError
135 # but Popen.__del__ should not complain (issue #12085)
Victor Stinnere9b185f2011-06-01 01:57:48 +0200136 with test_support.captured_stderr() as s:
Victor Stinner776e69b2011-06-01 01:03:00 +0200137 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
138 argcount = subprocess.Popen.__init__.__code__.co_argcount
139 too_many_args = [0] * (argcount + 1)
140 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
141 self.assertEqual(s.getvalue(), '')
142
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000143 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000144 # .stdin is None when not redirected
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
146 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000147 self.addCleanup(p.stdout.close)
148 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000149 p.wait()
150 self.assertEqual(p.stdin, None)
151
152 def test_stdout_none(self):
Ezio Melottiefaad092013-03-11 00:34:33 +0200153 # .stdout is None when not redirected, and the child's stdout will
154 # be inherited from the parent. In order to test this we run a
155 # subprocess in a subprocess:
156 # this_test
157 # \-- subprocess created by this test (parent)
158 # \-- subprocess created by the parent subprocess (child)
159 # The parent doesn't specify stdout, so the child will use the
160 # parent's stdout. This test checks that the message printed by the
161 # child goes to the parent stdout. The parent also checks that the
162 # child's stdout is None. See #11963.
163 code = ('import sys; from subprocess import Popen, PIPE;'
164 'p = Popen([sys.executable, "-c", "print \'test_stdout_none\'"],'
165 ' stdin=PIPE, stderr=PIPE);'
166 'p.wait(); assert p.stdout is None;')
167 p = subprocess.Popen([sys.executable, "-c", code],
168 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
169 self.addCleanup(p.stdout.close)
Brian Curtind117b562010-11-05 04:09:09 +0000170 self.addCleanup(p.stderr.close)
Ezio Melottiefaad092013-03-11 00:34:33 +0200171 out, err = p.communicate()
172 self.assertEqual(p.returncode, 0, err)
173 self.assertEqual(out.rstrip(), 'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000174
175 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000176 # .stderr is None when not redirected
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000177 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
178 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000179 self.addCleanup(p.stdout.close)
180 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000181 p.wait()
182 self.assertEqual(p.stderr, None)
183
Ezio Melotti8f6a2872010-02-10 21:40:33 +0000184 def test_executable_with_cwd(self):
Florent Xicluna63763702010-03-11 01:50:48 +0000185 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti8f6a2872010-02-10 21:40:33 +0000186 p = subprocess.Popen(["somethingyoudonthave", "-c",
187 "import sys; sys.exit(47)"],
188 executable=sys.executable, cwd=python_dir)
189 p.wait()
190 self.assertEqual(p.returncode, 47)
191
192 @unittest.skipIf(sysconfig.is_python_build(),
193 "need an installed Python. See #7774")
194 def test_executable_without_cwd(self):
195 # For a normal installation, it should work without 'cwd'
196 # argument. For test runs in the build directory, see #7774.
197 p = subprocess.Popen(["somethingyoudonthave", "-c",
198 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000199 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000200 p.wait()
201 self.assertEqual(p.returncode, 47)
202
203 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000204 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000205 p = subprocess.Popen([sys.executable, "-c",
206 'import sys; sys.exit(sys.stdin.read() == "pear")'],
207 stdin=subprocess.PIPE)
208 p.stdin.write("pear")
209 p.stdin.close()
210 p.wait()
211 self.assertEqual(p.returncode, 1)
212
213 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000214 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000215 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000216 d = tf.fileno()
217 os.write(d, "pear")
218 os.lseek(d, 0, 0)
219 p = subprocess.Popen([sys.executable, "-c",
220 'import sys; sys.exit(sys.stdin.read() == "pear")'],
221 stdin=d)
222 p.wait()
223 self.assertEqual(p.returncode, 1)
224
225 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000226 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 tf = tempfile.TemporaryFile()
228 tf.write("pear")
229 tf.seek(0)
230 p = subprocess.Popen([sys.executable, "-c",
231 'import sys; sys.exit(sys.stdin.read() == "pear")'],
232 stdin=tf)
233 p.wait()
234 self.assertEqual(p.returncode, 1)
235
236 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000237 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238 p = subprocess.Popen([sys.executable, "-c",
239 'import sys; sys.stdout.write("orange")'],
240 stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000241 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 self.assertEqual(p.stdout.read(), "orange")
243
244 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000245 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000246 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 d = tf.fileno()
248 p = subprocess.Popen([sys.executable, "-c",
249 'import sys; sys.stdout.write("orange")'],
250 stdout=d)
251 p.wait()
252 os.lseek(d, 0, 0)
253 self.assertEqual(os.read(d, 1024), "orange")
254
255 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000256 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000257 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000258 p = subprocess.Popen([sys.executable, "-c",
259 'import sys; sys.stdout.write("orange")'],
260 stdout=tf)
261 p.wait()
262 tf.seek(0)
263 self.assertEqual(tf.read(), "orange")
264
265 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000266 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000267 p = subprocess.Popen([sys.executable, "-c",
268 'import sys; sys.stderr.write("strawberry")'],
269 stderr=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000270 self.addCleanup(p.stderr.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000271 self.assertStderrEqual(p.stderr.read(), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000272
273 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000274 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000275 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276 d = tf.fileno()
277 p = subprocess.Popen([sys.executable, "-c",
278 'import sys; sys.stderr.write("strawberry")'],
279 stderr=d)
280 p.wait()
281 os.lseek(d, 0, 0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000282 self.assertStderrEqual(os.read(d, 1024), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000283
284 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000285 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000286 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000287 p = subprocess.Popen([sys.executable, "-c",
288 'import sys; sys.stderr.write("strawberry")'],
289 stderr=tf)
290 p.wait()
291 tf.seek(0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000292 self.assertStderrEqual(tf.read(), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293
Martin Panter1edccfa2016-05-13 01:54:44 +0000294 def test_stderr_redirect_with_no_stdout_redirect(self):
295 # test stderr=STDOUT while stdout=None (not set)
296
297 # - grandchild prints to stderr
298 # - child redirects grandchild's stderr to its stdout
299 # - the parent should get grandchild's stderr in child's stdout
300 p = subprocess.Popen([sys.executable, "-c",
301 'import sys, subprocess;'
302 'rc = subprocess.call([sys.executable, "-c",'
303 ' "import sys;"'
304 ' "sys.stderr.write(\'42\')"],'
305 ' stderr=subprocess.STDOUT);'
306 'sys.exit(rc)'],
307 stdout=subprocess.PIPE,
308 stderr=subprocess.PIPE)
309 stdout, stderr = p.communicate()
310 #NOTE: stdout should get stderr from grandchild
311 self.assertStderrEqual(stdout, b'42')
312 self.assertStderrEqual(stderr, b'') # should be empty
313 self.assertEqual(p.returncode, 0)
314
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000315 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000316 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000317 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000318 'import sys;'
319 'sys.stdout.write("apple");'
320 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000321 'sys.stderr.write("orange")'],
322 stdout=subprocess.PIPE,
323 stderr=subprocess.STDOUT)
Brian Curtind117b562010-11-05 04:09:09 +0000324 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000325 self.assertStderrEqual(p.stdout.read(), "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000326
327 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000328 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000329 tf = tempfile.TemporaryFile()
330 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000331 'import sys;'
332 'sys.stdout.write("apple");'
333 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334 'sys.stderr.write("orange")'],
335 stdout=tf,
336 stderr=tf)
337 p.wait()
338 tf.seek(0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000339 self.assertStderrEqual(tf.read(), "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000340
Gustavo Niemeyerc36bede2006-09-07 00:48:33 +0000341 def test_stdout_filedes_of_stdout(self):
342 # stdout is set to 1 (#1531862).
Ezio Melotti9b9cd4c2013-03-11 03:21:08 +0200343 # To avoid printing the text on stdout, we do something similar to
Ezio Melottiefaad092013-03-11 00:34:33 +0200344 # test_stdout_none (see above). The parent subprocess calls the child
345 # subprocess passing stdout=1, and this test uses stdout=PIPE in
346 # order to capture and check the output of the parent. See #11963.
347 code = ('import sys, subprocess; '
348 'rc = subprocess.call([sys.executable, "-c", '
349 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
Ezio Melotti9b9cd4c2013-03-11 03:21:08 +0200350 '\'test with stdout=1\'))"], stdout=1); '
351 'assert rc == 18')
Ezio Melottiefaad092013-03-11 00:34:33 +0200352 p = subprocess.Popen([sys.executable, "-c", code],
353 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
354 self.addCleanup(p.stdout.close)
355 self.addCleanup(p.stderr.close)
356 out, err = p.communicate()
357 self.assertEqual(p.returncode, 0, err)
Ezio Melotti9b9cd4c2013-03-11 03:21:08 +0200358 self.assertEqual(out.rstrip(), 'test with stdout=1')
Gustavo Niemeyerc36bede2006-09-07 00:48:33 +0000359
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000360 def test_cwd(self):
Guido van Rossume9a0e882007-12-20 17:28:10 +0000361 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000362 # We cannot use os.path.realpath to canonicalize the path,
363 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
364 cwd = os.getcwd()
365 os.chdir(tmpdir)
366 tmpdir = os.getcwd()
367 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000368 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000369 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370 'sys.stdout.write(os.getcwd())'],
371 stdout=subprocess.PIPE,
372 cwd=tmpdir)
Brian Curtind117b562010-11-05 04:09:09 +0000373 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000374 normcase = os.path.normcase
375 self.assertEqual(normcase(p.stdout.read()), normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000376
377 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000378 newenv = os.environ.copy()
379 newenv["FRUIT"] = "orange"
380 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000381 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000382 'sys.stdout.write(os.getenv("FRUIT"))'],
383 stdout=subprocess.PIPE,
384 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000385 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000386 self.assertEqual(p.stdout.read(), "orange")
387
Peter Astrandcbac93c2005-03-03 20:24:28 +0000388 def test_communicate_stdin(self):
389 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000390 'import sys;'
391 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000392 stdin=subprocess.PIPE)
393 p.communicate("pear")
394 self.assertEqual(p.returncode, 1)
395
396 def test_communicate_stdout(self):
397 p = subprocess.Popen([sys.executable, "-c",
398 'import sys; sys.stdout.write("pineapple")'],
399 stdout=subprocess.PIPE)
400 (stdout, stderr) = p.communicate()
401 self.assertEqual(stdout, "pineapple")
402 self.assertEqual(stderr, None)
403
404 def test_communicate_stderr(self):
405 p = subprocess.Popen([sys.executable, "-c",
406 'import sys; sys.stderr.write("pineapple")'],
407 stderr=subprocess.PIPE)
408 (stdout, stderr) = p.communicate()
409 self.assertEqual(stdout, None)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000410 self.assertStderrEqual(stderr, "pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000411
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000412 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413 p = subprocess.Popen([sys.executable, "-c",
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000414 'import sys,os;'
415 'sys.stderr.write("pineapple");'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000417 stdin=subprocess.PIPE,
418 stdout=subprocess.PIPE,
419 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000420 self.addCleanup(p.stdout.close)
421 self.addCleanup(p.stderr.close)
422 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 (stdout, stderr) = p.communicate("banana")
424 self.assertEqual(stdout, "banana")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000425 self.assertStderrEqual(stderr, "pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000427 # This test is Linux specific for simplicity to at least have
428 # some coverage. It is not a platform specific bug.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000429 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
430 "Linux specific")
431 # Test for the fd leak reported in http://bugs.python.org/issue2791.
432 def test_communicate_pipe_fd_leak(self):
433 fd_directory = '/proc/%d/fd' % os.getpid()
434 num_fds_before_popen = len(os.listdir(fd_directory))
Martin Panterad6a99c2016-09-10 10:38:22 +0000435 p = subprocess.Popen([sys.executable, "-c", "print('')"],
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000436 stdout=subprocess.PIPE)
437 p.communicate()
438 num_fds_after_communicate = len(os.listdir(fd_directory))
439 del p
440 num_fds_after_destruction = len(os.listdir(fd_directory))
441 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
442 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000443
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000445 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000446 p = subprocess.Popen([sys.executable, "-c",
447 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000448 (stdout, stderr) = p.communicate()
449 self.assertEqual(stdout, None)
450 self.assertEqual(stderr, None)
451
452 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000453 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000455 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000456 x, y = os.pipe()
457 if mswindows:
458 pipe_buf = 512
459 else:
460 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
461 os.close(x)
462 os.close(y)
463 p = subprocess.Popen([sys.executable, "-c",
Tim Peterse718f612004-10-12 21:51:32 +0000464 'import sys,os;'
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000465 'sys.stdout.write(sys.stdin.read(47));'
466 'sys.stderr.write("xyz"*%d);'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000467 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
Tim Peters3b01a702004-10-12 22:19:32 +0000468 stdin=subprocess.PIPE,
469 stdout=subprocess.PIPE,
470 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000471 self.addCleanup(p.stdout.close)
472 self.addCleanup(p.stderr.close)
473 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474 string_to_write = "abc"*pipe_buf
475 (stdout, stderr) = p.communicate(string_to_write)
476 self.assertEqual(stdout, string_to_write)
477
478 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000479 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000480 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000481 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000483 stdin=subprocess.PIPE,
484 stdout=subprocess.PIPE,
485 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000486 self.addCleanup(p.stdout.close)
487 self.addCleanup(p.stderr.close)
488 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 p.stdin.write("banana")
490 (stdout, stderr) = p.communicate("split")
491 self.assertEqual(stdout, "bananasplit")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000492 self.assertStderrEqual(stderr, "")
Tim Peterse718f612004-10-12 21:51:32 +0000493
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000496 'import sys,os;' + SETBINARY +
497 'sys.stdout.write("line1\\n");'
498 'sys.stdout.flush();'
499 'sys.stdout.write("line2\\r");'
500 'sys.stdout.flush();'
501 'sys.stdout.write("line3\\r\\n");'
502 'sys.stdout.flush();'
503 'sys.stdout.write("line4\\r");'
504 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000505 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000506 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507 'sys.stdout.write("\\nline6");'],
508 stdout=subprocess.PIPE,
509 universal_newlines=1)
Brian Curtind117b562010-11-05 04:09:09 +0000510 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000511 stdout = p.stdout.read()
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000512 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000513 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000514 self.assertEqual(stdout,
515 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 else:
517 # Interpreter without universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000518 self.assertEqual(stdout,
519 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520
521 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000522 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000524 'import sys,os;' + SETBINARY +
525 'sys.stdout.write("line1\\n");'
526 'sys.stdout.flush();'
527 'sys.stdout.write("line2\\r");'
528 'sys.stdout.flush();'
529 'sys.stdout.write("line3\\r\\n");'
530 'sys.stdout.flush();'
531 'sys.stdout.write("line4\\r");'
532 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000533 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000534 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000535 'sys.stdout.write("\\nline6");'],
536 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
537 universal_newlines=1)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000538 self.addCleanup(p.stdout.close)
539 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540 (stdout, stderr) = p.communicate()
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000541 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000543 self.assertEqual(stdout,
544 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 else:
546 # Interpreter without universal newline support
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000547 self.assertEqual(stdout,
548 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549
550 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000551 # Make sure we leak no resources
Antoine Pitroub0b3bff2010-09-18 22:42:30 +0000552 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000553 max_handles = 1026 # too much for most UNIX systems
554 else:
Antoine Pitroub0b3bff2010-09-18 22:42:30 +0000555 max_handles = 2050 # too much for (at least some) Windows setups
556 handles = []
557 try:
558 for i in range(max_handles):
559 try:
560 handles.append(os.open(test_support.TESTFN,
561 os.O_WRONLY | os.O_CREAT))
562 except OSError as e:
563 if e.errno != errno.EMFILE:
564 raise
565 break
566 else:
567 self.skipTest("failed to reach the file descriptor limit "
568 "(tried %d)" % max_handles)
569 # Close a couple of them (should be enough for a subprocess)
570 for i in range(10):
571 os.close(handles.pop())
572 # Loop creating some subprocesses. If one of them leaks some fds,
573 # the next loop iteration will fail by reaching the max fd limit.
574 for i in range(15):
575 p = subprocess.Popen([sys.executable, "-c",
576 "import sys;"
577 "sys.stdout.write(sys.stdin.read())"],
578 stdin=subprocess.PIPE,
579 stdout=subprocess.PIPE,
580 stderr=subprocess.PIPE)
581 data = p.communicate(b"lime")[0]
582 self.assertEqual(data, b"lime")
583 finally:
584 for h in handles:
585 os.close(h)
Mark Dickinson313dc9b2012-10-07 15:41:38 +0100586 test_support.unlink(test_support.TESTFN)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000587
588 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
590 '"a b c" d e')
591 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
592 'ab\\"c \\ d')
Gregory P. Smithe047e6d2008-01-19 20:49:02 +0000593 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
594 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000595 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
596 'a\\\\\\b "de fg" h')
597 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
598 'a\\\\\\"b c d')
599 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
600 '"a\\\\b c" d e')
601 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
602 '"a\\\\b\\ c" d e')
Peter Astrand10514a72007-01-13 22:35:35 +0000603 self.assertEqual(subprocess.list2cmdline(['ab', '']),
604 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000605
606
607 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000608 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000609 "-c", "import time; time.sleep(1)"])
610 count = 0
611 while p.poll() is None:
612 time.sleep(0.1)
613 count += 1
614 # We expect that the poll loop probably went around about 10 times,
615 # but, based on system scheduling we can't control, it's possible
616 # poll() never returned None. It "should be" very rare that it
617 # didn't go around at least twice.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000618 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619 # Subsequent invocations should just return the returncode
620 self.assertEqual(p.poll(), 0)
621
622
623 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624 p = subprocess.Popen([sys.executable,
625 "-c", "import time; time.sleep(2)"])
626 self.assertEqual(p.wait(), 0)
627 # Subsequent invocations should just return the returncode
628 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000629
Peter Astrand738131d2004-11-30 21:04:45 +0000630
631 def test_invalid_bufsize(self):
632 # an invalid type of the bufsize argument should raise
633 # TypeError.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000634 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000635 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000636
Georg Brandlf3715d22009-02-14 17:01:36 +0000637 def test_leaking_fds_on_error(self):
638 # see bug #5179: Popen leaks file descriptors to PIPEs if
639 # the child fails to execute; this will eventually exhaust
640 # the maximum number of open fds. 1024 seems a very common
641 # value for that limit, but Windows has 2048, so we loop
642 # 1024 times (each call leaked two fds).
643 for i in range(1024):
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000644 # Windows raises IOError. Others raise OSError.
645 with self.assertRaises(EnvironmentError) as c:
Georg Brandlf3715d22009-02-14 17:01:36 +0000646 subprocess.Popen(['nonexisting_i_hope'],
647 stdout=subprocess.PIPE,
648 stderr=subprocess.PIPE)
R David Murraycdd5fc92011-03-13 22:37:18 -0400649 # ignore errors that indicate the command was not found
650 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000651 raise c.exception
Georg Brandlf3715d22009-02-14 17:01:36 +0000652
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200653 @unittest.skipIf(threading is None, "threading required")
654 def test_double_close_on_error(self):
655 # Issue #18851
656 fds = []
657 def open_fds():
658 for i in range(20):
659 fds.extend(os.pipe())
660 time.sleep(0.001)
661 t = threading.Thread(target=open_fds)
662 t.start()
663 try:
664 with self.assertRaises(EnvironmentError):
665 subprocess.Popen(['nonexisting_i_hope'],
666 stdin=subprocess.PIPE,
667 stdout=subprocess.PIPE,
668 stderr=subprocess.PIPE)
669 finally:
670 t.join()
671 exc = None
672 for fd in fds:
673 # If a double close occurred, some of those fds will
674 # already have been closed by mistake, and os.close()
675 # here will raise.
676 try:
677 os.close(fd)
678 except OSError as e:
679 exc = e
680 if exc is not None:
681 raise exc
682
Tim Golden90374f52010-08-06 13:14:33 +0000683 def test_handles_closed_on_exception(self):
684 # If CreateProcess exits with an error, ensure the
685 # duplicate output handles are released
Berker Peksagb7c35152015-09-28 15:37:57 +0300686 ifhandle, ifname = tempfile.mkstemp()
687 ofhandle, ofname = tempfile.mkstemp()
688 efhandle, efname = tempfile.mkstemp()
Tim Golden90374f52010-08-06 13:14:33 +0000689 try:
690 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
691 stderr=efhandle)
692 except OSError:
693 os.close(ifhandle)
694 os.remove(ifname)
695 os.close(ofhandle)
696 os.remove(ofname)
697 os.close(efhandle)
698 os.remove(efname)
699 self.assertFalse(os.path.exists(ifname))
700 self.assertFalse(os.path.exists(ofname))
701 self.assertFalse(os.path.exists(efname))
702
Ross Lagerwall104c3f12011-04-05 15:24:34 +0200703 def test_communicate_epipe(self):
704 # Issue 10963: communicate() should hide EPIPE
705 p = subprocess.Popen([sys.executable, "-c", 'pass'],
706 stdin=subprocess.PIPE,
707 stdout=subprocess.PIPE,
708 stderr=subprocess.PIPE)
709 self.addCleanup(p.stdout.close)
710 self.addCleanup(p.stderr.close)
711 self.addCleanup(p.stdin.close)
712 p.communicate("x" * 2**20)
713
714 def test_communicate_epipe_only_stdin(self):
715 # Issue 10963: communicate() should hide EPIPE
716 p = subprocess.Popen([sys.executable, "-c", 'pass'],
717 stdin=subprocess.PIPE)
718 self.addCleanup(p.stdin.close)
719 time.sleep(2)
720 p.communicate("x" * 2**20)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000721
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -0800722 # This test is Linux-ish specific for simplicity to at least have
723 # some coverage. It is not a platform specific bug.
724 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
725 "Linux specific")
726 def test_failed_child_execute_fd_leak(self):
727 """Test for the fork() failure fd leak reported in issue16327."""
728 fd_directory = '/proc/%d/fd' % os.getpid()
729 fds_before_popen = os.listdir(fd_directory)
730 with self.assertRaises(PopenTestException):
731 PopenExecuteChildRaises(
732 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
733 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
734
735 # NOTE: This test doesn't verify that the real _execute_child
736 # does not close the file descriptors itself on the way out
737 # during an exception. Code inspection has confirmed that.
738
739 fds_after_exception = os.listdir(fd_directory)
740 self.assertEqual(fds_before_popen, fds_after_exception)
741
742
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000743# context manager
744class _SuppressCoreFiles(object):
745 """Try to prevent core files from being created."""
746 old_limit = None
747
748 def __enter__(self):
749 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson8b59c232011-12-10 12:31:42 -0500750 if resource is not None:
751 try:
752 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
753 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
754 except (ValueError, resource.error):
755 pass
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000756
Ronald Oussoren21b44e02010-07-23 12:26:30 +0000757 if sys.platform == 'darwin':
758 # Check if the 'Crash Reporter' on OSX was configured
759 # in 'Developer' mode and warn that it will get triggered
760 # when it is.
761 #
762 # This assumes that this context manager is used in tests
763 # that might trigger the next manager.
764 value = subprocess.Popen(['/usr/bin/defaults', 'read',
765 'com.apple.CrashReporter', 'DialogType'],
766 stdout=subprocess.PIPE).communicate()[0]
767 if value.strip() == b'developer':
768 print "this tests triggers the Crash Reporter, that is intentional"
769 sys.stdout.flush()
770
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000771 def __exit__(self, *args):
772 """Return core file behavior to default."""
773 if self.old_limit is None:
774 return
Benjamin Peterson8b59c232011-12-10 12:31:42 -0500775 if resource is not None:
776 try:
777 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
778 except (ValueError, resource.error):
779 pass
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000780
Victor Stinnerb78fed92011-07-05 14:50:35 +0200781 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
782 "Requires signal.SIGALRM")
Victor Stinnere7901312011-07-05 14:08:01 +0200783 def test_communicate_eintr(self):
784 # Issue #12493: communicate() should handle EINTR
785 def handler(signum, frame):
786 pass
787 old_handler = signal.signal(signal.SIGALRM, handler)
788 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
789
790 # the process is running for 2 seconds
791 args = [sys.executable, "-c", 'import time; time.sleep(2)']
792 for stream in ('stdout', 'stderr'):
793 kw = {stream: subprocess.PIPE}
794 with subprocess.Popen(args, **kw) as process:
795 signal.alarm(1)
796 # communicate() will be interrupted by SIGALRM
797 process.communicate()
798
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000799
Florent Xiclunabab22a72010-03-04 19:40:48 +0000800@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000801class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +0000802
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000803 def test_exceptions(self):
804 # caught & re-raised exceptions
805 with self.assertRaises(OSError) as c:
806 p = subprocess.Popen([sys.executable, "-c", ""],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000807 cwd="/this/path/does/not/exist")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000808 # The attribute child_traceback should contain "os.chdir" somewhere.
809 self.assertIn("os.chdir", c.exception.child_traceback)
Tim Peterse718f612004-10-12 21:51:32 +0000810
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000811 def test_run_abort(self):
812 # returncode handles signal termination
813 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000814 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000815 "import os; os.abort()"])
816 p.wait()
817 self.assertEqual(-p.returncode, signal.SIGABRT)
818
819 def test_preexec(self):
820 # preexec function
821 p = subprocess.Popen([sys.executable, "-c",
822 "import sys, os;"
823 "sys.stdout.write(os.getenv('FRUIT'))"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000824 stdout=subprocess.PIPE,
825 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtind117b562010-11-05 04:09:09 +0000826 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000827 self.assertEqual(p.stdout.read(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000828
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800829 class _TestExecuteChildPopen(subprocess.Popen):
830 """Used to test behavior at the end of _execute_child."""
831 def __init__(self, testcase, *args, **kwargs):
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800832 self._testcase = testcase
833 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith211248b2012-11-11 02:00:49 -0800834
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800835 def _execute_child(
836 self, args, executable, preexec_fn, close_fds, cwd, env,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200837 universal_newlines, startupinfo, creationflags, shell, to_close,
Gregory P. Smith211248b2012-11-11 02:00:49 -0800838 p2cread, p2cwrite,
839 c2pread, c2pwrite,
840 errread, errwrite):
841 try:
842 subprocess.Popen._execute_child(
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800843 self, args, executable, preexec_fn, close_fds,
Gregory P. Smith211248b2012-11-11 02:00:49 -0800844 cwd, env, universal_newlines,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200845 startupinfo, creationflags, shell, to_close,
Gregory P. Smith211248b2012-11-11 02:00:49 -0800846 p2cread, p2cwrite,
847 c2pread, c2pwrite,
848 errread, errwrite)
849 finally:
850 # Open a bunch of file descriptors and verify that
851 # none of them are the same as the ones the Popen
852 # instance is using for stdin/stdout/stderr.
853 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
854 for _ in range(8)]
855 try:
856 for fd in devzero_fds:
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800857 self._testcase.assertNotIn(
858 fd, (p2cwrite, c2pread, errread))
Gregory P. Smith211248b2012-11-11 02:00:49 -0800859 finally:
Richard Oudkerk045e4572013-06-10 16:27:45 +0100860 for fd in devzero_fds:
861 os.close(fd)
Gregory P. Smith211248b2012-11-11 02:00:49 -0800862
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800863 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
864 def test_preexec_errpipe_does_not_double_close_pipes(self):
865 """Issue16140: Don't double close pipes on preexec error."""
866
867 def raise_it():
868 raise RuntimeError("force the _execute_child() errpipe_data path.")
Gregory P. Smith211248b2012-11-11 02:00:49 -0800869
870 with self.assertRaises(RuntimeError):
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800871 self._TestExecuteChildPopen(
872 self, [sys.executable, "-c", "pass"],
873 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
874 stderr=subprocess.PIPE, preexec_fn=raise_it)
Gregory P. Smith211248b2012-11-11 02:00:49 -0800875
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000876 def test_args_string(self):
877 # args is a string
Berker Peksagb7c35152015-09-28 15:37:57 +0300878 f, fname = tempfile.mkstemp()
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000879 os.write(f, "#!/bin/sh\n")
880 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
881 sys.executable)
882 os.close(f)
883 os.chmod(fname, 0o700)
884 p = subprocess.Popen(fname)
885 p.wait()
886 os.remove(fname)
887 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000888
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000889 def test_invalid_args(self):
890 # invalid arguments should raise ValueError
891 self.assertRaises(ValueError, subprocess.call,
892 [sys.executable, "-c",
893 "import sys; sys.exit(47)"],
894 startupinfo=47)
895 self.assertRaises(ValueError, subprocess.call,
896 [sys.executable, "-c",
897 "import sys; sys.exit(47)"],
898 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000899
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000900 def test_shell_sequence(self):
901 # Run command through the shell (sequence)
902 newenv = os.environ.copy()
903 newenv["FRUIT"] = "apple"
904 p = subprocess.Popen(["echo $FRUIT"], shell=1,
905 stdout=subprocess.PIPE,
906 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000907 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000908 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000909
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000910 def test_shell_string(self):
911 # Run command through the shell (string)
912 newenv = os.environ.copy()
913 newenv["FRUIT"] = "apple"
914 p = subprocess.Popen("echo $FRUIT", shell=1,
915 stdout=subprocess.PIPE,
916 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000917 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000918 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000920 def test_call_string(self):
921 # call() function with string argument on UNIX
Berker Peksagb7c35152015-09-28 15:37:57 +0300922 f, fname = tempfile.mkstemp()
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000923 os.write(f, "#!/bin/sh\n")
924 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
925 sys.executable)
926 os.close(f)
927 os.chmod(fname, 0700)
928 rc = subprocess.call(fname)
929 os.remove(fname)
930 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000932 def test_specific_shell(self):
933 # Issue #9265: Incorrect name passed as arg[0].
934 shells = []
935 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
936 for name in ['bash', 'ksh']:
937 sh = os.path.join(prefix, name)
938 if os.path.isfile(sh):
939 shells.append(sh)
940 if not shells: # Will probably work for any shell but csh.
941 self.skipTest("bash or ksh required for this test")
942 sh = '/bin/sh'
943 if os.path.isfile(sh) and not os.path.islink(sh):
944 # Test will fail if /bin/sh is a symlink to csh.
945 shells.append(sh)
946 for sh in shells:
947 p = subprocess.Popen("echo $0", executable=sh, shell=True,
948 stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000949 self.addCleanup(p.stdout.close)
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000950 self.assertEqual(p.stdout.read().strip(), sh)
951
Florent Xiclunac0838642010-03-07 15:27:39 +0000952 def _kill_process(self, method, *args):
Florent Xiclunacecef392010-03-05 19:31:21 +0000953 # Do not inherit file handles from the parent.
954 # It should fix failures on some platforms.
Antoine Pitroua6166da2010-09-20 11:20:44 +0000955 p = subprocess.Popen([sys.executable, "-c", """if 1:
956 import sys, time
957 sys.stdout.write('x\\n')
958 sys.stdout.flush()
959 time.sleep(30)
960 """],
961 close_fds=True,
962 stdin=subprocess.PIPE,
963 stdout=subprocess.PIPE,
964 stderr=subprocess.PIPE)
965 # Wait for the interpreter to be completely initialized before
966 # sending any signal.
967 p.stdout.read(1)
968 getattr(p, method)(*args)
Florent Xiclunac0838642010-03-07 15:27:39 +0000969 return p
970
Charles-François Natalief2bd672013-01-12 16:52:20 +0100971 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
972 "Due to known OS bug (issue #16762)")
Antoine Pitrouf60845b2012-03-11 19:29:12 +0100973 def _kill_dead_process(self, method, *args):
974 # Do not inherit file handles from the parent.
975 # It should fix failures on some platforms.
976 p = subprocess.Popen([sys.executable, "-c", """if 1:
977 import sys, time
978 sys.stdout.write('x\\n')
979 sys.stdout.flush()
980 """],
981 close_fds=True,
982 stdin=subprocess.PIPE,
983 stdout=subprocess.PIPE,
984 stderr=subprocess.PIPE)
985 # Wait for the interpreter to be completely initialized before
986 # sending any signal.
987 p.stdout.read(1)
988 # The process should end after this
989 time.sleep(1)
990 # This shouldn't raise even though the child is now dead
991 getattr(p, method)(*args)
992 p.communicate()
993
Florent Xiclunac0838642010-03-07 15:27:39 +0000994 def test_send_signal(self):
995 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000996 _, stderr = p.communicate()
Florent Xicluna3c919cf2010-03-23 19:19:16 +0000997 self.assertIn('KeyboardInterrupt', stderr)
Florent Xicluna446ff142010-03-23 15:05:30 +0000998 self.assertNotEqual(p.wait(), 0)
Christian Heimese74c8f22008-04-19 02:23:57 +0000999
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001000 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001001 p = self._kill_process('kill')
Florent Xicluna446ff142010-03-23 15:05:30 +00001002 _, stderr = p.communicate()
1003 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001004 self.assertEqual(p.wait(), -signal.SIGKILL)
Christian Heimese74c8f22008-04-19 02:23:57 +00001005
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001006 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001007 p = self._kill_process('terminate')
Florent Xicluna446ff142010-03-23 15:05:30 +00001008 _, stderr = p.communicate()
1009 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001010 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +00001011
Antoine Pitrouf60845b2012-03-11 19:29:12 +01001012 def test_send_signal_dead(self):
1013 # Sending a signal to a dead process
1014 self._kill_dead_process('send_signal', signal.SIGINT)
1015
1016 def test_kill_dead(self):
1017 # Killing a dead process
1018 self._kill_dead_process('kill')
1019
1020 def test_terminate_dead(self):
1021 # Terminating a dead process
1022 self._kill_dead_process('terminate')
1023
Antoine Pitrou91ce0d92011-01-03 18:45:09 +00001024 def check_close_std_fds(self, fds):
1025 # Issue #9905: test that subprocess pipes still work properly with
1026 # some standard fds closed
1027 stdin = 0
1028 newfds = []
1029 for a in fds:
1030 b = os.dup(a)
1031 newfds.append(b)
1032 if a == 0:
1033 stdin = b
1034 try:
1035 for fd in fds:
1036 os.close(fd)
1037 out, err = subprocess.Popen([sys.executable, "-c",
1038 'import sys;'
1039 'sys.stdout.write("apple");'
1040 'sys.stdout.flush();'
1041 'sys.stderr.write("orange")'],
1042 stdin=stdin,
1043 stdout=subprocess.PIPE,
1044 stderr=subprocess.PIPE).communicate()
1045 err = test_support.strip_python_stderr(err)
1046 self.assertEqual((out, err), (b'apple', b'orange'))
1047 finally:
1048 for b, a in zip(newfds, fds):
1049 os.dup2(b, a)
1050 for b in newfds:
1051 os.close(b)
1052
1053 def test_close_fd_0(self):
1054 self.check_close_std_fds([0])
1055
1056 def test_close_fd_1(self):
1057 self.check_close_std_fds([1])
1058
1059 def test_close_fd_2(self):
1060 self.check_close_std_fds([2])
1061
1062 def test_close_fds_0_1(self):
1063 self.check_close_std_fds([0, 1])
1064
1065 def test_close_fds_0_2(self):
1066 self.check_close_std_fds([0, 2])
1067
1068 def test_close_fds_1_2(self):
1069 self.check_close_std_fds([1, 2])
1070
1071 def test_close_fds_0_1_2(self):
1072 # Issue #10806: test that subprocess pipes still work properly with
1073 # all standard fds closed.
1074 self.check_close_std_fds([0, 1, 2])
1075
Ross Lagerwalld8e39012011-07-27 18:54:53 +02001076 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1077 # open up some temporary files
Berker Peksagb7c35152015-09-28 15:37:57 +03001078 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld8e39012011-07-27 18:54:53 +02001079 temp_fds = [fd for fd, fname in temps]
1080 try:
1081 # unlink the files -- we won't need to reopen them
1082 for fd, fname in temps:
1083 os.unlink(fname)
1084
1085 # save a copy of the standard file descriptors
1086 saved_fds = [os.dup(fd) for fd in range(3)]
1087 try:
1088 # duplicate the temp files over the standard fd's 0, 1, 2
1089 for fd, temp_fd in enumerate(temp_fds):
1090 os.dup2(temp_fd, fd)
1091
1092 # write some data to what will become stdin, and rewind
1093 os.write(stdin_no, b"STDIN")
1094 os.lseek(stdin_no, 0, 0)
1095
1096 # now use those files in the given order, so that subprocess
1097 # has to rearrange them in the child
1098 p = subprocess.Popen([sys.executable, "-c",
1099 'import sys; got = sys.stdin.read();'
1100 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1101 stdin=stdin_no,
1102 stdout=stdout_no,
1103 stderr=stderr_no)
1104 p.wait()
1105
1106 for fd in temp_fds:
1107 os.lseek(fd, 0, 0)
1108
1109 out = os.read(stdout_no, 1024)
1110 err = test_support.strip_python_stderr(os.read(stderr_no, 1024))
1111 finally:
1112 for std, saved in enumerate(saved_fds):
1113 os.dup2(saved, std)
1114 os.close(saved)
1115
1116 self.assertEqual(out, b"got STDIN")
1117 self.assertEqual(err, b"err")
1118
1119 finally:
1120 for fd in temp_fds:
1121 os.close(fd)
1122
1123 # When duping fds, if there arises a situation where one of the fds is
1124 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1125 # This tests all combinations of this.
1126 def test_swap_fds(self):
1127 self.check_swap_fds(0, 1, 2)
1128 self.check_swap_fds(0, 2, 1)
1129 self.check_swap_fds(1, 0, 2)
1130 self.check_swap_fds(1, 2, 0)
1131 self.check_swap_fds(2, 0, 1)
1132 self.check_swap_fds(2, 1, 0)
1133
Gregory P. Smith312efbc2010-12-14 15:02:53 +00001134 def test_wait_when_sigchild_ignored(self):
1135 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1136 sigchild_ignore = test_support.findfile("sigchild_ignore.py",
1137 subdir="subprocessdata")
1138 p = subprocess.Popen([sys.executable, sigchild_ignore],
1139 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1140 stdout, stderr = p.communicate()
1141 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
1142 " non-zero with this error:\n%s" % stderr)
1143
Charles-François Natali100df0f2011-08-18 17:56:02 +02001144 def test_zombie_fast_process_del(self):
1145 # Issue #12650: on Unix, if Popen.__del__() was called before the
1146 # process exited, it wouldn't be added to subprocess._active, and would
1147 # remain a zombie.
1148 # spawn a Popen, and delete its reference before it exits
1149 p = subprocess.Popen([sys.executable, "-c",
1150 'import sys, time;'
1151 'time.sleep(0.2)'],
1152 stdout=subprocess.PIPE,
1153 stderr=subprocess.PIPE)
Nadeem Vawda86059362011-08-19 05:22:24 +02001154 self.addCleanup(p.stdout.close)
1155 self.addCleanup(p.stderr.close)
Charles-François Natali100df0f2011-08-18 17:56:02 +02001156 ident = id(p)
1157 pid = p.pid
1158 del p
1159 # check that p is in the active processes list
1160 self.assertIn(ident, [id(o) for o in subprocess._active])
1161
Charles-François Natali100df0f2011-08-18 17:56:02 +02001162 def test_leak_fast_process_del_killed(self):
1163 # Issue #12650: on Unix, if Popen.__del__() was called before the
1164 # process exited, and the process got killed by a signal, it would never
1165 # be removed from subprocess._active, which triggered a FD and memory
1166 # leak.
1167 # spawn a Popen, delete its reference and kill it
1168 p = subprocess.Popen([sys.executable, "-c",
1169 'import time;'
1170 'time.sleep(3)'],
1171 stdout=subprocess.PIPE,
1172 stderr=subprocess.PIPE)
Nadeem Vawda86059362011-08-19 05:22:24 +02001173 self.addCleanup(p.stdout.close)
1174 self.addCleanup(p.stderr.close)
Charles-François Natali100df0f2011-08-18 17:56:02 +02001175 ident = id(p)
1176 pid = p.pid
1177 del p
1178 os.kill(pid, signal.SIGKILL)
1179 # check that p is in the active processes list
1180 self.assertIn(ident, [id(o) for o in subprocess._active])
1181
1182 # let some time for the process to exit, and create a new Popen: this
1183 # should trigger the wait() of p
1184 time.sleep(0.2)
1185 with self.assertRaises(EnvironmentError) as c:
1186 with subprocess.Popen(['nonexisting_i_hope'],
1187 stdout=subprocess.PIPE,
1188 stderr=subprocess.PIPE) as proc:
1189 pass
1190 # p should have been wait()ed on, and removed from the _active list
1191 self.assertRaises(OSError, os.waitpid, pid, 0)
1192 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1193
Charles-François Natali2a34eb32011-08-25 21:20:54 +02001194 def test_pipe_cloexec(self):
1195 # Issue 12786: check that the communication pipes' FDs are set CLOEXEC,
1196 # and are not inherited by another child process.
1197 p1 = subprocess.Popen([sys.executable, "-c",
1198 'import os;'
1199 'os.read(0, 1)'
1200 ],
1201 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1202 stderr=subprocess.PIPE)
1203
1204 p2 = subprocess.Popen([sys.executable, "-c", """if True:
1205 import os, errno, sys
1206 for fd in %r:
1207 try:
1208 os.close(fd)
1209 except OSError as e:
1210 if e.errno != errno.EBADF:
1211 raise
1212 else:
1213 sys.exit(1)
1214 sys.exit(0)
1215 """ % [f.fileno() for f in (p1.stdin, p1.stdout,
1216 p1.stderr)]
1217 ],
1218 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1219 stderr=subprocess.PIPE, close_fds=False)
1220 p1.communicate('foo')
1221 _, stderr = p2.communicate()
1222
1223 self.assertEqual(p2.returncode, 0, "Unexpected error: " + repr(stderr))
1224
Gregory P. Smithf0739cb2017-01-22 22:38:28 -08001225 _libc_file_extensions = {
1226 'Linux': 'so.6',
1227 'Darwin': 'dylib',
1228 }
1229 @unittest.skipIf(not ctypes, 'ctypes module required.')
1230 @unittest.skipIf(platform.uname()[0] not in _libc_file_extensions,
1231 'Test requires a libc this code can load with ctypes.')
1232 @unittest.skipIf(not sys.executable, 'Test requires sys.executable.')
1233 def test_child_terminated_in_stopped_state(self):
1234 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
1235 PTRACE_TRACEME = 0 # From glibc and MacOS (PT_TRACE_ME).
1236 libc_name = 'libc.' + self._libc_file_extensions[platform.uname()[0]]
1237 libc = ctypes.CDLL(libc_name)
1238 if not hasattr(libc, 'ptrace'):
1239 raise unittest.SkipTest('ptrace() required.')
1240 test_ptrace = subprocess.Popen(
1241 [sys.executable, '-c', """if True:
1242 import ctypes
1243 libc = ctypes.CDLL({libc_name!r})
1244 libc.ptrace({PTRACE_TRACEME}, 0, 0)
1245 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
1246 ])
1247 if test_ptrace.wait() != 0:
1248 raise unittest.SkipTest('ptrace() failed - unable to test.')
1249 child = subprocess.Popen(
1250 [sys.executable, '-c', """if True:
1251 import ctypes
1252 libc = ctypes.CDLL({libc_name!r})
1253 libc.ptrace({PTRACE_TRACEME}, 0, 0)
1254 libc.printf(ctypes.c_char_p(0xdeadbeef)) # Crash the process.
1255 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
1256 ])
1257 try:
1258 returncode = child.wait()
1259 except Exception as e:
1260 child.kill() # Clean up the hung stopped process.
1261 raise e
1262 self.assertNotEqual(0, returncode)
1263 self.assertLess(returncode, 0) # signal death, likely SIGSEGV.
1264
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001265
Florent Xiclunabab22a72010-03-04 19:40:48 +00001266@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +00001267class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +00001268
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001269 def test_startupinfo(self):
1270 # startupinfo argument
1271 # We uses hardcoded constants, because we do not want to
1272 # depend on win32all.
1273 STARTF_USESHOWWINDOW = 1
1274 SW_MAXIMIZE = 3
1275 startupinfo = subprocess.STARTUPINFO()
1276 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1277 startupinfo.wShowWindow = SW_MAXIMIZE
1278 # Since Python is a console process, it won't be affected
1279 # by wShowWindow, but the argument should be silently
1280 # ignored
1281 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001282 startupinfo=startupinfo)
1283
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001284 def test_creationflags(self):
1285 # creationflags argument
1286 CREATE_NEW_CONSOLE = 16
1287 sys.stderr.write(" a DOS box should flash briefly ...\n")
1288 subprocess.call(sys.executable +
1289 ' -c "import time; time.sleep(0.25)"',
1290 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001291
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001292 def test_invalid_args(self):
1293 # invalid arguments should raise ValueError
1294 self.assertRaises(ValueError, subprocess.call,
1295 [sys.executable, "-c",
1296 "import sys; sys.exit(47)"],
1297 preexec_fn=lambda: 1)
1298 self.assertRaises(ValueError, subprocess.call,
1299 [sys.executable, "-c",
1300 "import sys; sys.exit(47)"],
1301 stdout=subprocess.PIPE,
1302 close_fds=True)
1303
1304 def test_close_fds(self):
1305 # close file descriptors
1306 rc = subprocess.call([sys.executable, "-c",
1307 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001308 close_fds=True)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001309 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001310
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001311 def test_shell_sequence(self):
1312 # Run command through the shell (sequence)
1313 newenv = os.environ.copy()
1314 newenv["FRUIT"] = "physalis"
1315 p = subprocess.Popen(["set"], shell=1,
1316 stdout=subprocess.PIPE,
1317 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001318 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001319 self.assertIn("physalis", p.stdout.read())
Peter Astrand81a191b2007-05-26 22:18:20 +00001320
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001321 def test_shell_string(self):
1322 # Run command through the shell (string)
1323 newenv = os.environ.copy()
1324 newenv["FRUIT"] = "physalis"
1325 p = subprocess.Popen("set", shell=1,
1326 stdout=subprocess.PIPE,
1327 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001328 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001329 self.assertIn("physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001330
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001331 def test_call_string(self):
1332 # call() function with string argument on Windows
1333 rc = subprocess.call(sys.executable +
1334 ' -c "import sys; sys.exit(47)"')
1335 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001336
Florent Xiclunac0838642010-03-07 15:27:39 +00001337 def _kill_process(self, method, *args):
Florent Xicluna400efc22010-03-07 17:12:23 +00001338 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroudee00972010-09-24 19:00:29 +00001339 p = subprocess.Popen([sys.executable, "-c", """if 1:
1340 import sys, time
1341 sys.stdout.write('x\\n')
1342 sys.stdout.flush()
1343 time.sleep(30)
1344 """],
1345 stdin=subprocess.PIPE,
1346 stdout=subprocess.PIPE,
1347 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001348 self.addCleanup(p.stdout.close)
1349 self.addCleanup(p.stderr.close)
1350 self.addCleanup(p.stdin.close)
Antoine Pitroudee00972010-09-24 19:00:29 +00001351 # Wait for the interpreter to be completely initialized before
1352 # sending any signal.
1353 p.stdout.read(1)
1354 getattr(p, method)(*args)
Florent Xicluna446ff142010-03-23 15:05:30 +00001355 _, stderr = p.communicate()
1356 self.assertStderrEqual(stderr, '')
Antoine Pitroudee00972010-09-24 19:00:29 +00001357 returncode = p.wait()
Florent Xiclunafaf17532010-03-08 10:59:33 +00001358 self.assertNotEqual(returncode, 0)
Florent Xiclunac0838642010-03-07 15:27:39 +00001359
Antoine Pitrouf60845b2012-03-11 19:29:12 +01001360 def _kill_dead_process(self, method, *args):
1361 p = subprocess.Popen([sys.executable, "-c", """if 1:
1362 import sys, time
1363 sys.stdout.write('x\\n')
1364 sys.stdout.flush()
1365 sys.exit(42)
1366 """],
1367 stdin=subprocess.PIPE,
1368 stdout=subprocess.PIPE,
1369 stderr=subprocess.PIPE)
1370 self.addCleanup(p.stdout.close)
1371 self.addCleanup(p.stderr.close)
1372 self.addCleanup(p.stdin.close)
1373 # Wait for the interpreter to be completely initialized before
1374 # sending any signal.
1375 p.stdout.read(1)
1376 # The process should end after this
1377 time.sleep(1)
1378 # This shouldn't raise even though the child is now dead
1379 getattr(p, method)(*args)
1380 _, stderr = p.communicate()
1381 self.assertStderrEqual(stderr, b'')
1382 rc = p.wait()
1383 self.assertEqual(rc, 42)
1384
Florent Xiclunac0838642010-03-07 15:27:39 +00001385 def test_send_signal(self):
1386 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimese74c8f22008-04-19 02:23:57 +00001387
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001388 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001389 self._kill_process('kill')
Christian Heimese74c8f22008-04-19 02:23:57 +00001390
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001391 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001392 self._kill_process('terminate')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001393
Antoine Pitrouf60845b2012-03-11 19:29:12 +01001394 def test_send_signal_dead(self):
1395 self._kill_dead_process('send_signal', signal.SIGTERM)
1396
1397 def test_kill_dead(self):
1398 self._kill_dead_process('kill')
1399
1400 def test_terminate_dead(self):
1401 self._kill_dead_process('terminate')
1402
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001403
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001404@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1405 "poll system call not supported")
1406class ProcessTestCaseNoPoll(ProcessTestCase):
1407 def setUp(self):
1408 subprocess._has_poll = False
1409 ProcessTestCase.setUp(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001410
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001411 def tearDown(self):
1412 subprocess._has_poll = True
1413 ProcessTestCase.tearDown(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001414
1415
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001416class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithc1baf4a2010-03-01 02:53:24 +00001417 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001418 def test_eintr_retry_call(self):
1419 record_calls = []
1420 def fake_os_func(*args):
1421 record_calls.append(args)
1422 if len(record_calls) == 2:
1423 raise OSError(errno.EINTR, "fake interrupted system call")
1424 return tuple(reversed(args))
1425
1426 self.assertEqual((999, 256),
1427 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1428 self.assertEqual([(256, 999)], record_calls)
1429 # This time there will be an EINTR so it will loop once.
1430 self.assertEqual((666,),
1431 subprocess._eintr_retry_call(fake_os_func, 666))
1432 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1433
Tim Golden8e4756c2010-08-12 11:00:35 +00001434@unittest.skipUnless(mswindows, "mswindows only")
1435class CommandsWithSpaces (BaseTestCase):
1436
1437 def setUp(self):
1438 super(CommandsWithSpaces, self).setUp()
Berker Peksagb7c35152015-09-28 15:37:57 +03001439 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden8e4756c2010-08-12 11:00:35 +00001440 self.fname = fname.lower ()
1441 os.write(f, b"import sys;"
1442 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1443 )
1444 os.close(f)
1445
1446 def tearDown(self):
1447 os.remove(self.fname)
1448 super(CommandsWithSpaces, self).tearDown()
1449
1450 def with_spaces(self, *args, **kwargs):
1451 kwargs['stdout'] = subprocess.PIPE
1452 p = subprocess.Popen(*args, **kwargs)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001453 self.addCleanup(p.stdout.close)
Tim Golden8e4756c2010-08-12 11:00:35 +00001454 self.assertEqual(
1455 p.stdout.read ().decode("mbcs"),
1456 "2 [%r, 'ab cd']" % self.fname
1457 )
1458
1459 def test_shell_string_with_spaces(self):
1460 # call() function with string argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +00001461 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1462 "ab cd"), shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +00001463
1464 def test_shell_sequence_with_spaces(self):
1465 # call() function with sequence argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +00001466 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +00001467
1468 def test_noshell_string_with_spaces(self):
1469 # call() function with string argument with spaces on Windows
1470 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1471 "ab cd"))
1472
1473 def test_noshell_sequence_with_spaces(self):
1474 # call() function with sequence argument with spaces on Windows
1475 self.with_spaces([sys.executable, self.fname, "ab cd"])
1476
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001477def test_main():
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001478 unit_tests = (ProcessTestCase,
1479 POSIXProcessTestCase,
1480 Win32ProcessTestCase,
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001481 ProcessTestCaseNoPoll,
Tim Golden8e4756c2010-08-12 11:00:35 +00001482 HelperFunctionTests,
1483 CommandsWithSpaces)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001484
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001485 test_support.run_unittest(*unit_tests)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001486 test_support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001487
1488if __name__ == "__main__":
1489 test_main()