blob: 620cd8e5f35f14abdb4dc5d3205eef44eab67d36 [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
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04006import io
Andrew Svetlov82860712012-08-19 22:13:41 +03007import locale
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00009import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000010import tempfile
11import time
Tim Peters3761e8d2004-10-13 04:07:12 +000012import re
Ezio Melotti184bdfb2010-02-18 09:37:05 +000013import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000014import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000015import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040016import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050017import gc
Benjamin Peterson964561b2011-12-10 12:31:42 -050018
19try:
20 import resource
21except ImportError:
22 resource = None
23
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000024mswindows = (sys.platform == "win32")
25
26#
27# Depends on the following external programs: Python
28#
29
30if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000031 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
32 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000033else:
34 SETBINARY = ''
35
Florent Xiclunab1e94e82010-02-27 22:12:37 +000036
37try:
38 mkstemp = tempfile.mkstemp
39except AttributeError:
40 # tempfile.mkstemp is not available
41 def mkstemp():
42 """Replacement for mkstemp, calling mktemp."""
43 fname = tempfile.mktemp()
44 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
45
Tim Peters3761e8d2004-10-13 04:07:12 +000046
Florent Xiclunac049d872010-03-27 22:47:23 +000047class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000048 def setUp(self):
49 # Try to minimize the number of children we have so this test
50 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000051 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000052
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000053 def tearDown(self):
54 for inst in subprocess._active:
55 inst.wait()
56 subprocess._cleanup()
57 self.assertFalse(subprocess._active, "subprocess._active not empty")
58
Florent Xiclunab1e94e82010-02-27 22:12:37 +000059 def assertStderrEqual(self, stderr, expected, msg=None):
60 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
61 # shutdown time. That frustrates tests trying to check stderr produced
62 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000063 actual = support.strip_python_stderr(stderr)
Florent Xiclunab1e94e82010-02-27 22:12:37 +000064 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000065
Florent Xiclunac049d872010-03-27 22:47:23 +000066
67class ProcessTestCase(BaseTestCase):
68
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000069 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000070 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000071 rc = subprocess.call([sys.executable, "-c",
72 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000073 self.assertEqual(rc, 47)
74
Peter Astrand454f7672005-01-01 09:36:35 +000075 def test_check_call_zero(self):
76 # check_call() function with zero return code
77 rc = subprocess.check_call([sys.executable, "-c",
78 "import sys; sys.exit(0)"])
79 self.assertEqual(rc, 0)
80
81 def test_check_call_nonzero(self):
82 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000083 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000084 subprocess.check_call([sys.executable, "-c",
85 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000086 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000087
Georg Brandlf9734072008-12-07 15:30:06 +000088 def test_check_output(self):
89 # check_output() function with zero return code
90 output = subprocess.check_output(
91 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000092 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000093
94 def test_check_output_nonzero(self):
95 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000096 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +000097 subprocess.check_output(
98 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000099 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000100
101 def test_check_output_stderr(self):
102 # check_output() function stderr redirected to stdout
103 output = subprocess.check_output(
104 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
105 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000106 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000107
108 def test_check_output_stdout_arg(self):
109 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000110 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000111 output = subprocess.check_output(
112 [sys.executable, "-c", "print('will not be run')"],
113 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000114 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000115 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000116
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000117 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000118 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000119 newenv = os.environ.copy()
120 newenv["FRUIT"] = "banana"
121 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000122 'import sys, os;'
123 'sys.exit(os.getenv("FRUIT")=="banana")'],
124 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000125 self.assertEqual(rc, 1)
126
Victor Stinner87b9bc32011-06-01 00:57:47 +0200127 def test_invalid_args(self):
128 # Popen() called with invalid arguments should raise TypeError
129 # but Popen.__del__ should not complain (issue #12085)
130 with support.captured_stderr() as s:
131 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
132 argcount = subprocess.Popen.__init__.__code__.co_argcount
133 too_many_args = [0] * (argcount + 1)
134 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
135 self.assertEqual(s.getvalue(), '')
136
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000137 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000138 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000139 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000141 self.addCleanup(p.stdout.close)
142 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000143 p.wait()
144 self.assertEqual(p.stdin, None)
145
146 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000147 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000148 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000149 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000150 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000151 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000152 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000153 self.addCleanup(p.stdin.close)
154 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000155 p.wait()
156 self.assertEqual(p.stdout, None)
157
158 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000159 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000160 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000161 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000162 self.addCleanup(p.stdout.close)
163 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000164 p.wait()
165 self.assertEqual(p.stderr, None)
166
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000167 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000168 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000169 p = subprocess.Popen(["somethingyoudonthave", "-c",
170 "import sys; sys.exit(47)"],
171 executable=sys.executable, cwd=python_dir)
172 p.wait()
173 self.assertEqual(p.returncode, 47)
174
175 @unittest.skipIf(sysconfig.is_python_build(),
176 "need an installed Python. See #7774")
177 def test_executable_without_cwd(self):
178 # For a normal installation, it should work without 'cwd'
179 # argument. For test runs in the build directory, see #7774.
180 p = subprocess.Popen(["somethingyoudonthave", "-c",
181 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000182 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000183 p.wait()
184 self.assertEqual(p.returncode, 47)
185
186 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000187 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000188 p = subprocess.Popen([sys.executable, "-c",
189 'import sys; sys.exit(sys.stdin.read() == "pear")'],
190 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000191 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000192 p.stdin.close()
193 p.wait()
194 self.assertEqual(p.returncode, 1)
195
196 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000197 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000198 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000199 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000200 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000201 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000202 os.lseek(d, 0, 0)
203 p = subprocess.Popen([sys.executable, "-c",
204 'import sys; sys.exit(sys.stdin.read() == "pear")'],
205 stdin=d)
206 p.wait()
207 self.assertEqual(p.returncode, 1)
208
209 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000210 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000211 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000212 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000213 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000214 tf.seek(0)
215 p = subprocess.Popen([sys.executable, "-c",
216 'import sys; sys.exit(sys.stdin.read() == "pear")'],
217 stdin=tf)
218 p.wait()
219 self.assertEqual(p.returncode, 1)
220
221 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000222 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223 p = subprocess.Popen([sys.executable, "-c",
224 'import sys; sys.stdout.write("orange")'],
225 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000226 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000227 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000228
229 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000230 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000231 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000232 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233 d = tf.fileno()
234 p = subprocess.Popen([sys.executable, "-c",
235 'import sys; sys.stdout.write("orange")'],
236 stdout=d)
237 p.wait()
238 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000239 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000240
241 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000242 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000243 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000244 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 p = subprocess.Popen([sys.executable, "-c",
246 'import sys; sys.stdout.write("orange")'],
247 stdout=tf)
248 p.wait()
249 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000250 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251
252 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000253 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000254 p = subprocess.Popen([sys.executable, "-c",
255 'import sys; sys.stderr.write("strawberry")'],
256 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000257 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000258 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000259
260 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000261 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000262 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000263 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000264 d = tf.fileno()
265 p = subprocess.Popen([sys.executable, "-c",
266 'import sys; sys.stderr.write("strawberry")'],
267 stderr=d)
268 p.wait()
269 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000270 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271
272 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000273 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000274 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000275 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276 p = subprocess.Popen([sys.executable, "-c",
277 'import sys; sys.stderr.write("strawberry")'],
278 stderr=tf)
279 p.wait()
280 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000281 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282
283 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000284 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000286 'import sys;'
287 'sys.stdout.write("apple");'
288 'sys.stdout.flush();'
289 'sys.stderr.write("orange")'],
290 stdout=subprocess.PIPE,
291 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000292 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000293 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294
295 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000296 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000297 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000298 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000299 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000300 'import sys;'
301 'sys.stdout.write("apple");'
302 'sys.stdout.flush();'
303 'sys.stderr.write("orange")'],
304 stdout=tf,
305 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306 p.wait()
307 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000308 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309
Thomas Wouters89f507f2006-12-13 04:49:30 +0000310 def test_stdout_filedes_of_stdout(self):
311 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000312 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000313 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000314 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000315
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000316 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000317 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000318 # We cannot use os.path.realpath to canonicalize the path,
319 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
320 cwd = os.getcwd()
321 os.chdir(tmpdir)
322 tmpdir = os.getcwd()
323 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000324 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000325 'import sys,os;'
326 'sys.stdout.write(os.getcwd())'],
327 stdout=subprocess.PIPE,
328 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000329 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000330 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000331 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
332 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000333
334 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000335 newenv = os.environ.copy()
336 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200337 with subprocess.Popen([sys.executable, "-c",
338 'import sys,os;'
339 'sys.stdout.write(os.getenv("FRUIT"))'],
340 stdout=subprocess.PIPE,
341 env=newenv) as p:
342 stdout, stderr = p.communicate()
343 self.assertEqual(stdout, b"orange")
344
Victor Stinner62d51182011-06-23 01:02:25 +0200345 # Windows requires at least the SYSTEMROOT environment variable to start
346 # Python
347 @unittest.skipIf(sys.platform == 'win32',
348 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200349 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200350 'the python library cannot be loaded '
351 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200352 def test_empty_env(self):
353 with subprocess.Popen([sys.executable, "-c",
354 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200355 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200356 stdout=subprocess.PIPE,
357 env={}) as p:
358 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200359 self.assertIn(stdout.strip(),
360 (b"[]",
361 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
362 # environment
363 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000364
Peter Astrandcbac93c2005-03-03 20:24:28 +0000365 def test_communicate_stdin(self):
366 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000367 'import sys;'
368 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000369 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000370 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000371 self.assertEqual(p.returncode, 1)
372
373 def test_communicate_stdout(self):
374 p = subprocess.Popen([sys.executable, "-c",
375 'import sys; sys.stdout.write("pineapple")'],
376 stdout=subprocess.PIPE)
377 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000378 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000379 self.assertEqual(stderr, None)
380
381 def test_communicate_stderr(self):
382 p = subprocess.Popen([sys.executable, "-c",
383 'import sys; sys.stderr.write("pineapple")'],
384 stderr=subprocess.PIPE)
385 (stdout, stderr) = p.communicate()
386 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000387 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000388
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000389 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000391 'import sys,os;'
392 'sys.stderr.write("pineapple");'
393 'sys.stdout.write(sys.stdin.read())'],
394 stdin=subprocess.PIPE,
395 stdout=subprocess.PIPE,
396 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000397 self.addCleanup(p.stdout.close)
398 self.addCleanup(p.stderr.close)
399 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000400 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000401 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000402 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000403
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000404 # Test for the fd leak reported in http://bugs.python.org/issue2791.
405 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000406 for stdin_pipe in (False, True):
407 for stdout_pipe in (False, True):
408 for stderr_pipe in (False, True):
409 options = {}
410 if stdin_pipe:
411 options['stdin'] = subprocess.PIPE
412 if stdout_pipe:
413 options['stdout'] = subprocess.PIPE
414 if stderr_pipe:
415 options['stderr'] = subprocess.PIPE
416 if not options:
417 continue
418 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
419 p.communicate()
420 if p.stdin is not None:
421 self.assertTrue(p.stdin.closed)
422 if p.stdout is not None:
423 self.assertTrue(p.stdout.closed)
424 if p.stderr is not None:
425 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000426
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000427 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000428 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000429 p = subprocess.Popen([sys.executable, "-c",
430 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000431 (stdout, stderr) = p.communicate()
432 self.assertEqual(stdout, None)
433 self.assertEqual(stderr, None)
434
435 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000436 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000437 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000438 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000439 x, y = os.pipe()
440 if mswindows:
441 pipe_buf = 512
442 else:
443 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
444 os.close(x)
445 os.close(y)
446 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000447 'import sys,os;'
448 'sys.stdout.write(sys.stdin.read(47));'
449 'sys.stderr.write("xyz"*%d);'
450 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
451 stdin=subprocess.PIPE,
452 stdout=subprocess.PIPE,
453 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000454 self.addCleanup(p.stdout.close)
455 self.addCleanup(p.stderr.close)
456 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000457 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000458 (stdout, stderr) = p.communicate(string_to_write)
459 self.assertEqual(stdout, string_to_write)
460
461 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000462 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000464 'import sys,os;'
465 'sys.stdout.write(sys.stdin.read())'],
466 stdin=subprocess.PIPE,
467 stdout=subprocess.PIPE,
468 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000469 self.addCleanup(p.stdout.close)
470 self.addCleanup(p.stderr.close)
471 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000472 p.stdin.write(b"banana")
473 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000474 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000475 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000476
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000477 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000479 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200480 'buf = sys.stdout.buffer;'
481 'buf.write(sys.stdin.readline().encode());'
482 'buf.flush();'
483 'buf.write(b"line2\\n");'
484 'buf.flush();'
485 'buf.write(sys.stdin.read().encode());'
486 'buf.flush();'
487 'buf.write(b"line4\\n");'
488 'buf.flush();'
489 'buf.write(b"line5\\r\\n");'
490 'buf.flush();'
491 'buf.write(b"line6\\r");'
492 'buf.flush();'
493 'buf.write(b"\\nline7");'
494 'buf.flush();'
495 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200496 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000497 stdout=subprocess.PIPE,
498 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200499 p.stdin.write("line1\n")
500 self.assertEqual(p.stdout.readline(), "line1\n")
501 p.stdin.write("line3\n")
502 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000503 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200504 self.assertEqual(p.stdout.readline(),
505 "line2\n")
506 self.assertEqual(p.stdout.read(6),
507 "line3\n")
508 self.assertEqual(p.stdout.read(),
509 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000510
511 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000512 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000513 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000514 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200515 'buf = sys.stdout.buffer;'
516 'buf.write(b"line2\\n");'
517 'buf.flush();'
518 'buf.write(b"line4\\n");'
519 'buf.flush();'
520 'buf.write(b"line5\\r\\n");'
521 'buf.flush();'
522 'buf.write(b"line6\\r");'
523 'buf.flush();'
524 'buf.write(b"\\nline7");'
525 'buf.flush();'
526 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200527 stderr=subprocess.PIPE,
528 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000529 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000530 self.addCleanup(p.stdout.close)
531 self.addCleanup(p.stderr.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200532 # BUG: can't give a non-empty stdin because it breaks both the
533 # select- and poll-based communicate() implementations.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200535 self.assertEqual(stdout,
536 "line2\nline4\nline5\nline6\nline7\nline8")
537
538 def test_universal_newlines_communicate_stdin(self):
539 # universal newlines through communicate(), with only stdin
540 p = subprocess.Popen([sys.executable, "-c",
541 'import sys,os;' + SETBINARY + '''\nif True:
542 s = sys.stdin.readline()
543 assert s == "line1\\n", repr(s)
544 s = sys.stdin.read()
545 assert s == "line3\\n", repr(s)
546 '''],
547 stdin=subprocess.PIPE,
548 universal_newlines=1)
549 (stdout, stderr) = p.communicate("line1\nline3\n")
550 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551
Andrew Svetlovf3765072012-08-14 18:35:17 +0300552 def test_universal_newlines_communicate_input_none(self):
553 # Test communicate(input=None) with universal newlines.
554 #
555 # We set stdout to PIPE because, as of this writing, a different
556 # code path is tested when the number of pipes is zero or one.
557 p = subprocess.Popen([sys.executable, "-c", "pass"],
558 stdin=subprocess.PIPE,
559 stdout=subprocess.PIPE,
560 universal_newlines=True)
561 p.communicate()
562 self.assertEqual(p.returncode, 0)
563
Andrew Svetlov82860712012-08-19 22:13:41 +0300564 def test_universal_newlines_communicate_encodings(self):
565 # Check that universal newlines mode works for various encodings,
566 # in particular for encodings in the UTF-16 and UTF-32 families.
567 # See issue #15595.
568 #
569 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
570 # without, and UTF-16 and UTF-32.
571 for encoding in ['utf-16', 'utf-32-be']:
572 old_getpreferredencoding = locale.getpreferredencoding
573 # Indirectly via io.TextIOWrapper, Popen() defaults to
574 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
575 # locale.getpreferredencoding().
576 def getpreferredencoding(do_setlocale=True):
577 return encoding
578 code = ("import sys; "
579 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
580 encoding)
581 args = [sys.executable, '-c', code]
582 try:
583 locale.getpreferredencoding = getpreferredencoding
584 # We set stdin to be non-None because, as of this writing,
585 # a different code path is used when the number of pipes is
586 # zero or one.
587 popen = subprocess.Popen(args, universal_newlines=True,
588 stdin=subprocess.PIPE,
589 stdout=subprocess.PIPE)
590 stdout, stderr = popen.communicate(input='')
591 finally:
592 locale.getpreferredencoding = old_getpreferredencoding
593
594 self.assertEqual(stdout, '1\n2\n3\n4')
595
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000597 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000598 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000599 max_handles = 1026 # too much for most UNIX systems
600 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000601 max_handles = 2050 # too much for (at least some) Windows setups
602 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400603 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000604 try:
605 for i in range(max_handles):
606 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400607 tmpfile = os.path.join(tmpdir, support.TESTFN)
608 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000609 except OSError as e:
610 if e.errno != errno.EMFILE:
611 raise
612 break
613 else:
614 self.skipTest("failed to reach the file descriptor limit "
615 "(tried %d)" % max_handles)
616 # Close a couple of them (should be enough for a subprocess)
617 for i in range(10):
618 os.close(handles.pop())
619 # Loop creating some subprocesses. If one of them leaks some fds,
620 # the next loop iteration will fail by reaching the max fd limit.
621 for i in range(15):
622 p = subprocess.Popen([sys.executable, "-c",
623 "import sys;"
624 "sys.stdout.write(sys.stdin.read())"],
625 stdin=subprocess.PIPE,
626 stdout=subprocess.PIPE,
627 stderr=subprocess.PIPE)
628 data = p.communicate(b"lime")[0]
629 self.assertEqual(data, b"lime")
630 finally:
631 for h in handles:
632 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400633 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000634
635 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000636 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
637 '"a b c" d e')
638 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
639 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000640 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
641 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000642 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
643 'a\\\\\\b "de fg" h')
644 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
645 'a\\\\\\"b c d')
646 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
647 '"a\\\\b c" d e')
648 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
649 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000650 self.assertEqual(subprocess.list2cmdline(['ab', '']),
651 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000652
653
654 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000655 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000656 "-c", "import time; time.sleep(1)"])
657 count = 0
658 while p.poll() is None:
659 time.sleep(0.1)
660 count += 1
661 # We expect that the poll loop probably went around about 10 times,
662 # but, based on system scheduling we can't control, it's possible
663 # poll() never returned None. It "should be" very rare that it
664 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000665 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000666 # Subsequent invocations should just return the returncode
667 self.assertEqual(p.poll(), 0)
668
669
670 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000671 p = subprocess.Popen([sys.executable,
672 "-c", "import time; time.sleep(2)"])
673 self.assertEqual(p.wait(), 0)
674 # Subsequent invocations should just return the returncode
675 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000676
Peter Astrand738131d2004-11-30 21:04:45 +0000677
678 def test_invalid_bufsize(self):
679 # an invalid type of the bufsize argument should raise
680 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000681 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000682 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000683
Guido van Rossum46a05a72007-06-07 21:56:45 +0000684 def test_bufsize_is_none(self):
685 # bufsize=None should be the same as bufsize=0.
686 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
687 self.assertEqual(p.wait(), 0)
688 # Again with keyword arg
689 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
690 self.assertEqual(p.wait(), 0)
691
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000692 def test_leaking_fds_on_error(self):
693 # see bug #5179: Popen leaks file descriptors to PIPEs if
694 # the child fails to execute; this will eventually exhaust
695 # the maximum number of open fds. 1024 seems a very common
696 # value for that limit, but Windows has 2048, so we loop
697 # 1024 times (each call leaked two fds).
698 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000699 # Windows raises IOError. Others raise OSError.
700 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000701 subprocess.Popen(['nonexisting_i_hope'],
702 stdout=subprocess.PIPE,
703 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400704 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400705 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000706 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000707
Victor Stinnerb3693582010-05-21 20:13:12 +0000708 def test_issue8780(self):
709 # Ensure that stdout is inherited from the parent
710 # if stdout=PIPE is not used
711 code = ';'.join((
712 'import subprocess, sys',
713 'retcode = subprocess.call('
714 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
715 'assert retcode == 0'))
716 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000717 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000718
Tim Goldenaf5ac392010-08-06 13:03:56 +0000719 def test_handles_closed_on_exception(self):
720 # If CreateProcess exits with an error, ensure the
721 # duplicate output handles are released
722 ifhandle, ifname = mkstemp()
723 ofhandle, ofname = mkstemp()
724 efhandle, efname = mkstemp()
725 try:
726 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
727 stderr=efhandle)
728 except OSError:
729 os.close(ifhandle)
730 os.remove(ifname)
731 os.close(ofhandle)
732 os.remove(ofname)
733 os.close(efhandle)
734 os.remove(efname)
735 self.assertFalse(os.path.exists(ifname))
736 self.assertFalse(os.path.exists(ofname))
737 self.assertFalse(os.path.exists(efname))
738
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200739 def test_communicate_epipe(self):
740 # Issue 10963: communicate() should hide EPIPE
741 p = subprocess.Popen([sys.executable, "-c", 'pass'],
742 stdin=subprocess.PIPE,
743 stdout=subprocess.PIPE,
744 stderr=subprocess.PIPE)
745 self.addCleanup(p.stdout.close)
746 self.addCleanup(p.stderr.close)
747 self.addCleanup(p.stdin.close)
748 p.communicate(b"x" * 2**20)
749
750 def test_communicate_epipe_only_stdin(self):
751 # Issue 10963: communicate() should hide EPIPE
752 p = subprocess.Popen([sys.executable, "-c", 'pass'],
753 stdin=subprocess.PIPE)
754 self.addCleanup(p.stdin.close)
755 time.sleep(2)
756 p.communicate(b"x" * 2**20)
757
Victor Stinner1848db82011-07-05 14:49:46 +0200758 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
759 "Requires signal.SIGALRM")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200760 def test_communicate_eintr(self):
761 # Issue #12493: communicate() should handle EINTR
762 def handler(signum, frame):
763 pass
764 old_handler = signal.signal(signal.SIGALRM, handler)
765 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
766
767 # the process is running for 2 seconds
768 args = [sys.executable, "-c", 'import time; time.sleep(2)']
769 for stream in ('stdout', 'stderr'):
770 kw = {stream: subprocess.PIPE}
771 with subprocess.Popen(args, **kw) as process:
772 signal.alarm(1)
773 # communicate() will be interrupted by SIGALRM
774 process.communicate()
775
Tim Peterse718f612004-10-12 21:51:32 +0000776
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000777# context manager
778class _SuppressCoreFiles(object):
779 """Try to prevent core files from being created."""
780 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000781
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000782 def __enter__(self):
783 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500784 if resource is not None:
785 try:
786 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
787 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
788 except (ValueError, resource.error):
789 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000790
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000791 if sys.platform == 'darwin':
792 # Check if the 'Crash Reporter' on OSX was configured
793 # in 'Developer' mode and warn that it will get triggered
794 # when it is.
795 #
796 # This assumes that this context manager is used in tests
797 # that might trigger the next manager.
798 value = subprocess.Popen(['/usr/bin/defaults', 'read',
799 'com.apple.CrashReporter', 'DialogType'],
800 stdout=subprocess.PIPE).communicate()[0]
801 if value.strip() == b'developer':
802 print("this tests triggers the Crash Reporter, "
803 "that is intentional", end='')
804 sys.stdout.flush()
805
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000806 def __exit__(self, *args):
807 """Return core file behavior to default."""
808 if self.old_limit is None:
809 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500810 if resource is not None:
811 try:
812 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
813 except (ValueError, resource.error):
814 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000815
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000816
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000817@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000818class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000819
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000820 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000821 nonexistent_dir = "/_this/pa.th/does/not/exist"
822 try:
823 os.chdir(nonexistent_dir)
824 except OSError as e:
825 # This avoids hard coding the errno value or the OS perror()
826 # string and instead capture the exception that we want to see
827 # below for comparison.
828 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000829 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000830 else:
831 self.fail("chdir to nonexistant directory %s succeeded." %
832 nonexistent_dir)
833
834 # Error in the child re-raised in the parent.
835 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000836 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000837 cwd=nonexistent_dir)
838 except OSError as e:
839 # Test that the child process chdir failure actually makes
840 # it up to the parent process as the correct exception.
841 self.assertEqual(desired_exception.errno, e.errno)
842 self.assertEqual(desired_exception.strerror, e.strerror)
843 else:
844 self.fail("Expected OSError: %s" % desired_exception)
845
846 def test_restore_signals(self):
847 # Code coverage for both values of restore_signals to make sure it
848 # at least does not blow up.
849 # A test for behavior would be complex. Contributions welcome.
850 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
851 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
852
853 def test_start_new_session(self):
854 # For code coverage of calling setsid(). We don't care if we get an
855 # EPERM error from it depending on the test execution environment, that
856 # still indicates that it was called.
857 try:
858 output = subprocess.check_output(
859 [sys.executable, "-c",
860 "import os; print(os.getpgid(os.getpid()))"],
861 start_new_session=True)
862 except OSError as e:
863 if e.errno != errno.EPERM:
864 raise
865 else:
866 parent_pgid = os.getpgid(os.getpid())
867 child_pgid = int(output)
868 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000869
870 def test_run_abort(self):
871 # returncode handles signal termination
872 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000873 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000874 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000875 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000876 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000877
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000878 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000879 # DISCLAIMER: Setting environment variables is *not* a good use
880 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000881 p = subprocess.Popen([sys.executable, "-c",
882 'import sys,os;'
883 'sys.stdout.write(os.getenv("FRUIT"))'],
884 stdout=subprocess.PIPE,
885 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000886 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000887 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000888
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000889 def test_preexec_exception(self):
890 def raise_it():
891 raise ValueError("What if two swallows carried a coconut?")
892 try:
893 p = subprocess.Popen([sys.executable, "-c", ""],
894 preexec_fn=raise_it)
895 except RuntimeError as e:
896 self.assertTrue(
897 subprocess._posixsubprocess,
898 "Expected a ValueError from the preexec_fn")
899 except ValueError as e:
900 self.assertIn("coconut", e.args[0])
901 else:
902 self.fail("Exception raised by preexec_fn did not make it "
903 "to the parent process.")
904
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000905 def test_preexec_gc_module_failure(self):
906 # This tests the code that disables garbage collection if the child
907 # process will execute any Python.
908 def raise_runtime_error():
909 raise RuntimeError("this shouldn't escape")
910 enabled = gc.isenabled()
911 orig_gc_disable = gc.disable
912 orig_gc_isenabled = gc.isenabled
913 try:
914 gc.disable()
915 self.assertFalse(gc.isenabled())
916 subprocess.call([sys.executable, '-c', ''],
917 preexec_fn=lambda: None)
918 self.assertFalse(gc.isenabled(),
919 "Popen enabled gc when it shouldn't.")
920
921 gc.enable()
922 self.assertTrue(gc.isenabled())
923 subprocess.call([sys.executable, '-c', ''],
924 preexec_fn=lambda: None)
925 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
926
927 gc.disable = raise_runtime_error
928 self.assertRaises(RuntimeError, subprocess.Popen,
929 [sys.executable, '-c', ''],
930 preexec_fn=lambda: None)
931
932 del gc.isenabled # force an AttributeError
933 self.assertRaises(AttributeError, subprocess.Popen,
934 [sys.executable, '-c', ''],
935 preexec_fn=lambda: None)
936 finally:
937 gc.disable = orig_gc_disable
938 gc.isenabled = orig_gc_isenabled
939 if not enabled:
940 gc.disable()
941
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000942 def test_args_string(self):
943 # args is a string
944 fd, fname = mkstemp()
945 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000946 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000947 fobj.write("#!/bin/sh\n")
948 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
949 sys.executable)
950 os.chmod(fname, 0o700)
951 p = subprocess.Popen(fname)
952 p.wait()
953 os.remove(fname)
954 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000955
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000956 def test_invalid_args(self):
957 # invalid arguments should raise ValueError
958 self.assertRaises(ValueError, subprocess.call,
959 [sys.executable, "-c",
960 "import sys; sys.exit(47)"],
961 startupinfo=47)
962 self.assertRaises(ValueError, subprocess.call,
963 [sys.executable, "-c",
964 "import sys; sys.exit(47)"],
965 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000966
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000967 def test_shell_sequence(self):
968 # Run command through the shell (sequence)
969 newenv = os.environ.copy()
970 newenv["FRUIT"] = "apple"
971 p = subprocess.Popen(["echo $FRUIT"], shell=1,
972 stdout=subprocess.PIPE,
973 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000974 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000975 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000976
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000977 def test_shell_string(self):
978 # Run command through the shell (string)
979 newenv = os.environ.copy()
980 newenv["FRUIT"] = "apple"
981 p = subprocess.Popen("echo $FRUIT", shell=1,
982 stdout=subprocess.PIPE,
983 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000984 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000985 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000986
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000987 def test_call_string(self):
988 # call() function with string argument on UNIX
989 fd, fname = mkstemp()
990 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000991 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000992 fobj.write("#!/bin/sh\n")
993 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
994 sys.executable)
995 os.chmod(fname, 0o700)
996 rc = subprocess.call(fname)
997 os.remove(fname)
998 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000999
Stefan Krah9542cc62010-07-19 14:20:53 +00001000 def test_specific_shell(self):
1001 # Issue #9265: Incorrect name passed as arg[0].
1002 shells = []
1003 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1004 for name in ['bash', 'ksh']:
1005 sh = os.path.join(prefix, name)
1006 if os.path.isfile(sh):
1007 shells.append(sh)
1008 if not shells: # Will probably work for any shell but csh.
1009 self.skipTest("bash or ksh required for this test")
1010 sh = '/bin/sh'
1011 if os.path.isfile(sh) and not os.path.islink(sh):
1012 # Test will fail if /bin/sh is a symlink to csh.
1013 shells.append(sh)
1014 for sh in shells:
1015 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1016 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001017 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001018 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1019
Florent Xicluna4886d242010-03-08 13:27:26 +00001020 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001021 # Do not inherit file handles from the parent.
1022 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001023 p = subprocess.Popen([sys.executable, "-c", """if 1:
1024 import sys, time
1025 sys.stdout.write('x\\n')
1026 sys.stdout.flush()
1027 time.sleep(30)
1028 """],
1029 close_fds=True,
1030 stdin=subprocess.PIPE,
1031 stdout=subprocess.PIPE,
1032 stderr=subprocess.PIPE)
1033 # Wait for the interpreter to be completely initialized before
1034 # sending any signal.
1035 p.stdout.read(1)
1036 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001037 return p
1038
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001039 def _kill_dead_process(self, method, *args):
1040 # Do not inherit file handles from the parent.
1041 # It should fix failures on some platforms.
1042 p = subprocess.Popen([sys.executable, "-c", """if 1:
1043 import sys, time
1044 sys.stdout.write('x\\n')
1045 sys.stdout.flush()
1046 """],
1047 close_fds=True,
1048 stdin=subprocess.PIPE,
1049 stdout=subprocess.PIPE,
1050 stderr=subprocess.PIPE)
1051 # Wait for the interpreter to be completely initialized before
1052 # sending any signal.
1053 p.stdout.read(1)
1054 # The process should end after this
1055 time.sleep(1)
1056 # This shouldn't raise even though the child is now dead
1057 getattr(p, method)(*args)
1058 p.communicate()
1059
Florent Xicluna4886d242010-03-08 13:27:26 +00001060 def test_send_signal(self):
1061 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001062 _, stderr = p.communicate()
1063 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001064 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001065
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001066 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001067 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001068 _, stderr = p.communicate()
1069 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001070 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001071
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001072 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001073 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001074 _, stderr = p.communicate()
1075 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001076 self.assertEqual(p.wait(), -signal.SIGTERM)
1077
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001078 def test_send_signal_dead(self):
1079 # Sending a signal to a dead process
1080 self._kill_dead_process('send_signal', signal.SIGINT)
1081
1082 def test_kill_dead(self):
1083 # Killing a dead process
1084 self._kill_dead_process('kill')
1085
1086 def test_terminate_dead(self):
1087 # Terminating a dead process
1088 self._kill_dead_process('terminate')
1089
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001090 def check_close_std_fds(self, fds):
1091 # Issue #9905: test that subprocess pipes still work properly with
1092 # some standard fds closed
1093 stdin = 0
1094 newfds = []
1095 for a in fds:
1096 b = os.dup(a)
1097 newfds.append(b)
1098 if a == 0:
1099 stdin = b
1100 try:
1101 for fd in fds:
1102 os.close(fd)
1103 out, err = subprocess.Popen([sys.executable, "-c",
1104 'import sys;'
1105 'sys.stdout.write("apple");'
1106 'sys.stdout.flush();'
1107 'sys.stderr.write("orange")'],
1108 stdin=stdin,
1109 stdout=subprocess.PIPE,
1110 stderr=subprocess.PIPE).communicate()
1111 err = support.strip_python_stderr(err)
1112 self.assertEqual((out, err), (b'apple', b'orange'))
1113 finally:
1114 for b, a in zip(newfds, fds):
1115 os.dup2(b, a)
1116 for b in newfds:
1117 os.close(b)
1118
1119 def test_close_fd_0(self):
1120 self.check_close_std_fds([0])
1121
1122 def test_close_fd_1(self):
1123 self.check_close_std_fds([1])
1124
1125 def test_close_fd_2(self):
1126 self.check_close_std_fds([2])
1127
1128 def test_close_fds_0_1(self):
1129 self.check_close_std_fds([0, 1])
1130
1131 def test_close_fds_0_2(self):
1132 self.check_close_std_fds([0, 2])
1133
1134 def test_close_fds_1_2(self):
1135 self.check_close_std_fds([1, 2])
1136
1137 def test_close_fds_0_1_2(self):
1138 # Issue #10806: test that subprocess pipes still work properly with
1139 # all standard fds closed.
1140 self.check_close_std_fds([0, 1, 2])
1141
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001142 def test_remapping_std_fds(self):
1143 # open up some temporary files
1144 temps = [mkstemp() for i in range(3)]
1145 try:
1146 temp_fds = [fd for fd, fname in temps]
1147
1148 # unlink the files -- we won't need to reopen them
1149 for fd, fname in temps:
1150 os.unlink(fname)
1151
1152 # write some data to what will become stdin, and rewind
1153 os.write(temp_fds[1], b"STDIN")
1154 os.lseek(temp_fds[1], 0, 0)
1155
1156 # move the standard file descriptors out of the way
1157 saved_fds = [os.dup(fd) for fd in range(3)]
1158 try:
1159 # duplicate the file objects over the standard fd's
1160 for fd, temp_fd in enumerate(temp_fds):
1161 os.dup2(temp_fd, fd)
1162
1163 # now use those files in the "wrong" order, so that subprocess
1164 # has to rearrange them in the child
1165 p = subprocess.Popen([sys.executable, "-c",
1166 'import sys; got = sys.stdin.read();'
1167 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1168 stdin=temp_fds[1],
1169 stdout=temp_fds[2],
1170 stderr=temp_fds[0])
1171 p.wait()
1172 finally:
1173 # restore the original fd's underneath sys.stdin, etc.
1174 for std, saved in enumerate(saved_fds):
1175 os.dup2(saved, std)
1176 os.close(saved)
1177
1178 for fd in temp_fds:
1179 os.lseek(fd, 0, 0)
1180
1181 out = os.read(temp_fds[2], 1024)
1182 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1183 self.assertEqual(out, b"got STDIN")
1184 self.assertEqual(err, b"err")
1185
1186 finally:
1187 for fd in temp_fds:
1188 os.close(fd)
1189
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001190 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1191 # open up some temporary files
1192 temps = [mkstemp() for i in range(3)]
1193 temp_fds = [fd for fd, fname in temps]
1194 try:
1195 # unlink the files -- we won't need to reopen them
1196 for fd, fname in temps:
1197 os.unlink(fname)
1198
1199 # save a copy of the standard file descriptors
1200 saved_fds = [os.dup(fd) for fd in range(3)]
1201 try:
1202 # duplicate the temp files over the standard fd's 0, 1, 2
1203 for fd, temp_fd in enumerate(temp_fds):
1204 os.dup2(temp_fd, fd)
1205
1206 # write some data to what will become stdin, and rewind
1207 os.write(stdin_no, b"STDIN")
1208 os.lseek(stdin_no, 0, 0)
1209
1210 # now use those files in the given order, so that subprocess
1211 # has to rearrange them in the child
1212 p = subprocess.Popen([sys.executable, "-c",
1213 'import sys; got = sys.stdin.read();'
1214 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1215 stdin=stdin_no,
1216 stdout=stdout_no,
1217 stderr=stderr_no)
1218 p.wait()
1219
1220 for fd in temp_fds:
1221 os.lseek(fd, 0, 0)
1222
1223 out = os.read(stdout_no, 1024)
1224 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1225 finally:
1226 for std, saved in enumerate(saved_fds):
1227 os.dup2(saved, std)
1228 os.close(saved)
1229
1230 self.assertEqual(out, b"got STDIN")
1231 self.assertEqual(err, b"err")
1232
1233 finally:
1234 for fd in temp_fds:
1235 os.close(fd)
1236
1237 # When duping fds, if there arises a situation where one of the fds is
1238 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1239 # This tests all combinations of this.
1240 def test_swap_fds(self):
1241 self.check_swap_fds(0, 1, 2)
1242 self.check_swap_fds(0, 2, 1)
1243 self.check_swap_fds(1, 0, 2)
1244 self.check_swap_fds(1, 2, 0)
1245 self.check_swap_fds(2, 0, 1)
1246 self.check_swap_fds(2, 1, 0)
1247
Victor Stinner13bb71c2010-04-23 21:41:56 +00001248 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001249 def prepare():
1250 raise ValueError("surrogate:\uDCff")
1251
1252 try:
1253 subprocess.call(
1254 [sys.executable, "-c", "pass"],
1255 preexec_fn=prepare)
1256 except ValueError as err:
1257 # Pure Python implementations keeps the message
1258 self.assertIsNone(subprocess._posixsubprocess)
1259 self.assertEqual(str(err), "surrogate:\uDCff")
1260 except RuntimeError as err:
1261 # _posixsubprocess uses a default message
1262 self.assertIsNotNone(subprocess._posixsubprocess)
1263 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1264 else:
1265 self.fail("Expected ValueError or RuntimeError")
1266
Victor Stinner13bb71c2010-04-23 21:41:56 +00001267 def test_undecodable_env(self):
1268 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001269 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001270 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001271 env = os.environ.copy()
1272 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001273 # Use C locale to get ascii for the locale encoding to force
1274 # surrogate-escaping of \xFF in the child process; otherwise it can
1275 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001276 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001277 stdout = subprocess.check_output(
1278 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001279 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001280 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001281 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001282
1283 # test bytes
1284 key = key.encode("ascii", "surrogateescape")
1285 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001286 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001287 env = os.environ.copy()
1288 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001289 stdout = subprocess.check_output(
1290 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001291 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001292 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001293 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001294
Victor Stinnerb745a742010-05-18 17:17:23 +00001295 def test_bytes_program(self):
1296 abs_program = os.fsencode(sys.executable)
1297 path, program = os.path.split(sys.executable)
1298 program = os.fsencode(program)
1299
1300 # absolute bytes path
1301 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001302 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001303
1304 # bytes program, unicode PATH
1305 env = os.environ.copy()
1306 env["PATH"] = path
1307 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001308 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001309
1310 # bytes program, bytes PATH
1311 envb = os.environb.copy()
1312 envb[b"PATH"] = os.fsencode(path)
1313 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001314 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001315
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001316 def test_pipe_cloexec(self):
1317 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1318 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1319
1320 p1 = subprocess.Popen([sys.executable, sleeper],
1321 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1322 stderr=subprocess.PIPE, close_fds=False)
1323
1324 self.addCleanup(p1.communicate, b'')
1325
1326 p2 = subprocess.Popen([sys.executable, fd_status],
1327 stdout=subprocess.PIPE, close_fds=False)
1328
1329 output, error = p2.communicate()
1330 result_fds = set(map(int, output.split(b',')))
1331 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1332 p1.stderr.fileno()])
1333
1334 self.assertFalse(result_fds & unwanted_fds,
1335 "Expected no fds from %r to be open in child, "
1336 "found %r" %
1337 (unwanted_fds, result_fds & unwanted_fds))
1338
1339 def test_pipe_cloexec_real_tools(self):
1340 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1341 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1342
1343 subdata = b'zxcvbn'
1344 data = subdata * 4 + b'\n'
1345
1346 p1 = subprocess.Popen([sys.executable, qcat],
1347 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1348 close_fds=False)
1349
1350 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1351 stdin=p1.stdout, stdout=subprocess.PIPE,
1352 close_fds=False)
1353
1354 self.addCleanup(p1.wait)
1355 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001356 def kill_p1():
1357 try:
1358 p1.terminate()
1359 except ProcessLookupError:
1360 pass
1361 def kill_p2():
1362 try:
1363 p2.terminate()
1364 except ProcessLookupError:
1365 pass
1366 self.addCleanup(kill_p1)
1367 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001368
1369 p1.stdin.write(data)
1370 p1.stdin.close()
1371
1372 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1373
1374 self.assertTrue(readfiles, "The child hung")
1375 self.assertEqual(p2.stdout.read(), data)
1376
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001377 p1.stdout.close()
1378 p2.stdout.close()
1379
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001380 def test_close_fds(self):
1381 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1382
1383 fds = os.pipe()
1384 self.addCleanup(os.close, fds[0])
1385 self.addCleanup(os.close, fds[1])
1386
1387 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001388 # add a bunch more fds
1389 for _ in range(9):
1390 fd = os.open("/dev/null", os.O_RDONLY)
1391 self.addCleanup(os.close, fd)
1392 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001393
1394 p = subprocess.Popen([sys.executable, fd_status],
1395 stdout=subprocess.PIPE, close_fds=False)
1396 output, ignored = p.communicate()
1397 remaining_fds = set(map(int, output.split(b',')))
1398
1399 self.assertEqual(remaining_fds & open_fds, open_fds,
1400 "Some fds were closed")
1401
1402 p = subprocess.Popen([sys.executable, fd_status],
1403 stdout=subprocess.PIPE, close_fds=True)
1404 output, ignored = p.communicate()
1405 remaining_fds = set(map(int, output.split(b',')))
1406
1407 self.assertFalse(remaining_fds & open_fds,
1408 "Some fds were left open")
1409 self.assertIn(1, remaining_fds, "Subprocess failed")
1410
Gregory P. Smith8facece2012-01-21 14:01:08 -08001411 # Keep some of the fd's we opened open in the subprocess.
1412 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1413 fds_to_keep = set(open_fds.pop() for _ in range(8))
1414 p = subprocess.Popen([sys.executable, fd_status],
1415 stdout=subprocess.PIPE, close_fds=True,
1416 pass_fds=())
1417 output, ignored = p.communicate()
1418 remaining_fds = set(map(int, output.split(b',')))
1419
1420 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1421 "Some fds not in pass_fds were left open")
1422 self.assertIn(1, remaining_fds, "Subprocess failed")
1423
Victor Stinner88701e22011-06-01 13:13:04 +02001424 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1425 # descriptor of a pipe closed in the parent process is valid in the
1426 # child process according to fstat(), but the mode of the file
1427 # descriptor is invalid, and read or write raise an error.
1428 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001429 def test_pass_fds(self):
1430 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1431
1432 open_fds = set()
1433
1434 for x in range(5):
1435 fds = os.pipe()
1436 self.addCleanup(os.close, fds[0])
1437 self.addCleanup(os.close, fds[1])
1438 open_fds.update(fds)
1439
1440 for fd in open_fds:
1441 p = subprocess.Popen([sys.executable, fd_status],
1442 stdout=subprocess.PIPE, close_fds=True,
1443 pass_fds=(fd, ))
1444 output, ignored = p.communicate()
1445
1446 remaining_fds = set(map(int, output.split(b',')))
1447 to_be_closed = open_fds - {fd}
1448
1449 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1450 self.assertFalse(remaining_fds & to_be_closed,
1451 "fd to be closed passed")
1452
1453 # pass_fds overrides close_fds with a warning.
1454 with self.assertWarns(RuntimeWarning) as context:
1455 self.assertFalse(subprocess.call(
1456 [sys.executable, "-c", "import sys; sys.exit(0)"],
1457 close_fds=False, pass_fds=(fd, )))
1458 self.assertIn('overriding close_fds', str(context.warning))
1459
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001460 def test_stdout_stdin_are_single_inout_fd(self):
1461 with io.open(os.devnull, "r+") as inout:
1462 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1463 stdout=inout, stdin=inout)
1464 p.wait()
1465
1466 def test_stdout_stderr_are_single_inout_fd(self):
1467 with io.open(os.devnull, "r+") as inout:
1468 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1469 stdout=inout, stderr=inout)
1470 p.wait()
1471
1472 def test_stderr_stdin_are_single_inout_fd(self):
1473 with io.open(os.devnull, "r+") as inout:
1474 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1475 stderr=inout, stdin=inout)
1476 p.wait()
1477
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001478 def test_wait_when_sigchild_ignored(self):
1479 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1480 sigchild_ignore = support.findfile("sigchild_ignore.py",
1481 subdir="subprocessdata")
1482 p = subprocess.Popen([sys.executable, sigchild_ignore],
1483 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1484 stdout, stderr = p.communicate()
1485 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001486 " non-zero with this error:\n%s" %
1487 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001488
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001489 def test_select_unbuffered(self):
1490 # Issue #11459: bufsize=0 should really set the pipes as
1491 # unbuffered (and therefore let select() work properly).
1492 select = support.import_module("select")
1493 p = subprocess.Popen([sys.executable, "-c",
1494 'import sys;'
1495 'sys.stdout.write("apple")'],
1496 stdout=subprocess.PIPE,
1497 bufsize=0)
1498 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001499 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001500 try:
1501 self.assertEqual(f.read(4), b"appl")
1502 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1503 finally:
1504 p.wait()
1505
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001506 def test_zombie_fast_process_del(self):
1507 # Issue #12650: on Unix, if Popen.__del__() was called before the
1508 # process exited, it wouldn't be added to subprocess._active, and would
1509 # remain a zombie.
1510 # spawn a Popen, and delete its reference before it exits
1511 p = subprocess.Popen([sys.executable, "-c",
1512 'import sys, time;'
1513 'time.sleep(0.2)'],
1514 stdout=subprocess.PIPE,
1515 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001516 self.addCleanup(p.stdout.close)
1517 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001518 ident = id(p)
1519 pid = p.pid
1520 del p
1521 # check that p is in the active processes list
1522 self.assertIn(ident, [id(o) for o in subprocess._active])
1523
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001524 def test_leak_fast_process_del_killed(self):
1525 # Issue #12650: on Unix, if Popen.__del__() was called before the
1526 # process exited, and the process got killed by a signal, it would never
1527 # be removed from subprocess._active, which triggered a FD and memory
1528 # leak.
1529 # spawn a Popen, delete its reference and kill it
1530 p = subprocess.Popen([sys.executable, "-c",
1531 'import time;'
1532 'time.sleep(3)'],
1533 stdout=subprocess.PIPE,
1534 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001535 self.addCleanup(p.stdout.close)
1536 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001537 ident = id(p)
1538 pid = p.pid
1539 del p
1540 os.kill(pid, signal.SIGKILL)
1541 # check that p is in the active processes list
1542 self.assertIn(ident, [id(o) for o in subprocess._active])
1543
1544 # let some time for the process to exit, and create a new Popen: this
1545 # should trigger the wait() of p
1546 time.sleep(0.2)
1547 with self.assertRaises(EnvironmentError) as c:
1548 with subprocess.Popen(['nonexisting_i_hope'],
1549 stdout=subprocess.PIPE,
1550 stderr=subprocess.PIPE) as proc:
1551 pass
1552 # p should have been wait()ed on, and removed from the _active list
1553 self.assertRaises(OSError, os.waitpid, pid, 0)
1554 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1555
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001556
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001557@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001558class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001559
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001560 def test_startupinfo(self):
1561 # startupinfo argument
1562 # We uses hardcoded constants, because we do not want to
1563 # depend on win32all.
1564 STARTF_USESHOWWINDOW = 1
1565 SW_MAXIMIZE = 3
1566 startupinfo = subprocess.STARTUPINFO()
1567 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1568 startupinfo.wShowWindow = SW_MAXIMIZE
1569 # Since Python is a console process, it won't be affected
1570 # by wShowWindow, but the argument should be silently
1571 # ignored
1572 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001573 startupinfo=startupinfo)
1574
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001575 def test_creationflags(self):
1576 # creationflags argument
1577 CREATE_NEW_CONSOLE = 16
1578 sys.stderr.write(" a DOS box should flash briefly ...\n")
1579 subprocess.call(sys.executable +
1580 ' -c "import time; time.sleep(0.25)"',
1581 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001582
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001583 def test_invalid_args(self):
1584 # invalid arguments should raise ValueError
1585 self.assertRaises(ValueError, subprocess.call,
1586 [sys.executable, "-c",
1587 "import sys; sys.exit(47)"],
1588 preexec_fn=lambda: 1)
1589 self.assertRaises(ValueError, subprocess.call,
1590 [sys.executable, "-c",
1591 "import sys; sys.exit(47)"],
1592 stdout=subprocess.PIPE,
1593 close_fds=True)
1594
1595 def test_close_fds(self):
1596 # close file descriptors
1597 rc = subprocess.call([sys.executable, "-c",
1598 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001599 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001600 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001601
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001602 def test_shell_sequence(self):
1603 # Run command through the shell (sequence)
1604 newenv = os.environ.copy()
1605 newenv["FRUIT"] = "physalis"
1606 p = subprocess.Popen(["set"], shell=1,
1607 stdout=subprocess.PIPE,
1608 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001609 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001610 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001611
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001612 def test_shell_string(self):
1613 # Run command through the shell (string)
1614 newenv = os.environ.copy()
1615 newenv["FRUIT"] = "physalis"
1616 p = subprocess.Popen("set", shell=1,
1617 stdout=subprocess.PIPE,
1618 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001619 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001620 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001621
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001622 def test_call_string(self):
1623 # call() function with string argument on Windows
1624 rc = subprocess.call(sys.executable +
1625 ' -c "import sys; sys.exit(47)"')
1626 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001627
Florent Xicluna4886d242010-03-08 13:27:26 +00001628 def _kill_process(self, method, *args):
1629 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001630 p = subprocess.Popen([sys.executable, "-c", """if 1:
1631 import sys, time
1632 sys.stdout.write('x\\n')
1633 sys.stdout.flush()
1634 time.sleep(30)
1635 """],
1636 stdin=subprocess.PIPE,
1637 stdout=subprocess.PIPE,
1638 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001639 self.addCleanup(p.stdout.close)
1640 self.addCleanup(p.stderr.close)
1641 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001642 # Wait for the interpreter to be completely initialized before
1643 # sending any signal.
1644 p.stdout.read(1)
1645 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001646 _, stderr = p.communicate()
1647 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001648 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001649 self.assertNotEqual(returncode, 0)
1650
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001651 def _kill_dead_process(self, method, *args):
1652 p = subprocess.Popen([sys.executable, "-c", """if 1:
1653 import sys, time
1654 sys.stdout.write('x\\n')
1655 sys.stdout.flush()
1656 sys.exit(42)
1657 """],
1658 stdin=subprocess.PIPE,
1659 stdout=subprocess.PIPE,
1660 stderr=subprocess.PIPE)
1661 self.addCleanup(p.stdout.close)
1662 self.addCleanup(p.stderr.close)
1663 self.addCleanup(p.stdin.close)
1664 # Wait for the interpreter to be completely initialized before
1665 # sending any signal.
1666 p.stdout.read(1)
1667 # The process should end after this
1668 time.sleep(1)
1669 # This shouldn't raise even though the child is now dead
1670 getattr(p, method)(*args)
1671 _, stderr = p.communicate()
1672 self.assertStderrEqual(stderr, b'')
1673 rc = p.wait()
1674 self.assertEqual(rc, 42)
1675
Florent Xicluna4886d242010-03-08 13:27:26 +00001676 def test_send_signal(self):
1677 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001678
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001679 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001680 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001681
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001682 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001683 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001684
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001685 def test_send_signal_dead(self):
1686 self._kill_dead_process('send_signal', signal.SIGTERM)
1687
1688 def test_kill_dead(self):
1689 self._kill_dead_process('kill')
1690
1691 def test_terminate_dead(self):
1692 self._kill_dead_process('terminate')
1693
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001694
Brett Cannona23810f2008-05-26 19:04:21 +00001695# The module says:
1696# "NB This only works (and is only relevant) for UNIX."
1697#
1698# Actually, getoutput should work on any platform with an os.popen, but
1699# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001700@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001701class CommandTests(unittest.TestCase):
1702 def test_getoutput(self):
1703 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1704 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1705 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001706
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001707 # we use mkdtemp in the next line to create an empty directory
1708 # under our exclusive control; from that, we can invent a pathname
1709 # that we _know_ won't exist. This is guaranteed to fail.
1710 dir = None
1711 try:
1712 dir = tempfile.mkdtemp()
1713 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001714
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001715 status, output = subprocess.getstatusoutput('cat ' + name)
1716 self.assertNotEqual(status, 0)
1717 finally:
1718 if dir is not None:
1719 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001720
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001721
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001722@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1723 "poll system call not supported")
1724class ProcessTestCaseNoPoll(ProcessTestCase):
1725 def setUp(self):
1726 subprocess._has_poll = False
1727 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001728
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001729 def tearDown(self):
1730 subprocess._has_poll = True
1731 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001732
1733
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001734@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1735 "_posixsubprocess extension module not found.")
1736class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001737 @classmethod
1738 def setUpClass(cls):
1739 global subprocess
1740 assert subprocess._posixsubprocess
1741 # Reimport subprocess while forcing _posixsubprocess to not exist.
1742 with support.check_warnings(('.*_posixsubprocess .* not being used.*',
1743 RuntimeWarning)):
1744 subprocess = support.import_fresh_module(
1745 'subprocess', blocked=['_posixsubprocess'])
1746 assert not subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001747
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001748 @classmethod
1749 def tearDownClass(cls):
1750 global subprocess
1751 # Reimport subprocess as it should be, restoring order to the universe.
1752 subprocess = support.import_fresh_module('subprocess')
1753 assert subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001754
1755
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001756class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001757 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001758 def test_eintr_retry_call(self):
1759 record_calls = []
1760 def fake_os_func(*args):
1761 record_calls.append(args)
1762 if len(record_calls) == 2:
1763 raise OSError(errno.EINTR, "fake interrupted system call")
1764 return tuple(reversed(args))
1765
1766 self.assertEqual((999, 256),
1767 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1768 self.assertEqual([(256, 999)], record_calls)
1769 # This time there will be an EINTR so it will loop once.
1770 self.assertEqual((666,),
1771 subprocess._eintr_retry_call(fake_os_func, 666))
1772 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1773
1774
Tim Golden126c2962010-08-11 14:20:40 +00001775@unittest.skipUnless(mswindows, "Windows-specific tests")
1776class CommandsWithSpaces (BaseTestCase):
1777
1778 def setUp(self):
1779 super().setUp()
1780 f, fname = mkstemp(".py", "te st")
1781 self.fname = fname.lower ()
1782 os.write(f, b"import sys;"
1783 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1784 )
1785 os.close(f)
1786
1787 def tearDown(self):
1788 os.remove(self.fname)
1789 super().tearDown()
1790
1791 def with_spaces(self, *args, **kwargs):
1792 kwargs['stdout'] = subprocess.PIPE
1793 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001794 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001795 self.assertEqual(
1796 p.stdout.read ().decode("mbcs"),
1797 "2 [%r, 'ab cd']" % self.fname
1798 )
1799
1800 def test_shell_string_with_spaces(self):
1801 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001802 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1803 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001804
1805 def test_shell_sequence_with_spaces(self):
1806 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001807 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001808
1809 def test_noshell_string_with_spaces(self):
1810 # call() function with string argument with spaces on Windows
1811 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1812 "ab cd"))
1813
1814 def test_noshell_sequence_with_spaces(self):
1815 # call() function with sequence argument with spaces on Windows
1816 self.with_spaces([sys.executable, self.fname, "ab cd"])
1817
Brian Curtin79cdb662010-12-03 02:46:02 +00001818
Georg Brandla86b2622012-02-20 21:34:57 +01001819class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001820
1821 def test_pipe(self):
1822 with subprocess.Popen([sys.executable, "-c",
1823 "import sys;"
1824 "sys.stdout.write('stdout');"
1825 "sys.stderr.write('stderr');"],
1826 stdout=subprocess.PIPE,
1827 stderr=subprocess.PIPE) as proc:
1828 self.assertEqual(proc.stdout.read(), b"stdout")
1829 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1830
1831 self.assertTrue(proc.stdout.closed)
1832 self.assertTrue(proc.stderr.closed)
1833
1834 def test_returncode(self):
1835 with subprocess.Popen([sys.executable, "-c",
1836 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smithc9557af2011-05-11 22:18:23 -07001837 pass
1838 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001839 self.assertEqual(proc.returncode, 100)
1840
1841 def test_communicate_stdin(self):
1842 with subprocess.Popen([sys.executable, "-c",
1843 "import sys;"
1844 "sys.exit(sys.stdin.read() == 'context')"],
1845 stdin=subprocess.PIPE) as proc:
1846 proc.communicate(b"context")
1847 self.assertEqual(proc.returncode, 1)
1848
1849 def test_invalid_args(self):
1850 with self.assertRaises(EnvironmentError) as c:
1851 with subprocess.Popen(['nonexisting_i_hope'],
1852 stdout=subprocess.PIPE,
1853 stderr=subprocess.PIPE) as proc:
1854 pass
1855
1856 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1857 raise c.exception
1858
1859
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001860def test_main():
1861 unit_tests = (ProcessTestCase,
1862 POSIXProcessTestCase,
1863 Win32ProcessTestCase,
1864 ProcessTestCasePOSIXPurePython,
1865 CommandTests,
1866 ProcessTestCaseNoPoll,
1867 HelperFunctionTests,
1868 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001869 ContextManagerTests,
1870 )
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001871
1872 support.run_unittest(*unit_tests)
1873 support.reap_children()
1874
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001875if __name__ == "__main__":
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001876 unittest.main()