blob: f713fc60659b4ab30bff11402c4e2db88d47cfc4 [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):
757 # Do nothing so we can modify the instance for testing.
758 self._testcase = testcase
759 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith211248b2012-11-11 02:00:49 -0800760
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800761 def _execute_child(
762 self, args, executable, preexec_fn, close_fds, cwd, env,
Gregory P. Smith211248b2012-11-11 02:00:49 -0800763 universal_newlines, startupinfo, creationflags, shell,
764 p2cread, p2cwrite,
765 c2pread, c2pwrite,
766 errread, errwrite):
767 try:
768 subprocess.Popen._execute_child(
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800769 self, args, executable, preexec_fn, close_fds,
Gregory P. Smith211248b2012-11-11 02:00:49 -0800770 cwd, env, universal_newlines,
771 startupinfo, creationflags, shell,
772 p2cread, p2cwrite,
773 c2pread, c2pwrite,
774 errread, errwrite)
775 finally:
776 # Open a bunch of file descriptors and verify that
777 # none of them are the same as the ones the Popen
778 # instance is using for stdin/stdout/stderr.
779 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
780 for _ in range(8)]
781 try:
782 for fd in devzero_fds:
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800783 self._testcase.assertNotIn(
784 fd, (p2cwrite, c2pread, errread))
Gregory P. Smith211248b2012-11-11 02:00:49 -0800785 finally:
786 map(os.close, devzero_fds)
787
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800788 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
789 def test_preexec_errpipe_does_not_double_close_pipes(self):
790 """Issue16140: Don't double close pipes on preexec error."""
791
792 def raise_it():
793 raise RuntimeError("force the _execute_child() errpipe_data path.")
Gregory P. Smith211248b2012-11-11 02:00:49 -0800794
795 with self.assertRaises(RuntimeError):
Gregory P. Smithf047ba82012-11-11 09:49:02 -0800796 self._TestExecuteChildPopen(
797 self, [sys.executable, "-c", "pass"],
798 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
799 stderr=subprocess.PIPE, preexec_fn=raise_it)
Gregory P. Smith211248b2012-11-11 02:00:49 -0800800
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000801 def test_args_string(self):
802 # args is a string
803 f, fname = mkstemp()
804 os.write(f, "#!/bin/sh\n")
805 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
806 sys.executable)
807 os.close(f)
808 os.chmod(fname, 0o700)
809 p = subprocess.Popen(fname)
810 p.wait()
811 os.remove(fname)
812 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000813
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000814 def test_invalid_args(self):
815 # invalid arguments should raise ValueError
816 self.assertRaises(ValueError, subprocess.call,
817 [sys.executable, "-c",
818 "import sys; sys.exit(47)"],
819 startupinfo=47)
820 self.assertRaises(ValueError, subprocess.call,
821 [sys.executable, "-c",
822 "import sys; sys.exit(47)"],
823 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000824
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000825 def test_shell_sequence(self):
826 # Run command through the shell (sequence)
827 newenv = os.environ.copy()
828 newenv["FRUIT"] = "apple"
829 p = subprocess.Popen(["echo $FRUIT"], shell=1,
830 stdout=subprocess.PIPE,
831 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000832 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000833 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000834
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000835 def test_shell_string(self):
836 # Run command through the shell (string)
837 newenv = os.environ.copy()
838 newenv["FRUIT"] = "apple"
839 p = subprocess.Popen("echo $FRUIT", shell=1,
840 stdout=subprocess.PIPE,
841 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000842 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000843 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000844
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000845 def test_call_string(self):
846 # call() function with string argument on UNIX
847 f, fname = mkstemp()
848 os.write(f, "#!/bin/sh\n")
849 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
850 sys.executable)
851 os.close(f)
852 os.chmod(fname, 0700)
853 rc = subprocess.call(fname)
854 os.remove(fname)
855 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000856
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000857 def test_specific_shell(self):
858 # Issue #9265: Incorrect name passed as arg[0].
859 shells = []
860 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
861 for name in ['bash', 'ksh']:
862 sh = os.path.join(prefix, name)
863 if os.path.isfile(sh):
864 shells.append(sh)
865 if not shells: # Will probably work for any shell but csh.
866 self.skipTest("bash or ksh required for this test")
867 sh = '/bin/sh'
868 if os.path.isfile(sh) and not os.path.islink(sh):
869 # Test will fail if /bin/sh is a symlink to csh.
870 shells.append(sh)
871 for sh in shells:
872 p = subprocess.Popen("echo $0", executable=sh, shell=True,
873 stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000874 self.addCleanup(p.stdout.close)
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000875 self.assertEqual(p.stdout.read().strip(), sh)
876
Florent Xiclunac0838642010-03-07 15:27:39 +0000877 def _kill_process(self, method, *args):
Florent Xiclunacecef392010-03-05 19:31:21 +0000878 # Do not inherit file handles from the parent.
879 # It should fix failures on some platforms.
Antoine Pitroua6166da2010-09-20 11:20:44 +0000880 p = subprocess.Popen([sys.executable, "-c", """if 1:
881 import sys, time
882 sys.stdout.write('x\\n')
883 sys.stdout.flush()
884 time.sleep(30)
885 """],
886 close_fds=True,
887 stdin=subprocess.PIPE,
888 stdout=subprocess.PIPE,
889 stderr=subprocess.PIPE)
890 # Wait for the interpreter to be completely initialized before
891 # sending any signal.
892 p.stdout.read(1)
893 getattr(p, method)(*args)
Florent Xiclunac0838642010-03-07 15:27:39 +0000894 return p
895
Antoine Pitrouf60845b2012-03-11 19:29:12 +0100896 def _kill_dead_process(self, method, *args):
897 # Do not inherit file handles from the parent.
898 # It should fix failures on some platforms.
899 p = subprocess.Popen([sys.executable, "-c", """if 1:
900 import sys, time
901 sys.stdout.write('x\\n')
902 sys.stdout.flush()
903 """],
904 close_fds=True,
905 stdin=subprocess.PIPE,
906 stdout=subprocess.PIPE,
907 stderr=subprocess.PIPE)
908 # Wait for the interpreter to be completely initialized before
909 # sending any signal.
910 p.stdout.read(1)
911 # The process should end after this
912 time.sleep(1)
913 # This shouldn't raise even though the child is now dead
914 getattr(p, method)(*args)
915 p.communicate()
916
Florent Xiclunac0838642010-03-07 15:27:39 +0000917 def test_send_signal(self):
918 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000919 _, stderr = p.communicate()
Florent Xicluna3c919cf2010-03-23 19:19:16 +0000920 self.assertIn('KeyboardInterrupt', stderr)
Florent Xicluna446ff142010-03-23 15:05:30 +0000921 self.assertNotEqual(p.wait(), 0)
Christian Heimese74c8f22008-04-19 02:23:57 +0000922
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000923 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000924 p = self._kill_process('kill')
Florent Xicluna446ff142010-03-23 15:05:30 +0000925 _, stderr = p.communicate()
926 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000927 self.assertEqual(p.wait(), -signal.SIGKILL)
Christian Heimese74c8f22008-04-19 02:23:57 +0000928
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000929 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000930 p = self._kill_process('terminate')
Florent Xicluna446ff142010-03-23 15:05:30 +0000931 _, stderr = p.communicate()
932 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000933 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000934
Antoine Pitrouf60845b2012-03-11 19:29:12 +0100935 def test_send_signal_dead(self):
936 # Sending a signal to a dead process
937 self._kill_dead_process('send_signal', signal.SIGINT)
938
939 def test_kill_dead(self):
940 # Killing a dead process
941 self._kill_dead_process('kill')
942
943 def test_terminate_dead(self):
944 # Terminating a dead process
945 self._kill_dead_process('terminate')
946
Antoine Pitrou91ce0d92011-01-03 18:45:09 +0000947 def check_close_std_fds(self, fds):
948 # Issue #9905: test that subprocess pipes still work properly with
949 # some standard fds closed
950 stdin = 0
951 newfds = []
952 for a in fds:
953 b = os.dup(a)
954 newfds.append(b)
955 if a == 0:
956 stdin = b
957 try:
958 for fd in fds:
959 os.close(fd)
960 out, err = subprocess.Popen([sys.executable, "-c",
961 'import sys;'
962 'sys.stdout.write("apple");'
963 'sys.stdout.flush();'
964 'sys.stderr.write("orange")'],
965 stdin=stdin,
966 stdout=subprocess.PIPE,
967 stderr=subprocess.PIPE).communicate()
968 err = test_support.strip_python_stderr(err)
969 self.assertEqual((out, err), (b'apple', b'orange'))
970 finally:
971 for b, a in zip(newfds, fds):
972 os.dup2(b, a)
973 for b in newfds:
974 os.close(b)
975
976 def test_close_fd_0(self):
977 self.check_close_std_fds([0])
978
979 def test_close_fd_1(self):
980 self.check_close_std_fds([1])
981
982 def test_close_fd_2(self):
983 self.check_close_std_fds([2])
984
985 def test_close_fds_0_1(self):
986 self.check_close_std_fds([0, 1])
987
988 def test_close_fds_0_2(self):
989 self.check_close_std_fds([0, 2])
990
991 def test_close_fds_1_2(self):
992 self.check_close_std_fds([1, 2])
993
994 def test_close_fds_0_1_2(self):
995 # Issue #10806: test that subprocess pipes still work properly with
996 # all standard fds closed.
997 self.check_close_std_fds([0, 1, 2])
998
Ross Lagerwalld8e39012011-07-27 18:54:53 +0200999 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1000 # open up some temporary files
1001 temps = [mkstemp() for i in range(3)]
1002 temp_fds = [fd for fd, fname in temps]
1003 try:
1004 # unlink the files -- we won't need to reopen them
1005 for fd, fname in temps:
1006 os.unlink(fname)
1007
1008 # save a copy of the standard file descriptors
1009 saved_fds = [os.dup(fd) for fd in range(3)]
1010 try:
1011 # duplicate the temp files over the standard fd's 0, 1, 2
1012 for fd, temp_fd in enumerate(temp_fds):
1013 os.dup2(temp_fd, fd)
1014
1015 # write some data to what will become stdin, and rewind
1016 os.write(stdin_no, b"STDIN")
1017 os.lseek(stdin_no, 0, 0)
1018
1019 # now use those files in the given order, so that subprocess
1020 # has to rearrange them in the child
1021 p = subprocess.Popen([sys.executable, "-c",
1022 'import sys; got = sys.stdin.read();'
1023 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1024 stdin=stdin_no,
1025 stdout=stdout_no,
1026 stderr=stderr_no)
1027 p.wait()
1028
1029 for fd in temp_fds:
1030 os.lseek(fd, 0, 0)
1031
1032 out = os.read(stdout_no, 1024)
1033 err = test_support.strip_python_stderr(os.read(stderr_no, 1024))
1034 finally:
1035 for std, saved in enumerate(saved_fds):
1036 os.dup2(saved, std)
1037 os.close(saved)
1038
1039 self.assertEqual(out, b"got STDIN")
1040 self.assertEqual(err, b"err")
1041
1042 finally:
1043 for fd in temp_fds:
1044 os.close(fd)
1045
1046 # When duping fds, if there arises a situation where one of the fds is
1047 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1048 # This tests all combinations of this.
1049 def test_swap_fds(self):
1050 self.check_swap_fds(0, 1, 2)
1051 self.check_swap_fds(0, 2, 1)
1052 self.check_swap_fds(1, 0, 2)
1053 self.check_swap_fds(1, 2, 0)
1054 self.check_swap_fds(2, 0, 1)
1055 self.check_swap_fds(2, 1, 0)
1056
Gregory P. Smith312efbc2010-12-14 15:02:53 +00001057 def test_wait_when_sigchild_ignored(self):
1058 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1059 sigchild_ignore = test_support.findfile("sigchild_ignore.py",
1060 subdir="subprocessdata")
1061 p = subprocess.Popen([sys.executable, sigchild_ignore],
1062 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1063 stdout, stderr = p.communicate()
1064 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
1065 " non-zero with this error:\n%s" % stderr)
1066
Charles-François Natali100df0f2011-08-18 17:56:02 +02001067 def test_zombie_fast_process_del(self):
1068 # Issue #12650: on Unix, if Popen.__del__() was called before the
1069 # process exited, it wouldn't be added to subprocess._active, and would
1070 # remain a zombie.
1071 # spawn a Popen, and delete its reference before it exits
1072 p = subprocess.Popen([sys.executable, "-c",
1073 'import sys, time;'
1074 'time.sleep(0.2)'],
1075 stdout=subprocess.PIPE,
1076 stderr=subprocess.PIPE)
Nadeem Vawda86059362011-08-19 05:22:24 +02001077 self.addCleanup(p.stdout.close)
1078 self.addCleanup(p.stderr.close)
Charles-François Natali100df0f2011-08-18 17:56:02 +02001079 ident = id(p)
1080 pid = p.pid
1081 del p
1082 # check that p is in the active processes list
1083 self.assertIn(ident, [id(o) for o in subprocess._active])
1084
Charles-François Natali100df0f2011-08-18 17:56:02 +02001085 def test_leak_fast_process_del_killed(self):
1086 # Issue #12650: on Unix, if Popen.__del__() was called before the
1087 # process exited, and the process got killed by a signal, it would never
1088 # be removed from subprocess._active, which triggered a FD and memory
1089 # leak.
1090 # spawn a Popen, delete its reference and kill it
1091 p = subprocess.Popen([sys.executable, "-c",
1092 'import time;'
1093 'time.sleep(3)'],
1094 stdout=subprocess.PIPE,
1095 stderr=subprocess.PIPE)
Nadeem Vawda86059362011-08-19 05:22:24 +02001096 self.addCleanup(p.stdout.close)
1097 self.addCleanup(p.stderr.close)
Charles-François Natali100df0f2011-08-18 17:56:02 +02001098 ident = id(p)
1099 pid = p.pid
1100 del p
1101 os.kill(pid, signal.SIGKILL)
1102 # check that p is in the active processes list
1103 self.assertIn(ident, [id(o) for o in subprocess._active])
1104
1105 # let some time for the process to exit, and create a new Popen: this
1106 # should trigger the wait() of p
1107 time.sleep(0.2)
1108 with self.assertRaises(EnvironmentError) as c:
1109 with subprocess.Popen(['nonexisting_i_hope'],
1110 stdout=subprocess.PIPE,
1111 stderr=subprocess.PIPE) as proc:
1112 pass
1113 # p should have been wait()ed on, and removed from the _active list
1114 self.assertRaises(OSError, os.waitpid, pid, 0)
1115 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1116
Charles-François Natali2a34eb32011-08-25 21:20:54 +02001117 def test_pipe_cloexec(self):
1118 # Issue 12786: check that the communication pipes' FDs are set CLOEXEC,
1119 # and are not inherited by another child process.
1120 p1 = subprocess.Popen([sys.executable, "-c",
1121 'import os;'
1122 'os.read(0, 1)'
1123 ],
1124 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1125 stderr=subprocess.PIPE)
1126
1127 p2 = subprocess.Popen([sys.executable, "-c", """if True:
1128 import os, errno, sys
1129 for fd in %r:
1130 try:
1131 os.close(fd)
1132 except OSError as e:
1133 if e.errno != errno.EBADF:
1134 raise
1135 else:
1136 sys.exit(1)
1137 sys.exit(0)
1138 """ % [f.fileno() for f in (p1.stdin, p1.stdout,
1139 p1.stderr)]
1140 ],
1141 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1142 stderr=subprocess.PIPE, close_fds=False)
1143 p1.communicate('foo')
1144 _, stderr = p2.communicate()
1145
1146 self.assertEqual(p2.returncode, 0, "Unexpected error: " + repr(stderr))
1147
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001148
Florent Xiclunabab22a72010-03-04 19:40:48 +00001149@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +00001150class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +00001151
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001152 def test_startupinfo(self):
1153 # startupinfo argument
1154 # We uses hardcoded constants, because we do not want to
1155 # depend on win32all.
1156 STARTF_USESHOWWINDOW = 1
1157 SW_MAXIMIZE = 3
1158 startupinfo = subprocess.STARTUPINFO()
1159 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1160 startupinfo.wShowWindow = SW_MAXIMIZE
1161 # Since Python is a console process, it won't be affected
1162 # by wShowWindow, but the argument should be silently
1163 # ignored
1164 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001165 startupinfo=startupinfo)
1166
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001167 def test_creationflags(self):
1168 # creationflags argument
1169 CREATE_NEW_CONSOLE = 16
1170 sys.stderr.write(" a DOS box should flash briefly ...\n")
1171 subprocess.call(sys.executable +
1172 ' -c "import time; time.sleep(0.25)"',
1173 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001174
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001175 def test_invalid_args(self):
1176 # invalid arguments should raise ValueError
1177 self.assertRaises(ValueError, subprocess.call,
1178 [sys.executable, "-c",
1179 "import sys; sys.exit(47)"],
1180 preexec_fn=lambda: 1)
1181 self.assertRaises(ValueError, subprocess.call,
1182 [sys.executable, "-c",
1183 "import sys; sys.exit(47)"],
1184 stdout=subprocess.PIPE,
1185 close_fds=True)
1186
1187 def test_close_fds(self):
1188 # close file descriptors
1189 rc = subprocess.call([sys.executable, "-c",
1190 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001191 close_fds=True)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001192 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001193
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001194 def test_shell_sequence(self):
1195 # Run command through the shell (sequence)
1196 newenv = os.environ.copy()
1197 newenv["FRUIT"] = "physalis"
1198 p = subprocess.Popen(["set"], shell=1,
1199 stdout=subprocess.PIPE,
1200 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001201 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001202 self.assertIn("physalis", p.stdout.read())
Peter Astrand81a191b2007-05-26 22:18:20 +00001203
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001204 def test_shell_string(self):
1205 # Run command through the shell (string)
1206 newenv = os.environ.copy()
1207 newenv["FRUIT"] = "physalis"
1208 p = subprocess.Popen("set", shell=1,
1209 stdout=subprocess.PIPE,
1210 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001211 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001212 self.assertIn("physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001213
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001214 def test_call_string(self):
1215 # call() function with string argument on Windows
1216 rc = subprocess.call(sys.executable +
1217 ' -c "import sys; sys.exit(47)"')
1218 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001219
Florent Xiclunac0838642010-03-07 15:27:39 +00001220 def _kill_process(self, method, *args):
Florent Xicluna400efc22010-03-07 17:12:23 +00001221 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroudee00972010-09-24 19:00:29 +00001222 p = subprocess.Popen([sys.executable, "-c", """if 1:
1223 import sys, time
1224 sys.stdout.write('x\\n')
1225 sys.stdout.flush()
1226 time.sleep(30)
1227 """],
1228 stdin=subprocess.PIPE,
1229 stdout=subprocess.PIPE,
1230 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001231 self.addCleanup(p.stdout.close)
1232 self.addCleanup(p.stderr.close)
1233 self.addCleanup(p.stdin.close)
Antoine Pitroudee00972010-09-24 19:00:29 +00001234 # Wait for the interpreter to be completely initialized before
1235 # sending any signal.
1236 p.stdout.read(1)
1237 getattr(p, method)(*args)
Florent Xicluna446ff142010-03-23 15:05:30 +00001238 _, stderr = p.communicate()
1239 self.assertStderrEqual(stderr, '')
Antoine Pitroudee00972010-09-24 19:00:29 +00001240 returncode = p.wait()
Florent Xiclunafaf17532010-03-08 10:59:33 +00001241 self.assertNotEqual(returncode, 0)
Florent Xiclunac0838642010-03-07 15:27:39 +00001242
Antoine Pitrouf60845b2012-03-11 19:29:12 +01001243 def _kill_dead_process(self, method, *args):
1244 p = subprocess.Popen([sys.executable, "-c", """if 1:
1245 import sys, time
1246 sys.stdout.write('x\\n')
1247 sys.stdout.flush()
1248 sys.exit(42)
1249 """],
1250 stdin=subprocess.PIPE,
1251 stdout=subprocess.PIPE,
1252 stderr=subprocess.PIPE)
1253 self.addCleanup(p.stdout.close)
1254 self.addCleanup(p.stderr.close)
1255 self.addCleanup(p.stdin.close)
1256 # Wait for the interpreter to be completely initialized before
1257 # sending any signal.
1258 p.stdout.read(1)
1259 # The process should end after this
1260 time.sleep(1)
1261 # This shouldn't raise even though the child is now dead
1262 getattr(p, method)(*args)
1263 _, stderr = p.communicate()
1264 self.assertStderrEqual(stderr, b'')
1265 rc = p.wait()
1266 self.assertEqual(rc, 42)
1267
Florent Xiclunac0838642010-03-07 15:27:39 +00001268 def test_send_signal(self):
1269 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimese74c8f22008-04-19 02:23:57 +00001270
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001271 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001272 self._kill_process('kill')
Christian Heimese74c8f22008-04-19 02:23:57 +00001273
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001274 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001275 self._kill_process('terminate')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001276
Antoine Pitrouf60845b2012-03-11 19:29:12 +01001277 def test_send_signal_dead(self):
1278 self._kill_dead_process('send_signal', signal.SIGTERM)
1279
1280 def test_kill_dead(self):
1281 self._kill_dead_process('kill')
1282
1283 def test_terminate_dead(self):
1284 self._kill_dead_process('terminate')
1285
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001286
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001287@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1288 "poll system call not supported")
1289class ProcessTestCaseNoPoll(ProcessTestCase):
1290 def setUp(self):
1291 subprocess._has_poll = False
1292 ProcessTestCase.setUp(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001293
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001294 def tearDown(self):
1295 subprocess._has_poll = True
1296 ProcessTestCase.tearDown(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001297
1298
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001299class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithc1baf4a2010-03-01 02:53:24 +00001300 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001301 def test_eintr_retry_call(self):
1302 record_calls = []
1303 def fake_os_func(*args):
1304 record_calls.append(args)
1305 if len(record_calls) == 2:
1306 raise OSError(errno.EINTR, "fake interrupted system call")
1307 return tuple(reversed(args))
1308
1309 self.assertEqual((999, 256),
1310 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1311 self.assertEqual([(256, 999)], record_calls)
1312 # This time there will be an EINTR so it will loop once.
1313 self.assertEqual((666,),
1314 subprocess._eintr_retry_call(fake_os_func, 666))
1315 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1316
Tim Golden8e4756c2010-08-12 11:00:35 +00001317@unittest.skipUnless(mswindows, "mswindows only")
1318class CommandsWithSpaces (BaseTestCase):
1319
1320 def setUp(self):
1321 super(CommandsWithSpaces, self).setUp()
1322 f, fname = mkstemp(".py", "te st")
1323 self.fname = fname.lower ()
1324 os.write(f, b"import sys;"
1325 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1326 )
1327 os.close(f)
1328
1329 def tearDown(self):
1330 os.remove(self.fname)
1331 super(CommandsWithSpaces, self).tearDown()
1332
1333 def with_spaces(self, *args, **kwargs):
1334 kwargs['stdout'] = subprocess.PIPE
1335 p = subprocess.Popen(*args, **kwargs)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001336 self.addCleanup(p.stdout.close)
Tim Golden8e4756c2010-08-12 11:00:35 +00001337 self.assertEqual(
1338 p.stdout.read ().decode("mbcs"),
1339 "2 [%r, 'ab cd']" % self.fname
1340 )
1341
1342 def test_shell_string_with_spaces(self):
1343 # call() function with string argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +00001344 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1345 "ab cd"), shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +00001346
1347 def test_shell_sequence_with_spaces(self):
1348 # call() function with sequence argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +00001349 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +00001350
1351 def test_noshell_string_with_spaces(self):
1352 # call() function with string argument with spaces on Windows
1353 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1354 "ab cd"))
1355
1356 def test_noshell_sequence_with_spaces(self):
1357 # call() function with sequence argument with spaces on Windows
1358 self.with_spaces([sys.executable, self.fname, "ab cd"])
1359
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001360def test_main():
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001361 unit_tests = (ProcessTestCase,
1362 POSIXProcessTestCase,
1363 Win32ProcessTestCase,
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001364 ProcessTestCaseNoPoll,
Tim Golden8e4756c2010-08-12 11:00:35 +00001365 HelperFunctionTests,
1366 CommandsWithSpaces)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001367
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001368 test_support.run_unittest(*unit_tests)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001369 test_support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001370
1371if __name__ == "__main__":
1372 test_main()