blob: 40d0fb48be82ea9e5b6fcfda4a77f7b53c40ee72 [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 Pitrouab85ff32011-07-23 22:03:45 +0200479 'sys.stdout.write(sys.stdin.readline());'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000480 'sys.stdout.flush();'
481 'sys.stdout.write("line2\\n");'
482 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200483 'sys.stdout.write(sys.stdin.read());'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000484 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200485 'sys.stdout.write("line4\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000486 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200487 'sys.stdout.write("line5\\r\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000488 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200489 'sys.stdout.write("line6\\r");'
490 'sys.stdout.flush();'
491 'sys.stdout.write("\\nline7");'
492 'sys.stdout.flush();'
493 'sys.stdout.write("\\nline8");'],
494 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000495 stdout=subprocess.PIPE,
496 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200497 p.stdin.write("line1\n")
498 self.assertEqual(p.stdout.readline(), "line1\n")
499 p.stdin.write("line3\n")
500 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000501 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200502 self.assertEqual(p.stdout.readline(),
503 "line2\n")
504 self.assertEqual(p.stdout.read(6),
505 "line3\n")
506 self.assertEqual(p.stdout.read(),
507 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000508
509 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000510 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000511 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000512 'import sys,os;' + SETBINARY +
Guido van Rossum98297ee2007-11-06 21:34:58 +0000513 'sys.stdout.write("line2\\n");'
514 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200515 'sys.stdout.write("line4\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000516 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200517 'sys.stdout.write("line5\\r\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000518 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200519 'sys.stdout.write("line6\\r");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000520 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200521 'sys.stdout.write("\\nline7");'
522 'sys.stdout.flush();'
523 'sys.stdout.write("\\nline8");'],
524 stderr=subprocess.PIPE,
525 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000526 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000527 self.addCleanup(p.stdout.close)
528 self.addCleanup(p.stderr.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200529 # BUG: can't give a non-empty stdin because it breaks both the
530 # select- and poll-based communicate() implementations.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200532 self.assertEqual(stdout,
533 "line2\nline4\nline5\nline6\nline7\nline8")
534
535 def test_universal_newlines_communicate_stdin(self):
536 # universal newlines through communicate(), with only stdin
537 p = subprocess.Popen([sys.executable, "-c",
538 'import sys,os;' + SETBINARY + '''\nif True:
539 s = sys.stdin.readline()
540 assert s == "line1\\n", repr(s)
541 s = sys.stdin.read()
542 assert s == "line3\\n", repr(s)
543 '''],
544 stdin=subprocess.PIPE,
545 universal_newlines=1)
546 (stdout, stderr) = p.communicate("line1\nline3\n")
547 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548
549 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000550 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000551 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000552 max_handles = 1026 # too much for most UNIX systems
553 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000554 max_handles = 2050 # too much for (at least some) Windows setups
555 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400556 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000557 try:
558 for i in range(max_handles):
559 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400560 tmpfile = os.path.join(tmpdir, support.TESTFN)
561 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000562 except OSError as e:
563 if e.errno != errno.EMFILE:
564 raise
565 break
566 else:
567 self.skipTest("failed to reach the file descriptor limit "
568 "(tried %d)" % max_handles)
569 # Close a couple of them (should be enough for a subprocess)
570 for i in range(10):
571 os.close(handles.pop())
572 # Loop creating some subprocesses. If one of them leaks some fds,
573 # the next loop iteration will fail by reaching the max fd limit.
574 for i in range(15):
575 p = subprocess.Popen([sys.executable, "-c",
576 "import sys;"
577 "sys.stdout.write(sys.stdin.read())"],
578 stdin=subprocess.PIPE,
579 stdout=subprocess.PIPE,
580 stderr=subprocess.PIPE)
581 data = p.communicate(b"lime")[0]
582 self.assertEqual(data, b"lime")
583 finally:
584 for h in handles:
585 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400586 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000587
588 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
590 '"a b c" d e')
591 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
592 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000593 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
594 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000595 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
596 'a\\\\\\b "de fg" h')
597 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
598 'a\\\\\\"b c d')
599 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
600 '"a\\\\b c" d e')
601 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
602 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000603 self.assertEqual(subprocess.list2cmdline(['ab', '']),
604 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000605
606
607 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000608 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000609 "-c", "import time; time.sleep(1)"])
610 count = 0
611 while p.poll() is None:
612 time.sleep(0.1)
613 count += 1
614 # We expect that the poll loop probably went around about 10 times,
615 # but, based on system scheduling we can't control, it's possible
616 # poll() never returned None. It "should be" very rare that it
617 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000618 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619 # Subsequent invocations should just return the returncode
620 self.assertEqual(p.poll(), 0)
621
622
623 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624 p = subprocess.Popen([sys.executable,
625 "-c", "import time; time.sleep(2)"])
626 self.assertEqual(p.wait(), 0)
627 # Subsequent invocations should just return the returncode
628 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000629
Peter Astrand738131d2004-11-30 21:04:45 +0000630
631 def test_invalid_bufsize(self):
632 # an invalid type of the bufsize argument should raise
633 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000634 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000635 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000636
Guido van Rossum46a05a72007-06-07 21:56:45 +0000637 def test_bufsize_is_none(self):
638 # bufsize=None should be the same as bufsize=0.
639 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
640 self.assertEqual(p.wait(), 0)
641 # Again with keyword arg
642 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
643 self.assertEqual(p.wait(), 0)
644
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000645 def test_leaking_fds_on_error(self):
646 # see bug #5179: Popen leaks file descriptors to PIPEs if
647 # the child fails to execute; this will eventually exhaust
648 # the maximum number of open fds. 1024 seems a very common
649 # value for that limit, but Windows has 2048, so we loop
650 # 1024 times (each call leaked two fds).
651 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000652 # Windows raises IOError. Others raise OSError.
653 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000654 subprocess.Popen(['nonexisting_i_hope'],
655 stdout=subprocess.PIPE,
656 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400657 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400658 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000659 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000660
Victor Stinnerb3693582010-05-21 20:13:12 +0000661 def test_issue8780(self):
662 # Ensure that stdout is inherited from the parent
663 # if stdout=PIPE is not used
664 code = ';'.join((
665 'import subprocess, sys',
666 'retcode = subprocess.call('
667 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
668 'assert retcode == 0'))
669 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000670 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000671
Tim Goldenaf5ac392010-08-06 13:03:56 +0000672 def test_handles_closed_on_exception(self):
673 # If CreateProcess exits with an error, ensure the
674 # duplicate output handles are released
675 ifhandle, ifname = mkstemp()
676 ofhandle, ofname = mkstemp()
677 efhandle, efname = mkstemp()
678 try:
679 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
680 stderr=efhandle)
681 except OSError:
682 os.close(ifhandle)
683 os.remove(ifname)
684 os.close(ofhandle)
685 os.remove(ofname)
686 os.close(efhandle)
687 os.remove(efname)
688 self.assertFalse(os.path.exists(ifname))
689 self.assertFalse(os.path.exists(ofname))
690 self.assertFalse(os.path.exists(efname))
691
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200692 def test_communicate_epipe(self):
693 # Issue 10963: communicate() should hide EPIPE
694 p = subprocess.Popen([sys.executable, "-c", 'pass'],
695 stdin=subprocess.PIPE,
696 stdout=subprocess.PIPE,
697 stderr=subprocess.PIPE)
698 self.addCleanup(p.stdout.close)
699 self.addCleanup(p.stderr.close)
700 self.addCleanup(p.stdin.close)
701 p.communicate(b"x" * 2**20)
702
703 def test_communicate_epipe_only_stdin(self):
704 # Issue 10963: communicate() should hide EPIPE
705 p = subprocess.Popen([sys.executable, "-c", 'pass'],
706 stdin=subprocess.PIPE)
707 self.addCleanup(p.stdin.close)
708 time.sleep(2)
709 p.communicate(b"x" * 2**20)
710
Victor Stinner1848db82011-07-05 14:49:46 +0200711 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
712 "Requires signal.SIGALRM")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200713 def test_communicate_eintr(self):
714 # Issue #12493: communicate() should handle EINTR
715 def handler(signum, frame):
716 pass
717 old_handler = signal.signal(signal.SIGALRM, handler)
718 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
719
720 # the process is running for 2 seconds
721 args = [sys.executable, "-c", 'import time; time.sleep(2)']
722 for stream in ('stdout', 'stderr'):
723 kw = {stream: subprocess.PIPE}
724 with subprocess.Popen(args, **kw) as process:
725 signal.alarm(1)
726 # communicate() will be interrupted by SIGALRM
727 process.communicate()
728
Tim Peterse718f612004-10-12 21:51:32 +0000729
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000730# context manager
731class _SuppressCoreFiles(object):
732 """Try to prevent core files from being created."""
733 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000734
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000735 def __enter__(self):
736 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500737 if resource is not None:
738 try:
739 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
740 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
741 except (ValueError, resource.error):
742 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000743
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000744 if sys.platform == 'darwin':
745 # Check if the 'Crash Reporter' on OSX was configured
746 # in 'Developer' mode and warn that it will get triggered
747 # when it is.
748 #
749 # This assumes that this context manager is used in tests
750 # that might trigger the next manager.
751 value = subprocess.Popen(['/usr/bin/defaults', 'read',
752 'com.apple.CrashReporter', 'DialogType'],
753 stdout=subprocess.PIPE).communicate()[0]
754 if value.strip() == b'developer':
755 print("this tests triggers the Crash Reporter, "
756 "that is intentional", end='')
757 sys.stdout.flush()
758
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000759 def __exit__(self, *args):
760 """Return core file behavior to default."""
761 if self.old_limit is None:
762 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500763 if resource is not None:
764 try:
765 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
766 except (ValueError, resource.error):
767 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000768
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000769
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000770@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000771class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000772
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000773 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000774 nonexistent_dir = "/_this/pa.th/does/not/exist"
775 try:
776 os.chdir(nonexistent_dir)
777 except OSError as e:
778 # This avoids hard coding the errno value or the OS perror()
779 # string and instead capture the exception that we want to see
780 # below for comparison.
781 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000782 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000783 else:
784 self.fail("chdir to nonexistant directory %s succeeded." %
785 nonexistent_dir)
786
787 # Error in the child re-raised in the parent.
788 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000789 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000790 cwd=nonexistent_dir)
791 except OSError as e:
792 # Test that the child process chdir failure actually makes
793 # it up to the parent process as the correct exception.
794 self.assertEqual(desired_exception.errno, e.errno)
795 self.assertEqual(desired_exception.strerror, e.strerror)
796 else:
797 self.fail("Expected OSError: %s" % desired_exception)
798
799 def test_restore_signals(self):
800 # Code coverage for both values of restore_signals to make sure it
801 # at least does not blow up.
802 # A test for behavior would be complex. Contributions welcome.
803 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
804 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
805
806 def test_start_new_session(self):
807 # For code coverage of calling setsid(). We don't care if we get an
808 # EPERM error from it depending on the test execution environment, that
809 # still indicates that it was called.
810 try:
811 output = subprocess.check_output(
812 [sys.executable, "-c",
813 "import os; print(os.getpgid(os.getpid()))"],
814 start_new_session=True)
815 except OSError as e:
816 if e.errno != errno.EPERM:
817 raise
818 else:
819 parent_pgid = os.getpgid(os.getpid())
820 child_pgid = int(output)
821 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000822
823 def test_run_abort(self):
824 # returncode handles signal termination
825 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000826 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000827 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000828 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000829 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000830
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000831 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000832 # DISCLAIMER: Setting environment variables is *not* a good use
833 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000834 p = subprocess.Popen([sys.executable, "-c",
835 'import sys,os;'
836 'sys.stdout.write(os.getenv("FRUIT"))'],
837 stdout=subprocess.PIPE,
838 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000839 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000840 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000841
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000842 def test_preexec_exception(self):
843 def raise_it():
844 raise ValueError("What if two swallows carried a coconut?")
845 try:
846 p = subprocess.Popen([sys.executable, "-c", ""],
847 preexec_fn=raise_it)
848 except RuntimeError as e:
849 self.assertTrue(
850 subprocess._posixsubprocess,
851 "Expected a ValueError from the preexec_fn")
852 except ValueError as e:
853 self.assertIn("coconut", e.args[0])
854 else:
855 self.fail("Exception raised by preexec_fn did not make it "
856 "to the parent process.")
857
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000858 def test_preexec_gc_module_failure(self):
859 # This tests the code that disables garbage collection if the child
860 # process will execute any Python.
861 def raise_runtime_error():
862 raise RuntimeError("this shouldn't escape")
863 enabled = gc.isenabled()
864 orig_gc_disable = gc.disable
865 orig_gc_isenabled = gc.isenabled
866 try:
867 gc.disable()
868 self.assertFalse(gc.isenabled())
869 subprocess.call([sys.executable, '-c', ''],
870 preexec_fn=lambda: None)
871 self.assertFalse(gc.isenabled(),
872 "Popen enabled gc when it shouldn't.")
873
874 gc.enable()
875 self.assertTrue(gc.isenabled())
876 subprocess.call([sys.executable, '-c', ''],
877 preexec_fn=lambda: None)
878 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
879
880 gc.disable = raise_runtime_error
881 self.assertRaises(RuntimeError, subprocess.Popen,
882 [sys.executable, '-c', ''],
883 preexec_fn=lambda: None)
884
885 del gc.isenabled # force an AttributeError
886 self.assertRaises(AttributeError, subprocess.Popen,
887 [sys.executable, '-c', ''],
888 preexec_fn=lambda: None)
889 finally:
890 gc.disable = orig_gc_disable
891 gc.isenabled = orig_gc_isenabled
892 if not enabled:
893 gc.disable()
894
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000895 def test_args_string(self):
896 # args is a string
897 fd, fname = mkstemp()
898 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000899 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000900 fobj.write("#!/bin/sh\n")
901 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
902 sys.executable)
903 os.chmod(fname, 0o700)
904 p = subprocess.Popen(fname)
905 p.wait()
906 os.remove(fname)
907 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000908
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000909 def test_invalid_args(self):
910 # invalid arguments should raise ValueError
911 self.assertRaises(ValueError, subprocess.call,
912 [sys.executable, "-c",
913 "import sys; sys.exit(47)"],
914 startupinfo=47)
915 self.assertRaises(ValueError, subprocess.call,
916 [sys.executable, "-c",
917 "import sys; sys.exit(47)"],
918 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000920 def test_shell_sequence(self):
921 # Run command through the shell (sequence)
922 newenv = os.environ.copy()
923 newenv["FRUIT"] = "apple"
924 p = subprocess.Popen(["echo $FRUIT"], shell=1,
925 stdout=subprocess.PIPE,
926 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000927 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000928 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000929
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000930 def test_shell_string(self):
931 # Run command through the shell (string)
932 newenv = os.environ.copy()
933 newenv["FRUIT"] = "apple"
934 p = subprocess.Popen("echo $FRUIT", shell=1,
935 stdout=subprocess.PIPE,
936 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000937 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000938 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000939
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000940 def test_call_string(self):
941 # call() function with string argument on UNIX
942 fd, fname = mkstemp()
943 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000944 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000945 fobj.write("#!/bin/sh\n")
946 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
947 sys.executable)
948 os.chmod(fname, 0o700)
949 rc = subprocess.call(fname)
950 os.remove(fname)
951 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000952
Stefan Krah9542cc62010-07-19 14:20:53 +0000953 def test_specific_shell(self):
954 # Issue #9265: Incorrect name passed as arg[0].
955 shells = []
956 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
957 for name in ['bash', 'ksh']:
958 sh = os.path.join(prefix, name)
959 if os.path.isfile(sh):
960 shells.append(sh)
961 if not shells: # Will probably work for any shell but csh.
962 self.skipTest("bash or ksh required for this test")
963 sh = '/bin/sh'
964 if os.path.isfile(sh) and not os.path.islink(sh):
965 # Test will fail if /bin/sh is a symlink to csh.
966 shells.append(sh)
967 for sh in shells:
968 p = subprocess.Popen("echo $0", executable=sh, shell=True,
969 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000970 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000971 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
972
Florent Xicluna4886d242010-03-08 13:27:26 +0000973 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000974 # Do not inherit file handles from the parent.
975 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000976 p = subprocess.Popen([sys.executable, "-c", """if 1:
977 import sys, time
978 sys.stdout.write('x\\n')
979 sys.stdout.flush()
980 time.sleep(30)
981 """],
982 close_fds=True,
983 stdin=subprocess.PIPE,
984 stdout=subprocess.PIPE,
985 stderr=subprocess.PIPE)
986 # Wait for the interpreter to be completely initialized before
987 # sending any signal.
988 p.stdout.read(1)
989 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000990 return p
991
992 def test_send_signal(self):
993 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000994 _, stderr = p.communicate()
995 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000996 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000997
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000998 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000999 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001000 _, stderr = p.communicate()
1001 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001002 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001003
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001004 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001005 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001006 _, stderr = p.communicate()
1007 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001008 self.assertEqual(p.wait(), -signal.SIGTERM)
1009
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001010 def check_close_std_fds(self, fds):
1011 # Issue #9905: test that subprocess pipes still work properly with
1012 # some standard fds closed
1013 stdin = 0
1014 newfds = []
1015 for a in fds:
1016 b = os.dup(a)
1017 newfds.append(b)
1018 if a == 0:
1019 stdin = b
1020 try:
1021 for fd in fds:
1022 os.close(fd)
1023 out, err = subprocess.Popen([sys.executable, "-c",
1024 'import sys;'
1025 'sys.stdout.write("apple");'
1026 'sys.stdout.flush();'
1027 'sys.stderr.write("orange")'],
1028 stdin=stdin,
1029 stdout=subprocess.PIPE,
1030 stderr=subprocess.PIPE).communicate()
1031 err = support.strip_python_stderr(err)
1032 self.assertEqual((out, err), (b'apple', b'orange'))
1033 finally:
1034 for b, a in zip(newfds, fds):
1035 os.dup2(b, a)
1036 for b in newfds:
1037 os.close(b)
1038
1039 def test_close_fd_0(self):
1040 self.check_close_std_fds([0])
1041
1042 def test_close_fd_1(self):
1043 self.check_close_std_fds([1])
1044
1045 def test_close_fd_2(self):
1046 self.check_close_std_fds([2])
1047
1048 def test_close_fds_0_1(self):
1049 self.check_close_std_fds([0, 1])
1050
1051 def test_close_fds_0_2(self):
1052 self.check_close_std_fds([0, 2])
1053
1054 def test_close_fds_1_2(self):
1055 self.check_close_std_fds([1, 2])
1056
1057 def test_close_fds_0_1_2(self):
1058 # Issue #10806: test that subprocess pipes still work properly with
1059 # all standard fds closed.
1060 self.check_close_std_fds([0, 1, 2])
1061
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001062 def test_remapping_std_fds(self):
1063 # open up some temporary files
1064 temps = [mkstemp() for i in range(3)]
1065 try:
1066 temp_fds = [fd for fd, fname in temps]
1067
1068 # unlink the files -- we won't need to reopen them
1069 for fd, fname in temps:
1070 os.unlink(fname)
1071
1072 # write some data to what will become stdin, and rewind
1073 os.write(temp_fds[1], b"STDIN")
1074 os.lseek(temp_fds[1], 0, 0)
1075
1076 # move the standard file descriptors out of the way
1077 saved_fds = [os.dup(fd) for fd in range(3)]
1078 try:
1079 # duplicate the file objects over the standard fd's
1080 for fd, temp_fd in enumerate(temp_fds):
1081 os.dup2(temp_fd, fd)
1082
1083 # now use those files in the "wrong" order, so that subprocess
1084 # has to rearrange them in the child
1085 p = subprocess.Popen([sys.executable, "-c",
1086 'import sys; got = sys.stdin.read();'
1087 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1088 stdin=temp_fds[1],
1089 stdout=temp_fds[2],
1090 stderr=temp_fds[0])
1091 p.wait()
1092 finally:
1093 # restore the original fd's underneath sys.stdin, etc.
1094 for std, saved in enumerate(saved_fds):
1095 os.dup2(saved, std)
1096 os.close(saved)
1097
1098 for fd in temp_fds:
1099 os.lseek(fd, 0, 0)
1100
1101 out = os.read(temp_fds[2], 1024)
1102 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1103 self.assertEqual(out, b"got STDIN")
1104 self.assertEqual(err, b"err")
1105
1106 finally:
1107 for fd in temp_fds:
1108 os.close(fd)
1109
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001110 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1111 # open up some temporary files
1112 temps = [mkstemp() for i in range(3)]
1113 temp_fds = [fd for fd, fname in temps]
1114 try:
1115 # unlink the files -- we won't need to reopen them
1116 for fd, fname in temps:
1117 os.unlink(fname)
1118
1119 # save a copy of the standard file descriptors
1120 saved_fds = [os.dup(fd) for fd in range(3)]
1121 try:
1122 # duplicate the temp files over the standard fd's 0, 1, 2
1123 for fd, temp_fd in enumerate(temp_fds):
1124 os.dup2(temp_fd, fd)
1125
1126 # write some data to what will become stdin, and rewind
1127 os.write(stdin_no, b"STDIN")
1128 os.lseek(stdin_no, 0, 0)
1129
1130 # now use those files in the given order, so that subprocess
1131 # has to rearrange them in the child
1132 p = subprocess.Popen([sys.executable, "-c",
1133 'import sys; got = sys.stdin.read();'
1134 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1135 stdin=stdin_no,
1136 stdout=stdout_no,
1137 stderr=stderr_no)
1138 p.wait()
1139
1140 for fd in temp_fds:
1141 os.lseek(fd, 0, 0)
1142
1143 out = os.read(stdout_no, 1024)
1144 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1145 finally:
1146 for std, saved in enumerate(saved_fds):
1147 os.dup2(saved, std)
1148 os.close(saved)
1149
1150 self.assertEqual(out, b"got STDIN")
1151 self.assertEqual(err, b"err")
1152
1153 finally:
1154 for fd in temp_fds:
1155 os.close(fd)
1156
1157 # When duping fds, if there arises a situation where one of the fds is
1158 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1159 # This tests all combinations of this.
1160 def test_swap_fds(self):
1161 self.check_swap_fds(0, 1, 2)
1162 self.check_swap_fds(0, 2, 1)
1163 self.check_swap_fds(1, 0, 2)
1164 self.check_swap_fds(1, 2, 0)
1165 self.check_swap_fds(2, 0, 1)
1166 self.check_swap_fds(2, 1, 0)
1167
Victor Stinner13bb71c2010-04-23 21:41:56 +00001168 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001169 def prepare():
1170 raise ValueError("surrogate:\uDCff")
1171
1172 try:
1173 subprocess.call(
1174 [sys.executable, "-c", "pass"],
1175 preexec_fn=prepare)
1176 except ValueError as err:
1177 # Pure Python implementations keeps the message
1178 self.assertIsNone(subprocess._posixsubprocess)
1179 self.assertEqual(str(err), "surrogate:\uDCff")
1180 except RuntimeError as err:
1181 # _posixsubprocess uses a default message
1182 self.assertIsNotNone(subprocess._posixsubprocess)
1183 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1184 else:
1185 self.fail("Expected ValueError or RuntimeError")
1186
Victor Stinner13bb71c2010-04-23 21:41:56 +00001187 def test_undecodable_env(self):
1188 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001189 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001190 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001191 env = os.environ.copy()
1192 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001193 # Use C locale to get ascii for the locale encoding to force
1194 # surrogate-escaping of \xFF in the child process; otherwise it can
1195 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001196 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001197 stdout = subprocess.check_output(
1198 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001199 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001200 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001201 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001202
1203 # test bytes
1204 key = key.encode("ascii", "surrogateescape")
1205 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001206 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001207 env = os.environ.copy()
1208 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001209 stdout = subprocess.check_output(
1210 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001211 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001212 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001213 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001214
Victor Stinnerb745a742010-05-18 17:17:23 +00001215 def test_bytes_program(self):
1216 abs_program = os.fsencode(sys.executable)
1217 path, program = os.path.split(sys.executable)
1218 program = os.fsencode(program)
1219
1220 # absolute bytes path
1221 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001222 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001223
1224 # bytes program, unicode PATH
1225 env = os.environ.copy()
1226 env["PATH"] = path
1227 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001228 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001229
1230 # bytes program, bytes PATH
1231 envb = os.environb.copy()
1232 envb[b"PATH"] = os.fsencode(path)
1233 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001234 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001235
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001236 def test_pipe_cloexec(self):
1237 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1238 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1239
1240 p1 = subprocess.Popen([sys.executable, sleeper],
1241 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1242 stderr=subprocess.PIPE, close_fds=False)
1243
1244 self.addCleanup(p1.communicate, b'')
1245
1246 p2 = subprocess.Popen([sys.executable, fd_status],
1247 stdout=subprocess.PIPE, close_fds=False)
1248
1249 output, error = p2.communicate()
1250 result_fds = set(map(int, output.split(b',')))
1251 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1252 p1.stderr.fileno()])
1253
1254 self.assertFalse(result_fds & unwanted_fds,
1255 "Expected no fds from %r to be open in child, "
1256 "found %r" %
1257 (unwanted_fds, result_fds & unwanted_fds))
1258
1259 def test_pipe_cloexec_real_tools(self):
1260 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1261 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1262
1263 subdata = b'zxcvbn'
1264 data = subdata * 4 + b'\n'
1265
1266 p1 = subprocess.Popen([sys.executable, qcat],
1267 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1268 close_fds=False)
1269
1270 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1271 stdin=p1.stdout, stdout=subprocess.PIPE,
1272 close_fds=False)
1273
1274 self.addCleanup(p1.wait)
1275 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001276 def kill_p1():
1277 try:
1278 p1.terminate()
1279 except ProcessLookupError:
1280 pass
1281 def kill_p2():
1282 try:
1283 p2.terminate()
1284 except ProcessLookupError:
1285 pass
1286 self.addCleanup(kill_p1)
1287 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001288
1289 p1.stdin.write(data)
1290 p1.stdin.close()
1291
1292 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1293
1294 self.assertTrue(readfiles, "The child hung")
1295 self.assertEqual(p2.stdout.read(), data)
1296
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001297 p1.stdout.close()
1298 p2.stdout.close()
1299
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001300 def test_close_fds(self):
1301 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1302
1303 fds = os.pipe()
1304 self.addCleanup(os.close, fds[0])
1305 self.addCleanup(os.close, fds[1])
1306
1307 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001308 # add a bunch more fds
1309 for _ in range(9):
1310 fd = os.open("/dev/null", os.O_RDONLY)
1311 self.addCleanup(os.close, fd)
1312 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001313
1314 p = subprocess.Popen([sys.executable, fd_status],
1315 stdout=subprocess.PIPE, close_fds=False)
1316 output, ignored = p.communicate()
1317 remaining_fds = set(map(int, output.split(b',')))
1318
1319 self.assertEqual(remaining_fds & open_fds, open_fds,
1320 "Some fds were closed")
1321
1322 p = subprocess.Popen([sys.executable, fd_status],
1323 stdout=subprocess.PIPE, close_fds=True)
1324 output, ignored = p.communicate()
1325 remaining_fds = set(map(int, output.split(b',')))
1326
1327 self.assertFalse(remaining_fds & open_fds,
1328 "Some fds were left open")
1329 self.assertIn(1, remaining_fds, "Subprocess failed")
1330
Gregory P. Smith8facece2012-01-21 14:01:08 -08001331 # Keep some of the fd's we opened open in the subprocess.
1332 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1333 fds_to_keep = set(open_fds.pop() for _ in range(8))
1334 p = subprocess.Popen([sys.executable, fd_status],
1335 stdout=subprocess.PIPE, close_fds=True,
1336 pass_fds=())
1337 output, ignored = p.communicate()
1338 remaining_fds = set(map(int, output.split(b',')))
1339
1340 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1341 "Some fds not in pass_fds were left open")
1342 self.assertIn(1, remaining_fds, "Subprocess failed")
1343
Victor Stinner88701e22011-06-01 13:13:04 +02001344 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1345 # descriptor of a pipe closed in the parent process is valid in the
1346 # child process according to fstat(), but the mode of the file
1347 # descriptor is invalid, and read or write raise an error.
1348 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001349 def test_pass_fds(self):
1350 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1351
1352 open_fds = set()
1353
1354 for x in range(5):
1355 fds = os.pipe()
1356 self.addCleanup(os.close, fds[0])
1357 self.addCleanup(os.close, fds[1])
1358 open_fds.update(fds)
1359
1360 for fd in open_fds:
1361 p = subprocess.Popen([sys.executable, fd_status],
1362 stdout=subprocess.PIPE, close_fds=True,
1363 pass_fds=(fd, ))
1364 output, ignored = p.communicate()
1365
1366 remaining_fds = set(map(int, output.split(b',')))
1367 to_be_closed = open_fds - {fd}
1368
1369 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1370 self.assertFalse(remaining_fds & to_be_closed,
1371 "fd to be closed passed")
1372
1373 # pass_fds overrides close_fds with a warning.
1374 with self.assertWarns(RuntimeWarning) as context:
1375 self.assertFalse(subprocess.call(
1376 [sys.executable, "-c", "import sys; sys.exit(0)"],
1377 close_fds=False, pass_fds=(fd, )))
1378 self.assertIn('overriding close_fds', str(context.warning))
1379
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001380 def test_stdout_stdin_are_single_inout_fd(self):
1381 with io.open(os.devnull, "r+") as inout:
1382 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1383 stdout=inout, stdin=inout)
1384 p.wait()
1385
1386 def test_stdout_stderr_are_single_inout_fd(self):
1387 with io.open(os.devnull, "r+") as inout:
1388 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1389 stdout=inout, stderr=inout)
1390 p.wait()
1391
1392 def test_stderr_stdin_are_single_inout_fd(self):
1393 with io.open(os.devnull, "r+") as inout:
1394 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1395 stderr=inout, stdin=inout)
1396 p.wait()
1397
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001398 def test_wait_when_sigchild_ignored(self):
1399 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1400 sigchild_ignore = support.findfile("sigchild_ignore.py",
1401 subdir="subprocessdata")
1402 p = subprocess.Popen([sys.executable, sigchild_ignore],
1403 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1404 stdout, stderr = p.communicate()
1405 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001406 " non-zero with this error:\n%s" %
1407 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001408
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001409 def test_select_unbuffered(self):
1410 # Issue #11459: bufsize=0 should really set the pipes as
1411 # unbuffered (and therefore let select() work properly).
1412 select = support.import_module("select")
1413 p = subprocess.Popen([sys.executable, "-c",
1414 'import sys;'
1415 'sys.stdout.write("apple")'],
1416 stdout=subprocess.PIPE,
1417 bufsize=0)
1418 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001419 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001420 try:
1421 self.assertEqual(f.read(4), b"appl")
1422 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1423 finally:
1424 p.wait()
1425
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001426 def test_zombie_fast_process_del(self):
1427 # Issue #12650: on Unix, if Popen.__del__() was called before the
1428 # process exited, it wouldn't be added to subprocess._active, and would
1429 # remain a zombie.
1430 # spawn a Popen, and delete its reference before it exits
1431 p = subprocess.Popen([sys.executable, "-c",
1432 'import sys, time;'
1433 'time.sleep(0.2)'],
1434 stdout=subprocess.PIPE,
1435 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001436 self.addCleanup(p.stdout.close)
1437 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001438 ident = id(p)
1439 pid = p.pid
1440 del p
1441 # check that p is in the active processes list
1442 self.assertIn(ident, [id(o) for o in subprocess._active])
1443
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001444 def test_leak_fast_process_del_killed(self):
1445 # Issue #12650: on Unix, if Popen.__del__() was called before the
1446 # process exited, and the process got killed by a signal, it would never
1447 # be removed from subprocess._active, which triggered a FD and memory
1448 # leak.
1449 # spawn a Popen, delete its reference and kill it
1450 p = subprocess.Popen([sys.executable, "-c",
1451 'import time;'
1452 'time.sleep(3)'],
1453 stdout=subprocess.PIPE,
1454 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001455 self.addCleanup(p.stdout.close)
1456 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001457 ident = id(p)
1458 pid = p.pid
1459 del p
1460 os.kill(pid, signal.SIGKILL)
1461 # check that p is in the active processes list
1462 self.assertIn(ident, [id(o) for o in subprocess._active])
1463
1464 # let some time for the process to exit, and create a new Popen: this
1465 # should trigger the wait() of p
1466 time.sleep(0.2)
1467 with self.assertRaises(EnvironmentError) as c:
1468 with subprocess.Popen(['nonexisting_i_hope'],
1469 stdout=subprocess.PIPE,
1470 stderr=subprocess.PIPE) as proc:
1471 pass
1472 # p should have been wait()ed on, and removed from the _active list
1473 self.assertRaises(OSError, os.waitpid, pid, 0)
1474 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1475
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001476
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001477@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001478class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001479
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001480 def test_startupinfo(self):
1481 # startupinfo argument
1482 # We uses hardcoded constants, because we do not want to
1483 # depend on win32all.
1484 STARTF_USESHOWWINDOW = 1
1485 SW_MAXIMIZE = 3
1486 startupinfo = subprocess.STARTUPINFO()
1487 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1488 startupinfo.wShowWindow = SW_MAXIMIZE
1489 # Since Python is a console process, it won't be affected
1490 # by wShowWindow, but the argument should be silently
1491 # ignored
1492 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001493 startupinfo=startupinfo)
1494
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001495 def test_creationflags(self):
1496 # creationflags argument
1497 CREATE_NEW_CONSOLE = 16
1498 sys.stderr.write(" a DOS box should flash briefly ...\n")
1499 subprocess.call(sys.executable +
1500 ' -c "import time; time.sleep(0.25)"',
1501 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001502
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001503 def test_invalid_args(self):
1504 # invalid arguments should raise ValueError
1505 self.assertRaises(ValueError, subprocess.call,
1506 [sys.executable, "-c",
1507 "import sys; sys.exit(47)"],
1508 preexec_fn=lambda: 1)
1509 self.assertRaises(ValueError, subprocess.call,
1510 [sys.executable, "-c",
1511 "import sys; sys.exit(47)"],
1512 stdout=subprocess.PIPE,
1513 close_fds=True)
1514
1515 def test_close_fds(self):
1516 # close file descriptors
1517 rc = subprocess.call([sys.executable, "-c",
1518 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001519 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001520 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001521
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001522 def test_shell_sequence(self):
1523 # Run command through the shell (sequence)
1524 newenv = os.environ.copy()
1525 newenv["FRUIT"] = "physalis"
1526 p = subprocess.Popen(["set"], shell=1,
1527 stdout=subprocess.PIPE,
1528 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001529 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001530 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001531
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001532 def test_shell_string(self):
1533 # Run command through the shell (string)
1534 newenv = os.environ.copy()
1535 newenv["FRUIT"] = "physalis"
1536 p = subprocess.Popen("set", shell=1,
1537 stdout=subprocess.PIPE,
1538 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001539 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001540 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001541
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001542 def test_call_string(self):
1543 # call() function with string argument on Windows
1544 rc = subprocess.call(sys.executable +
1545 ' -c "import sys; sys.exit(47)"')
1546 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001547
Florent Xicluna4886d242010-03-08 13:27:26 +00001548 def _kill_process(self, method, *args):
1549 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001550 p = subprocess.Popen([sys.executable, "-c", """if 1:
1551 import sys, time
1552 sys.stdout.write('x\\n')
1553 sys.stdout.flush()
1554 time.sleep(30)
1555 """],
1556 stdin=subprocess.PIPE,
1557 stdout=subprocess.PIPE,
1558 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001559 self.addCleanup(p.stdout.close)
1560 self.addCleanup(p.stderr.close)
1561 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001562 # Wait for the interpreter to be completely initialized before
1563 # sending any signal.
1564 p.stdout.read(1)
1565 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001566 _, stderr = p.communicate()
1567 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001568 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001569 self.assertNotEqual(returncode, 0)
1570
1571 def test_send_signal(self):
1572 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001573
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001574 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001575 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001576
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001577 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001578 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001579
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001580
Brett Cannona23810f2008-05-26 19:04:21 +00001581# The module says:
1582# "NB This only works (and is only relevant) for UNIX."
1583#
1584# Actually, getoutput should work on any platform with an os.popen, but
1585# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001586@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001587class CommandTests(unittest.TestCase):
1588 def test_getoutput(self):
1589 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1590 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1591 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001592
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001593 # we use mkdtemp in the next line to create an empty directory
1594 # under our exclusive control; from that, we can invent a pathname
1595 # that we _know_ won't exist. This is guaranteed to fail.
1596 dir = None
1597 try:
1598 dir = tempfile.mkdtemp()
1599 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001600
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001601 status, output = subprocess.getstatusoutput('cat ' + name)
1602 self.assertNotEqual(status, 0)
1603 finally:
1604 if dir is not None:
1605 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001606
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001607
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001608@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1609 "poll system call not supported")
1610class ProcessTestCaseNoPoll(ProcessTestCase):
1611 def setUp(self):
1612 subprocess._has_poll = False
1613 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001614
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001615 def tearDown(self):
1616 subprocess._has_poll = True
1617 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001618
1619
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001620@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1621 "_posixsubprocess extension module not found.")
1622class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001623 @classmethod
1624 def setUpClass(cls):
1625 global subprocess
1626 assert subprocess._posixsubprocess
1627 # Reimport subprocess while forcing _posixsubprocess to not exist.
1628 with support.check_warnings(('.*_posixsubprocess .* not being used.*',
1629 RuntimeWarning)):
1630 subprocess = support.import_fresh_module(
1631 'subprocess', blocked=['_posixsubprocess'])
1632 assert not subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001633
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001634 @classmethod
1635 def tearDownClass(cls):
1636 global subprocess
1637 # Reimport subprocess as it should be, restoring order to the universe.
1638 subprocess = support.import_fresh_module('subprocess')
1639 assert subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001640
1641
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001642class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001643 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001644 def test_eintr_retry_call(self):
1645 record_calls = []
1646 def fake_os_func(*args):
1647 record_calls.append(args)
1648 if len(record_calls) == 2:
1649 raise OSError(errno.EINTR, "fake interrupted system call")
1650 return tuple(reversed(args))
1651
1652 self.assertEqual((999, 256),
1653 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1654 self.assertEqual([(256, 999)], record_calls)
1655 # This time there will be an EINTR so it will loop once.
1656 self.assertEqual((666,),
1657 subprocess._eintr_retry_call(fake_os_func, 666))
1658 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1659
1660
Tim Golden126c2962010-08-11 14:20:40 +00001661@unittest.skipUnless(mswindows, "Windows-specific tests")
1662class CommandsWithSpaces (BaseTestCase):
1663
1664 def setUp(self):
1665 super().setUp()
1666 f, fname = mkstemp(".py", "te st")
1667 self.fname = fname.lower ()
1668 os.write(f, b"import sys;"
1669 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1670 )
1671 os.close(f)
1672
1673 def tearDown(self):
1674 os.remove(self.fname)
1675 super().tearDown()
1676
1677 def with_spaces(self, *args, **kwargs):
1678 kwargs['stdout'] = subprocess.PIPE
1679 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001680 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001681 self.assertEqual(
1682 p.stdout.read ().decode("mbcs"),
1683 "2 [%r, 'ab cd']" % self.fname
1684 )
1685
1686 def test_shell_string_with_spaces(self):
1687 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001688 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1689 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001690
1691 def test_shell_sequence_with_spaces(self):
1692 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001693 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001694
1695 def test_noshell_string_with_spaces(self):
1696 # call() function with string argument with spaces on Windows
1697 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1698 "ab cd"))
1699
1700 def test_noshell_sequence_with_spaces(self):
1701 # call() function with sequence argument with spaces on Windows
1702 self.with_spaces([sys.executable, self.fname, "ab cd"])
1703
Brian Curtin79cdb662010-12-03 02:46:02 +00001704
1705class ContextManagerTests(ProcessTestCase):
1706
1707 def test_pipe(self):
1708 with subprocess.Popen([sys.executable, "-c",
1709 "import sys;"
1710 "sys.stdout.write('stdout');"
1711 "sys.stderr.write('stderr');"],
1712 stdout=subprocess.PIPE,
1713 stderr=subprocess.PIPE) as proc:
1714 self.assertEqual(proc.stdout.read(), b"stdout")
1715 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1716
1717 self.assertTrue(proc.stdout.closed)
1718 self.assertTrue(proc.stderr.closed)
1719
1720 def test_returncode(self):
1721 with subprocess.Popen([sys.executable, "-c",
1722 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smithc9557af2011-05-11 22:18:23 -07001723 pass
1724 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001725 self.assertEqual(proc.returncode, 100)
1726
1727 def test_communicate_stdin(self):
1728 with subprocess.Popen([sys.executable, "-c",
1729 "import sys;"
1730 "sys.exit(sys.stdin.read() == 'context')"],
1731 stdin=subprocess.PIPE) as proc:
1732 proc.communicate(b"context")
1733 self.assertEqual(proc.returncode, 1)
1734
1735 def test_invalid_args(self):
1736 with self.assertRaises(EnvironmentError) as c:
1737 with subprocess.Popen(['nonexisting_i_hope'],
1738 stdout=subprocess.PIPE,
1739 stderr=subprocess.PIPE) as proc:
1740 pass
1741
1742 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1743 raise c.exception
1744
1745
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001746def test_main():
1747 unit_tests = (ProcessTestCase,
1748 POSIXProcessTestCase,
1749 Win32ProcessTestCase,
1750 ProcessTestCasePOSIXPurePython,
1751 CommandTests,
1752 ProcessTestCaseNoPoll,
1753 HelperFunctionTests,
1754 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001755 ContextManagerTests,
1756 )
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001757
1758 support.run_unittest(*unit_tests)
1759 support.reap_children()
1760
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001761if __name__ == "__main__":
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001762 unittest.main()