blob: 38844888fdb87e21f201ca726329c32d6cf0eb85 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
2from test import test_support
3import subprocess
4import sys
5import signal
6import os
Gregory P. Smithcce211f2010-03-01 00:05:08 +00007import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008import tempfile
9import time
Tim Peters3761e8d2004-10-13 04:07:12 +000010import re
Ezio Melotti8f6a2872010-02-10 21:40:33 +000011import sysconfig
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000012
Benjamin Peterson8b59c232011-12-10 12:31:42 -050013try:
14 import resource
15except ImportError:
16 resource = None
17
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000018mswindows = (sys.platform == "win32")
19
20#
21# Depends on the following external programs: Python
22#
23
24if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000025 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
26 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000027else:
28 SETBINARY = ''
29
Florent Xicluna98e3fc32010-02-27 19:20:50 +000030
31try:
32 mkstemp = tempfile.mkstemp
33except AttributeError:
34 # tempfile.mkstemp is not available
35 def mkstemp():
36 """Replacement for mkstemp, calling mktemp."""
37 fname = tempfile.mktemp()
38 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
39
Tim Peters3761e8d2004-10-13 04:07:12 +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):
Tim Peters7b759da2004-10-12 22:29:54 +0000153 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000154 p = subprocess.Popen([sys.executable, "-c",
Tim Peters4052fe52004-10-13 03:29:54 +0000155 'print " this bit of output is from a '
156 'test of stdout in a different '
157 'process ..."'],
158 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000159 self.addCleanup(p.stdin.close)
160 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000161 p.wait()
162 self.assertEqual(p.stdout, None)
163
164 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000165 # .stderr is None when not redirected
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000166 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
167 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000168 self.addCleanup(p.stdout.close)
169 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000170 p.wait()
171 self.assertEqual(p.stderr, None)
172
Ezio Melotti8f6a2872010-02-10 21:40:33 +0000173 def test_executable_with_cwd(self):
Florent Xicluna63763702010-03-11 01:50:48 +0000174 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti8f6a2872010-02-10 21:40:33 +0000175 p = subprocess.Popen(["somethingyoudonthave", "-c",
176 "import sys; sys.exit(47)"],
177 executable=sys.executable, cwd=python_dir)
178 p.wait()
179 self.assertEqual(p.returncode, 47)
180
181 @unittest.skipIf(sysconfig.is_python_build(),
182 "need an installed Python. See #7774")
183 def test_executable_without_cwd(self):
184 # For a normal installation, it should work without 'cwd'
185 # argument. For test runs in the build directory, see #7774.
186 p = subprocess.Popen(["somethingyoudonthave", "-c",
187 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000188 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 p.wait()
190 self.assertEqual(p.returncode, 47)
191
192 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000193 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000194 p = subprocess.Popen([sys.executable, "-c",
195 'import sys; sys.exit(sys.stdin.read() == "pear")'],
196 stdin=subprocess.PIPE)
197 p.stdin.write("pear")
198 p.stdin.close()
199 p.wait()
200 self.assertEqual(p.returncode, 1)
201
202 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000203 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000204 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000205 d = tf.fileno()
206 os.write(d, "pear")
207 os.lseek(d, 0, 0)
208 p = subprocess.Popen([sys.executable, "-c",
209 'import sys; sys.exit(sys.stdin.read() == "pear")'],
210 stdin=d)
211 p.wait()
212 self.assertEqual(p.returncode, 1)
213
214 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000215 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000216 tf = tempfile.TemporaryFile()
217 tf.write("pear")
218 tf.seek(0)
219 p = subprocess.Popen([sys.executable, "-c",
220 'import sys; sys.exit(sys.stdin.read() == "pear")'],
221 stdin=tf)
222 p.wait()
223 self.assertEqual(p.returncode, 1)
224
225 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000226 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 p = subprocess.Popen([sys.executable, "-c",
228 'import sys; sys.stdout.write("orange")'],
229 stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000230 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000231 self.assertEqual(p.stdout.read(), "orange")
232
233 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000234 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000235 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236 d = tf.fileno()
237 p = subprocess.Popen([sys.executable, "-c",
238 'import sys; sys.stdout.write("orange")'],
239 stdout=d)
240 p.wait()
241 os.lseek(d, 0, 0)
242 self.assertEqual(os.read(d, 1024), "orange")
243
244 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000245 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000246 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 p = subprocess.Popen([sys.executable, "-c",
248 'import sys; sys.stdout.write("orange")'],
249 stdout=tf)
250 p.wait()
251 tf.seek(0)
252 self.assertEqual(tf.read(), "orange")
253
254 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000255 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000256 p = subprocess.Popen([sys.executable, "-c",
257 'import sys; sys.stderr.write("strawberry")'],
258 stderr=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000259 self.addCleanup(p.stderr.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000260 self.assertStderrEqual(p.stderr.read(), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000261
262 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000263 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000264 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265 d = tf.fileno()
266 p = subprocess.Popen([sys.executable, "-c",
267 'import sys; sys.stderr.write("strawberry")'],
268 stderr=d)
269 p.wait()
270 os.lseek(d, 0, 0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000271 self.assertStderrEqual(os.read(d, 1024), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000272
273 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000274 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000275 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276 p = subprocess.Popen([sys.executable, "-c",
277 'import sys; sys.stderr.write("strawberry")'],
278 stderr=tf)
279 p.wait()
280 tf.seek(0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000281 self.assertStderrEqual(tf.read(), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282
283 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000284 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000286 'import sys;'
287 'sys.stdout.write("apple");'
288 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000289 'sys.stderr.write("orange")'],
290 stdout=subprocess.PIPE,
291 stderr=subprocess.STDOUT)
Brian Curtind117b562010-11-05 04:09:09 +0000292 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000293 self.assertStderrEqual(p.stdout.read(), "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294
295 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000296 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000297 tf = tempfile.TemporaryFile()
298 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000299 'import sys;'
300 'sys.stdout.write("apple");'
301 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000302 'sys.stderr.write("orange")'],
303 stdout=tf,
304 stderr=tf)
305 p.wait()
306 tf.seek(0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000307 self.assertStderrEqual(tf.read(), "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308
Gustavo Niemeyerc36bede2006-09-07 00:48:33 +0000309 def test_stdout_filedes_of_stdout(self):
310 # stdout is set to 1 (#1531862).
311 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), '.\n'))"
312 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000313 self.assertEqual(rc, 2)
Gustavo Niemeyerc36bede2006-09-07 00:48:33 +0000314
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000315 def test_cwd(self):
Guido van Rossume9a0e882007-12-20 17:28:10 +0000316 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000317 # We cannot use os.path.realpath to canonicalize the path,
318 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
319 cwd = os.getcwd()
320 os.chdir(tmpdir)
321 tmpdir = os.getcwd()
322 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000323 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000324 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000325 'sys.stdout.write(os.getcwd())'],
326 stdout=subprocess.PIPE,
327 cwd=tmpdir)
Brian Curtind117b562010-11-05 04:09:09 +0000328 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000329 normcase = os.path.normcase
330 self.assertEqual(normcase(p.stdout.read()), normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000331
332 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000333 newenv = os.environ.copy()
334 newenv["FRUIT"] = "orange"
335 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000336 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000337 'sys.stdout.write(os.getenv("FRUIT"))'],
338 stdout=subprocess.PIPE,
339 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000340 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000341 self.assertEqual(p.stdout.read(), "orange")
342
Peter Astrandcbac93c2005-03-03 20:24:28 +0000343 def test_communicate_stdin(self):
344 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000345 'import sys;'
346 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000347 stdin=subprocess.PIPE)
348 p.communicate("pear")
349 self.assertEqual(p.returncode, 1)
350
351 def test_communicate_stdout(self):
352 p = subprocess.Popen([sys.executable, "-c",
353 'import sys; sys.stdout.write("pineapple")'],
354 stdout=subprocess.PIPE)
355 (stdout, stderr) = p.communicate()
356 self.assertEqual(stdout, "pineapple")
357 self.assertEqual(stderr, None)
358
359 def test_communicate_stderr(self):
360 p = subprocess.Popen([sys.executable, "-c",
361 'import sys; sys.stderr.write("pineapple")'],
362 stderr=subprocess.PIPE)
363 (stdout, stderr) = p.communicate()
364 self.assertEqual(stdout, None)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000365 self.assertStderrEqual(stderr, "pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000366
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000367 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000368 p = subprocess.Popen([sys.executable, "-c",
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000369 'import sys,os;'
370 'sys.stderr.write("pineapple");'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000371 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000372 stdin=subprocess.PIPE,
373 stdout=subprocess.PIPE,
374 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000375 self.addCleanup(p.stdout.close)
376 self.addCleanup(p.stderr.close)
377 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000378 (stdout, stderr) = p.communicate("banana")
379 self.assertEqual(stdout, "banana")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000380 self.assertStderrEqual(stderr, "pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000381
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000382 # This test is Linux specific for simplicity to at least have
383 # some coverage. It is not a platform specific bug.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000384 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
385 "Linux specific")
386 # Test for the fd leak reported in http://bugs.python.org/issue2791.
387 def test_communicate_pipe_fd_leak(self):
388 fd_directory = '/proc/%d/fd' % os.getpid()
389 num_fds_before_popen = len(os.listdir(fd_directory))
390 p = subprocess.Popen([sys.executable, "-c", "print()"],
391 stdout=subprocess.PIPE)
392 p.communicate()
393 num_fds_after_communicate = len(os.listdir(fd_directory))
394 del p
395 num_fds_after_destruction = len(os.listdir(fd_directory))
396 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
397 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000398
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000399 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000400 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000401 p = subprocess.Popen([sys.executable, "-c",
402 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000403 (stdout, stderr) = p.communicate()
404 self.assertEqual(stdout, None)
405 self.assertEqual(stderr, None)
406
407 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000408 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000409 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000410 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000411 x, y = os.pipe()
412 if mswindows:
413 pipe_buf = 512
414 else:
415 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
416 os.close(x)
417 os.close(y)
418 p = subprocess.Popen([sys.executable, "-c",
Tim Peterse718f612004-10-12 21:51:32 +0000419 'import sys,os;'
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000420 'sys.stdout.write(sys.stdin.read(47));'
421 'sys.stderr.write("xyz"*%d);'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000422 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
Tim Peters3b01a702004-10-12 22:19:32 +0000423 stdin=subprocess.PIPE,
424 stdout=subprocess.PIPE,
425 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000426 self.addCleanup(p.stdout.close)
427 self.addCleanup(p.stderr.close)
428 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000429 string_to_write = "abc"*pipe_buf
430 (stdout, stderr) = p.communicate(string_to_write)
431 self.assertEqual(stdout, string_to_write)
432
433 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000434 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000436 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000437 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000438 stdin=subprocess.PIPE,
439 stdout=subprocess.PIPE,
440 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000441 self.addCleanup(p.stdout.close)
442 self.addCleanup(p.stderr.close)
443 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 p.stdin.write("banana")
445 (stdout, stderr) = p.communicate("split")
446 self.assertEqual(stdout, "bananasplit")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000447 self.assertStderrEqual(stderr, "")
Tim Peterse718f612004-10-12 21:51:32 +0000448
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000450 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000451 'import sys,os;' + SETBINARY +
452 'sys.stdout.write("line1\\n");'
453 'sys.stdout.flush();'
454 'sys.stdout.write("line2\\r");'
455 'sys.stdout.flush();'
456 'sys.stdout.write("line3\\r\\n");'
457 'sys.stdout.flush();'
458 'sys.stdout.write("line4\\r");'
459 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000460 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000461 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000462 'sys.stdout.write("\\nline6");'],
463 stdout=subprocess.PIPE,
464 universal_newlines=1)
Brian Curtind117b562010-11-05 04:09:09 +0000465 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466 stdout = p.stdout.read()
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000467 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000469 self.assertEqual(stdout,
470 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471 else:
472 # Interpreter without universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000473 self.assertEqual(stdout,
474 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000475
476 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000477 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000479 'import sys,os;' + SETBINARY +
480 'sys.stdout.write("line1\\n");'
481 'sys.stdout.flush();'
482 'sys.stdout.write("line2\\r");'
483 'sys.stdout.flush();'
484 'sys.stdout.write("line3\\r\\n");'
485 'sys.stdout.flush();'
486 'sys.stdout.write("line4\\r");'
487 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000489 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490 'sys.stdout.write("\\nline6");'],
491 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
492 universal_newlines=1)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000493 self.addCleanup(p.stdout.close)
494 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495 (stdout, stderr) = p.communicate()
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000496 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000497 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000498 self.assertEqual(stdout,
499 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500 else:
501 # Interpreter without universal newline support
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000502 self.assertEqual(stdout,
503 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504
505 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000506 # Make sure we leak no resources
Antoine Pitroub0b3bff2010-09-18 22:42:30 +0000507 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000508 max_handles = 1026 # too much for most UNIX systems
509 else:
Antoine Pitroub0b3bff2010-09-18 22:42:30 +0000510 max_handles = 2050 # too much for (at least some) Windows setups
511 handles = []
512 try:
513 for i in range(max_handles):
514 try:
515 handles.append(os.open(test_support.TESTFN,
516 os.O_WRONLY | os.O_CREAT))
517 except OSError as e:
518 if e.errno != errno.EMFILE:
519 raise
520 break
521 else:
522 self.skipTest("failed to reach the file descriptor limit "
523 "(tried %d)" % max_handles)
524 # Close a couple of them (should be enough for a subprocess)
525 for i in range(10):
526 os.close(handles.pop())
527 # Loop creating some subprocesses. If one of them leaks some fds,
528 # the next loop iteration will fail by reaching the max fd limit.
529 for i in range(15):
530 p = subprocess.Popen([sys.executable, "-c",
531 "import sys;"
532 "sys.stdout.write(sys.stdin.read())"],
533 stdin=subprocess.PIPE,
534 stdout=subprocess.PIPE,
535 stderr=subprocess.PIPE)
536 data = p.communicate(b"lime")[0]
537 self.assertEqual(data, b"lime")
538 finally:
539 for h in handles:
540 os.close(h)
Mark Dickinson313dc9b2012-10-07 15:41:38 +0100541 test_support.unlink(test_support.TESTFN)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542
543 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000544 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
545 '"a b c" d e')
546 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
547 'ab\\"c \\ d')
Gregory P. Smithe047e6d2008-01-19 20:49:02 +0000548 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
549 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000550 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
551 'a\\\\\\b "de fg" h')
552 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
553 'a\\\\\\"b c d')
554 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
555 '"a\\\\b c" d e')
556 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
557 '"a\\\\b\\ c" d e')
Peter Astrand10514a72007-01-13 22:35:35 +0000558 self.assertEqual(subprocess.list2cmdline(['ab', '']),
559 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000560
561
562 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000564 "-c", "import time; time.sleep(1)"])
565 count = 0
566 while p.poll() is None:
567 time.sleep(0.1)
568 count += 1
569 # We expect that the poll loop probably went around about 10 times,
570 # but, based on system scheduling we can't control, it's possible
571 # poll() never returned None. It "should be" very rare that it
572 # didn't go around at least twice.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000573 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000574 # Subsequent invocations should just return the returncode
575 self.assertEqual(p.poll(), 0)
576
577
578 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000579 p = subprocess.Popen([sys.executable,
580 "-c", "import time; time.sleep(2)"])
581 self.assertEqual(p.wait(), 0)
582 # Subsequent invocations should just return the returncode
583 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000584
Peter Astrand738131d2004-11-30 21:04:45 +0000585
586 def test_invalid_bufsize(self):
587 # an invalid type of the bufsize argument should raise
588 # TypeError.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000589 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000590 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000591
Georg Brandlf3715d22009-02-14 17:01:36 +0000592 def test_leaking_fds_on_error(self):
593 # see bug #5179: Popen leaks file descriptors to PIPEs if
594 # the child fails to execute; this will eventually exhaust
595 # the maximum number of open fds. 1024 seems a very common
596 # value for that limit, but Windows has 2048, so we loop
597 # 1024 times (each call leaked two fds).
598 for i in range(1024):
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000599 # Windows raises IOError. Others raise OSError.
600 with self.assertRaises(EnvironmentError) as c:
Georg Brandlf3715d22009-02-14 17:01:36 +0000601 subprocess.Popen(['nonexisting_i_hope'],
602 stdout=subprocess.PIPE,
603 stderr=subprocess.PIPE)
R David Murraycdd5fc92011-03-13 22:37:18 -0400604 # ignore errors that indicate the command was not found
605 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000606 raise c.exception
Georg Brandlf3715d22009-02-14 17:01:36 +0000607
Tim Golden90374f52010-08-06 13:14:33 +0000608 def test_handles_closed_on_exception(self):
609 # If CreateProcess exits with an error, ensure the
610 # duplicate output handles are released
611 ifhandle, ifname = mkstemp()
612 ofhandle, ofname = mkstemp()
613 efhandle, efname = mkstemp()
614 try:
615 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
616 stderr=efhandle)
617 except OSError:
618 os.close(ifhandle)
619 os.remove(ifname)
620 os.close(ofhandle)
621 os.remove(ofname)
622 os.close(efhandle)
623 os.remove(efname)
624 self.assertFalse(os.path.exists(ifname))
625 self.assertFalse(os.path.exists(ofname))
626 self.assertFalse(os.path.exists(efname))
627
Ross Lagerwall104c3f12011-04-05 15:24:34 +0200628 def test_communicate_epipe(self):
629 # Issue 10963: communicate() should hide EPIPE
630 p = subprocess.Popen([sys.executable, "-c", 'pass'],
631 stdin=subprocess.PIPE,
632 stdout=subprocess.PIPE,
633 stderr=subprocess.PIPE)
634 self.addCleanup(p.stdout.close)
635 self.addCleanup(p.stderr.close)
636 self.addCleanup(p.stdin.close)
637 p.communicate("x" * 2**20)
638
639 def test_communicate_epipe_only_stdin(self):
640 # Issue 10963: communicate() should hide EPIPE
641 p = subprocess.Popen([sys.executable, "-c", 'pass'],
642 stdin=subprocess.PIPE)
643 self.addCleanup(p.stdin.close)
644 time.sleep(2)
645 p.communicate("x" * 2**20)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000646
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -0800647 # This test is Linux-ish specific for simplicity to at least have
648 # some coverage. It is not a platform specific bug.
649 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
650 "Linux specific")
651 def test_failed_child_execute_fd_leak(self):
652 """Test for the fork() failure fd leak reported in issue16327."""
653 fd_directory = '/proc/%d/fd' % os.getpid()
654 fds_before_popen = os.listdir(fd_directory)
655 with self.assertRaises(PopenTestException):
656 PopenExecuteChildRaises(
657 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
658 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
659
660 # NOTE: This test doesn't verify that the real _execute_child
661 # does not close the file descriptors itself on the way out
662 # during an exception. Code inspection has confirmed that.
663
664 fds_after_exception = os.listdir(fd_directory)
665 self.assertEqual(fds_before_popen, fds_after_exception)
666
667
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000668# context manager
669class _SuppressCoreFiles(object):
670 """Try to prevent core files from being created."""
671 old_limit = None
672
673 def __enter__(self):
674 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson8b59c232011-12-10 12:31:42 -0500675 if resource is not None:
676 try:
677 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
678 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
679 except (ValueError, resource.error):
680 pass
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000681
Ronald Oussoren21b44e02010-07-23 12:26:30 +0000682 if sys.platform == 'darwin':
683 # Check if the 'Crash Reporter' on OSX was configured
684 # in 'Developer' mode and warn that it will get triggered
685 # when it is.
686 #
687 # This assumes that this context manager is used in tests
688 # that might trigger the next manager.
689 value = subprocess.Popen(['/usr/bin/defaults', 'read',
690 'com.apple.CrashReporter', 'DialogType'],
691 stdout=subprocess.PIPE).communicate()[0]
692 if value.strip() == b'developer':
693 print "this tests triggers the Crash Reporter, that is intentional"
694 sys.stdout.flush()
695
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000696 def __exit__(self, *args):
697 """Return core file behavior to default."""
698 if self.old_limit is None:
699 return
Benjamin Peterson8b59c232011-12-10 12:31:42 -0500700 if resource is not None:
701 try:
702 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
703 except (ValueError, resource.error):
704 pass
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000705
Victor Stinnerb78fed92011-07-05 14:50:35 +0200706 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
707 "Requires signal.SIGALRM")
Victor Stinnere7901312011-07-05 14:08:01 +0200708 def test_communicate_eintr(self):
709 # Issue #12493: communicate() should handle EINTR
710 def handler(signum, frame):
711 pass
712 old_handler = signal.signal(signal.SIGALRM, handler)
713 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
714
715 # the process is running for 2 seconds
716 args = [sys.executable, "-c", 'import time; time.sleep(2)']
717 for stream in ('stdout', 'stderr'):
718 kw = {stream: subprocess.PIPE}
719 with subprocess.Popen(args, **kw) as process:
720 signal.alarm(1)
721 # communicate() will be interrupted by SIGALRM
722 process.communicate()
723
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000724
Florent Xiclunabab22a72010-03-04 19:40:48 +0000725@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000726class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +0000727
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000728 def test_exceptions(self):
729 # caught & re-raised exceptions
730 with self.assertRaises(OSError) as c:
731 p = subprocess.Popen([sys.executable, "-c", ""],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000732 cwd="/this/path/does/not/exist")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000733 # The attribute child_traceback should contain "os.chdir" somewhere.
734 self.assertIn("os.chdir", c.exception.child_traceback)
Tim Peterse718f612004-10-12 21:51:32 +0000735
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000736 def test_run_abort(self):
737 # returncode handles signal termination
738 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000739 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000740 "import os; os.abort()"])
741 p.wait()
742 self.assertEqual(-p.returncode, signal.SIGABRT)
743
744 def test_preexec(self):
745 # preexec function
746 p = subprocess.Popen([sys.executable, "-c",
747 "import sys, os;"
748 "sys.stdout.write(os.getenv('FRUIT'))"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000749 stdout=subprocess.PIPE,
750 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtind117b562010-11-05 04:09:09 +0000751 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000752 self.assertEqual(p.stdout.read(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000753
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800754 class _TestExecuteChildPopen(subprocess.Popen):
755 """Used to test behavior at the end of _execute_child."""
756 def __init__(self, testcase, *args, **kwargs):
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800757 self._testcase = testcase
758 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith211248b2012-11-11 02:00:49 -0800759
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800760 def _execute_child(
761 self, args, executable, preexec_fn, close_fds, cwd, env,
Gregory P. Smith211248b2012-11-11 02:00:49 -0800762 universal_newlines, startupinfo, creationflags, shell,
763 p2cread, p2cwrite,
764 c2pread, c2pwrite,
765 errread, errwrite):
766 try:
767 subprocess.Popen._execute_child(
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800768 self, args, executable, preexec_fn, close_fds,
Gregory P. Smith211248b2012-11-11 02:00:49 -0800769 cwd, env, universal_newlines,
770 startupinfo, creationflags, shell,
771 p2cread, p2cwrite,
772 c2pread, c2pwrite,
773 errread, errwrite)
774 finally:
775 # Open a bunch of file descriptors and verify that
776 # none of them are the same as the ones the Popen
777 # instance is using for stdin/stdout/stderr.
778 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
779 for _ in range(8)]
780 try:
781 for fd in devzero_fds:
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800782 self._testcase.assertNotIn(
783 fd, (p2cwrite, c2pread, errread))
Gregory P. Smith211248b2012-11-11 02:00:49 -0800784 finally:
785 map(os.close, devzero_fds)
786
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800787 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
788 def test_preexec_errpipe_does_not_double_close_pipes(self):
789 """Issue16140: Don't double close pipes on preexec error."""
790
791 def raise_it():
792 raise RuntimeError("force the _execute_child() errpipe_data path.")
Gregory P. Smith211248b2012-11-11 02:00:49 -0800793
794 with self.assertRaises(RuntimeError):
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800795 self._TestExecuteChildPopen(
796 self, [sys.executable, "-c", "pass"],
797 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
798 stderr=subprocess.PIPE, preexec_fn=raise_it)
Gregory P. Smith211248b2012-11-11 02:00:49 -0800799
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000800 def test_args_string(self):
801 # args is a string
802 f, fname = mkstemp()
803 os.write(f, "#!/bin/sh\n")
804 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
805 sys.executable)
806 os.close(f)
807 os.chmod(fname, 0o700)
808 p = subprocess.Popen(fname)
809 p.wait()
810 os.remove(fname)
811 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000812
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000813 def test_invalid_args(self):
814 # invalid arguments should raise ValueError
815 self.assertRaises(ValueError, subprocess.call,
816 [sys.executable, "-c",
817 "import sys; sys.exit(47)"],
818 startupinfo=47)
819 self.assertRaises(ValueError, subprocess.call,
820 [sys.executable, "-c",
821 "import sys; sys.exit(47)"],
822 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000823
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000824 def test_shell_sequence(self):
825 # Run command through the shell (sequence)
826 newenv = os.environ.copy()
827 newenv["FRUIT"] = "apple"
828 p = subprocess.Popen(["echo $FRUIT"], shell=1,
829 stdout=subprocess.PIPE,
830 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000831 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000832 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000833
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000834 def test_shell_string(self):
835 # Run command through the shell (string)
836 newenv = os.environ.copy()
837 newenv["FRUIT"] = "apple"
838 p = subprocess.Popen("echo $FRUIT", shell=1,
839 stdout=subprocess.PIPE,
840 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000841 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000842 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000844 def test_call_string(self):
845 # call() function with string argument on UNIX
846 f, fname = mkstemp()
847 os.write(f, "#!/bin/sh\n")
848 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
849 sys.executable)
850 os.close(f)
851 os.chmod(fname, 0700)
852 rc = subprocess.call(fname)
853 os.remove(fname)
854 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000856 def test_specific_shell(self):
857 # Issue #9265: Incorrect name passed as arg[0].
858 shells = []
859 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
860 for name in ['bash', 'ksh']:
861 sh = os.path.join(prefix, name)
862 if os.path.isfile(sh):
863 shells.append(sh)
864 if not shells: # Will probably work for any shell but csh.
865 self.skipTest("bash or ksh required for this test")
866 sh = '/bin/sh'
867 if os.path.isfile(sh) and not os.path.islink(sh):
868 # Test will fail if /bin/sh is a symlink to csh.
869 shells.append(sh)
870 for sh in shells:
871 p = subprocess.Popen("echo $0", executable=sh, shell=True,
872 stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000873 self.addCleanup(p.stdout.close)
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000874 self.assertEqual(p.stdout.read().strip(), sh)
875
Florent Xiclunac0838642010-03-07 15:27:39 +0000876 def _kill_process(self, method, *args):
Florent Xiclunacecef392010-03-05 19:31:21 +0000877 # Do not inherit file handles from the parent.
878 # It should fix failures on some platforms.
Antoine Pitroua6166da2010-09-20 11:20:44 +0000879 p = subprocess.Popen([sys.executable, "-c", """if 1:
880 import sys, time
881 sys.stdout.write('x\\n')
882 sys.stdout.flush()
883 time.sleep(30)
884 """],
885 close_fds=True,
886 stdin=subprocess.PIPE,
887 stdout=subprocess.PIPE,
888 stderr=subprocess.PIPE)
889 # Wait for the interpreter to be completely initialized before
890 # sending any signal.
891 p.stdout.read(1)
892 getattr(p, method)(*args)
Florent Xiclunac0838642010-03-07 15:27:39 +0000893 return p
894
Antoine Pitrouf60845b2012-03-11 19:29:12 +0100895 def _kill_dead_process(self, method, *args):
896 # Do not inherit file handles from the parent.
897 # It should fix failures on some platforms.
898 p = subprocess.Popen([sys.executable, "-c", """if 1:
899 import sys, time
900 sys.stdout.write('x\\n')
901 sys.stdout.flush()
902 """],
903 close_fds=True,
904 stdin=subprocess.PIPE,
905 stdout=subprocess.PIPE,
906 stderr=subprocess.PIPE)
907 # Wait for the interpreter to be completely initialized before
908 # sending any signal.
909 p.stdout.read(1)
910 # The process should end after this
911 time.sleep(1)
912 # This shouldn't raise even though the child is now dead
913 getattr(p, method)(*args)
914 p.communicate()
915
Florent Xiclunac0838642010-03-07 15:27:39 +0000916 def test_send_signal(self):
917 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000918 _, stderr = p.communicate()
Florent Xicluna3c919cf2010-03-23 19:19:16 +0000919 self.assertIn('KeyboardInterrupt', stderr)
Florent Xicluna446ff142010-03-23 15:05:30 +0000920 self.assertNotEqual(p.wait(), 0)
Christian Heimese74c8f22008-04-19 02:23:57 +0000921
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000922 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000923 p = self._kill_process('kill')
Florent Xicluna446ff142010-03-23 15:05:30 +0000924 _, stderr = p.communicate()
925 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000926 self.assertEqual(p.wait(), -signal.SIGKILL)
Christian Heimese74c8f22008-04-19 02:23:57 +0000927
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000928 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000929 p = self._kill_process('terminate')
Florent Xicluna446ff142010-03-23 15:05:30 +0000930 _, stderr = p.communicate()
931 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000932 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000933
Antoine Pitrouf60845b2012-03-11 19:29:12 +0100934 def test_send_signal_dead(self):
935 # Sending a signal to a dead process
936 self._kill_dead_process('send_signal', signal.SIGINT)
937
938 def test_kill_dead(self):
939 # Killing a dead process
940 self._kill_dead_process('kill')
941
942 def test_terminate_dead(self):
943 # Terminating a dead process
944 self._kill_dead_process('terminate')
945
Antoine Pitrou91ce0d92011-01-03 18:45:09 +0000946 def check_close_std_fds(self, fds):
947 # Issue #9905: test that subprocess pipes still work properly with
948 # some standard fds closed
949 stdin = 0
950 newfds = []
951 for a in fds:
952 b = os.dup(a)
953 newfds.append(b)
954 if a == 0:
955 stdin = b
956 try:
957 for fd in fds:
958 os.close(fd)
959 out, err = subprocess.Popen([sys.executable, "-c",
960 'import sys;'
961 'sys.stdout.write("apple");'
962 'sys.stdout.flush();'
963 'sys.stderr.write("orange")'],
964 stdin=stdin,
965 stdout=subprocess.PIPE,
966 stderr=subprocess.PIPE).communicate()
967 err = test_support.strip_python_stderr(err)
968 self.assertEqual((out, err), (b'apple', b'orange'))
969 finally:
970 for b, a in zip(newfds, fds):
971 os.dup2(b, a)
972 for b in newfds:
973 os.close(b)
974
975 def test_close_fd_0(self):
976 self.check_close_std_fds([0])
977
978 def test_close_fd_1(self):
979 self.check_close_std_fds([1])
980
981 def test_close_fd_2(self):
982 self.check_close_std_fds([2])
983
984 def test_close_fds_0_1(self):
985 self.check_close_std_fds([0, 1])
986
987 def test_close_fds_0_2(self):
988 self.check_close_std_fds([0, 2])
989
990 def test_close_fds_1_2(self):
991 self.check_close_std_fds([1, 2])
992
993 def test_close_fds_0_1_2(self):
994 # Issue #10806: test that subprocess pipes still work properly with
995 # all standard fds closed.
996 self.check_close_std_fds([0, 1, 2])
997
Ross Lagerwalld8e39012011-07-27 18:54:53 +0200998 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
999 # open up some temporary files
1000 temps = [mkstemp() for i in range(3)]
1001 temp_fds = [fd for fd, fname in temps]
1002 try:
1003 # unlink the files -- we won't need to reopen them
1004 for fd, fname in temps:
1005 os.unlink(fname)
1006
1007 # save a copy of the standard file descriptors
1008 saved_fds = [os.dup(fd) for fd in range(3)]
1009 try:
1010 # duplicate the temp files over the standard fd's 0, 1, 2
1011 for fd, temp_fd in enumerate(temp_fds):
1012 os.dup2(temp_fd, fd)
1013
1014 # write some data to what will become stdin, and rewind
1015 os.write(stdin_no, b"STDIN")
1016 os.lseek(stdin_no, 0, 0)
1017
1018 # now use those files in the given order, so that subprocess
1019 # has to rearrange them in the child
1020 p = subprocess.Popen([sys.executable, "-c",
1021 'import sys; got = sys.stdin.read();'
1022 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1023 stdin=stdin_no,
1024 stdout=stdout_no,
1025 stderr=stderr_no)
1026 p.wait()
1027
1028 for fd in temp_fds:
1029 os.lseek(fd, 0, 0)
1030
1031 out = os.read(stdout_no, 1024)
1032 err = test_support.strip_python_stderr(os.read(stderr_no, 1024))
1033 finally:
1034 for std, saved in enumerate(saved_fds):
1035 os.dup2(saved, std)
1036 os.close(saved)
1037
1038 self.assertEqual(out, b"got STDIN")
1039 self.assertEqual(err, b"err")
1040
1041 finally:
1042 for fd in temp_fds:
1043 os.close(fd)
1044
1045 # When duping fds, if there arises a situation where one of the fds is
1046 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1047 # This tests all combinations of this.
1048 def test_swap_fds(self):
1049 self.check_swap_fds(0, 1, 2)
1050 self.check_swap_fds(0, 2, 1)
1051 self.check_swap_fds(1, 0, 2)
1052 self.check_swap_fds(1, 2, 0)
1053 self.check_swap_fds(2, 0, 1)
1054 self.check_swap_fds(2, 1, 0)
1055
Gregory P. Smith312efbc2010-12-14 15:02:53 +00001056 def test_wait_when_sigchild_ignored(self):
1057 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1058 sigchild_ignore = test_support.findfile("sigchild_ignore.py",
1059 subdir="subprocessdata")
1060 p = subprocess.Popen([sys.executable, sigchild_ignore],
1061 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1062 stdout, stderr = p.communicate()
1063 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
1064 " non-zero with this error:\n%s" % stderr)
1065
Charles-François Natali100df0f2011-08-18 17:56:02 +02001066 def test_zombie_fast_process_del(self):
1067 # Issue #12650: on Unix, if Popen.__del__() was called before the
1068 # process exited, it wouldn't be added to subprocess._active, and would
1069 # remain a zombie.
1070 # spawn a Popen, and delete its reference before it exits
1071 p = subprocess.Popen([sys.executable, "-c",
1072 'import sys, time;'
1073 'time.sleep(0.2)'],
1074 stdout=subprocess.PIPE,
1075 stderr=subprocess.PIPE)
Nadeem Vawda86059362011-08-19 05:22:24 +02001076 self.addCleanup(p.stdout.close)
1077 self.addCleanup(p.stderr.close)
Charles-François Natali100df0f2011-08-18 17:56:02 +02001078 ident = id(p)
1079 pid = p.pid
1080 del p
1081 # check that p is in the active processes list
1082 self.assertIn(ident, [id(o) for o in subprocess._active])
1083
Charles-François Natali100df0f2011-08-18 17:56:02 +02001084 def test_leak_fast_process_del_killed(self):
1085 # Issue #12650: on Unix, if Popen.__del__() was called before the
1086 # process exited, and the process got killed by a signal, it would never
1087 # be removed from subprocess._active, which triggered a FD and memory
1088 # leak.
1089 # spawn a Popen, delete its reference and kill it
1090 p = subprocess.Popen([sys.executable, "-c",
1091 'import time;'
1092 'time.sleep(3)'],
1093 stdout=subprocess.PIPE,
1094 stderr=subprocess.PIPE)
Nadeem Vawda86059362011-08-19 05:22:24 +02001095 self.addCleanup(p.stdout.close)
1096 self.addCleanup(p.stderr.close)
Charles-François Natali100df0f2011-08-18 17:56:02 +02001097 ident = id(p)
1098 pid = p.pid
1099 del p
1100 os.kill(pid, signal.SIGKILL)
1101 # check that p is in the active processes list
1102 self.assertIn(ident, [id(o) for o in subprocess._active])
1103
1104 # let some time for the process to exit, and create a new Popen: this
1105 # should trigger the wait() of p
1106 time.sleep(0.2)
1107 with self.assertRaises(EnvironmentError) as c:
1108 with subprocess.Popen(['nonexisting_i_hope'],
1109 stdout=subprocess.PIPE,
1110 stderr=subprocess.PIPE) as proc:
1111 pass
1112 # p should have been wait()ed on, and removed from the _active list
1113 self.assertRaises(OSError, os.waitpid, pid, 0)
1114 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1115
Charles-François Natali2a34eb32011-08-25 21:20:54 +02001116 def test_pipe_cloexec(self):
1117 # Issue 12786: check that the communication pipes' FDs are set CLOEXEC,
1118 # and are not inherited by another child process.
1119 p1 = subprocess.Popen([sys.executable, "-c",
1120 'import os;'
1121 'os.read(0, 1)'
1122 ],
1123 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1124 stderr=subprocess.PIPE)
1125
1126 p2 = subprocess.Popen([sys.executable, "-c", """if True:
1127 import os, errno, sys
1128 for fd in %r:
1129 try:
1130 os.close(fd)
1131 except OSError as e:
1132 if e.errno != errno.EBADF:
1133 raise
1134 else:
1135 sys.exit(1)
1136 sys.exit(0)
1137 """ % [f.fileno() for f in (p1.stdin, p1.stdout,
1138 p1.stderr)]
1139 ],
1140 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1141 stderr=subprocess.PIPE, close_fds=False)
1142 p1.communicate('foo')
1143 _, stderr = p2.communicate()
1144
1145 self.assertEqual(p2.returncode, 0, "Unexpected error: " + repr(stderr))
1146
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001147
Florent Xiclunabab22a72010-03-04 19:40:48 +00001148@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +00001149class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +00001150
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001151 def test_startupinfo(self):
1152 # startupinfo argument
1153 # We uses hardcoded constants, because we do not want to
1154 # depend on win32all.
1155 STARTF_USESHOWWINDOW = 1
1156 SW_MAXIMIZE = 3
1157 startupinfo = subprocess.STARTUPINFO()
1158 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1159 startupinfo.wShowWindow = SW_MAXIMIZE
1160 # Since Python is a console process, it won't be affected
1161 # by wShowWindow, but the argument should be silently
1162 # ignored
1163 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001164 startupinfo=startupinfo)
1165
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001166 def test_creationflags(self):
1167 # creationflags argument
1168 CREATE_NEW_CONSOLE = 16
1169 sys.stderr.write(" a DOS box should flash briefly ...\n")
1170 subprocess.call(sys.executable +
1171 ' -c "import time; time.sleep(0.25)"',
1172 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001173
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001174 def test_invalid_args(self):
1175 # invalid arguments should raise ValueError
1176 self.assertRaises(ValueError, subprocess.call,
1177 [sys.executable, "-c",
1178 "import sys; sys.exit(47)"],
1179 preexec_fn=lambda: 1)
1180 self.assertRaises(ValueError, subprocess.call,
1181 [sys.executable, "-c",
1182 "import sys; sys.exit(47)"],
1183 stdout=subprocess.PIPE,
1184 close_fds=True)
1185
1186 def test_close_fds(self):
1187 # close file descriptors
1188 rc = subprocess.call([sys.executable, "-c",
1189 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001190 close_fds=True)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001191 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001192
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001193 def test_shell_sequence(self):
1194 # Run command through the shell (sequence)
1195 newenv = os.environ.copy()
1196 newenv["FRUIT"] = "physalis"
1197 p = subprocess.Popen(["set"], shell=1,
1198 stdout=subprocess.PIPE,
1199 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001200 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001201 self.assertIn("physalis", p.stdout.read())
Peter Astrand81a191b2007-05-26 22:18:20 +00001202
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001203 def test_shell_string(self):
1204 # Run command through the shell (string)
1205 newenv = os.environ.copy()
1206 newenv["FRUIT"] = "physalis"
1207 p = subprocess.Popen("set", shell=1,
1208 stdout=subprocess.PIPE,
1209 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001210 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001211 self.assertIn("physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001212
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001213 def test_call_string(self):
1214 # call() function with string argument on Windows
1215 rc = subprocess.call(sys.executable +
1216 ' -c "import sys; sys.exit(47)"')
1217 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001218
Florent Xiclunac0838642010-03-07 15:27:39 +00001219 def _kill_process(self, method, *args):
Florent Xicluna400efc22010-03-07 17:12:23 +00001220 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroudee00972010-09-24 19:00:29 +00001221 p = subprocess.Popen([sys.executable, "-c", """if 1:
1222 import sys, time
1223 sys.stdout.write('x\\n')
1224 sys.stdout.flush()
1225 time.sleep(30)
1226 """],
1227 stdin=subprocess.PIPE,
1228 stdout=subprocess.PIPE,
1229 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001230 self.addCleanup(p.stdout.close)
1231 self.addCleanup(p.stderr.close)
1232 self.addCleanup(p.stdin.close)
Antoine Pitroudee00972010-09-24 19:00:29 +00001233 # Wait for the interpreter to be completely initialized before
1234 # sending any signal.
1235 p.stdout.read(1)
1236 getattr(p, method)(*args)
Florent Xicluna446ff142010-03-23 15:05:30 +00001237 _, stderr = p.communicate()
1238 self.assertStderrEqual(stderr, '')
Antoine Pitroudee00972010-09-24 19:00:29 +00001239 returncode = p.wait()
Florent Xiclunafaf17532010-03-08 10:59:33 +00001240 self.assertNotEqual(returncode, 0)
Florent Xiclunac0838642010-03-07 15:27:39 +00001241
Antoine Pitrouf60845b2012-03-11 19:29:12 +01001242 def _kill_dead_process(self, method, *args):
1243 p = subprocess.Popen([sys.executable, "-c", """if 1:
1244 import sys, time
1245 sys.stdout.write('x\\n')
1246 sys.stdout.flush()
1247 sys.exit(42)
1248 """],
1249 stdin=subprocess.PIPE,
1250 stdout=subprocess.PIPE,
1251 stderr=subprocess.PIPE)
1252 self.addCleanup(p.stdout.close)
1253 self.addCleanup(p.stderr.close)
1254 self.addCleanup(p.stdin.close)
1255 # Wait for the interpreter to be completely initialized before
1256 # sending any signal.
1257 p.stdout.read(1)
1258 # The process should end after this
1259 time.sleep(1)
1260 # This shouldn't raise even though the child is now dead
1261 getattr(p, method)(*args)
1262 _, stderr = p.communicate()
1263 self.assertStderrEqual(stderr, b'')
1264 rc = p.wait()
1265 self.assertEqual(rc, 42)
1266
Florent Xiclunac0838642010-03-07 15:27:39 +00001267 def test_send_signal(self):
1268 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimese74c8f22008-04-19 02:23:57 +00001269
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001270 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001271 self._kill_process('kill')
Christian Heimese74c8f22008-04-19 02:23:57 +00001272
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001273 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001274 self._kill_process('terminate')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001275
Antoine Pitrouf60845b2012-03-11 19:29:12 +01001276 def test_send_signal_dead(self):
1277 self._kill_dead_process('send_signal', signal.SIGTERM)
1278
1279 def test_kill_dead(self):
1280 self._kill_dead_process('kill')
1281
1282 def test_terminate_dead(self):
1283 self._kill_dead_process('terminate')
1284
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001285
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001286@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1287 "poll system call not supported")
1288class ProcessTestCaseNoPoll(ProcessTestCase):
1289 def setUp(self):
1290 subprocess._has_poll = False
1291 ProcessTestCase.setUp(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001292
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001293 def tearDown(self):
1294 subprocess._has_poll = True
1295 ProcessTestCase.tearDown(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001296
1297
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001298class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithc1baf4a2010-03-01 02:53:24 +00001299 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001300 def test_eintr_retry_call(self):
1301 record_calls = []
1302 def fake_os_func(*args):
1303 record_calls.append(args)
1304 if len(record_calls) == 2:
1305 raise OSError(errno.EINTR, "fake interrupted system call")
1306 return tuple(reversed(args))
1307
1308 self.assertEqual((999, 256),
1309 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1310 self.assertEqual([(256, 999)], record_calls)
1311 # This time there will be an EINTR so it will loop once.
1312 self.assertEqual((666,),
1313 subprocess._eintr_retry_call(fake_os_func, 666))
1314 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1315
Tim Golden8e4756c2010-08-12 11:00:35 +00001316@unittest.skipUnless(mswindows, "mswindows only")
1317class CommandsWithSpaces (BaseTestCase):
1318
1319 def setUp(self):
1320 super(CommandsWithSpaces, self).setUp()
1321 f, fname = mkstemp(".py", "te st")
1322 self.fname = fname.lower ()
1323 os.write(f, b"import sys;"
1324 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1325 )
1326 os.close(f)
1327
1328 def tearDown(self):
1329 os.remove(self.fname)
1330 super(CommandsWithSpaces, self).tearDown()
1331
1332 def with_spaces(self, *args, **kwargs):
1333 kwargs['stdout'] = subprocess.PIPE
1334 p = subprocess.Popen(*args, **kwargs)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001335 self.addCleanup(p.stdout.close)
Tim Golden8e4756c2010-08-12 11:00:35 +00001336 self.assertEqual(
1337 p.stdout.read ().decode("mbcs"),
1338 "2 [%r, 'ab cd']" % self.fname
1339 )
1340
1341 def test_shell_string_with_spaces(self):
1342 # call() function with string argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +00001343 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1344 "ab cd"), shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +00001345
1346 def test_shell_sequence_with_spaces(self):
1347 # call() function with sequence argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +00001348 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +00001349
1350 def test_noshell_string_with_spaces(self):
1351 # call() function with string argument with spaces on Windows
1352 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1353 "ab cd"))
1354
1355 def test_noshell_sequence_with_spaces(self):
1356 # call() function with sequence argument with spaces on Windows
1357 self.with_spaces([sys.executable, self.fname, "ab cd"])
1358
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001359def test_main():
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001360 unit_tests = (ProcessTestCase,
1361 POSIXProcessTestCase,
1362 Win32ProcessTestCase,
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001363 ProcessTestCaseNoPoll,
Tim Golden8e4756c2010-08-12 11:00:35 +00001364 HelperFunctionTests,
1365 CommandsWithSpaces)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001366
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001367 test_support.run_unittest(*unit_tests)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001368 test_support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001369
1370if __name__ == "__main__":
1371 test_main()