blob: 984a87971a8b8cdb1303058593e616c03fc8fd11 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003import subprocess
4import sys
5import signal
6import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00007import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008import tempfile
9import time
Tim Peters3761e8d2004-10-13 04:07:12 +000010import re
Ezio Melotti184bdfb2010-02-18 09:37:05 +000011import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000012import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000013import select
Gregory P. Smith32ec9da2010-03-19 16:53:08 +000014try:
15 import gc
16except ImportError:
17 gc = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000018
19mswindows = (sys.platform == "win32")
20
21#
22# Depends on the following external programs: Python
23#
24
25if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000026 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
27 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000028else:
29 SETBINARY = ''
30
Florent Xiclunab1e94e82010-02-27 22:12:37 +000031
32try:
33 mkstemp = tempfile.mkstemp
34except AttributeError:
35 # tempfile.mkstemp is not available
36 def mkstemp():
37 """Replacement for mkstemp, calling mktemp."""
38 fname = tempfile.mktemp()
39 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
40
Tim Peters3761e8d2004-10-13 04:07:12 +000041
Florent Xiclunac049d872010-03-27 22:47:23 +000042class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000043 def setUp(self):
44 # Try to minimize the number of children we have so this test
45 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000046 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000047
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000048 def tearDown(self):
49 for inst in subprocess._active:
50 inst.wait()
51 subprocess._cleanup()
52 self.assertFalse(subprocess._active, "subprocess._active not empty")
53
Florent Xiclunab1e94e82010-02-27 22:12:37 +000054 def assertStderrEqual(self, stderr, expected, msg=None):
55 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
56 # shutdown time. That frustrates tests trying to check stderr produced
57 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000058 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040059 # strip_python_stderr also strips whitespace, so we do too.
60 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000061 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000062
Florent Xiclunac049d872010-03-27 22:47:23 +000063
64class ProcessTestCase(BaseTestCase):
65
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000066 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000067 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000068 rc = subprocess.call([sys.executable, "-c",
69 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000070 self.assertEqual(rc, 47)
71
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040072 def test_call_timeout(self):
73 # call() function with timeout argument; we want to test that the child
74 # process gets killed when the timeout expires. If the child isn't
75 # killed, this call will deadlock since subprocess.call waits for the
76 # child.
77 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
78 [sys.executable, "-c", "while True: pass"],
79 timeout=0.1)
80
Peter Astrand454f7672005-01-01 09:36:35 +000081 def test_check_call_zero(self):
82 # check_call() function with zero return code
83 rc = subprocess.check_call([sys.executable, "-c",
84 "import sys; sys.exit(0)"])
85 self.assertEqual(rc, 0)
86
87 def test_check_call_nonzero(self):
88 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000089 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000090 subprocess.check_call([sys.executable, "-c",
91 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000092 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000093
Georg Brandlf9734072008-12-07 15:30:06 +000094 def test_check_output(self):
95 # check_output() function with zero return code
96 output = subprocess.check_output(
97 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000098 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000099
100 def test_check_output_nonzero(self):
101 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000102 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000103 subprocess.check_output(
104 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000105 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000106
107 def test_check_output_stderr(self):
108 # check_output() function stderr redirected to stdout
109 output = subprocess.check_output(
110 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
111 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000112 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000113
114 def test_check_output_stdout_arg(self):
115 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000116 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000117 output = subprocess.check_output(
118 [sys.executable, "-c", "print('will not be run')"],
119 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000120 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000121 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000122
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400123 def test_check_output_timeout(self):
124 # check_output() function with timeout arg
125 with self.assertRaises(subprocess.TimeoutExpired) as c:
126 output = subprocess.check_output(
127 [sys.executable, "-c",
128 "import sys; sys.stdout.write('BDFL')\n"
129 "sys.stdout.flush()\n"
130 "while True: pass"],
Reid Kleckner80b92d12011-03-14 13:34:12 -0400131 timeout=1.5)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400132 self.fail("Expected TimeoutExpired.")
133 self.assertEqual(c.exception.output, b'BDFL')
134
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000135 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000136 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000137 newenv = os.environ.copy()
138 newenv["FRUIT"] = "banana"
139 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000140 'import sys, os;'
141 'sys.exit(os.getenv("FRUIT")=="banana")'],
142 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000143 self.assertEqual(rc, 1)
144
145 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000146 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000147 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000148 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000149 self.addCleanup(p.stdout.close)
150 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000151 p.wait()
152 self.assertEqual(p.stdin, None)
153
154 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000155 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000156 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000157 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000158 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000159 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000160 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000161 self.addCleanup(p.stdin.close)
162 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000163 p.wait()
164 self.assertEqual(p.stdout, None)
165
166 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000167 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000168 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000169 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000170 self.addCleanup(p.stdout.close)
171 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000172 p.wait()
173 self.assertEqual(p.stderr, None)
174
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000175 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000176 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000177 p = subprocess.Popen(["somethingyoudonthave", "-c",
178 "import sys; sys.exit(47)"],
179 executable=sys.executable, cwd=python_dir)
180 p.wait()
181 self.assertEqual(p.returncode, 47)
182
183 @unittest.skipIf(sysconfig.is_python_build(),
184 "need an installed Python. See #7774")
185 def test_executable_without_cwd(self):
186 # For a normal installation, it should work without 'cwd'
187 # argument. For test runs in the build directory, see #7774.
188 p = subprocess.Popen(["somethingyoudonthave", "-c",
189 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000190 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000191 p.wait()
192 self.assertEqual(p.returncode, 47)
193
194 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000195 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000196 p = subprocess.Popen([sys.executable, "-c",
197 'import sys; sys.exit(sys.stdin.read() == "pear")'],
198 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000199 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000200 p.stdin.close()
201 p.wait()
202 self.assertEqual(p.returncode, 1)
203
204 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000205 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000206 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000207 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000208 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000209 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210 os.lseek(d, 0, 0)
211 p = subprocess.Popen([sys.executable, "-c",
212 'import sys; sys.exit(sys.stdin.read() == "pear")'],
213 stdin=d)
214 p.wait()
215 self.assertEqual(p.returncode, 1)
216
217 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000218 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000219 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000220 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000221 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000222 tf.seek(0)
223 p = subprocess.Popen([sys.executable, "-c",
224 'import sys; sys.exit(sys.stdin.read() == "pear")'],
225 stdin=tf)
226 p.wait()
227 self.assertEqual(p.returncode, 1)
228
229 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000230 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000231 p = subprocess.Popen([sys.executable, "-c",
232 'import sys; sys.stdout.write("orange")'],
233 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000234 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000235 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236
237 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000238 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000239 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000240 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000241 d = tf.fileno()
242 p = subprocess.Popen([sys.executable, "-c",
243 'import sys; sys.stdout.write("orange")'],
244 stdout=d)
245 p.wait()
246 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000247 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000248
249 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000250 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000251 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000252 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000253 p = subprocess.Popen([sys.executable, "-c",
254 'import sys; sys.stdout.write("orange")'],
255 stdout=tf)
256 p.wait()
257 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000258 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000259
260 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000261 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262 p = subprocess.Popen([sys.executable, "-c",
263 'import sys; sys.stderr.write("strawberry")'],
264 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000265 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000266 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000267
268 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000269 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000270 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000271 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000272 d = tf.fileno()
273 p = subprocess.Popen([sys.executable, "-c",
274 'import sys; sys.stderr.write("strawberry")'],
275 stderr=d)
276 p.wait()
277 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000278 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000279
280 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000281 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000282 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000283 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000284 p = subprocess.Popen([sys.executable, "-c",
285 'import sys; sys.stderr.write("strawberry")'],
286 stderr=tf)
287 p.wait()
288 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000289 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000290
291 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000292 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000294 'import sys;'
295 'sys.stdout.write("apple");'
296 'sys.stdout.flush();'
297 'sys.stderr.write("orange")'],
298 stdout=subprocess.PIPE,
299 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000300 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000301 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000302
303 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000304 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000305 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000306 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000307 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000308 'import sys;'
309 'sys.stdout.write("apple");'
310 'sys.stdout.flush();'
311 'sys.stderr.write("orange")'],
312 stdout=tf,
313 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000314 p.wait()
315 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000316 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000317
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318 def test_stdout_filedes_of_stdout(self):
319 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000320 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000321 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000322 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000323
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000324 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000325 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000326 # We cannot use os.path.realpath to canonicalize the path,
327 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
328 cwd = os.getcwd()
329 os.chdir(tmpdir)
330 tmpdir = os.getcwd()
331 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000332 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000333 'import sys,os;'
334 'sys.stdout.write(os.getcwd())'],
335 stdout=subprocess.PIPE,
336 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000337 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000338 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000339 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
340 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000341
342 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000343 newenv = os.environ.copy()
344 newenv["FRUIT"] = "orange"
345 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000346 'import sys,os;'
347 'sys.stdout.write(os.getenv("FRUIT"))'],
348 stdout=subprocess.PIPE,
349 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000350 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000351 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000352
Peter Astrandcbac93c2005-03-03 20:24:28 +0000353 def test_communicate_stdin(self):
354 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000355 'import sys;'
356 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000357 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000358 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000359 self.assertEqual(p.returncode, 1)
360
361 def test_communicate_stdout(self):
362 p = subprocess.Popen([sys.executable, "-c",
363 'import sys; sys.stdout.write("pineapple")'],
364 stdout=subprocess.PIPE)
365 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000366 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000367 self.assertEqual(stderr, None)
368
369 def test_communicate_stderr(self):
370 p = subprocess.Popen([sys.executable, "-c",
371 'import sys; sys.stderr.write("pineapple")'],
372 stderr=subprocess.PIPE)
373 (stdout, stderr) = p.communicate()
374 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000375 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000376
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000377 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000378 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000379 'import sys,os;'
380 'sys.stderr.write("pineapple");'
381 'sys.stdout.write(sys.stdin.read())'],
382 stdin=subprocess.PIPE,
383 stdout=subprocess.PIPE,
384 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000385 self.addCleanup(p.stdout.close)
386 self.addCleanup(p.stderr.close)
387 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000388 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000389 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000390 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000391
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400392 def test_communicate_timeout(self):
393 p = subprocess.Popen([sys.executable, "-c",
394 'import sys,os,time;'
395 'sys.stderr.write("pineapple\\n");'
396 'time.sleep(1);'
397 'sys.stderr.write("pear\\n");'
398 'sys.stdout.write(sys.stdin.read())'],
399 universal_newlines=True,
400 stdin=subprocess.PIPE,
401 stdout=subprocess.PIPE,
402 stderr=subprocess.PIPE)
403 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
404 timeout=0.3)
405 # Make sure we can keep waiting for it, and that we get the whole output
406 # after it completes.
407 (stdout, stderr) = p.communicate()
408 self.assertEqual(stdout, "banana")
409 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
410
411 def test_communicate_timeout_large_ouput(self):
412 # Test a expring timeout while the child is outputting lots of data.
413 p = subprocess.Popen([sys.executable, "-c",
414 'import sys,os,time;'
415 'sys.stdout.write("a" * (64 * 1024));'
416 'time.sleep(0.2);'
417 'sys.stdout.write("a" * (64 * 1024));'
418 'time.sleep(0.2);'
419 'sys.stdout.write("a" * (64 * 1024));'
420 'time.sleep(0.2);'
421 'sys.stdout.write("a" * (64 * 1024));'],
422 stdout=subprocess.PIPE)
423 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
424 (stdout, _) = p.communicate()
425 self.assertEqual(len(stdout), 4 * 64 * 1024)
426
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000427 # Test for the fd leak reported in http://bugs.python.org/issue2791.
428 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000429 for stdin_pipe in (False, True):
430 for stdout_pipe in (False, True):
431 for stderr_pipe in (False, True):
432 options = {}
433 if stdin_pipe:
434 options['stdin'] = subprocess.PIPE
435 if stdout_pipe:
436 options['stdout'] = subprocess.PIPE
437 if stderr_pipe:
438 options['stderr'] = subprocess.PIPE
439 if not options:
440 continue
441 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
442 p.communicate()
443 if p.stdin is not None:
444 self.assertTrue(p.stdin.closed)
445 if p.stdout is not None:
446 self.assertTrue(p.stdout.closed)
447 if p.stderr is not None:
448 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000449
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000450 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000451 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000452 p = subprocess.Popen([sys.executable, "-c",
453 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454 (stdout, stderr) = p.communicate()
455 self.assertEqual(stdout, None)
456 self.assertEqual(stderr, None)
457
458 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000459 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000460 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000461 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000462 x, y = os.pipe()
463 if mswindows:
464 pipe_buf = 512
465 else:
466 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
467 os.close(x)
468 os.close(y)
469 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000470 'import sys,os;'
471 'sys.stdout.write(sys.stdin.read(47));'
472 'sys.stderr.write("xyz"*%d);'
473 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
474 stdin=subprocess.PIPE,
475 stdout=subprocess.PIPE,
476 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000477 self.addCleanup(p.stdout.close)
478 self.addCleanup(p.stderr.close)
479 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000480 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481 (stdout, stderr) = p.communicate(string_to_write)
482 self.assertEqual(stdout, string_to_write)
483
484 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000485 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000486 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000487 'import sys,os;'
488 'sys.stdout.write(sys.stdin.read())'],
489 stdin=subprocess.PIPE,
490 stdout=subprocess.PIPE,
491 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000492 self.addCleanup(p.stdout.close)
493 self.addCleanup(p.stderr.close)
494 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000495 p.stdin.write(b"banana")
496 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000497 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000498 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000499
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000502 'import sys,os;' + SETBINARY +
503 'sys.stdout.write("line1\\n");'
504 'sys.stdout.flush();'
505 'sys.stdout.write("line2\\n");'
506 'sys.stdout.flush();'
507 'sys.stdout.write("line3\\r\\n");'
508 'sys.stdout.flush();'
509 'sys.stdout.write("line4\\r");'
510 'sys.stdout.flush();'
511 'sys.stdout.write("\\nline5");'
512 'sys.stdout.flush();'
513 'sys.stdout.write("\\nline6");'],
514 stdout=subprocess.PIPE,
515 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000516 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000518 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000519
520 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000521 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000523 'import sys,os;' + SETBINARY +
524 'sys.stdout.write("line1\\n");'
525 'sys.stdout.flush();'
526 'sys.stdout.write("line2\\n");'
527 'sys.stdout.flush();'
528 'sys.stdout.write("line3\\r\\n");'
529 'sys.stdout.flush();'
530 'sys.stdout.write("line4\\r");'
531 'sys.stdout.flush();'
532 'sys.stdout.write("\\nline5");'
533 'sys.stdout.flush();'
534 'sys.stdout.write("\\nline6");'],
535 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
536 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000537 self.addCleanup(p.stdout.close)
538 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000539 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000540 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000541
542 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000543 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000544 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000545 max_handles = 1026 # too much for most UNIX systems
546 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000547 max_handles = 2050 # too much for (at least some) Windows setups
548 handles = []
549 try:
550 for i in range(max_handles):
551 try:
552 handles.append(os.open(support.TESTFN,
553 os.O_WRONLY | os.O_CREAT))
554 except OSError as e:
555 if e.errno != errno.EMFILE:
556 raise
557 break
558 else:
559 self.skipTest("failed to reach the file descriptor limit "
560 "(tried %d)" % max_handles)
561 # Close a couple of them (should be enough for a subprocess)
562 for i in range(10):
563 os.close(handles.pop())
564 # Loop creating some subprocesses. If one of them leaks some fds,
565 # the next loop iteration will fail by reaching the max fd limit.
566 for i in range(15):
567 p = subprocess.Popen([sys.executable, "-c",
568 "import sys;"
569 "sys.stdout.write(sys.stdin.read())"],
570 stdin=subprocess.PIPE,
571 stdout=subprocess.PIPE,
572 stderr=subprocess.PIPE)
573 data = p.communicate(b"lime")[0]
574 self.assertEqual(data, b"lime")
575 finally:
576 for h in handles:
577 os.close(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578
579 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000580 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
581 '"a b c" d e')
582 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
583 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000584 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
585 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000586 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
587 'a\\\\\\b "de fg" h')
588 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
589 'a\\\\\\"b c d')
590 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
591 '"a\\\\b c" d e')
592 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
593 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000594 self.assertEqual(subprocess.list2cmdline(['ab', '']),
595 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596
597
598 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000599 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000600 "-c", "import time; time.sleep(1)"])
601 count = 0
602 while p.poll() is None:
603 time.sleep(0.1)
604 count += 1
605 # We expect that the poll loop probably went around about 10 times,
606 # but, based on system scheduling we can't control, it's possible
607 # poll() never returned None. It "should be" very rare that it
608 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000609 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000610 # Subsequent invocations should just return the returncode
611 self.assertEqual(p.poll(), 0)
612
613
614 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000615 p = subprocess.Popen([sys.executable,
616 "-c", "import time; time.sleep(2)"])
617 self.assertEqual(p.wait(), 0)
618 # Subsequent invocations should just return the returncode
619 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000620
Peter Astrand738131d2004-11-30 21:04:45 +0000621
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400622 def test_wait_timeout(self):
623 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400624 "-c", "import time; time.sleep(0.1)"])
625 self.assertRaises(subprocess.TimeoutExpired, p.wait, timeout=0.01)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400626 self.assertEqual(p.wait(timeout=2), 0)
627
628
Peter Astrand738131d2004-11-30 21:04:45 +0000629 def test_invalid_bufsize(self):
630 # an invalid type of the bufsize argument should raise
631 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000632 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000633 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000634
Guido van Rossum46a05a72007-06-07 21:56:45 +0000635 def test_bufsize_is_none(self):
636 # bufsize=None should be the same as bufsize=0.
637 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
638 self.assertEqual(p.wait(), 0)
639 # Again with keyword arg
640 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
641 self.assertEqual(p.wait(), 0)
642
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000643 def test_leaking_fds_on_error(self):
644 # see bug #5179: Popen leaks file descriptors to PIPEs if
645 # the child fails to execute; this will eventually exhaust
646 # the maximum number of open fds. 1024 seems a very common
647 # value for that limit, but Windows has 2048, so we loop
648 # 1024 times (each call leaked two fds).
649 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000650 # Windows raises IOError. Others raise OSError.
651 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000652 subprocess.Popen(['nonexisting_i_hope'],
653 stdout=subprocess.PIPE,
654 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400655 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400656 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000657 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000658
Victor Stinnerb3693582010-05-21 20:13:12 +0000659 def test_issue8780(self):
660 # Ensure that stdout is inherited from the parent
661 # if stdout=PIPE is not used
662 code = ';'.join((
663 'import subprocess, sys',
664 'retcode = subprocess.call('
665 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
666 'assert retcode == 0'))
667 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000668 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000669
Tim Goldenaf5ac392010-08-06 13:03:56 +0000670 def test_handles_closed_on_exception(self):
671 # If CreateProcess exits with an error, ensure the
672 # duplicate output handles are released
673 ifhandle, ifname = mkstemp()
674 ofhandle, ofname = mkstemp()
675 efhandle, efname = mkstemp()
676 try:
677 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
678 stderr=efhandle)
679 except OSError:
680 os.close(ifhandle)
681 os.remove(ifname)
682 os.close(ofhandle)
683 os.remove(ofname)
684 os.close(efhandle)
685 os.remove(efname)
686 self.assertFalse(os.path.exists(ifname))
687 self.assertFalse(os.path.exists(ofname))
688 self.assertFalse(os.path.exists(efname))
689
Tim Peterse718f612004-10-12 21:51:32 +0000690
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000691# context manager
692class _SuppressCoreFiles(object):
693 """Try to prevent core files from being created."""
694 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000695
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000696 def __enter__(self):
697 """Try to save previous ulimit, then set it to (0, 0)."""
698 try:
699 import resource
700 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
701 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
702 except (ImportError, ValueError, resource.error):
703 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000704
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000705 if sys.platform == 'darwin':
706 # Check if the 'Crash Reporter' on OSX was configured
707 # in 'Developer' mode and warn that it will get triggered
708 # when it is.
709 #
710 # This assumes that this context manager is used in tests
711 # that might trigger the next manager.
712 value = subprocess.Popen(['/usr/bin/defaults', 'read',
713 'com.apple.CrashReporter', 'DialogType'],
714 stdout=subprocess.PIPE).communicate()[0]
715 if value.strip() == b'developer':
716 print("this tests triggers the Crash Reporter, "
717 "that is intentional", end='')
718 sys.stdout.flush()
719
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000720 def __exit__(self, *args):
721 """Return core file behavior to default."""
722 if self.old_limit is None:
723 return
724 try:
725 import resource
726 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
727 except (ImportError, ValueError, resource.error):
728 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000729
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000730
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000731@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000732class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000733
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000734 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000735 nonexistent_dir = "/_this/pa.th/does/not/exist"
736 try:
737 os.chdir(nonexistent_dir)
738 except OSError as e:
739 # This avoids hard coding the errno value or the OS perror()
740 # string and instead capture the exception that we want to see
741 # below for comparison.
742 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000743 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000744 else:
745 self.fail("chdir to nonexistant directory %s succeeded." %
746 nonexistent_dir)
747
748 # Error in the child re-raised in the parent.
749 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000750 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000751 cwd=nonexistent_dir)
752 except OSError as e:
753 # Test that the child process chdir failure actually makes
754 # it up to the parent process as the correct exception.
755 self.assertEqual(desired_exception.errno, e.errno)
756 self.assertEqual(desired_exception.strerror, e.strerror)
757 else:
758 self.fail("Expected OSError: %s" % desired_exception)
759
760 def test_restore_signals(self):
761 # Code coverage for both values of restore_signals to make sure it
762 # at least does not blow up.
763 # A test for behavior would be complex. Contributions welcome.
764 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
765 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
766
767 def test_start_new_session(self):
768 # For code coverage of calling setsid(). We don't care if we get an
769 # EPERM error from it depending on the test execution environment, that
770 # still indicates that it was called.
771 try:
772 output = subprocess.check_output(
773 [sys.executable, "-c",
774 "import os; print(os.getpgid(os.getpid()))"],
775 start_new_session=True)
776 except OSError as e:
777 if e.errno != errno.EPERM:
778 raise
779 else:
780 parent_pgid = os.getpgid(os.getpid())
781 child_pgid = int(output)
782 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000783
784 def test_run_abort(self):
785 # returncode handles signal termination
786 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000787 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000788 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000789 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000790 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000791
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000792 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000793 # DISCLAIMER: Setting environment variables is *not* a good use
794 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000795 p = subprocess.Popen([sys.executable, "-c",
796 'import sys,os;'
797 'sys.stdout.write(os.getenv("FRUIT"))'],
798 stdout=subprocess.PIPE,
799 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000800 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000801 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000802
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000803 def test_preexec_exception(self):
804 def raise_it():
805 raise ValueError("What if two swallows carried a coconut?")
806 try:
807 p = subprocess.Popen([sys.executable, "-c", ""],
808 preexec_fn=raise_it)
809 except RuntimeError as e:
810 self.assertTrue(
811 subprocess._posixsubprocess,
812 "Expected a ValueError from the preexec_fn")
813 except ValueError as e:
814 self.assertIn("coconut", e.args[0])
815 else:
816 self.fail("Exception raised by preexec_fn did not make it "
817 "to the parent process.")
818
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000819 @unittest.skipUnless(gc, "Requires a gc module.")
820 def test_preexec_gc_module_failure(self):
821 # This tests the code that disables garbage collection if the child
822 # process will execute any Python.
823 def raise_runtime_error():
824 raise RuntimeError("this shouldn't escape")
825 enabled = gc.isenabled()
826 orig_gc_disable = gc.disable
827 orig_gc_isenabled = gc.isenabled
828 try:
829 gc.disable()
830 self.assertFalse(gc.isenabled())
831 subprocess.call([sys.executable, '-c', ''],
832 preexec_fn=lambda: None)
833 self.assertFalse(gc.isenabled(),
834 "Popen enabled gc when it shouldn't.")
835
836 gc.enable()
837 self.assertTrue(gc.isenabled())
838 subprocess.call([sys.executable, '-c', ''],
839 preexec_fn=lambda: None)
840 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
841
842 gc.disable = raise_runtime_error
843 self.assertRaises(RuntimeError, subprocess.Popen,
844 [sys.executable, '-c', ''],
845 preexec_fn=lambda: None)
846
847 del gc.isenabled # force an AttributeError
848 self.assertRaises(AttributeError, subprocess.Popen,
849 [sys.executable, '-c', ''],
850 preexec_fn=lambda: None)
851 finally:
852 gc.disable = orig_gc_disable
853 gc.isenabled = orig_gc_isenabled
854 if not enabled:
855 gc.disable()
856
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000857 def test_args_string(self):
858 # args is a string
859 fd, fname = mkstemp()
860 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000861 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000862 fobj.write("#!/bin/sh\n")
863 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
864 sys.executable)
865 os.chmod(fname, 0o700)
866 p = subprocess.Popen(fname)
867 p.wait()
868 os.remove(fname)
869 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000870
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000871 def test_invalid_args(self):
872 # invalid arguments should raise ValueError
873 self.assertRaises(ValueError, subprocess.call,
874 [sys.executable, "-c",
875 "import sys; sys.exit(47)"],
876 startupinfo=47)
877 self.assertRaises(ValueError, subprocess.call,
878 [sys.executable, "-c",
879 "import sys; sys.exit(47)"],
880 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000881
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000882 def test_shell_sequence(self):
883 # Run command through the shell (sequence)
884 newenv = os.environ.copy()
885 newenv["FRUIT"] = "apple"
886 p = subprocess.Popen(["echo $FRUIT"], shell=1,
887 stdout=subprocess.PIPE,
888 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000889 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000890 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000891
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000892 def test_shell_string(self):
893 # Run command through the shell (string)
894 newenv = os.environ.copy()
895 newenv["FRUIT"] = "apple"
896 p = subprocess.Popen("echo $FRUIT", shell=1,
897 stdout=subprocess.PIPE,
898 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000899 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000900 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000901
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000902 def test_call_string(self):
903 # call() function with string argument on UNIX
904 fd, fname = mkstemp()
905 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000906 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000907 fobj.write("#!/bin/sh\n")
908 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
909 sys.executable)
910 os.chmod(fname, 0o700)
911 rc = subprocess.call(fname)
912 os.remove(fname)
913 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000914
Stefan Krah9542cc62010-07-19 14:20:53 +0000915 def test_specific_shell(self):
916 # Issue #9265: Incorrect name passed as arg[0].
917 shells = []
918 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
919 for name in ['bash', 'ksh']:
920 sh = os.path.join(prefix, name)
921 if os.path.isfile(sh):
922 shells.append(sh)
923 if not shells: # Will probably work for any shell but csh.
924 self.skipTest("bash or ksh required for this test")
925 sh = '/bin/sh'
926 if os.path.isfile(sh) and not os.path.islink(sh):
927 # Test will fail if /bin/sh is a symlink to csh.
928 shells.append(sh)
929 for sh in shells:
930 p = subprocess.Popen("echo $0", executable=sh, shell=True,
931 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000932 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000933 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
934
Florent Xicluna4886d242010-03-08 13:27:26 +0000935 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000936 # Do not inherit file handles from the parent.
937 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000938 p = subprocess.Popen([sys.executable, "-c", """if 1:
939 import sys, time
940 sys.stdout.write('x\\n')
941 sys.stdout.flush()
942 time.sleep(30)
943 """],
944 close_fds=True,
945 stdin=subprocess.PIPE,
946 stdout=subprocess.PIPE,
947 stderr=subprocess.PIPE)
948 # Wait for the interpreter to be completely initialized before
949 # sending any signal.
950 p.stdout.read(1)
951 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000952 return p
953
954 def test_send_signal(self):
955 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000956 _, stderr = p.communicate()
957 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000958 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000959
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000960 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000961 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000962 _, stderr = p.communicate()
963 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000964 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000965
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000966 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000967 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000968 _, stderr = p.communicate()
969 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000970 self.assertEqual(p.wait(), -signal.SIGTERM)
971
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000972 def check_close_std_fds(self, fds):
973 # Issue #9905: test that subprocess pipes still work properly with
974 # some standard fds closed
975 stdin = 0
976 newfds = []
977 for a in fds:
978 b = os.dup(a)
979 newfds.append(b)
980 if a == 0:
981 stdin = b
982 try:
983 for fd in fds:
984 os.close(fd)
985 out, err = subprocess.Popen([sys.executable, "-c",
986 'import sys;'
987 'sys.stdout.write("apple");'
988 'sys.stdout.flush();'
989 'sys.stderr.write("orange")'],
990 stdin=stdin,
991 stdout=subprocess.PIPE,
992 stderr=subprocess.PIPE).communicate()
993 err = support.strip_python_stderr(err)
994 self.assertEqual((out, err), (b'apple', b'orange'))
995 finally:
996 for b, a in zip(newfds, fds):
997 os.dup2(b, a)
998 for b in newfds:
999 os.close(b)
1000
1001 def test_close_fd_0(self):
1002 self.check_close_std_fds([0])
1003
1004 def test_close_fd_1(self):
1005 self.check_close_std_fds([1])
1006
1007 def test_close_fd_2(self):
1008 self.check_close_std_fds([2])
1009
1010 def test_close_fds_0_1(self):
1011 self.check_close_std_fds([0, 1])
1012
1013 def test_close_fds_0_2(self):
1014 self.check_close_std_fds([0, 2])
1015
1016 def test_close_fds_1_2(self):
1017 self.check_close_std_fds([1, 2])
1018
1019 def test_close_fds_0_1_2(self):
1020 # Issue #10806: test that subprocess pipes still work properly with
1021 # all standard fds closed.
1022 self.check_close_std_fds([0, 1, 2])
1023
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001024 def test_remapping_std_fds(self):
1025 # open up some temporary files
1026 temps = [mkstemp() for i in range(3)]
1027 try:
1028 temp_fds = [fd for fd, fname in temps]
1029
1030 # unlink the files -- we won't need to reopen them
1031 for fd, fname in temps:
1032 os.unlink(fname)
1033
1034 # write some data to what will become stdin, and rewind
1035 os.write(temp_fds[1], b"STDIN")
1036 os.lseek(temp_fds[1], 0, 0)
1037
1038 # move the standard file descriptors out of the way
1039 saved_fds = [os.dup(fd) for fd in range(3)]
1040 try:
1041 # duplicate the file objects over the standard fd's
1042 for fd, temp_fd in enumerate(temp_fds):
1043 os.dup2(temp_fd, fd)
1044
1045 # now use those files in the "wrong" order, so that subprocess
1046 # has to rearrange them in the child
1047 p = subprocess.Popen([sys.executable, "-c",
1048 'import sys; got = sys.stdin.read();'
1049 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1050 stdin=temp_fds[1],
1051 stdout=temp_fds[2],
1052 stderr=temp_fds[0])
1053 p.wait()
1054 finally:
1055 # restore the original fd's underneath sys.stdin, etc.
1056 for std, saved in enumerate(saved_fds):
1057 os.dup2(saved, std)
1058 os.close(saved)
1059
1060 for fd in temp_fds:
1061 os.lseek(fd, 0, 0)
1062
1063 out = os.read(temp_fds[2], 1024)
1064 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1065 self.assertEqual(out, b"got STDIN")
1066 self.assertEqual(err, b"err")
1067
1068 finally:
1069 for fd in temp_fds:
1070 os.close(fd)
1071
Victor Stinner13bb71c2010-04-23 21:41:56 +00001072 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001073 def prepare():
1074 raise ValueError("surrogate:\uDCff")
1075
1076 try:
1077 subprocess.call(
1078 [sys.executable, "-c", "pass"],
1079 preexec_fn=prepare)
1080 except ValueError as err:
1081 # Pure Python implementations keeps the message
1082 self.assertIsNone(subprocess._posixsubprocess)
1083 self.assertEqual(str(err), "surrogate:\uDCff")
1084 except RuntimeError as err:
1085 # _posixsubprocess uses a default message
1086 self.assertIsNotNone(subprocess._posixsubprocess)
1087 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1088 else:
1089 self.fail("Expected ValueError or RuntimeError")
1090
Victor Stinner13bb71c2010-04-23 21:41:56 +00001091 def test_undecodable_env(self):
1092 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001093 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001094 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001095 env = os.environ.copy()
1096 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001097 # Use C locale to get ascii for the locale encoding to force
1098 # surrogate-escaping of \xFF in the child process; otherwise it can
1099 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001100 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001101 stdout = subprocess.check_output(
1102 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001103 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001104 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001105 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001106
1107 # test bytes
1108 key = key.encode("ascii", "surrogateescape")
1109 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001110 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001111 env = os.environ.copy()
1112 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001113 stdout = subprocess.check_output(
1114 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001115 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001116 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001117 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001118
Victor Stinnerb745a742010-05-18 17:17:23 +00001119 def test_bytes_program(self):
1120 abs_program = os.fsencode(sys.executable)
1121 path, program = os.path.split(sys.executable)
1122 program = os.fsencode(program)
1123
1124 # absolute bytes path
1125 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001126 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001127
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001128 # absolute bytes path as a string
1129 cmd = b"'" + abs_program + b"' -c pass"
1130 exitcode = subprocess.call(cmd, shell=True)
1131 self.assertEqual(exitcode, 0)
1132
Victor Stinnerb745a742010-05-18 17:17:23 +00001133 # bytes program, unicode PATH
1134 env = os.environ.copy()
1135 env["PATH"] = path
1136 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001137 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001138
1139 # bytes program, bytes PATH
1140 envb = os.environb.copy()
1141 envb[b"PATH"] = os.fsencode(path)
1142 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001143 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001144
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001145 def test_pipe_cloexec(self):
1146 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1147 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1148
1149 p1 = subprocess.Popen([sys.executable, sleeper],
1150 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1151 stderr=subprocess.PIPE, close_fds=False)
1152
1153 self.addCleanup(p1.communicate, b'')
1154
1155 p2 = subprocess.Popen([sys.executable, fd_status],
1156 stdout=subprocess.PIPE, close_fds=False)
1157
1158 output, error = p2.communicate()
1159 result_fds = set(map(int, output.split(b',')))
1160 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1161 p1.stderr.fileno()])
1162
1163 self.assertFalse(result_fds & unwanted_fds,
1164 "Expected no fds from %r to be open in child, "
1165 "found %r" %
1166 (unwanted_fds, result_fds & unwanted_fds))
1167
1168 def test_pipe_cloexec_real_tools(self):
1169 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1170 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1171
1172 subdata = b'zxcvbn'
1173 data = subdata * 4 + b'\n'
1174
1175 p1 = subprocess.Popen([sys.executable, qcat],
1176 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1177 close_fds=False)
1178
1179 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1180 stdin=p1.stdout, stdout=subprocess.PIPE,
1181 close_fds=False)
1182
1183 self.addCleanup(p1.wait)
1184 self.addCleanup(p2.wait)
1185 self.addCleanup(p1.terminate)
1186 self.addCleanup(p2.terminate)
1187
1188 p1.stdin.write(data)
1189 p1.stdin.close()
1190
1191 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1192
1193 self.assertTrue(readfiles, "The child hung")
1194 self.assertEqual(p2.stdout.read(), data)
1195
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001196 p1.stdout.close()
1197 p2.stdout.close()
1198
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001199 def test_close_fds(self):
1200 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1201
1202 fds = os.pipe()
1203 self.addCleanup(os.close, fds[0])
1204 self.addCleanup(os.close, fds[1])
1205
1206 open_fds = set(fds)
1207
1208 p = subprocess.Popen([sys.executable, fd_status],
1209 stdout=subprocess.PIPE, close_fds=False)
1210 output, ignored = p.communicate()
1211 remaining_fds = set(map(int, output.split(b',')))
1212
1213 self.assertEqual(remaining_fds & open_fds, open_fds,
1214 "Some fds were closed")
1215
1216 p = subprocess.Popen([sys.executable, fd_status],
1217 stdout=subprocess.PIPE, close_fds=True)
1218 output, ignored = p.communicate()
1219 remaining_fds = set(map(int, output.split(b',')))
1220
1221 self.assertFalse(remaining_fds & open_fds,
1222 "Some fds were left open")
1223 self.assertIn(1, remaining_fds, "Subprocess failed")
1224
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001225 def test_pass_fds(self):
1226 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1227
1228 open_fds = set()
1229
1230 for x in range(5):
1231 fds = os.pipe()
1232 self.addCleanup(os.close, fds[0])
1233 self.addCleanup(os.close, fds[1])
1234 open_fds.update(fds)
1235
1236 for fd in open_fds:
1237 p = subprocess.Popen([sys.executable, fd_status],
1238 stdout=subprocess.PIPE, close_fds=True,
1239 pass_fds=(fd, ))
1240 output, ignored = p.communicate()
1241
1242 remaining_fds = set(map(int, output.split(b',')))
1243 to_be_closed = open_fds - {fd}
1244
1245 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1246 self.assertFalse(remaining_fds & to_be_closed,
1247 "fd to be closed passed")
1248
1249 # pass_fds overrides close_fds with a warning.
1250 with self.assertWarns(RuntimeWarning) as context:
1251 self.assertFalse(subprocess.call(
1252 [sys.executable, "-c", "import sys; sys.exit(0)"],
1253 close_fds=False, pass_fds=(fd, )))
1254 self.assertIn('overriding close_fds', str(context.warning))
1255
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001256 def test_wait_when_sigchild_ignored(self):
1257 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1258 sigchild_ignore = support.findfile("sigchild_ignore.py",
1259 subdir="subprocessdata")
1260 p = subprocess.Popen([sys.executable, sigchild_ignore],
1261 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1262 stdout, stderr = p.communicate()
1263 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001264 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001265 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001266
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001267
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001268@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001269class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001270
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001271 def test_startupinfo(self):
1272 # startupinfo argument
1273 # We uses hardcoded constants, because we do not want to
1274 # depend on win32all.
1275 STARTF_USESHOWWINDOW = 1
1276 SW_MAXIMIZE = 3
1277 startupinfo = subprocess.STARTUPINFO()
1278 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1279 startupinfo.wShowWindow = SW_MAXIMIZE
1280 # Since Python is a console process, it won't be affected
1281 # by wShowWindow, but the argument should be silently
1282 # ignored
1283 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001284 startupinfo=startupinfo)
1285
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001286 def test_creationflags(self):
1287 # creationflags argument
1288 CREATE_NEW_CONSOLE = 16
1289 sys.stderr.write(" a DOS box should flash briefly ...\n")
1290 subprocess.call(sys.executable +
1291 ' -c "import time; time.sleep(0.25)"',
1292 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001293
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001294 def test_invalid_args(self):
1295 # invalid arguments should raise ValueError
1296 self.assertRaises(ValueError, subprocess.call,
1297 [sys.executable, "-c",
1298 "import sys; sys.exit(47)"],
1299 preexec_fn=lambda: 1)
1300 self.assertRaises(ValueError, subprocess.call,
1301 [sys.executable, "-c",
1302 "import sys; sys.exit(47)"],
1303 stdout=subprocess.PIPE,
1304 close_fds=True)
1305
1306 def test_close_fds(self):
1307 # close file descriptors
1308 rc = subprocess.call([sys.executable, "-c",
1309 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001310 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001311 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001312
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001313 def test_shell_sequence(self):
1314 # Run command through the shell (sequence)
1315 newenv = os.environ.copy()
1316 newenv["FRUIT"] = "physalis"
1317 p = subprocess.Popen(["set"], shell=1,
1318 stdout=subprocess.PIPE,
1319 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001320 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001321 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001322
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001323 def test_shell_string(self):
1324 # Run command through the shell (string)
1325 newenv = os.environ.copy()
1326 newenv["FRUIT"] = "physalis"
1327 p = subprocess.Popen("set", shell=1,
1328 stdout=subprocess.PIPE,
1329 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001330 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001331 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001332
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001333 def test_call_string(self):
1334 # call() function with string argument on Windows
1335 rc = subprocess.call(sys.executable +
1336 ' -c "import sys; sys.exit(47)"')
1337 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001338
Florent Xicluna4886d242010-03-08 13:27:26 +00001339 def _kill_process(self, method, *args):
1340 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001341 p = subprocess.Popen([sys.executable, "-c", """if 1:
1342 import sys, time
1343 sys.stdout.write('x\\n')
1344 sys.stdout.flush()
1345 time.sleep(30)
1346 """],
1347 stdin=subprocess.PIPE,
1348 stdout=subprocess.PIPE,
1349 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001350 self.addCleanup(p.stdout.close)
1351 self.addCleanup(p.stderr.close)
1352 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001353 # Wait for the interpreter to be completely initialized before
1354 # sending any signal.
1355 p.stdout.read(1)
1356 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001357 _, stderr = p.communicate()
1358 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001359 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001360 self.assertNotEqual(returncode, 0)
1361
1362 def test_send_signal(self):
1363 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001364
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001365 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001366 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001367
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001368 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001369 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001370
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001371
Brett Cannona23810f2008-05-26 19:04:21 +00001372# The module says:
1373# "NB This only works (and is only relevant) for UNIX."
1374#
1375# Actually, getoutput should work on any platform with an os.popen, but
1376# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001377@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001378class CommandTests(unittest.TestCase):
1379 def test_getoutput(self):
1380 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1381 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1382 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001383
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001384 # we use mkdtemp in the next line to create an empty directory
1385 # under our exclusive control; from that, we can invent a pathname
1386 # that we _know_ won't exist. This is guaranteed to fail.
1387 dir = None
1388 try:
1389 dir = tempfile.mkdtemp()
1390 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001391
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001392 status, output = subprocess.getstatusoutput('cat ' + name)
1393 self.assertNotEqual(status, 0)
1394 finally:
1395 if dir is not None:
1396 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001397
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001398
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001399@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1400 "poll system call not supported")
1401class ProcessTestCaseNoPoll(ProcessTestCase):
1402 def setUp(self):
1403 subprocess._has_poll = False
1404 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001405
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001406 def tearDown(self):
1407 subprocess._has_poll = True
1408 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001409
1410
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001411@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1412 "_posixsubprocess extension module not found.")
1413class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
1414 def setUp(self):
1415 subprocess._posixsubprocess = None
1416 ProcessTestCase.setUp(self)
1417 POSIXProcessTestCase.setUp(self)
1418
1419 def tearDown(self):
1420 subprocess._posixsubprocess = sys.modules['_posixsubprocess']
1421 POSIXProcessTestCase.tearDown(self)
1422 ProcessTestCase.tearDown(self)
1423
1424
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001425class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001426 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001427 def test_eintr_retry_call(self):
1428 record_calls = []
1429 def fake_os_func(*args):
1430 record_calls.append(args)
1431 if len(record_calls) == 2:
1432 raise OSError(errno.EINTR, "fake interrupted system call")
1433 return tuple(reversed(args))
1434
1435 self.assertEqual((999, 256),
1436 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1437 self.assertEqual([(256, 999)], record_calls)
1438 # This time there will be an EINTR so it will loop once.
1439 self.assertEqual((666,),
1440 subprocess._eintr_retry_call(fake_os_func, 666))
1441 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1442
1443
Tim Golden126c2962010-08-11 14:20:40 +00001444@unittest.skipUnless(mswindows, "Windows-specific tests")
1445class CommandsWithSpaces (BaseTestCase):
1446
1447 def setUp(self):
1448 super().setUp()
1449 f, fname = mkstemp(".py", "te st")
1450 self.fname = fname.lower ()
1451 os.write(f, b"import sys;"
1452 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1453 )
1454 os.close(f)
1455
1456 def tearDown(self):
1457 os.remove(self.fname)
1458 super().tearDown()
1459
1460 def with_spaces(self, *args, **kwargs):
1461 kwargs['stdout'] = subprocess.PIPE
1462 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001463 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001464 self.assertEqual(
1465 p.stdout.read ().decode("mbcs"),
1466 "2 [%r, 'ab cd']" % self.fname
1467 )
1468
1469 def test_shell_string_with_spaces(self):
1470 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001471 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1472 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001473
1474 def test_shell_sequence_with_spaces(self):
1475 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001476 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001477
1478 def test_noshell_string_with_spaces(self):
1479 # call() function with string argument with spaces on Windows
1480 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1481 "ab cd"))
1482
1483 def test_noshell_sequence_with_spaces(self):
1484 # call() function with sequence argument with spaces on Windows
1485 self.with_spaces([sys.executable, self.fname, "ab cd"])
1486
Brian Curtin79cdb662010-12-03 02:46:02 +00001487
1488class ContextManagerTests(ProcessTestCase):
1489
1490 def test_pipe(self):
1491 with subprocess.Popen([sys.executable, "-c",
1492 "import sys;"
1493 "sys.stdout.write('stdout');"
1494 "sys.stderr.write('stderr');"],
1495 stdout=subprocess.PIPE,
1496 stderr=subprocess.PIPE) as proc:
1497 self.assertEqual(proc.stdout.read(), b"stdout")
1498 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1499
1500 self.assertTrue(proc.stdout.closed)
1501 self.assertTrue(proc.stderr.closed)
1502
1503 def test_returncode(self):
1504 with subprocess.Popen([sys.executable, "-c",
1505 "import sys; sys.exit(100)"]) as proc:
1506 proc.wait()
1507 self.assertEqual(proc.returncode, 100)
1508
1509 def test_communicate_stdin(self):
1510 with subprocess.Popen([sys.executable, "-c",
1511 "import sys;"
1512 "sys.exit(sys.stdin.read() == 'context')"],
1513 stdin=subprocess.PIPE) as proc:
1514 proc.communicate(b"context")
1515 self.assertEqual(proc.returncode, 1)
1516
1517 def test_invalid_args(self):
1518 with self.assertRaises(EnvironmentError) as c:
1519 with subprocess.Popen(['nonexisting_i_hope'],
1520 stdout=subprocess.PIPE,
1521 stderr=subprocess.PIPE) as proc:
1522 pass
1523
1524 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1525 raise c.exception
1526
1527
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001528def test_main():
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001529 unit_tests = (ProcessTestCase,
1530 POSIXProcessTestCase,
1531 Win32ProcessTestCase,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001532 ProcessTestCasePOSIXPurePython,
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001533 CommandTests,
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001534 ProcessTestCaseNoPoll,
Tim Golden126c2962010-08-11 14:20:40 +00001535 HelperFunctionTests,
Brian Curtin79cdb662010-12-03 02:46:02 +00001536 CommandsWithSpaces,
Gregory P. Smithf5604852010-12-13 06:45:02 +00001537 ContextManagerTests)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001538
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001539 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +00001540 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001541
1542if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +00001543 test_main()