blob: 1aa2c0a41fe93fb517c6c4b273e8c52d44ef159c [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
13mswindows = (sys.platform == "win32")
14
15#
16# Depends on the following external programs: Python
17#
18
19if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000020 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
21 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000022else:
23 SETBINARY = ''
24
Florent Xicluna98e3fc32010-02-27 19:20:50 +000025
26try:
27 mkstemp = tempfile.mkstemp
28except AttributeError:
29 # tempfile.mkstemp is not available
30 def mkstemp():
31 """Replacement for mkstemp, calling mktemp."""
32 fname = tempfile.mktemp()
33 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
34
Tim Peters3761e8d2004-10-13 04:07:12 +000035
Florent Xiclunafc4d6d72010-03-23 14:36:45 +000036class BaseTestCase(unittest.TestCase):
Neal Norwitzb15ac312006-06-29 04:10:08 +000037 def setUp(self):
Tim Peters38ff36c2006-06-30 06:18:39 +000038 # Try to minimize the number of children we have so this test
39 # doesn't crash on some buildbots (Alphas in particular).
Florent Xicluna98e3fc32010-02-27 19:20:50 +000040 test_support.reap_children()
Neal Norwitzb15ac312006-06-29 04:10:08 +000041
Florent Xiclunaab5e17f2010-03-04 21:31:58 +000042 def tearDown(self):
43 for inst in subprocess._active:
44 inst.wait()
45 subprocess._cleanup()
46 self.assertFalse(subprocess._active, "subprocess._active not empty")
47
Florent Xicluna98e3fc32010-02-27 19:20:50 +000048 def assertStderrEqual(self, stderr, expected, msg=None):
49 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
50 # shutdown time. That frustrates tests trying to check stderr produced
51 # from a spawned Python process.
52 actual = re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr)
53 self.assertEqual(actual, expected, msg)
Neal Norwitzb15ac312006-06-29 04:10:08 +000054
Florent Xiclunafc4d6d72010-03-23 14:36:45 +000055
56class ProcessTestCase(BaseTestCase):
57
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000058 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000059 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000060 rc = subprocess.call([sys.executable, "-c",
61 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000062 self.assertEqual(rc, 47)
63
Peter Astrand454f7672005-01-01 09:36:35 +000064 def test_check_call_zero(self):
65 # check_call() function with zero return code
66 rc = subprocess.check_call([sys.executable, "-c",
67 "import sys; sys.exit(0)"])
68 self.assertEqual(rc, 0)
69
70 def test_check_call_nonzero(self):
71 # check_call() function with non-zero return code
Florent Xicluna98e3fc32010-02-27 19:20:50 +000072 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000073 subprocess.check_call([sys.executable, "-c",
74 "import sys; sys.exit(47)"])
Florent Xicluna98e3fc32010-02-27 19:20:50 +000075 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000076
Gregory P. Smith26576802008-12-05 02:27:01 +000077 def test_check_output(self):
78 # check_output() function with zero return code
79 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +000080 [sys.executable, "-c", "print 'BDFL'"])
Ezio Melottiaa980582010-01-23 23:04:36 +000081 self.assertIn('BDFL', output)
Gregory P. Smith97f49f42008-12-04 20:21:09 +000082
Gregory P. Smith26576802008-12-05 02:27:01 +000083 def test_check_output_nonzero(self):
Gregory P. Smith97f49f42008-12-04 20:21:09 +000084 # check_call() function with non-zero return code
Florent Xicluna98e3fc32010-02-27 19:20:50 +000085 with self.assertRaises(subprocess.CalledProcessError) as c:
Gregory P. Smith26576802008-12-05 02:27:01 +000086 subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +000087 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xicluna98e3fc32010-02-27 19:20:50 +000088 self.assertEqual(c.exception.returncode, 5)
Gregory P. Smith97f49f42008-12-04 20:21:09 +000089
Gregory P. Smith26576802008-12-05 02:27:01 +000090 def test_check_output_stderr(self):
91 # check_output() function stderr redirected to stdout
92 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +000093 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
94 stderr=subprocess.STDOUT)
Ezio Melottiaa980582010-01-23 23:04:36 +000095 self.assertIn('BDFL', output)
Gregory P. Smith97f49f42008-12-04 20:21:09 +000096
Gregory P. Smith26576802008-12-05 02:27:01 +000097 def test_check_output_stdout_arg(self):
98 # check_output() function stderr redirected to stdout
Florent Xicluna98e3fc32010-02-27 19:20:50 +000099 with self.assertRaises(ValueError) as c:
Gregory P. Smith26576802008-12-05 02:27:01 +0000100 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000101 [sys.executable, "-c", "print 'will not be run'"],
102 stdout=sys.stdout)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000103 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000104 self.assertIn('stdout', c.exception.args[0])
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000105
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000106 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000107 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000108 newenv = os.environ.copy()
109 newenv["FRUIT"] = "banana"
110 rc = subprocess.call([sys.executable, "-c",
Florent Xiclunabab22a72010-03-04 19:40:48 +0000111 'import sys, os;'
112 'sys.exit(os.getenv("FRUIT")=="banana")'],
113 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 self.assertEqual(rc, 1)
115
Victor Stinner776e69b2011-06-01 01:03:00 +0200116 def test_invalid_args(self):
117 # Popen() called with invalid arguments should raise TypeError
118 # but Popen.__del__ should not complain (issue #12085)
Victor Stinnere9b185f2011-06-01 01:57:48 +0200119 with test_support.captured_stderr() as s:
Victor Stinner776e69b2011-06-01 01:03:00 +0200120 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
121 argcount = subprocess.Popen.__init__.__code__.co_argcount
122 too_many_args = [0] * (argcount + 1)
123 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
124 self.assertEqual(s.getvalue(), '')
125
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000126 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000127 # .stdin is None when not redirected
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000128 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
129 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000130 self.addCleanup(p.stdout.close)
131 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000132 p.wait()
133 self.assertEqual(p.stdin, None)
134
135 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000136 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000137 p = subprocess.Popen([sys.executable, "-c",
Tim Peters4052fe52004-10-13 03:29:54 +0000138 'print " this bit of output is from a '
139 'test of stdout in a different '
140 'process ..."'],
141 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000142 self.addCleanup(p.stdin.close)
143 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000144 p.wait()
145 self.assertEqual(p.stdout, None)
146
147 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000148 # .stderr is None when not redirected
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000149 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
150 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000151 self.addCleanup(p.stdout.close)
152 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000153 p.wait()
154 self.assertEqual(p.stderr, None)
155
Ezio Melotti8f6a2872010-02-10 21:40:33 +0000156 def test_executable_with_cwd(self):
Florent Xicluna63763702010-03-11 01:50:48 +0000157 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti8f6a2872010-02-10 21:40:33 +0000158 p = subprocess.Popen(["somethingyoudonthave", "-c",
159 "import sys; sys.exit(47)"],
160 executable=sys.executable, cwd=python_dir)
161 p.wait()
162 self.assertEqual(p.returncode, 47)
163
164 @unittest.skipIf(sysconfig.is_python_build(),
165 "need an installed Python. See #7774")
166 def test_executable_without_cwd(self):
167 # For a normal installation, it should work without 'cwd'
168 # argument. For test runs in the build directory, see #7774.
169 p = subprocess.Popen(["somethingyoudonthave", "-c",
170 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000171 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000172 p.wait()
173 self.assertEqual(p.returncode, 47)
174
175 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000176 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000177 p = subprocess.Popen([sys.executable, "-c",
178 'import sys; sys.exit(sys.stdin.read() == "pear")'],
179 stdin=subprocess.PIPE)
180 p.stdin.write("pear")
181 p.stdin.close()
182 p.wait()
183 self.assertEqual(p.returncode, 1)
184
185 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000186 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000187 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000188 d = tf.fileno()
189 os.write(d, "pear")
190 os.lseek(d, 0, 0)
191 p = subprocess.Popen([sys.executable, "-c",
192 'import sys; sys.exit(sys.stdin.read() == "pear")'],
193 stdin=d)
194 p.wait()
195 self.assertEqual(p.returncode, 1)
196
197 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000198 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000199 tf = tempfile.TemporaryFile()
200 tf.write("pear")
201 tf.seek(0)
202 p = subprocess.Popen([sys.executable, "-c",
203 'import sys; sys.exit(sys.stdin.read() == "pear")'],
204 stdin=tf)
205 p.wait()
206 self.assertEqual(p.returncode, 1)
207
208 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000209 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210 p = subprocess.Popen([sys.executable, "-c",
211 'import sys; sys.stdout.write("orange")'],
212 stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000213 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000214 self.assertEqual(p.stdout.read(), "orange")
215
216 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000217 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000218 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000219 d = tf.fileno()
220 p = subprocess.Popen([sys.executable, "-c",
221 'import sys; sys.stdout.write("orange")'],
222 stdout=d)
223 p.wait()
224 os.lseek(d, 0, 0)
225 self.assertEqual(os.read(d, 1024), "orange")
226
227 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000228 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000229 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000230 p = subprocess.Popen([sys.executable, "-c",
231 'import sys; sys.stdout.write("orange")'],
232 stdout=tf)
233 p.wait()
234 tf.seek(0)
235 self.assertEqual(tf.read(), "orange")
236
237 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000238 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239 p = subprocess.Popen([sys.executable, "-c",
240 'import sys; sys.stderr.write("strawberry")'],
241 stderr=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000242 self.addCleanup(p.stderr.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000243 self.assertStderrEqual(p.stderr.read(), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244
245 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000246 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000247 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000248 d = tf.fileno()
249 p = subprocess.Popen([sys.executable, "-c",
250 'import sys; sys.stderr.write("strawberry")'],
251 stderr=d)
252 p.wait()
253 os.lseek(d, 0, 0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000254 self.assertStderrEqual(os.read(d, 1024), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000255
256 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000257 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000258 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000259 p = subprocess.Popen([sys.executable, "-c",
260 'import sys; sys.stderr.write("strawberry")'],
261 stderr=tf)
262 p.wait()
263 tf.seek(0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000264 self.assertStderrEqual(tf.read(), "strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265
266 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000267 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000269 'import sys;'
270 'sys.stdout.write("apple");'
271 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000272 'sys.stderr.write("orange")'],
273 stdout=subprocess.PIPE,
274 stderr=subprocess.STDOUT)
Brian Curtind117b562010-11-05 04:09:09 +0000275 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000276 self.assertStderrEqual(p.stdout.read(), "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000277
278 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000279 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000280 tf = tempfile.TemporaryFile()
281 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000282 'import sys;'
283 'sys.stdout.write("apple");'
284 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285 'sys.stderr.write("orange")'],
286 stdout=tf,
287 stderr=tf)
288 p.wait()
289 tf.seek(0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000290 self.assertStderrEqual(tf.read(), "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291
Gustavo Niemeyerc36bede2006-09-07 00:48:33 +0000292 def test_stdout_filedes_of_stdout(self):
293 # stdout is set to 1 (#1531862).
294 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), '.\n'))"
295 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000296 self.assertEqual(rc, 2)
Gustavo Niemeyerc36bede2006-09-07 00:48:33 +0000297
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298 def test_cwd(self):
Guido van Rossume9a0e882007-12-20 17:28:10 +0000299 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000300 # We cannot use os.path.realpath to canonicalize the path,
301 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
302 cwd = os.getcwd()
303 os.chdir(tmpdir)
304 tmpdir = os.getcwd()
305 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000307 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308 'sys.stdout.write(os.getcwd())'],
309 stdout=subprocess.PIPE,
310 cwd=tmpdir)
Brian Curtind117b562010-11-05 04:09:09 +0000311 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000312 normcase = os.path.normcase
313 self.assertEqual(normcase(p.stdout.read()), normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000314
315 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000316 newenv = os.environ.copy()
317 newenv["FRUIT"] = "orange"
318 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000319 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000320 'sys.stdout.write(os.getenv("FRUIT"))'],
321 stdout=subprocess.PIPE,
322 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000323 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000324 self.assertEqual(p.stdout.read(), "orange")
325
Peter Astrandcbac93c2005-03-03 20:24:28 +0000326 def test_communicate_stdin(self):
327 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000328 'import sys;'
329 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000330 stdin=subprocess.PIPE)
331 p.communicate("pear")
332 self.assertEqual(p.returncode, 1)
333
334 def test_communicate_stdout(self):
335 p = subprocess.Popen([sys.executable, "-c",
336 'import sys; sys.stdout.write("pineapple")'],
337 stdout=subprocess.PIPE)
338 (stdout, stderr) = p.communicate()
339 self.assertEqual(stdout, "pineapple")
340 self.assertEqual(stderr, None)
341
342 def test_communicate_stderr(self):
343 p = subprocess.Popen([sys.executable, "-c",
344 'import sys; sys.stderr.write("pineapple")'],
345 stderr=subprocess.PIPE)
346 (stdout, stderr) = p.communicate()
347 self.assertEqual(stdout, None)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000348 self.assertStderrEqual(stderr, "pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000349
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000350 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000351 p = subprocess.Popen([sys.executable, "-c",
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000352 'import sys,os;'
353 'sys.stderr.write("pineapple");'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000355 stdin=subprocess.PIPE,
356 stdout=subprocess.PIPE,
357 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000358 self.addCleanup(p.stdout.close)
359 self.addCleanup(p.stderr.close)
360 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361 (stdout, stderr) = p.communicate("banana")
362 self.assertEqual(stdout, "banana")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000363 self.assertStderrEqual(stderr, "pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000364
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000365 # This test is Linux specific for simplicity to at least have
366 # some coverage. It is not a platform specific bug.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000367 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
368 "Linux specific")
369 # Test for the fd leak reported in http://bugs.python.org/issue2791.
370 def test_communicate_pipe_fd_leak(self):
371 fd_directory = '/proc/%d/fd' % os.getpid()
372 num_fds_before_popen = len(os.listdir(fd_directory))
373 p = subprocess.Popen([sys.executable, "-c", "print()"],
374 stdout=subprocess.PIPE)
375 p.communicate()
376 num_fds_after_communicate = len(os.listdir(fd_directory))
377 del p
378 num_fds_after_destruction = len(os.listdir(fd_directory))
379 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
380 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000381
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000382 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000383 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000384 p = subprocess.Popen([sys.executable, "-c",
385 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000386 (stdout, stderr) = p.communicate()
387 self.assertEqual(stdout, None)
388 self.assertEqual(stderr, None)
389
390 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000391 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000392 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000393 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000394 x, y = os.pipe()
395 if mswindows:
396 pipe_buf = 512
397 else:
398 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
399 os.close(x)
400 os.close(y)
401 p = subprocess.Popen([sys.executable, "-c",
Tim Peterse718f612004-10-12 21:51:32 +0000402 'import sys,os;'
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000403 'sys.stdout.write(sys.stdin.read(47));'
404 'sys.stderr.write("xyz"*%d);'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000405 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
Tim Peters3b01a702004-10-12 22:19:32 +0000406 stdin=subprocess.PIPE,
407 stdout=subprocess.PIPE,
408 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000409 self.addCleanup(p.stdout.close)
410 self.addCleanup(p.stderr.close)
411 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000412 string_to_write = "abc"*pipe_buf
413 (stdout, stderr) = p.communicate(string_to_write)
414 self.assertEqual(stdout, string_to_write)
415
416 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000417 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000418 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000419 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000420 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000421 stdin=subprocess.PIPE,
422 stdout=subprocess.PIPE,
423 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000424 self.addCleanup(p.stdout.close)
425 self.addCleanup(p.stderr.close)
426 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000427 p.stdin.write("banana")
428 (stdout, stderr) = p.communicate("split")
429 self.assertEqual(stdout, "bananasplit")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000430 self.assertStderrEqual(stderr, "")
Tim Peterse718f612004-10-12 21:51:32 +0000431
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000432 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000434 'import sys,os;' + SETBINARY +
435 'sys.stdout.write("line1\\n");'
436 'sys.stdout.flush();'
437 'sys.stdout.write("line2\\r");'
438 'sys.stdout.flush();'
439 'sys.stdout.write("line3\\r\\n");'
440 'sys.stdout.flush();'
441 'sys.stdout.write("line4\\r");'
442 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000443 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000444 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000445 'sys.stdout.write("\\nline6");'],
446 stdout=subprocess.PIPE,
447 universal_newlines=1)
Brian Curtind117b562010-11-05 04:09:09 +0000448 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449 stdout = p.stdout.read()
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000450 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000451 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000452 self.assertEqual(stdout,
453 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454 else:
455 # Interpreter without universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000456 self.assertEqual(stdout,
457 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000458
459 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000460 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000461 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000462 'import sys,os;' + SETBINARY +
463 'sys.stdout.write("line1\\n");'
464 'sys.stdout.flush();'
465 'sys.stdout.write("line2\\r");'
466 'sys.stdout.flush();'
467 'sys.stdout.write("line3\\r\\n");'
468 'sys.stdout.flush();'
469 'sys.stdout.write("line4\\r");'
470 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000472 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000473 'sys.stdout.write("\\nline6");'],
474 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
475 universal_newlines=1)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000476 self.addCleanup(p.stdout.close)
477 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478 (stdout, stderr) = p.communicate()
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000479 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000480 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000481 self.assertEqual(stdout,
482 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483 else:
484 # Interpreter without universal newline support
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000485 self.assertEqual(stdout,
486 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000487
488 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000489 # Make sure we leak no resources
Antoine Pitroub0b3bff2010-09-18 22:42:30 +0000490 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000491 max_handles = 1026 # too much for most UNIX systems
492 else:
Antoine Pitroub0b3bff2010-09-18 22:42:30 +0000493 max_handles = 2050 # too much for (at least some) Windows setups
494 handles = []
495 try:
496 for i in range(max_handles):
497 try:
498 handles.append(os.open(test_support.TESTFN,
499 os.O_WRONLY | os.O_CREAT))
500 except OSError as e:
501 if e.errno != errno.EMFILE:
502 raise
503 break
504 else:
505 self.skipTest("failed to reach the file descriptor limit "
506 "(tried %d)" % max_handles)
507 # Close a couple of them (should be enough for a subprocess)
508 for i in range(10):
509 os.close(handles.pop())
510 # Loop creating some subprocesses. If one of them leaks some fds,
511 # the next loop iteration will fail by reaching the max fd limit.
512 for i in range(15):
513 p = subprocess.Popen([sys.executable, "-c",
514 "import sys;"
515 "sys.stdout.write(sys.stdin.read())"],
516 stdin=subprocess.PIPE,
517 stdout=subprocess.PIPE,
518 stderr=subprocess.PIPE)
519 data = p.communicate(b"lime")[0]
520 self.assertEqual(data, b"lime")
521 finally:
522 for h in handles:
523 os.close(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000524
525 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
527 '"a b c" d e')
528 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
529 'ab\\"c \\ d')
Gregory P. Smithe047e6d2008-01-19 20:49:02 +0000530 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
531 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
533 'a\\\\\\b "de fg" h')
534 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
535 'a\\\\\\"b c d')
536 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
537 '"a\\\\b c" d e')
538 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
539 '"a\\\\b\\ c" d e')
Peter Astrand10514a72007-01-13 22:35:35 +0000540 self.assertEqual(subprocess.list2cmdline(['ab', '']),
541 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542
543
544 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000546 "-c", "import time; time.sleep(1)"])
547 count = 0
548 while p.poll() is None:
549 time.sleep(0.1)
550 count += 1
551 # We expect that the poll loop probably went around about 10 times,
552 # but, based on system scheduling we can't control, it's possible
553 # poll() never returned None. It "should be" very rare that it
554 # didn't go around at least twice.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000555 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556 # Subsequent invocations should just return the returncode
557 self.assertEqual(p.poll(), 0)
558
559
560 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561 p = subprocess.Popen([sys.executable,
562 "-c", "import time; time.sleep(2)"])
563 self.assertEqual(p.wait(), 0)
564 # Subsequent invocations should just return the returncode
565 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000566
Peter Astrand738131d2004-11-30 21:04:45 +0000567
568 def test_invalid_bufsize(self):
569 # an invalid type of the bufsize argument should raise
570 # TypeError.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000571 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000572 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000573
Georg Brandlf3715d22009-02-14 17:01:36 +0000574 def test_leaking_fds_on_error(self):
575 # see bug #5179: Popen leaks file descriptors to PIPEs if
576 # the child fails to execute; this will eventually exhaust
577 # the maximum number of open fds. 1024 seems a very common
578 # value for that limit, but Windows has 2048, so we loop
579 # 1024 times (each call leaked two fds).
580 for i in range(1024):
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000581 # Windows raises IOError. Others raise OSError.
582 with self.assertRaises(EnvironmentError) as c:
Georg Brandlf3715d22009-02-14 17:01:36 +0000583 subprocess.Popen(['nonexisting_i_hope'],
584 stdout=subprocess.PIPE,
585 stderr=subprocess.PIPE)
R David Murraycdd5fc92011-03-13 22:37:18 -0400586 # ignore errors that indicate the command was not found
587 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000588 raise c.exception
Georg Brandlf3715d22009-02-14 17:01:36 +0000589
Tim Golden90374f52010-08-06 13:14:33 +0000590 def test_handles_closed_on_exception(self):
591 # If CreateProcess exits with an error, ensure the
592 # duplicate output handles are released
593 ifhandle, ifname = mkstemp()
594 ofhandle, ofname = mkstemp()
595 efhandle, efname = mkstemp()
596 try:
597 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
598 stderr=efhandle)
599 except OSError:
600 os.close(ifhandle)
601 os.remove(ifname)
602 os.close(ofhandle)
603 os.remove(ofname)
604 os.close(efhandle)
605 os.remove(efname)
606 self.assertFalse(os.path.exists(ifname))
607 self.assertFalse(os.path.exists(ofname))
608 self.assertFalse(os.path.exists(efname))
609
Ross Lagerwall104c3f12011-04-05 15:24:34 +0200610 def test_communicate_epipe(self):
611 # Issue 10963: communicate() should hide EPIPE
612 p = subprocess.Popen([sys.executable, "-c", 'pass'],
613 stdin=subprocess.PIPE,
614 stdout=subprocess.PIPE,
615 stderr=subprocess.PIPE)
616 self.addCleanup(p.stdout.close)
617 self.addCleanup(p.stderr.close)
618 self.addCleanup(p.stdin.close)
619 p.communicate("x" * 2**20)
620
621 def test_communicate_epipe_only_stdin(self):
622 # Issue 10963: communicate() should hide EPIPE
623 p = subprocess.Popen([sys.executable, "-c", 'pass'],
624 stdin=subprocess.PIPE)
625 self.addCleanup(p.stdin.close)
626 time.sleep(2)
627 p.communicate("x" * 2**20)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000628
629# context manager
630class _SuppressCoreFiles(object):
631 """Try to prevent core files from being created."""
632 old_limit = None
633
634 def __enter__(self):
635 """Try to save previous ulimit, then set it to (0, 0)."""
636 try:
637 import resource
638 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
639 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
640 except (ImportError, ValueError, resource.error):
641 pass
642
Ronald Oussoren21b44e02010-07-23 12:26:30 +0000643 if sys.platform == 'darwin':
644 # Check if the 'Crash Reporter' on OSX was configured
645 # in 'Developer' mode and warn that it will get triggered
646 # when it is.
647 #
648 # This assumes that this context manager is used in tests
649 # that might trigger the next manager.
650 value = subprocess.Popen(['/usr/bin/defaults', 'read',
651 'com.apple.CrashReporter', 'DialogType'],
652 stdout=subprocess.PIPE).communicate()[0]
653 if value.strip() == b'developer':
654 print "this tests triggers the Crash Reporter, that is intentional"
655 sys.stdout.flush()
656
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000657 def __exit__(self, *args):
658 """Return core file behavior to default."""
659 if self.old_limit is None:
660 return
661 try:
662 import resource
663 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
664 except (ImportError, ValueError, resource.error):
665 pass
666
Victor Stinnerb78fed92011-07-05 14:50:35 +0200667 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
668 "Requires signal.SIGALRM")
Victor Stinnere7901312011-07-05 14:08:01 +0200669 def test_communicate_eintr(self):
670 # Issue #12493: communicate() should handle EINTR
671 def handler(signum, frame):
672 pass
673 old_handler = signal.signal(signal.SIGALRM, handler)
674 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
675
676 # the process is running for 2 seconds
677 args = [sys.executable, "-c", 'import time; time.sleep(2)']
678 for stream in ('stdout', 'stderr'):
679 kw = {stream: subprocess.PIPE}
680 with subprocess.Popen(args, **kw) as process:
681 signal.alarm(1)
682 # communicate() will be interrupted by SIGALRM
683 process.communicate()
684
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000685
Florent Xiclunabab22a72010-03-04 19:40:48 +0000686@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000687class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +0000688
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000689 def test_exceptions(self):
690 # caught & re-raised exceptions
691 with self.assertRaises(OSError) as c:
692 p = subprocess.Popen([sys.executable, "-c", ""],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000693 cwd="/this/path/does/not/exist")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000694 # The attribute child_traceback should contain "os.chdir" somewhere.
695 self.assertIn("os.chdir", c.exception.child_traceback)
Tim Peterse718f612004-10-12 21:51:32 +0000696
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000697 def test_run_abort(self):
698 # returncode handles signal termination
699 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000700 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000701 "import os; os.abort()"])
702 p.wait()
703 self.assertEqual(-p.returncode, signal.SIGABRT)
704
705 def test_preexec(self):
706 # preexec function
707 p = subprocess.Popen([sys.executable, "-c",
708 "import sys, os;"
709 "sys.stdout.write(os.getenv('FRUIT'))"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000710 stdout=subprocess.PIPE,
711 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtind117b562010-11-05 04:09:09 +0000712 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000713 self.assertEqual(p.stdout.read(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000714
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000715 def test_args_string(self):
716 # args is a string
717 f, fname = mkstemp()
718 os.write(f, "#!/bin/sh\n")
719 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
720 sys.executable)
721 os.close(f)
722 os.chmod(fname, 0o700)
723 p = subprocess.Popen(fname)
724 p.wait()
725 os.remove(fname)
726 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000727
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000728 def test_invalid_args(self):
729 # invalid arguments should raise ValueError
730 self.assertRaises(ValueError, subprocess.call,
731 [sys.executable, "-c",
732 "import sys; sys.exit(47)"],
733 startupinfo=47)
734 self.assertRaises(ValueError, subprocess.call,
735 [sys.executable, "-c",
736 "import sys; sys.exit(47)"],
737 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000739 def test_shell_sequence(self):
740 # Run command through the shell (sequence)
741 newenv = os.environ.copy()
742 newenv["FRUIT"] = "apple"
743 p = subprocess.Popen(["echo $FRUIT"], shell=1,
744 stdout=subprocess.PIPE,
745 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000746 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000747 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000748
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000749 def test_shell_string(self):
750 # Run command through the shell (string)
751 newenv = os.environ.copy()
752 newenv["FRUIT"] = "apple"
753 p = subprocess.Popen("echo $FRUIT", shell=1,
754 stdout=subprocess.PIPE,
755 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000756 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000757 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000758
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000759 def test_call_string(self):
760 # call() function with string argument on UNIX
761 f, fname = mkstemp()
762 os.write(f, "#!/bin/sh\n")
763 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
764 sys.executable)
765 os.close(f)
766 os.chmod(fname, 0700)
767 rc = subprocess.call(fname)
768 os.remove(fname)
769 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000770
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000771 def test_specific_shell(self):
772 # Issue #9265: Incorrect name passed as arg[0].
773 shells = []
774 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
775 for name in ['bash', 'ksh']:
776 sh = os.path.join(prefix, name)
777 if os.path.isfile(sh):
778 shells.append(sh)
779 if not shells: # Will probably work for any shell but csh.
780 self.skipTest("bash or ksh required for this test")
781 sh = '/bin/sh'
782 if os.path.isfile(sh) and not os.path.islink(sh):
783 # Test will fail if /bin/sh is a symlink to csh.
784 shells.append(sh)
785 for sh in shells:
786 p = subprocess.Popen("echo $0", executable=sh, shell=True,
787 stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000788 self.addCleanup(p.stdout.close)
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000789 self.assertEqual(p.stdout.read().strip(), sh)
790
Florent Xiclunac0838642010-03-07 15:27:39 +0000791 def _kill_process(self, method, *args):
Florent Xiclunacecef392010-03-05 19:31:21 +0000792 # Do not inherit file handles from the parent.
793 # It should fix failures on some platforms.
Antoine Pitroua6166da2010-09-20 11:20:44 +0000794 p = subprocess.Popen([sys.executable, "-c", """if 1:
795 import sys, time
796 sys.stdout.write('x\\n')
797 sys.stdout.flush()
798 time.sleep(30)
799 """],
800 close_fds=True,
801 stdin=subprocess.PIPE,
802 stdout=subprocess.PIPE,
803 stderr=subprocess.PIPE)
804 # Wait for the interpreter to be completely initialized before
805 # sending any signal.
806 p.stdout.read(1)
807 getattr(p, method)(*args)
Florent Xiclunac0838642010-03-07 15:27:39 +0000808 return p
809
810 def test_send_signal(self):
811 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000812 _, stderr = p.communicate()
Florent Xicluna3c919cf2010-03-23 19:19:16 +0000813 self.assertIn('KeyboardInterrupt', stderr)
Florent Xicluna446ff142010-03-23 15:05:30 +0000814 self.assertNotEqual(p.wait(), 0)
Christian Heimese74c8f22008-04-19 02:23:57 +0000815
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000816 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000817 p = self._kill_process('kill')
Florent Xicluna446ff142010-03-23 15:05:30 +0000818 _, stderr = p.communicate()
819 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000820 self.assertEqual(p.wait(), -signal.SIGKILL)
Christian Heimese74c8f22008-04-19 02:23:57 +0000821
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000822 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000823 p = self._kill_process('terminate')
Florent Xicluna446ff142010-03-23 15:05:30 +0000824 _, stderr = p.communicate()
825 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000826 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000827
Antoine Pitrou91ce0d92011-01-03 18:45:09 +0000828 def check_close_std_fds(self, fds):
829 # Issue #9905: test that subprocess pipes still work properly with
830 # some standard fds closed
831 stdin = 0
832 newfds = []
833 for a in fds:
834 b = os.dup(a)
835 newfds.append(b)
836 if a == 0:
837 stdin = b
838 try:
839 for fd in fds:
840 os.close(fd)
841 out, err = subprocess.Popen([sys.executable, "-c",
842 'import sys;'
843 'sys.stdout.write("apple");'
844 'sys.stdout.flush();'
845 'sys.stderr.write("orange")'],
846 stdin=stdin,
847 stdout=subprocess.PIPE,
848 stderr=subprocess.PIPE).communicate()
849 err = test_support.strip_python_stderr(err)
850 self.assertEqual((out, err), (b'apple', b'orange'))
851 finally:
852 for b, a in zip(newfds, fds):
853 os.dup2(b, a)
854 for b in newfds:
855 os.close(b)
856
857 def test_close_fd_0(self):
858 self.check_close_std_fds([0])
859
860 def test_close_fd_1(self):
861 self.check_close_std_fds([1])
862
863 def test_close_fd_2(self):
864 self.check_close_std_fds([2])
865
866 def test_close_fds_0_1(self):
867 self.check_close_std_fds([0, 1])
868
869 def test_close_fds_0_2(self):
870 self.check_close_std_fds([0, 2])
871
872 def test_close_fds_1_2(self):
873 self.check_close_std_fds([1, 2])
874
875 def test_close_fds_0_1_2(self):
876 # Issue #10806: test that subprocess pipes still work properly with
877 # all standard fds closed.
878 self.check_close_std_fds([0, 1, 2])
879
Ross Lagerwalld8e39012011-07-27 18:54:53 +0200880 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
881 # open up some temporary files
882 temps = [mkstemp() for i in range(3)]
883 temp_fds = [fd for fd, fname in temps]
884 try:
885 # unlink the files -- we won't need to reopen them
886 for fd, fname in temps:
887 os.unlink(fname)
888
889 # save a copy of the standard file descriptors
890 saved_fds = [os.dup(fd) for fd in range(3)]
891 try:
892 # duplicate the temp files over the standard fd's 0, 1, 2
893 for fd, temp_fd in enumerate(temp_fds):
894 os.dup2(temp_fd, fd)
895
896 # write some data to what will become stdin, and rewind
897 os.write(stdin_no, b"STDIN")
898 os.lseek(stdin_no, 0, 0)
899
900 # now use those files in the given order, so that subprocess
901 # has to rearrange them in the child
902 p = subprocess.Popen([sys.executable, "-c",
903 'import sys; got = sys.stdin.read();'
904 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
905 stdin=stdin_no,
906 stdout=stdout_no,
907 stderr=stderr_no)
908 p.wait()
909
910 for fd in temp_fds:
911 os.lseek(fd, 0, 0)
912
913 out = os.read(stdout_no, 1024)
914 err = test_support.strip_python_stderr(os.read(stderr_no, 1024))
915 finally:
916 for std, saved in enumerate(saved_fds):
917 os.dup2(saved, std)
918 os.close(saved)
919
920 self.assertEqual(out, b"got STDIN")
921 self.assertEqual(err, b"err")
922
923 finally:
924 for fd in temp_fds:
925 os.close(fd)
926
927 # When duping fds, if there arises a situation where one of the fds is
928 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
929 # This tests all combinations of this.
930 def test_swap_fds(self):
931 self.check_swap_fds(0, 1, 2)
932 self.check_swap_fds(0, 2, 1)
933 self.check_swap_fds(1, 0, 2)
934 self.check_swap_fds(1, 2, 0)
935 self.check_swap_fds(2, 0, 1)
936 self.check_swap_fds(2, 1, 0)
937
Gregory P. Smith312efbc2010-12-14 15:02:53 +0000938 def test_wait_when_sigchild_ignored(self):
939 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
940 sigchild_ignore = test_support.findfile("sigchild_ignore.py",
941 subdir="subprocessdata")
942 p = subprocess.Popen([sys.executable, sigchild_ignore],
943 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
944 stdout, stderr = p.communicate()
945 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
946 " non-zero with this error:\n%s" % stderr)
947
Charles-François Natali100df0f2011-08-18 17:56:02 +0200948 def test_zombie_fast_process_del(self):
949 # Issue #12650: on Unix, if Popen.__del__() was called before the
950 # process exited, it wouldn't be added to subprocess._active, and would
951 # remain a zombie.
952 # spawn a Popen, and delete its reference before it exits
953 p = subprocess.Popen([sys.executable, "-c",
954 'import sys, time;'
955 'time.sleep(0.2)'],
956 stdout=subprocess.PIPE,
957 stderr=subprocess.PIPE)
Nadeem Vawda86059362011-08-19 05:22:24 +0200958 self.addCleanup(p.stdout.close)
959 self.addCleanup(p.stderr.close)
Charles-François Natali100df0f2011-08-18 17:56:02 +0200960 ident = id(p)
961 pid = p.pid
962 del p
963 # check that p is in the active processes list
964 self.assertIn(ident, [id(o) for o in subprocess._active])
965
Charles-François Natali100df0f2011-08-18 17:56:02 +0200966 def test_leak_fast_process_del_killed(self):
967 # Issue #12650: on Unix, if Popen.__del__() was called before the
968 # process exited, and the process got killed by a signal, it would never
969 # be removed from subprocess._active, which triggered a FD and memory
970 # leak.
971 # spawn a Popen, delete its reference and kill it
972 p = subprocess.Popen([sys.executable, "-c",
973 'import time;'
974 'time.sleep(3)'],
975 stdout=subprocess.PIPE,
976 stderr=subprocess.PIPE)
Nadeem Vawda86059362011-08-19 05:22:24 +0200977 self.addCleanup(p.stdout.close)
978 self.addCleanup(p.stderr.close)
Charles-François Natali100df0f2011-08-18 17:56:02 +0200979 ident = id(p)
980 pid = p.pid
981 del p
982 os.kill(pid, signal.SIGKILL)
983 # check that p is in the active processes list
984 self.assertIn(ident, [id(o) for o in subprocess._active])
985
986 # let some time for the process to exit, and create a new Popen: this
987 # should trigger the wait() of p
988 time.sleep(0.2)
989 with self.assertRaises(EnvironmentError) as c:
990 with subprocess.Popen(['nonexisting_i_hope'],
991 stdout=subprocess.PIPE,
992 stderr=subprocess.PIPE) as proc:
993 pass
994 # p should have been wait()ed on, and removed from the _active list
995 self.assertRaises(OSError, os.waitpid, pid, 0)
996 self.assertNotIn(ident, [id(o) for o in subprocess._active])
997
Charles-François Natali2a34eb32011-08-25 21:20:54 +0200998 def test_pipe_cloexec(self):
999 # Issue 12786: check that the communication pipes' FDs are set CLOEXEC,
1000 # and are not inherited by another child process.
1001 p1 = subprocess.Popen([sys.executable, "-c",
1002 'import os;'
1003 'os.read(0, 1)'
1004 ],
1005 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1006 stderr=subprocess.PIPE)
1007
1008 p2 = subprocess.Popen([sys.executable, "-c", """if True:
1009 import os, errno, sys
1010 for fd in %r:
1011 try:
1012 os.close(fd)
1013 except OSError as e:
1014 if e.errno != errno.EBADF:
1015 raise
1016 else:
1017 sys.exit(1)
1018 sys.exit(0)
1019 """ % [f.fileno() for f in (p1.stdin, p1.stdout,
1020 p1.stderr)]
1021 ],
1022 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1023 stderr=subprocess.PIPE, close_fds=False)
1024 p1.communicate('foo')
1025 _, stderr = p2.communicate()
1026
1027 self.assertEqual(p2.returncode, 0, "Unexpected error: " + repr(stderr))
1028
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001029
Florent Xiclunabab22a72010-03-04 19:40:48 +00001030@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +00001031class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +00001032
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001033 def test_startupinfo(self):
1034 # startupinfo argument
1035 # We uses hardcoded constants, because we do not want to
1036 # depend on win32all.
1037 STARTF_USESHOWWINDOW = 1
1038 SW_MAXIMIZE = 3
1039 startupinfo = subprocess.STARTUPINFO()
1040 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1041 startupinfo.wShowWindow = SW_MAXIMIZE
1042 # Since Python is a console process, it won't be affected
1043 # by wShowWindow, but the argument should be silently
1044 # ignored
1045 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001046 startupinfo=startupinfo)
1047
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001048 def test_creationflags(self):
1049 # creationflags argument
1050 CREATE_NEW_CONSOLE = 16
1051 sys.stderr.write(" a DOS box should flash briefly ...\n")
1052 subprocess.call(sys.executable +
1053 ' -c "import time; time.sleep(0.25)"',
1054 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001055
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001056 def test_invalid_args(self):
1057 # invalid arguments should raise ValueError
1058 self.assertRaises(ValueError, subprocess.call,
1059 [sys.executable, "-c",
1060 "import sys; sys.exit(47)"],
1061 preexec_fn=lambda: 1)
1062 self.assertRaises(ValueError, subprocess.call,
1063 [sys.executable, "-c",
1064 "import sys; sys.exit(47)"],
1065 stdout=subprocess.PIPE,
1066 close_fds=True)
1067
1068 def test_close_fds(self):
1069 # close file descriptors
1070 rc = subprocess.call([sys.executable, "-c",
1071 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001072 close_fds=True)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001073 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001074
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001075 def test_shell_sequence(self):
1076 # Run command through the shell (sequence)
1077 newenv = os.environ.copy()
1078 newenv["FRUIT"] = "physalis"
1079 p = subprocess.Popen(["set"], shell=1,
1080 stdout=subprocess.PIPE,
1081 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001082 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001083 self.assertIn("physalis", p.stdout.read())
Peter Astrand81a191b2007-05-26 22:18:20 +00001084
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001085 def test_shell_string(self):
1086 # Run command through the shell (string)
1087 newenv = os.environ.copy()
1088 newenv["FRUIT"] = "physalis"
1089 p = subprocess.Popen("set", shell=1,
1090 stdout=subprocess.PIPE,
1091 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001092 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001093 self.assertIn("physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001094
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001095 def test_call_string(self):
1096 # call() function with string argument on Windows
1097 rc = subprocess.call(sys.executable +
1098 ' -c "import sys; sys.exit(47)"')
1099 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001100
Florent Xiclunac0838642010-03-07 15:27:39 +00001101 def _kill_process(self, method, *args):
Florent Xicluna400efc22010-03-07 17:12:23 +00001102 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroudee00972010-09-24 19:00:29 +00001103 p = subprocess.Popen([sys.executable, "-c", """if 1:
1104 import sys, time
1105 sys.stdout.write('x\\n')
1106 sys.stdout.flush()
1107 time.sleep(30)
1108 """],
1109 stdin=subprocess.PIPE,
1110 stdout=subprocess.PIPE,
1111 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001112 self.addCleanup(p.stdout.close)
1113 self.addCleanup(p.stderr.close)
1114 self.addCleanup(p.stdin.close)
Antoine Pitroudee00972010-09-24 19:00:29 +00001115 # Wait for the interpreter to be completely initialized before
1116 # sending any signal.
1117 p.stdout.read(1)
1118 getattr(p, method)(*args)
Florent Xicluna446ff142010-03-23 15:05:30 +00001119 _, stderr = p.communicate()
1120 self.assertStderrEqual(stderr, '')
Antoine Pitroudee00972010-09-24 19:00:29 +00001121 returncode = p.wait()
Florent Xiclunafaf17532010-03-08 10:59:33 +00001122 self.assertNotEqual(returncode, 0)
Florent Xiclunac0838642010-03-07 15:27:39 +00001123
1124 def test_send_signal(self):
1125 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimese74c8f22008-04-19 02:23:57 +00001126
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001127 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001128 self._kill_process('kill')
Christian Heimese74c8f22008-04-19 02:23:57 +00001129
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001130 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +00001131 self._kill_process('terminate')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001132
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001133
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001134@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1135 "poll system call not supported")
1136class ProcessTestCaseNoPoll(ProcessTestCase):
1137 def setUp(self):
1138 subprocess._has_poll = False
1139 ProcessTestCase.setUp(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001140
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001141 def tearDown(self):
1142 subprocess._has_poll = True
1143 ProcessTestCase.tearDown(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001144
1145
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001146class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithc1baf4a2010-03-01 02:53:24 +00001147 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001148 def test_eintr_retry_call(self):
1149 record_calls = []
1150 def fake_os_func(*args):
1151 record_calls.append(args)
1152 if len(record_calls) == 2:
1153 raise OSError(errno.EINTR, "fake interrupted system call")
1154 return tuple(reversed(args))
1155
1156 self.assertEqual((999, 256),
1157 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1158 self.assertEqual([(256, 999)], record_calls)
1159 # This time there will be an EINTR so it will loop once.
1160 self.assertEqual((666,),
1161 subprocess._eintr_retry_call(fake_os_func, 666))
1162 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1163
Tim Golden8e4756c2010-08-12 11:00:35 +00001164@unittest.skipUnless(mswindows, "mswindows only")
1165class CommandsWithSpaces (BaseTestCase):
1166
1167 def setUp(self):
1168 super(CommandsWithSpaces, self).setUp()
1169 f, fname = mkstemp(".py", "te st")
1170 self.fname = fname.lower ()
1171 os.write(f, b"import sys;"
1172 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1173 )
1174 os.close(f)
1175
1176 def tearDown(self):
1177 os.remove(self.fname)
1178 super(CommandsWithSpaces, self).tearDown()
1179
1180 def with_spaces(self, *args, **kwargs):
1181 kwargs['stdout'] = subprocess.PIPE
1182 p = subprocess.Popen(*args, **kwargs)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001183 self.addCleanup(p.stdout.close)
Tim Golden8e4756c2010-08-12 11:00:35 +00001184 self.assertEqual(
1185 p.stdout.read ().decode("mbcs"),
1186 "2 [%r, 'ab cd']" % self.fname
1187 )
1188
1189 def test_shell_string_with_spaces(self):
1190 # call() function with string argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +00001191 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1192 "ab cd"), shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +00001193
1194 def test_shell_sequence_with_spaces(self):
1195 # call() function with sequence argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +00001196 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +00001197
1198 def test_noshell_string_with_spaces(self):
1199 # call() function with string argument with spaces on Windows
1200 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1201 "ab cd"))
1202
1203 def test_noshell_sequence_with_spaces(self):
1204 # call() function with sequence argument with spaces on Windows
1205 self.with_spaces([sys.executable, self.fname, "ab cd"])
1206
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001207def test_main():
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001208 unit_tests = (ProcessTestCase,
1209 POSIXProcessTestCase,
1210 Win32ProcessTestCase,
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001211 ProcessTestCaseNoPoll,
Tim Golden8e4756c2010-08-12 11:00:35 +00001212 HelperFunctionTests,
1213 CommandsWithSpaces)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001214
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001215 test_support.run_unittest(*unit_tests)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001216 test_support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001217
1218if __name__ == "__main__":
1219 test_main()