blob: 73c1b5c76b470d421f183439019cb17937d41ae3 [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)
119 with support.captured_stderr() as s:
120 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
667
Florent Xiclunabab22a72010-03-04 19:40:48 +0000668@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000669class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +0000670
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000671 def test_exceptions(self):
672 # caught & re-raised exceptions
673 with self.assertRaises(OSError) as c:
674 p = subprocess.Popen([sys.executable, "-c", ""],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000675 cwd="/this/path/does/not/exist")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000676 # The attribute child_traceback should contain "os.chdir" somewhere.
677 self.assertIn("os.chdir", c.exception.child_traceback)
Tim Peterse718f612004-10-12 21:51:32 +0000678
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000679 def test_run_abort(self):
680 # returncode handles signal termination
681 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000682 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000683 "import os; os.abort()"])
684 p.wait()
685 self.assertEqual(-p.returncode, signal.SIGABRT)
686
687 def test_preexec(self):
688 # preexec function
689 p = subprocess.Popen([sys.executable, "-c",
690 "import sys, os;"
691 "sys.stdout.write(os.getenv('FRUIT'))"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000692 stdout=subprocess.PIPE,
693 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtind117b562010-11-05 04:09:09 +0000694 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000695 self.assertEqual(p.stdout.read(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000696
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000697 def test_args_string(self):
698 # args is a string
699 f, fname = mkstemp()
700 os.write(f, "#!/bin/sh\n")
701 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
702 sys.executable)
703 os.close(f)
704 os.chmod(fname, 0o700)
705 p = subprocess.Popen(fname)
706 p.wait()
707 os.remove(fname)
708 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000709
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000710 def test_invalid_args(self):
711 # invalid arguments should raise ValueError
712 self.assertRaises(ValueError, subprocess.call,
713 [sys.executable, "-c",
714 "import sys; sys.exit(47)"],
715 startupinfo=47)
716 self.assertRaises(ValueError, subprocess.call,
717 [sys.executable, "-c",
718 "import sys; sys.exit(47)"],
719 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000720
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000721 def test_shell_sequence(self):
722 # Run command through the shell (sequence)
723 newenv = os.environ.copy()
724 newenv["FRUIT"] = "apple"
725 p = subprocess.Popen(["echo $FRUIT"], shell=1,
726 stdout=subprocess.PIPE,
727 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000728 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000729 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000731 def test_shell_string(self):
732 # Run command through the shell (string)
733 newenv = os.environ.copy()
734 newenv["FRUIT"] = "apple"
735 p = subprocess.Popen("echo $FRUIT", shell=1,
736 stdout=subprocess.PIPE,
737 env=newenv)
Brian Curtind117b562010-11-05 04:09:09 +0000738 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000739 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000740
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000741 def test_call_string(self):
742 # call() function with string argument on UNIX
743 f, fname = mkstemp()
744 os.write(f, "#!/bin/sh\n")
745 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
746 sys.executable)
747 os.close(f)
748 os.chmod(fname, 0700)
749 rc = subprocess.call(fname)
750 os.remove(fname)
751 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000752
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000753 def test_specific_shell(self):
754 # Issue #9265: Incorrect name passed as arg[0].
755 shells = []
756 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
757 for name in ['bash', 'ksh']:
758 sh = os.path.join(prefix, name)
759 if os.path.isfile(sh):
760 shells.append(sh)
761 if not shells: # Will probably work for any shell but csh.
762 self.skipTest("bash or ksh required for this test")
763 sh = '/bin/sh'
764 if os.path.isfile(sh) and not os.path.islink(sh):
765 # Test will fail if /bin/sh is a symlink to csh.
766 shells.append(sh)
767 for sh in shells:
768 p = subprocess.Popen("echo $0", executable=sh, shell=True,
769 stdout=subprocess.PIPE)
Brian Curtind117b562010-11-05 04:09:09 +0000770 self.addCleanup(p.stdout.close)
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000771 self.assertEqual(p.stdout.read().strip(), sh)
772
Florent Xiclunac0838642010-03-07 15:27:39 +0000773 def _kill_process(self, method, *args):
Florent Xiclunacecef392010-03-05 19:31:21 +0000774 # Do not inherit file handles from the parent.
775 # It should fix failures on some platforms.
Antoine Pitroua6166da2010-09-20 11:20:44 +0000776 p = subprocess.Popen([sys.executable, "-c", """if 1:
777 import sys, time
778 sys.stdout.write('x\\n')
779 sys.stdout.flush()
780 time.sleep(30)
781 """],
782 close_fds=True,
783 stdin=subprocess.PIPE,
784 stdout=subprocess.PIPE,
785 stderr=subprocess.PIPE)
786 # Wait for the interpreter to be completely initialized before
787 # sending any signal.
788 p.stdout.read(1)
789 getattr(p, method)(*args)
Florent Xiclunac0838642010-03-07 15:27:39 +0000790 return p
791
792 def test_send_signal(self):
793 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000794 _, stderr = p.communicate()
Florent Xicluna3c919cf2010-03-23 19:19:16 +0000795 self.assertIn('KeyboardInterrupt', stderr)
Florent Xicluna446ff142010-03-23 15:05:30 +0000796 self.assertNotEqual(p.wait(), 0)
Christian Heimese74c8f22008-04-19 02:23:57 +0000797
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000798 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000799 p = self._kill_process('kill')
Florent Xicluna446ff142010-03-23 15:05:30 +0000800 _, stderr = p.communicate()
801 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000802 self.assertEqual(p.wait(), -signal.SIGKILL)
Christian Heimese74c8f22008-04-19 02:23:57 +0000803
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000804 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000805 p = self._kill_process('terminate')
Florent Xicluna446ff142010-03-23 15:05:30 +0000806 _, stderr = p.communicate()
807 self.assertStderrEqual(stderr, '')
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000808 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000809
Antoine Pitrou91ce0d92011-01-03 18:45:09 +0000810 def check_close_std_fds(self, fds):
811 # Issue #9905: test that subprocess pipes still work properly with
812 # some standard fds closed
813 stdin = 0
814 newfds = []
815 for a in fds:
816 b = os.dup(a)
817 newfds.append(b)
818 if a == 0:
819 stdin = b
820 try:
821 for fd in fds:
822 os.close(fd)
823 out, err = subprocess.Popen([sys.executable, "-c",
824 'import sys;'
825 'sys.stdout.write("apple");'
826 'sys.stdout.flush();'
827 'sys.stderr.write("orange")'],
828 stdin=stdin,
829 stdout=subprocess.PIPE,
830 stderr=subprocess.PIPE).communicate()
831 err = test_support.strip_python_stderr(err)
832 self.assertEqual((out, err), (b'apple', b'orange'))
833 finally:
834 for b, a in zip(newfds, fds):
835 os.dup2(b, a)
836 for b in newfds:
837 os.close(b)
838
839 def test_close_fd_0(self):
840 self.check_close_std_fds([0])
841
842 def test_close_fd_1(self):
843 self.check_close_std_fds([1])
844
845 def test_close_fd_2(self):
846 self.check_close_std_fds([2])
847
848 def test_close_fds_0_1(self):
849 self.check_close_std_fds([0, 1])
850
851 def test_close_fds_0_2(self):
852 self.check_close_std_fds([0, 2])
853
854 def test_close_fds_1_2(self):
855 self.check_close_std_fds([1, 2])
856
857 def test_close_fds_0_1_2(self):
858 # Issue #10806: test that subprocess pipes still work properly with
859 # all standard fds closed.
860 self.check_close_std_fds([0, 1, 2])
861
Gregory P. Smith312efbc2010-12-14 15:02:53 +0000862 def test_wait_when_sigchild_ignored(self):
863 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
864 sigchild_ignore = test_support.findfile("sigchild_ignore.py",
865 subdir="subprocessdata")
866 p = subprocess.Popen([sys.executable, sigchild_ignore],
867 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
868 stdout, stderr = p.communicate()
869 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
870 " non-zero with this error:\n%s" % stderr)
871
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000872
Florent Xiclunabab22a72010-03-04 19:40:48 +0000873@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunafc4d6d72010-03-23 14:36:45 +0000874class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaab5e17f2010-03-04 21:31:58 +0000875
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000876 def test_startupinfo(self):
877 # startupinfo argument
878 # We uses hardcoded constants, because we do not want to
879 # depend on win32all.
880 STARTF_USESHOWWINDOW = 1
881 SW_MAXIMIZE = 3
882 startupinfo = subprocess.STARTUPINFO()
883 startupinfo.dwFlags = STARTF_USESHOWWINDOW
884 startupinfo.wShowWindow = SW_MAXIMIZE
885 # Since Python is a console process, it won't be affected
886 # by wShowWindow, but the argument should be silently
887 # ignored
888 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000889 startupinfo=startupinfo)
890
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000891 def test_creationflags(self):
892 # creationflags argument
893 CREATE_NEW_CONSOLE = 16
894 sys.stderr.write(" a DOS box should flash briefly ...\n")
895 subprocess.call(sys.executable +
896 ' -c "import time; time.sleep(0.25)"',
897 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000898
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000899 def test_invalid_args(self):
900 # invalid arguments should raise ValueError
901 self.assertRaises(ValueError, subprocess.call,
902 [sys.executable, "-c",
903 "import sys; sys.exit(47)"],
904 preexec_fn=lambda: 1)
905 self.assertRaises(ValueError, subprocess.call,
906 [sys.executable, "-c",
907 "import sys; sys.exit(47)"],
908 stdout=subprocess.PIPE,
909 close_fds=True)
910
911 def test_close_fds(self):
912 # close file descriptors
913 rc = subprocess.call([sys.executable, "-c",
914 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000915 close_fds=True)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000916 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000917
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000918 def test_shell_sequence(self):
919 # Run command through the shell (sequence)
920 newenv = os.environ.copy()
921 newenv["FRUIT"] = "physalis"
922 p = subprocess.Popen(["set"], shell=1,
923 stdout=subprocess.PIPE,
924 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000925 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000926 self.assertIn("physalis", p.stdout.read())
Peter Astrand81a191b2007-05-26 22:18:20 +0000927
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000928 def test_shell_string(self):
929 # Run command through the shell (string)
930 newenv = os.environ.copy()
931 newenv["FRUIT"] = "physalis"
932 p = subprocess.Popen("set", shell=1,
933 stdout=subprocess.PIPE,
934 env=newenv)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000935 self.addCleanup(p.stdout.close)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000936 self.assertIn("physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000937
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000938 def test_call_string(self):
939 # call() function with string argument on Windows
940 rc = subprocess.call(sys.executable +
941 ' -c "import sys; sys.exit(47)"')
942 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000943
Florent Xiclunac0838642010-03-07 15:27:39 +0000944 def _kill_process(self, method, *args):
Florent Xicluna400efc22010-03-07 17:12:23 +0000945 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroudee00972010-09-24 19:00:29 +0000946 p = subprocess.Popen([sys.executable, "-c", """if 1:
947 import sys, time
948 sys.stdout.write('x\\n')
949 sys.stdout.flush()
950 time.sleep(30)
951 """],
952 stdin=subprocess.PIPE,
953 stdout=subprocess.PIPE,
954 stderr=subprocess.PIPE)
Brian Curtin7fe045e2010-11-05 17:19:38 +0000955 self.addCleanup(p.stdout.close)
956 self.addCleanup(p.stderr.close)
957 self.addCleanup(p.stdin.close)
Antoine Pitroudee00972010-09-24 19:00:29 +0000958 # Wait for the interpreter to be completely initialized before
959 # sending any signal.
960 p.stdout.read(1)
961 getattr(p, method)(*args)
Florent Xicluna446ff142010-03-23 15:05:30 +0000962 _, stderr = p.communicate()
963 self.assertStderrEqual(stderr, '')
Antoine Pitroudee00972010-09-24 19:00:29 +0000964 returncode = p.wait()
Florent Xiclunafaf17532010-03-08 10:59:33 +0000965 self.assertNotEqual(returncode, 0)
Florent Xiclunac0838642010-03-07 15:27:39 +0000966
967 def test_send_signal(self):
968 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimese74c8f22008-04-19 02:23:57 +0000969
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000970 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000971 self._kill_process('kill')
Christian Heimese74c8f22008-04-19 02:23:57 +0000972
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000973 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000974 self._kill_process('terminate')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000975
Gregory P. Smithdd7ca242009-07-04 01:49:29 +0000976
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000977@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
978 "poll system call not supported")
979class ProcessTestCaseNoPoll(ProcessTestCase):
980 def setUp(self):
981 subprocess._has_poll = False
982 ProcessTestCase.setUp(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +0000983
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000984 def tearDown(self):
985 subprocess._has_poll = True
986 ProcessTestCase.tearDown(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +0000987
988
Gregory P. Smithcce211f2010-03-01 00:05:08 +0000989class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithc1baf4a2010-03-01 02:53:24 +0000990 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smithcce211f2010-03-01 00:05:08 +0000991 def test_eintr_retry_call(self):
992 record_calls = []
993 def fake_os_func(*args):
994 record_calls.append(args)
995 if len(record_calls) == 2:
996 raise OSError(errno.EINTR, "fake interrupted system call")
997 return tuple(reversed(args))
998
999 self.assertEqual((999, 256),
1000 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1001 self.assertEqual([(256, 999)], record_calls)
1002 # This time there will be an EINTR so it will loop once.
1003 self.assertEqual((666,),
1004 subprocess._eintr_retry_call(fake_os_func, 666))
1005 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1006
1007
Tim Golden8e4756c2010-08-12 11:00:35 +00001008@unittest.skipUnless(mswindows, "mswindows only")
1009class CommandsWithSpaces (BaseTestCase):
1010
1011 def setUp(self):
1012 super(CommandsWithSpaces, self).setUp()
1013 f, fname = mkstemp(".py", "te st")
1014 self.fname = fname.lower ()
1015 os.write(f, b"import sys;"
1016 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1017 )
1018 os.close(f)
1019
1020 def tearDown(self):
1021 os.remove(self.fname)
1022 super(CommandsWithSpaces, self).tearDown()
1023
1024 def with_spaces(self, *args, **kwargs):
1025 kwargs['stdout'] = subprocess.PIPE
1026 p = subprocess.Popen(*args, **kwargs)
Brian Curtin7fe045e2010-11-05 17:19:38 +00001027 self.addCleanup(p.stdout.close)
Tim Golden8e4756c2010-08-12 11:00:35 +00001028 self.assertEqual(
1029 p.stdout.read ().decode("mbcs"),
1030 "2 [%r, 'ab cd']" % self.fname
1031 )
1032
1033 def test_shell_string_with_spaces(self):
1034 # call() function with string argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +00001035 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1036 "ab cd"), shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +00001037
1038 def test_shell_sequence_with_spaces(self):
1039 # call() function with sequence argument with spaces on Windows
Brian Curtine8c49202010-08-13 21:01:52 +00001040 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden8e4756c2010-08-12 11:00:35 +00001041
1042 def test_noshell_string_with_spaces(self):
1043 # call() function with string argument with spaces on Windows
1044 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1045 "ab cd"))
1046
1047 def test_noshell_sequence_with_spaces(self):
1048 # call() function with sequence argument with spaces on Windows
1049 self.with_spaces([sys.executable, self.fname, "ab cd"])
1050
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001051def test_main():
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001052 unit_tests = (ProcessTestCase,
1053 POSIXProcessTestCase,
1054 Win32ProcessTestCase,
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001055 ProcessTestCaseNoPoll,
Tim Golden8e4756c2010-08-12 11:00:35 +00001056 HelperFunctionTests,
1057 CommandsWithSpaces)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001058
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001059 test_support.run_unittest(*unit_tests)
Florent Xicluna98e3fc32010-02-27 19:20:50 +00001060 test_support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001061
1062if __name__ == "__main__":
1063 test_main()