blob: 52de5c064c886adf69165dee836d7cced48b548c [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
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00008import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import tempfile
10import time
Tim Peters3761e8d2004-10-13 04:07:12 +000011import re
Ezio Melotti184bdfb2010-02-18 09:37:05 +000012import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000013import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000014import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040015import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050016import gc
Benjamin Peterson964561b2011-12-10 12:31:42 -050017
18try:
19 import resource
20except ImportError:
21 resource = None
22
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000023mswindows = (sys.platform == "win32")
24
25#
26# Depends on the following external programs: Python
27#
28
29if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000030 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
31 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000032else:
33 SETBINARY = ''
34
Florent Xiclunab1e94e82010-02-27 22:12:37 +000035
36try:
37 mkstemp = tempfile.mkstemp
38except AttributeError:
39 # tempfile.mkstemp is not available
40 def mkstemp():
41 """Replacement for mkstemp, calling mktemp."""
42 fname = tempfile.mktemp()
43 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
44
Tim Peters3761e8d2004-10-13 04:07:12 +000045
Florent Xiclunac049d872010-03-27 22:47:23 +000046class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000047 def setUp(self):
48 # Try to minimize the number of children we have so this test
49 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000050 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000051
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000052 def tearDown(self):
53 for inst in subprocess._active:
54 inst.wait()
55 subprocess._cleanup()
56 self.assertFalse(subprocess._active, "subprocess._active not empty")
57
Florent Xiclunab1e94e82010-02-27 22:12:37 +000058 def assertStderrEqual(self, stderr, expected, msg=None):
59 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
60 # shutdown time. That frustrates tests trying to check stderr produced
61 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000062 actual = support.strip_python_stderr(stderr)
Florent Xiclunab1e94e82010-02-27 22:12:37 +000063 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000064
Florent Xiclunac049d872010-03-27 22:47:23 +000065
66class ProcessTestCase(BaseTestCase):
67
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000068 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000069 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000070 rc = subprocess.call([sys.executable, "-c",
71 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000072 self.assertEqual(rc, 47)
73
Peter Astrand454f7672005-01-01 09:36:35 +000074 def test_check_call_zero(self):
75 # check_call() function with zero return code
76 rc = subprocess.check_call([sys.executable, "-c",
77 "import sys; sys.exit(0)"])
78 self.assertEqual(rc, 0)
79
80 def test_check_call_nonzero(self):
81 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000082 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000083 subprocess.check_call([sys.executable, "-c",
84 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000085 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000086
Georg Brandlf9734072008-12-07 15:30:06 +000087 def test_check_output(self):
88 # check_output() function with zero return code
89 output = subprocess.check_output(
90 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000091 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000092
93 def test_check_output_nonzero(self):
94 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000095 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +000096 subprocess.check_output(
97 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000098 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +000099
100 def test_check_output_stderr(self):
101 # check_output() function stderr redirected to stdout
102 output = subprocess.check_output(
103 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
104 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000105 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000106
107 def test_check_output_stdout_arg(self):
108 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000109 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000110 output = subprocess.check_output(
111 [sys.executable, "-c", "print('will not be run')"],
112 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000113 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000114 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000115
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000116 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000117 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000118 newenv = os.environ.copy()
119 newenv["FRUIT"] = "banana"
120 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000121 'import sys, os;'
122 'sys.exit(os.getenv("FRUIT")=="banana")'],
123 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000124 self.assertEqual(rc, 1)
125
Victor Stinner87b9bc32011-06-01 00:57:47 +0200126 def test_invalid_args(self):
127 # Popen() called with invalid arguments should raise TypeError
128 # but Popen.__del__ should not complain (issue #12085)
129 with support.captured_stderr() as s:
130 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
131 argcount = subprocess.Popen.__init__.__code__.co_argcount
132 too_many_args = [0] * (argcount + 1)
133 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
134 self.assertEqual(s.getvalue(), '')
135
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000136 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000137 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000138 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000139 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000140 self.addCleanup(p.stdout.close)
141 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000142 p.wait()
143 self.assertEqual(p.stdin, None)
144
145 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000146 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000147 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000148 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000149 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000150 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000151 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000152 self.addCleanup(p.stdin.close)
153 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000154 p.wait()
155 self.assertEqual(p.stdout, None)
156
157 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000158 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000159 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000160 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000161 self.addCleanup(p.stdout.close)
162 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000163 p.wait()
164 self.assertEqual(p.stderr, None)
165
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000166 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000167 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000168 p = subprocess.Popen(["somethingyoudonthave", "-c",
169 "import sys; sys.exit(47)"],
170 executable=sys.executable, cwd=python_dir)
171 p.wait()
172 self.assertEqual(p.returncode, 47)
173
174 @unittest.skipIf(sysconfig.is_python_build(),
175 "need an installed Python. See #7774")
176 def test_executable_without_cwd(self):
177 # For a normal installation, it should work without 'cwd'
178 # argument. For test runs in the build directory, see #7774.
179 p = subprocess.Popen(["somethingyoudonthave", "-c",
180 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000181 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000182 p.wait()
183 self.assertEqual(p.returncode, 47)
184
185 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000186 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000187 p = subprocess.Popen([sys.executable, "-c",
188 'import sys; sys.exit(sys.stdin.read() == "pear")'],
189 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000190 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000191 p.stdin.close()
192 p.wait()
193 self.assertEqual(p.returncode, 1)
194
195 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000196 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000197 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000198 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000199 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000200 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000201 os.lseek(d, 0, 0)
202 p = subprocess.Popen([sys.executable, "-c",
203 'import sys; sys.exit(sys.stdin.read() == "pear")'],
204 stdin=d)
205 p.wait()
206 self.assertEqual(p.returncode, 1)
207
208 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000209 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000211 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000212 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000213 tf.seek(0)
214 p = subprocess.Popen([sys.executable, "-c",
215 'import sys; sys.exit(sys.stdin.read() == "pear")'],
216 stdin=tf)
217 p.wait()
218 self.assertEqual(p.returncode, 1)
219
220 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000221 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000222 p = subprocess.Popen([sys.executable, "-c",
223 'import sys; sys.stdout.write("orange")'],
224 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000225 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000226 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227
228 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000229 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000230 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000231 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000232 d = tf.fileno()
233 p = subprocess.Popen([sys.executable, "-c",
234 'import sys; sys.stdout.write("orange")'],
235 stdout=d)
236 p.wait()
237 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000238 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239
240 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000241 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000242 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000243 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244 p = subprocess.Popen([sys.executable, "-c",
245 'import sys; sys.stdout.write("orange")'],
246 stdout=tf)
247 p.wait()
248 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000249 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000250
251 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000252 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000253 p = subprocess.Popen([sys.executable, "-c",
254 'import sys; sys.stderr.write("strawberry")'],
255 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000256 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000257 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000258
259 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000260 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000261 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000262 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263 d = tf.fileno()
264 p = subprocess.Popen([sys.executable, "-c",
265 'import sys; sys.stderr.write("strawberry")'],
266 stderr=d)
267 p.wait()
268 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000269 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270
271 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000272 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000273 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000274 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000275 p = subprocess.Popen([sys.executable, "-c",
276 'import sys; sys.stderr.write("strawberry")'],
277 stderr=tf)
278 p.wait()
279 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000280 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281
282 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000283 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000284 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000285 'import sys;'
286 'sys.stdout.write("apple");'
287 'sys.stdout.flush();'
288 'sys.stderr.write("orange")'],
289 stdout=subprocess.PIPE,
290 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000291 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000292 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293
294 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000295 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000297 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000299 'import sys;'
300 'sys.stdout.write("apple");'
301 'sys.stdout.flush();'
302 'sys.stderr.write("orange")'],
303 stdout=tf,
304 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000305 p.wait()
306 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000307 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308
Thomas Wouters89f507f2006-12-13 04:49:30 +0000309 def test_stdout_filedes_of_stdout(self):
310 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000311 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000312 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000313 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000314
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000315 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000316 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000317 # We cannot use os.path.realpath to canonicalize the path,
318 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
319 cwd = os.getcwd()
320 os.chdir(tmpdir)
321 tmpdir = os.getcwd()
322 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000323 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000324 'import sys,os;'
325 'sys.stdout.write(os.getcwd())'],
326 stdout=subprocess.PIPE,
327 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000328 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000329 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000330 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
331 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000332
333 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334 newenv = os.environ.copy()
335 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200336 with subprocess.Popen([sys.executable, "-c",
337 'import sys,os;'
338 'sys.stdout.write(os.getenv("FRUIT"))'],
339 stdout=subprocess.PIPE,
340 env=newenv) as p:
341 stdout, stderr = p.communicate()
342 self.assertEqual(stdout, b"orange")
343
Victor Stinner62d51182011-06-23 01:02:25 +0200344 # Windows requires at least the SYSTEMROOT environment variable to start
345 # Python
346 @unittest.skipIf(sys.platform == 'win32',
347 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200348 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200349 'the python library cannot be loaded '
350 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200351 def test_empty_env(self):
352 with subprocess.Popen([sys.executable, "-c",
353 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200354 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200355 stdout=subprocess.PIPE,
356 env={}) as p:
357 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200358 self.assertIn(stdout.strip(),
359 (b"[]",
360 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
361 # environment
362 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000363
Peter Astrandcbac93c2005-03-03 20:24:28 +0000364 def test_communicate_stdin(self):
365 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000366 'import sys;'
367 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000368 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000369 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000370 self.assertEqual(p.returncode, 1)
371
372 def test_communicate_stdout(self):
373 p = subprocess.Popen([sys.executable, "-c",
374 'import sys; sys.stdout.write("pineapple")'],
375 stdout=subprocess.PIPE)
376 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000377 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000378 self.assertEqual(stderr, None)
379
380 def test_communicate_stderr(self):
381 p = subprocess.Popen([sys.executable, "-c",
382 'import sys; sys.stderr.write("pineapple")'],
383 stderr=subprocess.PIPE)
384 (stdout, stderr) = p.communicate()
385 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000386 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000387
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000388 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000389 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000390 'import sys,os;'
391 'sys.stderr.write("pineapple");'
392 'sys.stdout.write(sys.stdin.read())'],
393 stdin=subprocess.PIPE,
394 stdout=subprocess.PIPE,
395 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000396 self.addCleanup(p.stdout.close)
397 self.addCleanup(p.stderr.close)
398 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000399 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000400 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000401 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000402
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000403 # Test for the fd leak reported in http://bugs.python.org/issue2791.
404 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000405 for stdin_pipe in (False, True):
406 for stdout_pipe in (False, True):
407 for stderr_pipe in (False, True):
408 options = {}
409 if stdin_pipe:
410 options['stdin'] = subprocess.PIPE
411 if stdout_pipe:
412 options['stdout'] = subprocess.PIPE
413 if stderr_pipe:
414 options['stderr'] = subprocess.PIPE
415 if not options:
416 continue
417 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
418 p.communicate()
419 if p.stdin is not None:
420 self.assertTrue(p.stdin.closed)
421 if p.stdout is not None:
422 self.assertTrue(p.stdout.closed)
423 if p.stderr is not None:
424 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000425
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000427 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000428 p = subprocess.Popen([sys.executable, "-c",
429 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000430 (stdout, stderr) = p.communicate()
431 self.assertEqual(stdout, None)
432 self.assertEqual(stderr, None)
433
434 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000435 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000436 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000437 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438 x, y = os.pipe()
439 if mswindows:
440 pipe_buf = 512
441 else:
442 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
443 os.close(x)
444 os.close(y)
445 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000446 'import sys,os;'
447 'sys.stdout.write(sys.stdin.read(47));'
448 'sys.stderr.write("xyz"*%d);'
449 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
450 stdin=subprocess.PIPE,
451 stdout=subprocess.PIPE,
452 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000453 self.addCleanup(p.stdout.close)
454 self.addCleanup(p.stderr.close)
455 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000456 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000457 (stdout, stderr) = p.communicate(string_to_write)
458 self.assertEqual(stdout, string_to_write)
459
460 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000461 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000462 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000463 'import sys,os;'
464 'sys.stdout.write(sys.stdin.read())'],
465 stdin=subprocess.PIPE,
466 stdout=subprocess.PIPE,
467 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000468 self.addCleanup(p.stdout.close)
469 self.addCleanup(p.stderr.close)
470 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000471 p.stdin.write(b"banana")
472 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000473 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000474 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000475
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000477 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000478 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200479 'buf = sys.stdout.buffer;'
480 'buf.write(sys.stdin.readline().encode());'
481 'buf.flush();'
482 'buf.write(b"line2\\n");'
483 'buf.flush();'
484 'buf.write(sys.stdin.read().encode());'
485 'buf.flush();'
486 'buf.write(b"line4\\n");'
487 'buf.flush();'
488 'buf.write(b"line5\\r\\n");'
489 'buf.flush();'
490 'buf.write(b"line6\\r");'
491 'buf.flush();'
492 'buf.write(b"\\nline7");'
493 'buf.flush();'
494 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200495 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000496 stdout=subprocess.PIPE,
497 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200498 p.stdin.write("line1\n")
499 self.assertEqual(p.stdout.readline(), "line1\n")
500 p.stdin.write("line3\n")
501 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000502 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200503 self.assertEqual(p.stdout.readline(),
504 "line2\n")
505 self.assertEqual(p.stdout.read(6),
506 "line3\n")
507 self.assertEqual(p.stdout.read(),
508 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000509
510 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000511 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000513 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200514 'buf = sys.stdout.buffer;'
515 'buf.write(b"line2\\n");'
516 'buf.flush();'
517 'buf.write(b"line4\\n");'
518 'buf.flush();'
519 'buf.write(b"line5\\r\\n");'
520 'buf.flush();'
521 'buf.write(b"line6\\r");'
522 'buf.flush();'
523 'buf.write(b"\\nline7");'
524 'buf.flush();'
525 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200526 stderr=subprocess.PIPE,
527 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000528 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000529 self.addCleanup(p.stdout.close)
530 self.addCleanup(p.stderr.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200531 # BUG: can't give a non-empty stdin because it breaks both the
532 # select- and poll-based communicate() implementations.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000533 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200534 self.assertEqual(stdout,
535 "line2\nline4\nline5\nline6\nline7\nline8")
536
537 def test_universal_newlines_communicate_stdin(self):
538 # universal newlines through communicate(), with only stdin
539 p = subprocess.Popen([sys.executable, "-c",
540 'import sys,os;' + SETBINARY + '''\nif True:
541 s = sys.stdin.readline()
542 assert s == "line1\\n", repr(s)
543 s = sys.stdin.read()
544 assert s == "line3\\n", repr(s)
545 '''],
546 stdin=subprocess.PIPE,
547 universal_newlines=1)
548 (stdout, stderr) = p.communicate("line1\nline3\n")
549 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000550
551 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000552 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000553 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000554 max_handles = 1026 # too much for most UNIX systems
555 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000556 max_handles = 2050 # too much for (at least some) Windows setups
557 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400558 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000559 try:
560 for i in range(max_handles):
561 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400562 tmpfile = os.path.join(tmpdir, support.TESTFN)
563 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000564 except OSError as e:
565 if e.errno != errno.EMFILE:
566 raise
567 break
568 else:
569 self.skipTest("failed to reach the file descriptor limit "
570 "(tried %d)" % max_handles)
571 # Close a couple of them (should be enough for a subprocess)
572 for i in range(10):
573 os.close(handles.pop())
574 # Loop creating some subprocesses. If one of them leaks some fds,
575 # the next loop iteration will fail by reaching the max fd limit.
576 for i in range(15):
577 p = subprocess.Popen([sys.executable, "-c",
578 "import sys;"
579 "sys.stdout.write(sys.stdin.read())"],
580 stdin=subprocess.PIPE,
581 stdout=subprocess.PIPE,
582 stderr=subprocess.PIPE)
583 data = p.communicate(b"lime")[0]
584 self.assertEqual(data, b"lime")
585 finally:
586 for h in handles:
587 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400588 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589
590 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000591 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
592 '"a b c" d e')
593 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
594 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000595 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
596 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000597 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
598 'a\\\\\\b "de fg" h')
599 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
600 'a\\\\\\"b c d')
601 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
602 '"a\\\\b c" d e')
603 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
604 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000605 self.assertEqual(subprocess.list2cmdline(['ab', '']),
606 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000607
608
609 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000610 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000611 "-c", "import time; time.sleep(1)"])
612 count = 0
613 while p.poll() is None:
614 time.sleep(0.1)
615 count += 1
616 # We expect that the poll loop probably went around about 10 times,
617 # but, based on system scheduling we can't control, it's possible
618 # poll() never returned None. It "should be" very rare that it
619 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000620 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000621 # Subsequent invocations should just return the returncode
622 self.assertEqual(p.poll(), 0)
623
624
625 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000626 p = subprocess.Popen([sys.executable,
627 "-c", "import time; time.sleep(2)"])
628 self.assertEqual(p.wait(), 0)
629 # Subsequent invocations should just return the returncode
630 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000631
Peter Astrand738131d2004-11-30 21:04:45 +0000632
633 def test_invalid_bufsize(self):
634 # an invalid type of the bufsize argument should raise
635 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000636 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000637 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000638
Guido van Rossum46a05a72007-06-07 21:56:45 +0000639 def test_bufsize_is_none(self):
640 # bufsize=None should be the same as bufsize=0.
641 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
642 self.assertEqual(p.wait(), 0)
643 # Again with keyword arg
644 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
645 self.assertEqual(p.wait(), 0)
646
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000647 def test_leaking_fds_on_error(self):
648 # see bug #5179: Popen leaks file descriptors to PIPEs if
649 # the child fails to execute; this will eventually exhaust
650 # the maximum number of open fds. 1024 seems a very common
651 # value for that limit, but Windows has 2048, so we loop
652 # 1024 times (each call leaked two fds).
653 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000654 # Windows raises IOError. Others raise OSError.
655 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000656 subprocess.Popen(['nonexisting_i_hope'],
657 stdout=subprocess.PIPE,
658 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400659 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400660 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000661 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000662
Victor Stinnerb3693582010-05-21 20:13:12 +0000663 def test_issue8780(self):
664 # Ensure that stdout is inherited from the parent
665 # if stdout=PIPE is not used
666 code = ';'.join((
667 'import subprocess, sys',
668 'retcode = subprocess.call('
669 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
670 'assert retcode == 0'))
671 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000672 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000673
Tim Goldenaf5ac392010-08-06 13:03:56 +0000674 def test_handles_closed_on_exception(self):
675 # If CreateProcess exits with an error, ensure the
676 # duplicate output handles are released
677 ifhandle, ifname = mkstemp()
678 ofhandle, ofname = mkstemp()
679 efhandle, efname = mkstemp()
680 try:
681 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
682 stderr=efhandle)
683 except OSError:
684 os.close(ifhandle)
685 os.remove(ifname)
686 os.close(ofhandle)
687 os.remove(ofname)
688 os.close(efhandle)
689 os.remove(efname)
690 self.assertFalse(os.path.exists(ifname))
691 self.assertFalse(os.path.exists(ofname))
692 self.assertFalse(os.path.exists(efname))
693
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200694 def test_communicate_epipe(self):
695 # Issue 10963: communicate() should hide EPIPE
696 p = subprocess.Popen([sys.executable, "-c", 'pass'],
697 stdin=subprocess.PIPE,
698 stdout=subprocess.PIPE,
699 stderr=subprocess.PIPE)
700 self.addCleanup(p.stdout.close)
701 self.addCleanup(p.stderr.close)
702 self.addCleanup(p.stdin.close)
703 p.communicate(b"x" * 2**20)
704
705 def test_communicate_epipe_only_stdin(self):
706 # Issue 10963: communicate() should hide EPIPE
707 p = subprocess.Popen([sys.executable, "-c", 'pass'],
708 stdin=subprocess.PIPE)
709 self.addCleanup(p.stdin.close)
710 time.sleep(2)
711 p.communicate(b"x" * 2**20)
712
Victor Stinner1848db82011-07-05 14:49:46 +0200713 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
714 "Requires signal.SIGALRM")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200715 def test_communicate_eintr(self):
716 # Issue #12493: communicate() should handle EINTR
717 def handler(signum, frame):
718 pass
719 old_handler = signal.signal(signal.SIGALRM, handler)
720 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
721
722 # the process is running for 2 seconds
723 args = [sys.executable, "-c", 'import time; time.sleep(2)']
724 for stream in ('stdout', 'stderr'):
725 kw = {stream: subprocess.PIPE}
726 with subprocess.Popen(args, **kw) as process:
727 signal.alarm(1)
728 # communicate() will be interrupted by SIGALRM
729 process.communicate()
730
Tim Peterse718f612004-10-12 21:51:32 +0000731
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000732# context manager
733class _SuppressCoreFiles(object):
734 """Try to prevent core files from being created."""
735 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000736
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000737 def __enter__(self):
738 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500739 if resource is not None:
740 try:
741 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
742 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
743 except (ValueError, resource.error):
744 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000745
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000746 if sys.platform == 'darwin':
747 # Check if the 'Crash Reporter' on OSX was configured
748 # in 'Developer' mode and warn that it will get triggered
749 # when it is.
750 #
751 # This assumes that this context manager is used in tests
752 # that might trigger the next manager.
753 value = subprocess.Popen(['/usr/bin/defaults', 'read',
754 'com.apple.CrashReporter', 'DialogType'],
755 stdout=subprocess.PIPE).communicate()[0]
756 if value.strip() == b'developer':
757 print("this tests triggers the Crash Reporter, "
758 "that is intentional", end='')
759 sys.stdout.flush()
760
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000761 def __exit__(self, *args):
762 """Return core file behavior to default."""
763 if self.old_limit is None:
764 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500765 if resource is not None:
766 try:
767 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
768 except (ValueError, resource.error):
769 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000770
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000771
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000772@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000773class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000774
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000775 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000776 nonexistent_dir = "/_this/pa.th/does/not/exist"
777 try:
778 os.chdir(nonexistent_dir)
779 except OSError as e:
780 # This avoids hard coding the errno value or the OS perror()
781 # string and instead capture the exception that we want to see
782 # below for comparison.
783 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000784 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000785 else:
786 self.fail("chdir to nonexistant directory %s succeeded." %
787 nonexistent_dir)
788
789 # Error in the child re-raised in the parent.
790 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000791 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000792 cwd=nonexistent_dir)
793 except OSError as e:
794 # Test that the child process chdir failure actually makes
795 # it up to the parent process as the correct exception.
796 self.assertEqual(desired_exception.errno, e.errno)
797 self.assertEqual(desired_exception.strerror, e.strerror)
798 else:
799 self.fail("Expected OSError: %s" % desired_exception)
800
801 def test_restore_signals(self):
802 # Code coverage for both values of restore_signals to make sure it
803 # at least does not blow up.
804 # A test for behavior would be complex. Contributions welcome.
805 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
806 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
807
808 def test_start_new_session(self):
809 # For code coverage of calling setsid(). We don't care if we get an
810 # EPERM error from it depending on the test execution environment, that
811 # still indicates that it was called.
812 try:
813 output = subprocess.check_output(
814 [sys.executable, "-c",
815 "import os; print(os.getpgid(os.getpid()))"],
816 start_new_session=True)
817 except OSError as e:
818 if e.errno != errno.EPERM:
819 raise
820 else:
821 parent_pgid = os.getpgid(os.getpid())
822 child_pgid = int(output)
823 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000824
825 def test_run_abort(self):
826 # returncode handles signal termination
827 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000828 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000829 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000830 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000831 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000832
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000833 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000834 # DISCLAIMER: Setting environment variables is *not* a good use
835 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000836 p = subprocess.Popen([sys.executable, "-c",
837 'import sys,os;'
838 'sys.stdout.write(os.getenv("FRUIT"))'],
839 stdout=subprocess.PIPE,
840 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000841 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000842 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000844 def test_preexec_exception(self):
845 def raise_it():
846 raise ValueError("What if two swallows carried a coconut?")
847 try:
848 p = subprocess.Popen([sys.executable, "-c", ""],
849 preexec_fn=raise_it)
850 except RuntimeError as e:
851 self.assertTrue(
852 subprocess._posixsubprocess,
853 "Expected a ValueError from the preexec_fn")
854 except ValueError as e:
855 self.assertIn("coconut", e.args[0])
856 else:
857 self.fail("Exception raised by preexec_fn did not make it "
858 "to the parent process.")
859
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000860 def test_preexec_gc_module_failure(self):
861 # This tests the code that disables garbage collection if the child
862 # process will execute any Python.
863 def raise_runtime_error():
864 raise RuntimeError("this shouldn't escape")
865 enabled = gc.isenabled()
866 orig_gc_disable = gc.disable
867 orig_gc_isenabled = gc.isenabled
868 try:
869 gc.disable()
870 self.assertFalse(gc.isenabled())
871 subprocess.call([sys.executable, '-c', ''],
872 preexec_fn=lambda: None)
873 self.assertFalse(gc.isenabled(),
874 "Popen enabled gc when it shouldn't.")
875
876 gc.enable()
877 self.assertTrue(gc.isenabled())
878 subprocess.call([sys.executable, '-c', ''],
879 preexec_fn=lambda: None)
880 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
881
882 gc.disable = raise_runtime_error
883 self.assertRaises(RuntimeError, subprocess.Popen,
884 [sys.executable, '-c', ''],
885 preexec_fn=lambda: None)
886
887 del gc.isenabled # force an AttributeError
888 self.assertRaises(AttributeError, subprocess.Popen,
889 [sys.executable, '-c', ''],
890 preexec_fn=lambda: None)
891 finally:
892 gc.disable = orig_gc_disable
893 gc.isenabled = orig_gc_isenabled
894 if not enabled:
895 gc.disable()
896
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000897 def test_args_string(self):
898 # args is a string
899 fd, fname = mkstemp()
900 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000901 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000902 fobj.write("#!/bin/sh\n")
903 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
904 sys.executable)
905 os.chmod(fname, 0o700)
906 p = subprocess.Popen(fname)
907 p.wait()
908 os.remove(fname)
909 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000910
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000911 def test_invalid_args(self):
912 # invalid arguments should raise ValueError
913 self.assertRaises(ValueError, subprocess.call,
914 [sys.executable, "-c",
915 "import sys; sys.exit(47)"],
916 startupinfo=47)
917 self.assertRaises(ValueError, subprocess.call,
918 [sys.executable, "-c",
919 "import sys; sys.exit(47)"],
920 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000921
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000922 def test_shell_sequence(self):
923 # Run command through the shell (sequence)
924 newenv = os.environ.copy()
925 newenv["FRUIT"] = "apple"
926 p = subprocess.Popen(["echo $FRUIT"], shell=1,
927 stdout=subprocess.PIPE,
928 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000929 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000930 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000932 def test_shell_string(self):
933 # Run command through the shell (string)
934 newenv = os.environ.copy()
935 newenv["FRUIT"] = "apple"
936 p = subprocess.Popen("echo $FRUIT", shell=1,
937 stdout=subprocess.PIPE,
938 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000939 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000940 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000941
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000942 def test_call_string(self):
943 # call() function with string argument on UNIX
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 rc = subprocess.call(fname)
952 os.remove(fname)
953 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000954
Stefan Krah9542cc62010-07-19 14:20:53 +0000955 def test_specific_shell(self):
956 # Issue #9265: Incorrect name passed as arg[0].
957 shells = []
958 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
959 for name in ['bash', 'ksh']:
960 sh = os.path.join(prefix, name)
961 if os.path.isfile(sh):
962 shells.append(sh)
963 if not shells: # Will probably work for any shell but csh.
964 self.skipTest("bash or ksh required for this test")
965 sh = '/bin/sh'
966 if os.path.isfile(sh) and not os.path.islink(sh):
967 # Test will fail if /bin/sh is a symlink to csh.
968 shells.append(sh)
969 for sh in shells:
970 p = subprocess.Popen("echo $0", executable=sh, shell=True,
971 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000972 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000973 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
974
Florent Xicluna4886d242010-03-08 13:27:26 +0000975 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000976 # Do not inherit file handles from the parent.
977 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000978 p = subprocess.Popen([sys.executable, "-c", """if 1:
979 import sys, time
980 sys.stdout.write('x\\n')
981 sys.stdout.flush()
982 time.sleep(30)
983 """],
984 close_fds=True,
985 stdin=subprocess.PIPE,
986 stdout=subprocess.PIPE,
987 stderr=subprocess.PIPE)
988 # Wait for the interpreter to be completely initialized before
989 # sending any signal.
990 p.stdout.read(1)
991 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000992 return p
993
Antoine Pitrou1f9a8352012-03-11 19:29:12 +0100994 def _kill_dead_process(self, method, *args):
995 # Do not inherit file handles from the parent.
996 # It should fix failures on some platforms.
997 p = subprocess.Popen([sys.executable, "-c", """if 1:
998 import sys, time
999 sys.stdout.write('x\\n')
1000 sys.stdout.flush()
1001 """],
1002 close_fds=True,
1003 stdin=subprocess.PIPE,
1004 stdout=subprocess.PIPE,
1005 stderr=subprocess.PIPE)
1006 # Wait for the interpreter to be completely initialized before
1007 # sending any signal.
1008 p.stdout.read(1)
1009 # The process should end after this
1010 time.sleep(1)
1011 # This shouldn't raise even though the child is now dead
1012 getattr(p, method)(*args)
1013 p.communicate()
1014
Florent Xicluna4886d242010-03-08 13:27:26 +00001015 def test_send_signal(self):
1016 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001017 _, stderr = p.communicate()
1018 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001019 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001020
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001021 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001022 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001023 _, stderr = p.communicate()
1024 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001025 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001026
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001027 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001028 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001029 _, stderr = p.communicate()
1030 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001031 self.assertEqual(p.wait(), -signal.SIGTERM)
1032
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001033 def test_send_signal_dead(self):
1034 # Sending a signal to a dead process
1035 self._kill_dead_process('send_signal', signal.SIGINT)
1036
1037 def test_kill_dead(self):
1038 # Killing a dead process
1039 self._kill_dead_process('kill')
1040
1041 def test_terminate_dead(self):
1042 # Terminating a dead process
1043 self._kill_dead_process('terminate')
1044
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001045 def check_close_std_fds(self, fds):
1046 # Issue #9905: test that subprocess pipes still work properly with
1047 # some standard fds closed
1048 stdin = 0
1049 newfds = []
1050 for a in fds:
1051 b = os.dup(a)
1052 newfds.append(b)
1053 if a == 0:
1054 stdin = b
1055 try:
1056 for fd in fds:
1057 os.close(fd)
1058 out, err = subprocess.Popen([sys.executable, "-c",
1059 'import sys;'
1060 'sys.stdout.write("apple");'
1061 'sys.stdout.flush();'
1062 'sys.stderr.write("orange")'],
1063 stdin=stdin,
1064 stdout=subprocess.PIPE,
1065 stderr=subprocess.PIPE).communicate()
1066 err = support.strip_python_stderr(err)
1067 self.assertEqual((out, err), (b'apple', b'orange'))
1068 finally:
1069 for b, a in zip(newfds, fds):
1070 os.dup2(b, a)
1071 for b in newfds:
1072 os.close(b)
1073
1074 def test_close_fd_0(self):
1075 self.check_close_std_fds([0])
1076
1077 def test_close_fd_1(self):
1078 self.check_close_std_fds([1])
1079
1080 def test_close_fd_2(self):
1081 self.check_close_std_fds([2])
1082
1083 def test_close_fds_0_1(self):
1084 self.check_close_std_fds([0, 1])
1085
1086 def test_close_fds_0_2(self):
1087 self.check_close_std_fds([0, 2])
1088
1089 def test_close_fds_1_2(self):
1090 self.check_close_std_fds([1, 2])
1091
1092 def test_close_fds_0_1_2(self):
1093 # Issue #10806: test that subprocess pipes still work properly with
1094 # all standard fds closed.
1095 self.check_close_std_fds([0, 1, 2])
1096
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001097 def test_remapping_std_fds(self):
1098 # open up some temporary files
1099 temps = [mkstemp() for i in range(3)]
1100 try:
1101 temp_fds = [fd for fd, fname in temps]
1102
1103 # unlink the files -- we won't need to reopen them
1104 for fd, fname in temps:
1105 os.unlink(fname)
1106
1107 # write some data to what will become stdin, and rewind
1108 os.write(temp_fds[1], b"STDIN")
1109 os.lseek(temp_fds[1], 0, 0)
1110
1111 # move the standard file descriptors out of the way
1112 saved_fds = [os.dup(fd) for fd in range(3)]
1113 try:
1114 # duplicate the file objects over the standard fd's
1115 for fd, temp_fd in enumerate(temp_fds):
1116 os.dup2(temp_fd, fd)
1117
1118 # now use those files in the "wrong" order, so that subprocess
1119 # has to rearrange them in the child
1120 p = subprocess.Popen([sys.executable, "-c",
1121 'import sys; got = sys.stdin.read();'
1122 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1123 stdin=temp_fds[1],
1124 stdout=temp_fds[2],
1125 stderr=temp_fds[0])
1126 p.wait()
1127 finally:
1128 # restore the original fd's underneath sys.stdin, etc.
1129 for std, saved in enumerate(saved_fds):
1130 os.dup2(saved, std)
1131 os.close(saved)
1132
1133 for fd in temp_fds:
1134 os.lseek(fd, 0, 0)
1135
1136 out = os.read(temp_fds[2], 1024)
1137 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1138 self.assertEqual(out, b"got STDIN")
1139 self.assertEqual(err, b"err")
1140
1141 finally:
1142 for fd in temp_fds:
1143 os.close(fd)
1144
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001145 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1146 # open up some temporary files
1147 temps = [mkstemp() for i in range(3)]
1148 temp_fds = [fd for fd, fname in temps]
1149 try:
1150 # unlink the files -- we won't need to reopen them
1151 for fd, fname in temps:
1152 os.unlink(fname)
1153
1154 # save a copy of the standard file descriptors
1155 saved_fds = [os.dup(fd) for fd in range(3)]
1156 try:
1157 # duplicate the temp files over the standard fd's 0, 1, 2
1158 for fd, temp_fd in enumerate(temp_fds):
1159 os.dup2(temp_fd, fd)
1160
1161 # write some data to what will become stdin, and rewind
1162 os.write(stdin_no, b"STDIN")
1163 os.lseek(stdin_no, 0, 0)
1164
1165 # now use those files in the given order, so that subprocess
1166 # has to rearrange them in the child
1167 p = subprocess.Popen([sys.executable, "-c",
1168 'import sys; got = sys.stdin.read();'
1169 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1170 stdin=stdin_no,
1171 stdout=stdout_no,
1172 stderr=stderr_no)
1173 p.wait()
1174
1175 for fd in temp_fds:
1176 os.lseek(fd, 0, 0)
1177
1178 out = os.read(stdout_no, 1024)
1179 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1180 finally:
1181 for std, saved in enumerate(saved_fds):
1182 os.dup2(saved, std)
1183 os.close(saved)
1184
1185 self.assertEqual(out, b"got STDIN")
1186 self.assertEqual(err, b"err")
1187
1188 finally:
1189 for fd in temp_fds:
1190 os.close(fd)
1191
1192 # When duping fds, if there arises a situation where one of the fds is
1193 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1194 # This tests all combinations of this.
1195 def test_swap_fds(self):
1196 self.check_swap_fds(0, 1, 2)
1197 self.check_swap_fds(0, 2, 1)
1198 self.check_swap_fds(1, 0, 2)
1199 self.check_swap_fds(1, 2, 0)
1200 self.check_swap_fds(2, 0, 1)
1201 self.check_swap_fds(2, 1, 0)
1202
Victor Stinner13bb71c2010-04-23 21:41:56 +00001203 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001204 def prepare():
1205 raise ValueError("surrogate:\uDCff")
1206
1207 try:
1208 subprocess.call(
1209 [sys.executable, "-c", "pass"],
1210 preexec_fn=prepare)
1211 except ValueError as err:
1212 # Pure Python implementations keeps the message
1213 self.assertIsNone(subprocess._posixsubprocess)
1214 self.assertEqual(str(err), "surrogate:\uDCff")
1215 except RuntimeError as err:
1216 # _posixsubprocess uses a default message
1217 self.assertIsNotNone(subprocess._posixsubprocess)
1218 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1219 else:
1220 self.fail("Expected ValueError or RuntimeError")
1221
Victor Stinner13bb71c2010-04-23 21:41:56 +00001222 def test_undecodable_env(self):
1223 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001224 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001225 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001226 env = os.environ.copy()
1227 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001228 # Use C locale to get ascii for the locale encoding to force
1229 # surrogate-escaping of \xFF in the child process; otherwise it can
1230 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001231 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001232 stdout = subprocess.check_output(
1233 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001234 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001235 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001236 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001237
1238 # test bytes
1239 key = key.encode("ascii", "surrogateescape")
1240 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001241 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001242 env = os.environ.copy()
1243 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001244 stdout = subprocess.check_output(
1245 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001246 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001247 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001248 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001249
Victor Stinnerb745a742010-05-18 17:17:23 +00001250 def test_bytes_program(self):
1251 abs_program = os.fsencode(sys.executable)
1252 path, program = os.path.split(sys.executable)
1253 program = os.fsencode(program)
1254
1255 # absolute bytes path
1256 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001257 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001258
1259 # bytes program, unicode PATH
1260 env = os.environ.copy()
1261 env["PATH"] = path
1262 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001263 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001264
1265 # bytes program, bytes PATH
1266 envb = os.environb.copy()
1267 envb[b"PATH"] = os.fsencode(path)
1268 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001269 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001270
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001271 def test_pipe_cloexec(self):
1272 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1273 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1274
1275 p1 = subprocess.Popen([sys.executable, sleeper],
1276 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1277 stderr=subprocess.PIPE, close_fds=False)
1278
1279 self.addCleanup(p1.communicate, b'')
1280
1281 p2 = subprocess.Popen([sys.executable, fd_status],
1282 stdout=subprocess.PIPE, close_fds=False)
1283
1284 output, error = p2.communicate()
1285 result_fds = set(map(int, output.split(b',')))
1286 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1287 p1.stderr.fileno()])
1288
1289 self.assertFalse(result_fds & unwanted_fds,
1290 "Expected no fds from %r to be open in child, "
1291 "found %r" %
1292 (unwanted_fds, result_fds & unwanted_fds))
1293
1294 def test_pipe_cloexec_real_tools(self):
1295 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1296 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1297
1298 subdata = b'zxcvbn'
1299 data = subdata * 4 + b'\n'
1300
1301 p1 = subprocess.Popen([sys.executable, qcat],
1302 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1303 close_fds=False)
1304
1305 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1306 stdin=p1.stdout, stdout=subprocess.PIPE,
1307 close_fds=False)
1308
1309 self.addCleanup(p1.wait)
1310 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001311 def kill_p1():
1312 try:
1313 p1.terminate()
1314 except ProcessLookupError:
1315 pass
1316 def kill_p2():
1317 try:
1318 p2.terminate()
1319 except ProcessLookupError:
1320 pass
1321 self.addCleanup(kill_p1)
1322 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001323
1324 p1.stdin.write(data)
1325 p1.stdin.close()
1326
1327 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1328
1329 self.assertTrue(readfiles, "The child hung")
1330 self.assertEqual(p2.stdout.read(), data)
1331
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001332 p1.stdout.close()
1333 p2.stdout.close()
1334
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001335 def test_close_fds(self):
1336 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1337
1338 fds = os.pipe()
1339 self.addCleanup(os.close, fds[0])
1340 self.addCleanup(os.close, fds[1])
1341
1342 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001343 # add a bunch more fds
1344 for _ in range(9):
1345 fd = os.open("/dev/null", os.O_RDONLY)
1346 self.addCleanup(os.close, fd)
1347 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001348
1349 p = subprocess.Popen([sys.executable, fd_status],
1350 stdout=subprocess.PIPE, close_fds=False)
1351 output, ignored = p.communicate()
1352 remaining_fds = set(map(int, output.split(b',')))
1353
1354 self.assertEqual(remaining_fds & open_fds, open_fds,
1355 "Some fds were closed")
1356
1357 p = subprocess.Popen([sys.executable, fd_status],
1358 stdout=subprocess.PIPE, close_fds=True)
1359 output, ignored = p.communicate()
1360 remaining_fds = set(map(int, output.split(b',')))
1361
1362 self.assertFalse(remaining_fds & open_fds,
1363 "Some fds were left open")
1364 self.assertIn(1, remaining_fds, "Subprocess failed")
1365
Gregory P. Smith8facece2012-01-21 14:01:08 -08001366 # Keep some of the fd's we opened open in the subprocess.
1367 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1368 fds_to_keep = set(open_fds.pop() for _ in range(8))
1369 p = subprocess.Popen([sys.executable, fd_status],
1370 stdout=subprocess.PIPE, close_fds=True,
1371 pass_fds=())
1372 output, ignored = p.communicate()
1373 remaining_fds = set(map(int, output.split(b',')))
1374
1375 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1376 "Some fds not in pass_fds were left open")
1377 self.assertIn(1, remaining_fds, "Subprocess failed")
1378
Victor Stinner88701e22011-06-01 13:13:04 +02001379 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1380 # descriptor of a pipe closed in the parent process is valid in the
1381 # child process according to fstat(), but the mode of the file
1382 # descriptor is invalid, and read or write raise an error.
1383 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001384 def test_pass_fds(self):
1385 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1386
1387 open_fds = set()
1388
1389 for x in range(5):
1390 fds = os.pipe()
1391 self.addCleanup(os.close, fds[0])
1392 self.addCleanup(os.close, fds[1])
1393 open_fds.update(fds)
1394
1395 for fd in open_fds:
1396 p = subprocess.Popen([sys.executable, fd_status],
1397 stdout=subprocess.PIPE, close_fds=True,
1398 pass_fds=(fd, ))
1399 output, ignored = p.communicate()
1400
1401 remaining_fds = set(map(int, output.split(b',')))
1402 to_be_closed = open_fds - {fd}
1403
1404 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1405 self.assertFalse(remaining_fds & to_be_closed,
1406 "fd to be closed passed")
1407
1408 # pass_fds overrides close_fds with a warning.
1409 with self.assertWarns(RuntimeWarning) as context:
1410 self.assertFalse(subprocess.call(
1411 [sys.executable, "-c", "import sys; sys.exit(0)"],
1412 close_fds=False, pass_fds=(fd, )))
1413 self.assertIn('overriding close_fds', str(context.warning))
1414
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001415 def test_stdout_stdin_are_single_inout_fd(self):
1416 with io.open(os.devnull, "r+") as inout:
1417 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1418 stdout=inout, stdin=inout)
1419 p.wait()
1420
1421 def test_stdout_stderr_are_single_inout_fd(self):
1422 with io.open(os.devnull, "r+") as inout:
1423 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1424 stdout=inout, stderr=inout)
1425 p.wait()
1426
1427 def test_stderr_stdin_are_single_inout_fd(self):
1428 with io.open(os.devnull, "r+") as inout:
1429 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1430 stderr=inout, stdin=inout)
1431 p.wait()
1432
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001433 def test_wait_when_sigchild_ignored(self):
1434 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1435 sigchild_ignore = support.findfile("sigchild_ignore.py",
1436 subdir="subprocessdata")
1437 p = subprocess.Popen([sys.executable, sigchild_ignore],
1438 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1439 stdout, stderr = p.communicate()
1440 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001441 " non-zero with this error:\n%s" %
1442 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001443
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001444 def test_select_unbuffered(self):
1445 # Issue #11459: bufsize=0 should really set the pipes as
1446 # unbuffered (and therefore let select() work properly).
1447 select = support.import_module("select")
1448 p = subprocess.Popen([sys.executable, "-c",
1449 'import sys;'
1450 'sys.stdout.write("apple")'],
1451 stdout=subprocess.PIPE,
1452 bufsize=0)
1453 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001454 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001455 try:
1456 self.assertEqual(f.read(4), b"appl")
1457 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1458 finally:
1459 p.wait()
1460
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001461 def test_zombie_fast_process_del(self):
1462 # Issue #12650: on Unix, if Popen.__del__() was called before the
1463 # process exited, it wouldn't be added to subprocess._active, and would
1464 # remain a zombie.
1465 # spawn a Popen, and delete its reference before it exits
1466 p = subprocess.Popen([sys.executable, "-c",
1467 'import sys, time;'
1468 'time.sleep(0.2)'],
1469 stdout=subprocess.PIPE,
1470 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001471 self.addCleanup(p.stdout.close)
1472 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001473 ident = id(p)
1474 pid = p.pid
1475 del p
1476 # check that p is in the active processes list
1477 self.assertIn(ident, [id(o) for o in subprocess._active])
1478
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001479 def test_leak_fast_process_del_killed(self):
1480 # Issue #12650: on Unix, if Popen.__del__() was called before the
1481 # process exited, and the process got killed by a signal, it would never
1482 # be removed from subprocess._active, which triggered a FD and memory
1483 # leak.
1484 # spawn a Popen, delete its reference and kill it
1485 p = subprocess.Popen([sys.executable, "-c",
1486 'import time;'
1487 'time.sleep(3)'],
1488 stdout=subprocess.PIPE,
1489 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001490 self.addCleanup(p.stdout.close)
1491 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001492 ident = id(p)
1493 pid = p.pid
1494 del p
1495 os.kill(pid, signal.SIGKILL)
1496 # check that p is in the active processes list
1497 self.assertIn(ident, [id(o) for o in subprocess._active])
1498
1499 # let some time for the process to exit, and create a new Popen: this
1500 # should trigger the wait() of p
1501 time.sleep(0.2)
1502 with self.assertRaises(EnvironmentError) as c:
1503 with subprocess.Popen(['nonexisting_i_hope'],
1504 stdout=subprocess.PIPE,
1505 stderr=subprocess.PIPE) as proc:
1506 pass
1507 # p should have been wait()ed on, and removed from the _active list
1508 self.assertRaises(OSError, os.waitpid, pid, 0)
1509 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1510
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001511
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001512@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001513class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001514
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001515 def test_startupinfo(self):
1516 # startupinfo argument
1517 # We uses hardcoded constants, because we do not want to
1518 # depend on win32all.
1519 STARTF_USESHOWWINDOW = 1
1520 SW_MAXIMIZE = 3
1521 startupinfo = subprocess.STARTUPINFO()
1522 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1523 startupinfo.wShowWindow = SW_MAXIMIZE
1524 # Since Python is a console process, it won't be affected
1525 # by wShowWindow, but the argument should be silently
1526 # ignored
1527 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001528 startupinfo=startupinfo)
1529
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001530 def test_creationflags(self):
1531 # creationflags argument
1532 CREATE_NEW_CONSOLE = 16
1533 sys.stderr.write(" a DOS box should flash briefly ...\n")
1534 subprocess.call(sys.executable +
1535 ' -c "import time; time.sleep(0.25)"',
1536 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001537
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001538 def test_invalid_args(self):
1539 # invalid arguments should raise ValueError
1540 self.assertRaises(ValueError, subprocess.call,
1541 [sys.executable, "-c",
1542 "import sys; sys.exit(47)"],
1543 preexec_fn=lambda: 1)
1544 self.assertRaises(ValueError, subprocess.call,
1545 [sys.executable, "-c",
1546 "import sys; sys.exit(47)"],
1547 stdout=subprocess.PIPE,
1548 close_fds=True)
1549
1550 def test_close_fds(self):
1551 # close file descriptors
1552 rc = subprocess.call([sys.executable, "-c",
1553 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001554 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001555 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001556
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001557 def test_shell_sequence(self):
1558 # Run command through the shell (sequence)
1559 newenv = os.environ.copy()
1560 newenv["FRUIT"] = "physalis"
1561 p = subprocess.Popen(["set"], shell=1,
1562 stdout=subprocess.PIPE,
1563 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001564 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001565 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001566
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001567 def test_shell_string(self):
1568 # Run command through the shell (string)
1569 newenv = os.environ.copy()
1570 newenv["FRUIT"] = "physalis"
1571 p = subprocess.Popen("set", shell=1,
1572 stdout=subprocess.PIPE,
1573 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001574 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001575 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001576
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001577 def test_call_string(self):
1578 # call() function with string argument on Windows
1579 rc = subprocess.call(sys.executable +
1580 ' -c "import sys; sys.exit(47)"')
1581 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001582
Florent Xicluna4886d242010-03-08 13:27:26 +00001583 def _kill_process(self, method, *args):
1584 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001585 p = subprocess.Popen([sys.executable, "-c", """if 1:
1586 import sys, time
1587 sys.stdout.write('x\\n')
1588 sys.stdout.flush()
1589 time.sleep(30)
1590 """],
1591 stdin=subprocess.PIPE,
1592 stdout=subprocess.PIPE,
1593 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001594 self.addCleanup(p.stdout.close)
1595 self.addCleanup(p.stderr.close)
1596 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001597 # Wait for the interpreter to be completely initialized before
1598 # sending any signal.
1599 p.stdout.read(1)
1600 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001601 _, stderr = p.communicate()
1602 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001603 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001604 self.assertNotEqual(returncode, 0)
1605
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001606 def _kill_dead_process(self, method, *args):
1607 p = subprocess.Popen([sys.executable, "-c", """if 1:
1608 import sys, time
1609 sys.stdout.write('x\\n')
1610 sys.stdout.flush()
1611 sys.exit(42)
1612 """],
1613 stdin=subprocess.PIPE,
1614 stdout=subprocess.PIPE,
1615 stderr=subprocess.PIPE)
1616 self.addCleanup(p.stdout.close)
1617 self.addCleanup(p.stderr.close)
1618 self.addCleanup(p.stdin.close)
1619 # Wait for the interpreter to be completely initialized before
1620 # sending any signal.
1621 p.stdout.read(1)
1622 # The process should end after this
1623 time.sleep(1)
1624 # This shouldn't raise even though the child is now dead
1625 getattr(p, method)(*args)
1626 _, stderr = p.communicate()
1627 self.assertStderrEqual(stderr, b'')
1628 rc = p.wait()
1629 self.assertEqual(rc, 42)
1630
Florent Xicluna4886d242010-03-08 13:27:26 +00001631 def test_send_signal(self):
1632 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001633
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001634 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001635 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001636
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001637 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001638 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001639
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001640 def test_send_signal_dead(self):
1641 self._kill_dead_process('send_signal', signal.SIGTERM)
1642
1643 def test_kill_dead(self):
1644 self._kill_dead_process('kill')
1645
1646 def test_terminate_dead(self):
1647 self._kill_dead_process('terminate')
1648
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001649
Brett Cannona23810f2008-05-26 19:04:21 +00001650# The module says:
1651# "NB This only works (and is only relevant) for UNIX."
1652#
1653# Actually, getoutput should work on any platform with an os.popen, but
1654# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001655@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001656class CommandTests(unittest.TestCase):
1657 def test_getoutput(self):
1658 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1659 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1660 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001661
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001662 # we use mkdtemp in the next line to create an empty directory
1663 # under our exclusive control; from that, we can invent a pathname
1664 # that we _know_ won't exist. This is guaranteed to fail.
1665 dir = None
1666 try:
1667 dir = tempfile.mkdtemp()
1668 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001669
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001670 status, output = subprocess.getstatusoutput('cat ' + name)
1671 self.assertNotEqual(status, 0)
1672 finally:
1673 if dir is not None:
1674 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001675
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001676
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001677@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1678 "poll system call not supported")
1679class ProcessTestCaseNoPoll(ProcessTestCase):
1680 def setUp(self):
1681 subprocess._has_poll = False
1682 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001683
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001684 def tearDown(self):
1685 subprocess._has_poll = True
1686 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001687
1688
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001689@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1690 "_posixsubprocess extension module not found.")
1691class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001692 @classmethod
1693 def setUpClass(cls):
1694 global subprocess
1695 assert subprocess._posixsubprocess
1696 # Reimport subprocess while forcing _posixsubprocess to not exist.
1697 with support.check_warnings(('.*_posixsubprocess .* not being used.*',
1698 RuntimeWarning)):
1699 subprocess = support.import_fresh_module(
1700 'subprocess', blocked=['_posixsubprocess'])
1701 assert not subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001702
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001703 @classmethod
1704 def tearDownClass(cls):
1705 global subprocess
1706 # Reimport subprocess as it should be, restoring order to the universe.
1707 subprocess = support.import_fresh_module('subprocess')
1708 assert subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001709
1710
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001711class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001712 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001713 def test_eintr_retry_call(self):
1714 record_calls = []
1715 def fake_os_func(*args):
1716 record_calls.append(args)
1717 if len(record_calls) == 2:
1718 raise OSError(errno.EINTR, "fake interrupted system call")
1719 return tuple(reversed(args))
1720
1721 self.assertEqual((999, 256),
1722 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1723 self.assertEqual([(256, 999)], record_calls)
1724 # This time there will be an EINTR so it will loop once.
1725 self.assertEqual((666,),
1726 subprocess._eintr_retry_call(fake_os_func, 666))
1727 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1728
1729
Tim Golden126c2962010-08-11 14:20:40 +00001730@unittest.skipUnless(mswindows, "Windows-specific tests")
1731class CommandsWithSpaces (BaseTestCase):
1732
1733 def setUp(self):
1734 super().setUp()
1735 f, fname = mkstemp(".py", "te st")
1736 self.fname = fname.lower ()
1737 os.write(f, b"import sys;"
1738 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1739 )
1740 os.close(f)
1741
1742 def tearDown(self):
1743 os.remove(self.fname)
1744 super().tearDown()
1745
1746 def with_spaces(self, *args, **kwargs):
1747 kwargs['stdout'] = subprocess.PIPE
1748 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001749 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001750 self.assertEqual(
1751 p.stdout.read ().decode("mbcs"),
1752 "2 [%r, 'ab cd']" % self.fname
1753 )
1754
1755 def test_shell_string_with_spaces(self):
1756 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001757 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1758 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001759
1760 def test_shell_sequence_with_spaces(self):
1761 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001762 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001763
1764 def test_noshell_string_with_spaces(self):
1765 # call() function with string argument with spaces on Windows
1766 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1767 "ab cd"))
1768
1769 def test_noshell_sequence_with_spaces(self):
1770 # call() function with sequence argument with spaces on Windows
1771 self.with_spaces([sys.executable, self.fname, "ab cd"])
1772
Brian Curtin79cdb662010-12-03 02:46:02 +00001773
Georg Brandla86b2622012-02-20 21:34:57 +01001774class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001775
1776 def test_pipe(self):
1777 with subprocess.Popen([sys.executable, "-c",
1778 "import sys;"
1779 "sys.stdout.write('stdout');"
1780 "sys.stderr.write('stderr');"],
1781 stdout=subprocess.PIPE,
1782 stderr=subprocess.PIPE) as proc:
1783 self.assertEqual(proc.stdout.read(), b"stdout")
1784 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1785
1786 self.assertTrue(proc.stdout.closed)
1787 self.assertTrue(proc.stderr.closed)
1788
1789 def test_returncode(self):
1790 with subprocess.Popen([sys.executable, "-c",
1791 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smithc9557af2011-05-11 22:18:23 -07001792 pass
1793 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001794 self.assertEqual(proc.returncode, 100)
1795
1796 def test_communicate_stdin(self):
1797 with subprocess.Popen([sys.executable, "-c",
1798 "import sys;"
1799 "sys.exit(sys.stdin.read() == 'context')"],
1800 stdin=subprocess.PIPE) as proc:
1801 proc.communicate(b"context")
1802 self.assertEqual(proc.returncode, 1)
1803
1804 def test_invalid_args(self):
1805 with self.assertRaises(EnvironmentError) as c:
1806 with subprocess.Popen(['nonexisting_i_hope'],
1807 stdout=subprocess.PIPE,
1808 stderr=subprocess.PIPE) as proc:
1809 pass
1810
1811 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1812 raise c.exception
1813
1814
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001815def test_main():
1816 unit_tests = (ProcessTestCase,
1817 POSIXProcessTestCase,
1818 Win32ProcessTestCase,
1819 ProcessTestCasePOSIXPurePython,
1820 CommandTests,
1821 ProcessTestCaseNoPoll,
1822 HelperFunctionTests,
1823 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001824 ContextManagerTests,
1825 )
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001826
1827 support.run_unittest(*unit_tests)
1828 support.reap_children()
1829
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001830if __name__ == "__main__":
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001831 unittest.main()