blob: 9e92a962277e5001b2fb24422be1a0249517bc3c [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
Andrew Svetlovf3765072012-08-14 18:35:17 +0300551 def test_universal_newlines_communicate_input_none(self):
552 # Test communicate(input=None) with universal newlines.
553 #
554 # We set stdout to PIPE because, as of this writing, a different
555 # code path is tested when the number of pipes is zero or one.
556 p = subprocess.Popen([sys.executable, "-c", "pass"],
557 stdin=subprocess.PIPE,
558 stdout=subprocess.PIPE,
559 universal_newlines=True)
560 p.communicate()
561 self.assertEqual(p.returncode, 0)
562
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000564 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000565 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000566 max_handles = 1026 # too much for most UNIX systems
567 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000568 max_handles = 2050 # too much for (at least some) Windows setups
569 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400570 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000571 try:
572 for i in range(max_handles):
573 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400574 tmpfile = os.path.join(tmpdir, support.TESTFN)
575 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000576 except OSError as e:
577 if e.errno != errno.EMFILE:
578 raise
579 break
580 else:
581 self.skipTest("failed to reach the file descriptor limit "
582 "(tried %d)" % max_handles)
583 # Close a couple of them (should be enough for a subprocess)
584 for i in range(10):
585 os.close(handles.pop())
586 # Loop creating some subprocesses. If one of them leaks some fds,
587 # the next loop iteration will fail by reaching the max fd limit.
588 for i in range(15):
589 p = subprocess.Popen([sys.executable, "-c",
590 "import sys;"
591 "sys.stdout.write(sys.stdin.read())"],
592 stdin=subprocess.PIPE,
593 stdout=subprocess.PIPE,
594 stderr=subprocess.PIPE)
595 data = p.communicate(b"lime")[0]
596 self.assertEqual(data, b"lime")
597 finally:
598 for h in handles:
599 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400600 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601
602 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000603 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
604 '"a b c" d e')
605 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
606 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000607 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
608 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000609 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
610 'a\\\\\\b "de fg" h')
611 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
612 'a\\\\\\"b c d')
613 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
614 '"a\\\\b c" d e')
615 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
616 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000617 self.assertEqual(subprocess.list2cmdline(['ab', '']),
618 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619
620
621 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000622 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000623 "-c", "import time; time.sleep(1)"])
624 count = 0
625 while p.poll() is None:
626 time.sleep(0.1)
627 count += 1
628 # We expect that the poll loop probably went around about 10 times,
629 # but, based on system scheduling we can't control, it's possible
630 # poll() never returned None. It "should be" very rare that it
631 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000632 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000633 # Subsequent invocations should just return the returncode
634 self.assertEqual(p.poll(), 0)
635
636
637 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000638 p = subprocess.Popen([sys.executable,
639 "-c", "import time; time.sleep(2)"])
640 self.assertEqual(p.wait(), 0)
641 # Subsequent invocations should just return the returncode
642 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000643
Peter Astrand738131d2004-11-30 21:04:45 +0000644
645 def test_invalid_bufsize(self):
646 # an invalid type of the bufsize argument should raise
647 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000648 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000649 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000650
Guido van Rossum46a05a72007-06-07 21:56:45 +0000651 def test_bufsize_is_none(self):
652 # bufsize=None should be the same as bufsize=0.
653 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
654 self.assertEqual(p.wait(), 0)
655 # Again with keyword arg
656 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
657 self.assertEqual(p.wait(), 0)
658
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000659 def test_leaking_fds_on_error(self):
660 # see bug #5179: Popen leaks file descriptors to PIPEs if
661 # the child fails to execute; this will eventually exhaust
662 # the maximum number of open fds. 1024 seems a very common
663 # value for that limit, but Windows has 2048, so we loop
664 # 1024 times (each call leaked two fds).
665 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000666 # Windows raises IOError. Others raise OSError.
667 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000668 subprocess.Popen(['nonexisting_i_hope'],
669 stdout=subprocess.PIPE,
670 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400671 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400672 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000673 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000674
Victor Stinnerb3693582010-05-21 20:13:12 +0000675 def test_issue8780(self):
676 # Ensure that stdout is inherited from the parent
677 # if stdout=PIPE is not used
678 code = ';'.join((
679 'import subprocess, sys',
680 'retcode = subprocess.call('
681 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
682 'assert retcode == 0'))
683 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000684 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000685
Tim Goldenaf5ac392010-08-06 13:03:56 +0000686 def test_handles_closed_on_exception(self):
687 # If CreateProcess exits with an error, ensure the
688 # duplicate output handles are released
689 ifhandle, ifname = mkstemp()
690 ofhandle, ofname = mkstemp()
691 efhandle, efname = mkstemp()
692 try:
693 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
694 stderr=efhandle)
695 except OSError:
696 os.close(ifhandle)
697 os.remove(ifname)
698 os.close(ofhandle)
699 os.remove(ofname)
700 os.close(efhandle)
701 os.remove(efname)
702 self.assertFalse(os.path.exists(ifname))
703 self.assertFalse(os.path.exists(ofname))
704 self.assertFalse(os.path.exists(efname))
705
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200706 def test_communicate_epipe(self):
707 # Issue 10963: communicate() should hide EPIPE
708 p = subprocess.Popen([sys.executable, "-c", 'pass'],
709 stdin=subprocess.PIPE,
710 stdout=subprocess.PIPE,
711 stderr=subprocess.PIPE)
712 self.addCleanup(p.stdout.close)
713 self.addCleanup(p.stderr.close)
714 self.addCleanup(p.stdin.close)
715 p.communicate(b"x" * 2**20)
716
717 def test_communicate_epipe_only_stdin(self):
718 # Issue 10963: communicate() should hide EPIPE
719 p = subprocess.Popen([sys.executable, "-c", 'pass'],
720 stdin=subprocess.PIPE)
721 self.addCleanup(p.stdin.close)
722 time.sleep(2)
723 p.communicate(b"x" * 2**20)
724
Victor Stinner1848db82011-07-05 14:49:46 +0200725 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
726 "Requires signal.SIGALRM")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200727 def test_communicate_eintr(self):
728 # Issue #12493: communicate() should handle EINTR
729 def handler(signum, frame):
730 pass
731 old_handler = signal.signal(signal.SIGALRM, handler)
732 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
733
734 # the process is running for 2 seconds
735 args = [sys.executable, "-c", 'import time; time.sleep(2)']
736 for stream in ('stdout', 'stderr'):
737 kw = {stream: subprocess.PIPE}
738 with subprocess.Popen(args, **kw) as process:
739 signal.alarm(1)
740 # communicate() will be interrupted by SIGALRM
741 process.communicate()
742
Tim Peterse718f612004-10-12 21:51:32 +0000743
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000744# context manager
745class _SuppressCoreFiles(object):
746 """Try to prevent core files from being created."""
747 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000748
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000749 def __enter__(self):
750 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500751 if resource is not None:
752 try:
753 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
754 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
755 except (ValueError, resource.error):
756 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000757
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000758 if sys.platform == 'darwin':
759 # Check if the 'Crash Reporter' on OSX was configured
760 # in 'Developer' mode and warn that it will get triggered
761 # when it is.
762 #
763 # This assumes that this context manager is used in tests
764 # that might trigger the next manager.
765 value = subprocess.Popen(['/usr/bin/defaults', 'read',
766 'com.apple.CrashReporter', 'DialogType'],
767 stdout=subprocess.PIPE).communicate()[0]
768 if value.strip() == b'developer':
769 print("this tests triggers the Crash Reporter, "
770 "that is intentional", end='')
771 sys.stdout.flush()
772
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000773 def __exit__(self, *args):
774 """Return core file behavior to default."""
775 if self.old_limit is None:
776 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500777 if resource is not None:
778 try:
779 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
780 except (ValueError, resource.error):
781 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000782
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000783
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000784@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000785class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000786
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000787 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000788 nonexistent_dir = "/_this/pa.th/does/not/exist"
789 try:
790 os.chdir(nonexistent_dir)
791 except OSError as e:
792 # This avoids hard coding the errno value or the OS perror()
793 # string and instead capture the exception that we want to see
794 # below for comparison.
795 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000796 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000797 else:
798 self.fail("chdir to nonexistant directory %s succeeded." %
799 nonexistent_dir)
800
801 # Error in the child re-raised in the parent.
802 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000803 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000804 cwd=nonexistent_dir)
805 except OSError as e:
806 # Test that the child process chdir failure actually makes
807 # it up to the parent process as the correct exception.
808 self.assertEqual(desired_exception.errno, e.errno)
809 self.assertEqual(desired_exception.strerror, e.strerror)
810 else:
811 self.fail("Expected OSError: %s" % desired_exception)
812
813 def test_restore_signals(self):
814 # Code coverage for both values of restore_signals to make sure it
815 # at least does not blow up.
816 # A test for behavior would be complex. Contributions welcome.
817 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
818 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
819
820 def test_start_new_session(self):
821 # For code coverage of calling setsid(). We don't care if we get an
822 # EPERM error from it depending on the test execution environment, that
823 # still indicates that it was called.
824 try:
825 output = subprocess.check_output(
826 [sys.executable, "-c",
827 "import os; print(os.getpgid(os.getpid()))"],
828 start_new_session=True)
829 except OSError as e:
830 if e.errno != errno.EPERM:
831 raise
832 else:
833 parent_pgid = os.getpgid(os.getpid())
834 child_pgid = int(output)
835 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000836
837 def test_run_abort(self):
838 # returncode handles signal termination
839 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000840 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000841 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000842 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000843 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000844
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000845 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000846 # DISCLAIMER: Setting environment variables is *not* a good use
847 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000848 p = subprocess.Popen([sys.executable, "-c",
849 'import sys,os;'
850 'sys.stdout.write(os.getenv("FRUIT"))'],
851 stdout=subprocess.PIPE,
852 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000853 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000854 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000856 def test_preexec_exception(self):
857 def raise_it():
858 raise ValueError("What if two swallows carried a coconut?")
859 try:
860 p = subprocess.Popen([sys.executable, "-c", ""],
861 preexec_fn=raise_it)
862 except RuntimeError as e:
863 self.assertTrue(
864 subprocess._posixsubprocess,
865 "Expected a ValueError from the preexec_fn")
866 except ValueError as e:
867 self.assertIn("coconut", e.args[0])
868 else:
869 self.fail("Exception raised by preexec_fn did not make it "
870 "to the parent process.")
871
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000872 def test_preexec_gc_module_failure(self):
873 # This tests the code that disables garbage collection if the child
874 # process will execute any Python.
875 def raise_runtime_error():
876 raise RuntimeError("this shouldn't escape")
877 enabled = gc.isenabled()
878 orig_gc_disable = gc.disable
879 orig_gc_isenabled = gc.isenabled
880 try:
881 gc.disable()
882 self.assertFalse(gc.isenabled())
883 subprocess.call([sys.executable, '-c', ''],
884 preexec_fn=lambda: None)
885 self.assertFalse(gc.isenabled(),
886 "Popen enabled gc when it shouldn't.")
887
888 gc.enable()
889 self.assertTrue(gc.isenabled())
890 subprocess.call([sys.executable, '-c', ''],
891 preexec_fn=lambda: None)
892 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
893
894 gc.disable = raise_runtime_error
895 self.assertRaises(RuntimeError, subprocess.Popen,
896 [sys.executable, '-c', ''],
897 preexec_fn=lambda: None)
898
899 del gc.isenabled # force an AttributeError
900 self.assertRaises(AttributeError, subprocess.Popen,
901 [sys.executable, '-c', ''],
902 preexec_fn=lambda: None)
903 finally:
904 gc.disable = orig_gc_disable
905 gc.isenabled = orig_gc_isenabled
906 if not enabled:
907 gc.disable()
908
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000909 def test_args_string(self):
910 # args is a string
911 fd, fname = mkstemp()
912 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000913 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000914 fobj.write("#!/bin/sh\n")
915 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
916 sys.executable)
917 os.chmod(fname, 0o700)
918 p = subprocess.Popen(fname)
919 p.wait()
920 os.remove(fname)
921 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000922
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000923 def test_invalid_args(self):
924 # invalid arguments should raise ValueError
925 self.assertRaises(ValueError, subprocess.call,
926 [sys.executable, "-c",
927 "import sys; sys.exit(47)"],
928 startupinfo=47)
929 self.assertRaises(ValueError, subprocess.call,
930 [sys.executable, "-c",
931 "import sys; sys.exit(47)"],
932 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000933
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000934 def test_shell_sequence(self):
935 # Run command through the shell (sequence)
936 newenv = os.environ.copy()
937 newenv["FRUIT"] = "apple"
938 p = subprocess.Popen(["echo $FRUIT"], shell=1,
939 stdout=subprocess.PIPE,
940 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000941 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000942 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000943
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000944 def test_shell_string(self):
945 # Run command through the shell (string)
946 newenv = os.environ.copy()
947 newenv["FRUIT"] = "apple"
948 p = subprocess.Popen("echo $FRUIT", shell=1,
949 stdout=subprocess.PIPE,
950 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000951 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000952 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000953
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000954 def test_call_string(self):
955 # call() function with string argument on UNIX
956 fd, fname = mkstemp()
957 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000958 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000959 fobj.write("#!/bin/sh\n")
960 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
961 sys.executable)
962 os.chmod(fname, 0o700)
963 rc = subprocess.call(fname)
964 os.remove(fname)
965 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000966
Stefan Krah9542cc62010-07-19 14:20:53 +0000967 def test_specific_shell(self):
968 # Issue #9265: Incorrect name passed as arg[0].
969 shells = []
970 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
971 for name in ['bash', 'ksh']:
972 sh = os.path.join(prefix, name)
973 if os.path.isfile(sh):
974 shells.append(sh)
975 if not shells: # Will probably work for any shell but csh.
976 self.skipTest("bash or ksh required for this test")
977 sh = '/bin/sh'
978 if os.path.isfile(sh) and not os.path.islink(sh):
979 # Test will fail if /bin/sh is a symlink to csh.
980 shells.append(sh)
981 for sh in shells:
982 p = subprocess.Popen("echo $0", executable=sh, shell=True,
983 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000984 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000985 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
986
Florent Xicluna4886d242010-03-08 13:27:26 +0000987 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000988 # Do not inherit file handles from the parent.
989 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000990 p = subprocess.Popen([sys.executable, "-c", """if 1:
991 import sys, time
992 sys.stdout.write('x\\n')
993 sys.stdout.flush()
994 time.sleep(30)
995 """],
996 close_fds=True,
997 stdin=subprocess.PIPE,
998 stdout=subprocess.PIPE,
999 stderr=subprocess.PIPE)
1000 # Wait for the interpreter to be completely initialized before
1001 # sending any signal.
1002 p.stdout.read(1)
1003 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001004 return p
1005
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001006 def _kill_dead_process(self, method, *args):
1007 # Do not inherit file handles from the parent.
1008 # It should fix failures on some platforms.
1009 p = subprocess.Popen([sys.executable, "-c", """if 1:
1010 import sys, time
1011 sys.stdout.write('x\\n')
1012 sys.stdout.flush()
1013 """],
1014 close_fds=True,
1015 stdin=subprocess.PIPE,
1016 stdout=subprocess.PIPE,
1017 stderr=subprocess.PIPE)
1018 # Wait for the interpreter to be completely initialized before
1019 # sending any signal.
1020 p.stdout.read(1)
1021 # The process should end after this
1022 time.sleep(1)
1023 # This shouldn't raise even though the child is now dead
1024 getattr(p, method)(*args)
1025 p.communicate()
1026
Florent Xicluna4886d242010-03-08 13:27:26 +00001027 def test_send_signal(self):
1028 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001029 _, stderr = p.communicate()
1030 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001031 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001032
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001033 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001034 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001035 _, stderr = p.communicate()
1036 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001037 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001038
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001039 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001040 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001041 _, stderr = p.communicate()
1042 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001043 self.assertEqual(p.wait(), -signal.SIGTERM)
1044
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001045 def test_send_signal_dead(self):
1046 # Sending a signal to a dead process
1047 self._kill_dead_process('send_signal', signal.SIGINT)
1048
1049 def test_kill_dead(self):
1050 # Killing a dead process
1051 self._kill_dead_process('kill')
1052
1053 def test_terminate_dead(self):
1054 # Terminating a dead process
1055 self._kill_dead_process('terminate')
1056
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001057 def check_close_std_fds(self, fds):
1058 # Issue #9905: test that subprocess pipes still work properly with
1059 # some standard fds closed
1060 stdin = 0
1061 newfds = []
1062 for a in fds:
1063 b = os.dup(a)
1064 newfds.append(b)
1065 if a == 0:
1066 stdin = b
1067 try:
1068 for fd in fds:
1069 os.close(fd)
1070 out, err = subprocess.Popen([sys.executable, "-c",
1071 'import sys;'
1072 'sys.stdout.write("apple");'
1073 'sys.stdout.flush();'
1074 'sys.stderr.write("orange")'],
1075 stdin=stdin,
1076 stdout=subprocess.PIPE,
1077 stderr=subprocess.PIPE).communicate()
1078 err = support.strip_python_stderr(err)
1079 self.assertEqual((out, err), (b'apple', b'orange'))
1080 finally:
1081 for b, a in zip(newfds, fds):
1082 os.dup2(b, a)
1083 for b in newfds:
1084 os.close(b)
1085
1086 def test_close_fd_0(self):
1087 self.check_close_std_fds([0])
1088
1089 def test_close_fd_1(self):
1090 self.check_close_std_fds([1])
1091
1092 def test_close_fd_2(self):
1093 self.check_close_std_fds([2])
1094
1095 def test_close_fds_0_1(self):
1096 self.check_close_std_fds([0, 1])
1097
1098 def test_close_fds_0_2(self):
1099 self.check_close_std_fds([0, 2])
1100
1101 def test_close_fds_1_2(self):
1102 self.check_close_std_fds([1, 2])
1103
1104 def test_close_fds_0_1_2(self):
1105 # Issue #10806: test that subprocess pipes still work properly with
1106 # all standard fds closed.
1107 self.check_close_std_fds([0, 1, 2])
1108
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001109 def test_remapping_std_fds(self):
1110 # open up some temporary files
1111 temps = [mkstemp() for i in range(3)]
1112 try:
1113 temp_fds = [fd for fd, fname in temps]
1114
1115 # unlink the files -- we won't need to reopen them
1116 for fd, fname in temps:
1117 os.unlink(fname)
1118
1119 # write some data to what will become stdin, and rewind
1120 os.write(temp_fds[1], b"STDIN")
1121 os.lseek(temp_fds[1], 0, 0)
1122
1123 # move the standard file descriptors out of the way
1124 saved_fds = [os.dup(fd) for fd in range(3)]
1125 try:
1126 # duplicate the file objects over the standard fd's
1127 for fd, temp_fd in enumerate(temp_fds):
1128 os.dup2(temp_fd, fd)
1129
1130 # now use those files in the "wrong" 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=temp_fds[1],
1136 stdout=temp_fds[2],
1137 stderr=temp_fds[0])
1138 p.wait()
1139 finally:
1140 # restore the original fd's underneath sys.stdin, etc.
1141 for std, saved in enumerate(saved_fds):
1142 os.dup2(saved, std)
1143 os.close(saved)
1144
1145 for fd in temp_fds:
1146 os.lseek(fd, 0, 0)
1147
1148 out = os.read(temp_fds[2], 1024)
1149 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
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
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001157 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1158 # open up some temporary files
1159 temps = [mkstemp() for i in range(3)]
1160 temp_fds = [fd for fd, fname in temps]
1161 try:
1162 # unlink the files -- we won't need to reopen them
1163 for fd, fname in temps:
1164 os.unlink(fname)
1165
1166 # save a copy of the standard file descriptors
1167 saved_fds = [os.dup(fd) for fd in range(3)]
1168 try:
1169 # duplicate the temp files over the standard fd's 0, 1, 2
1170 for fd, temp_fd in enumerate(temp_fds):
1171 os.dup2(temp_fd, fd)
1172
1173 # write some data to what will become stdin, and rewind
1174 os.write(stdin_no, b"STDIN")
1175 os.lseek(stdin_no, 0, 0)
1176
1177 # now use those files in the given order, so that subprocess
1178 # has to rearrange them in the child
1179 p = subprocess.Popen([sys.executable, "-c",
1180 'import sys; got = sys.stdin.read();'
1181 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1182 stdin=stdin_no,
1183 stdout=stdout_no,
1184 stderr=stderr_no)
1185 p.wait()
1186
1187 for fd in temp_fds:
1188 os.lseek(fd, 0, 0)
1189
1190 out = os.read(stdout_no, 1024)
1191 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1192 finally:
1193 for std, saved in enumerate(saved_fds):
1194 os.dup2(saved, std)
1195 os.close(saved)
1196
1197 self.assertEqual(out, b"got STDIN")
1198 self.assertEqual(err, b"err")
1199
1200 finally:
1201 for fd in temp_fds:
1202 os.close(fd)
1203
1204 # When duping fds, if there arises a situation where one of the fds is
1205 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1206 # This tests all combinations of this.
1207 def test_swap_fds(self):
1208 self.check_swap_fds(0, 1, 2)
1209 self.check_swap_fds(0, 2, 1)
1210 self.check_swap_fds(1, 0, 2)
1211 self.check_swap_fds(1, 2, 0)
1212 self.check_swap_fds(2, 0, 1)
1213 self.check_swap_fds(2, 1, 0)
1214
Victor Stinner13bb71c2010-04-23 21:41:56 +00001215 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001216 def prepare():
1217 raise ValueError("surrogate:\uDCff")
1218
1219 try:
1220 subprocess.call(
1221 [sys.executable, "-c", "pass"],
1222 preexec_fn=prepare)
1223 except ValueError as err:
1224 # Pure Python implementations keeps the message
1225 self.assertIsNone(subprocess._posixsubprocess)
1226 self.assertEqual(str(err), "surrogate:\uDCff")
1227 except RuntimeError as err:
1228 # _posixsubprocess uses a default message
1229 self.assertIsNotNone(subprocess._posixsubprocess)
1230 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1231 else:
1232 self.fail("Expected ValueError or RuntimeError")
1233
Victor Stinner13bb71c2010-04-23 21:41:56 +00001234 def test_undecodable_env(self):
1235 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001236 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001237 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001238 env = os.environ.copy()
1239 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001240 # Use C locale to get ascii for the locale encoding to force
1241 # surrogate-escaping of \xFF in the child process; otherwise it can
1242 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001243 env['LC_ALL'] = 'C'
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
1250 # test bytes
1251 key = key.encode("ascii", "surrogateescape")
1252 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001253 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001254 env = os.environ.copy()
1255 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001256 stdout = subprocess.check_output(
1257 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001258 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001259 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001260 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001261
Victor Stinnerb745a742010-05-18 17:17:23 +00001262 def test_bytes_program(self):
1263 abs_program = os.fsencode(sys.executable)
1264 path, program = os.path.split(sys.executable)
1265 program = os.fsencode(program)
1266
1267 # absolute bytes path
1268 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001269 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001270
1271 # bytes program, unicode PATH
1272 env = os.environ.copy()
1273 env["PATH"] = path
1274 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001275 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001276
1277 # bytes program, bytes PATH
1278 envb = os.environb.copy()
1279 envb[b"PATH"] = os.fsencode(path)
1280 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001281 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001282
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001283 def test_pipe_cloexec(self):
1284 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1285 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1286
1287 p1 = subprocess.Popen([sys.executable, sleeper],
1288 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1289 stderr=subprocess.PIPE, close_fds=False)
1290
1291 self.addCleanup(p1.communicate, b'')
1292
1293 p2 = subprocess.Popen([sys.executable, fd_status],
1294 stdout=subprocess.PIPE, close_fds=False)
1295
1296 output, error = p2.communicate()
1297 result_fds = set(map(int, output.split(b',')))
1298 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1299 p1.stderr.fileno()])
1300
1301 self.assertFalse(result_fds & unwanted_fds,
1302 "Expected no fds from %r to be open in child, "
1303 "found %r" %
1304 (unwanted_fds, result_fds & unwanted_fds))
1305
1306 def test_pipe_cloexec_real_tools(self):
1307 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1308 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1309
1310 subdata = b'zxcvbn'
1311 data = subdata * 4 + b'\n'
1312
1313 p1 = subprocess.Popen([sys.executable, qcat],
1314 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1315 close_fds=False)
1316
1317 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1318 stdin=p1.stdout, stdout=subprocess.PIPE,
1319 close_fds=False)
1320
1321 self.addCleanup(p1.wait)
1322 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001323 def kill_p1():
1324 try:
1325 p1.terminate()
1326 except ProcessLookupError:
1327 pass
1328 def kill_p2():
1329 try:
1330 p2.terminate()
1331 except ProcessLookupError:
1332 pass
1333 self.addCleanup(kill_p1)
1334 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001335
1336 p1.stdin.write(data)
1337 p1.stdin.close()
1338
1339 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1340
1341 self.assertTrue(readfiles, "The child hung")
1342 self.assertEqual(p2.stdout.read(), data)
1343
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001344 p1.stdout.close()
1345 p2.stdout.close()
1346
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001347 def test_close_fds(self):
1348 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1349
1350 fds = os.pipe()
1351 self.addCleanup(os.close, fds[0])
1352 self.addCleanup(os.close, fds[1])
1353
1354 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001355 # add a bunch more fds
1356 for _ in range(9):
1357 fd = os.open("/dev/null", os.O_RDONLY)
1358 self.addCleanup(os.close, fd)
1359 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001360
1361 p = subprocess.Popen([sys.executable, fd_status],
1362 stdout=subprocess.PIPE, close_fds=False)
1363 output, ignored = p.communicate()
1364 remaining_fds = set(map(int, output.split(b',')))
1365
1366 self.assertEqual(remaining_fds & open_fds, open_fds,
1367 "Some fds were closed")
1368
1369 p = subprocess.Popen([sys.executable, fd_status],
1370 stdout=subprocess.PIPE, close_fds=True)
1371 output, ignored = p.communicate()
1372 remaining_fds = set(map(int, output.split(b',')))
1373
1374 self.assertFalse(remaining_fds & open_fds,
1375 "Some fds were left open")
1376 self.assertIn(1, remaining_fds, "Subprocess failed")
1377
Gregory P. Smith8facece2012-01-21 14:01:08 -08001378 # Keep some of the fd's we opened open in the subprocess.
1379 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1380 fds_to_keep = set(open_fds.pop() for _ in range(8))
1381 p = subprocess.Popen([sys.executable, fd_status],
1382 stdout=subprocess.PIPE, close_fds=True,
1383 pass_fds=())
1384 output, ignored = p.communicate()
1385 remaining_fds = set(map(int, output.split(b',')))
1386
1387 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1388 "Some fds not in pass_fds were left open")
1389 self.assertIn(1, remaining_fds, "Subprocess failed")
1390
Victor Stinner88701e22011-06-01 13:13:04 +02001391 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1392 # descriptor of a pipe closed in the parent process is valid in the
1393 # child process according to fstat(), but the mode of the file
1394 # descriptor is invalid, and read or write raise an error.
1395 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001396 def test_pass_fds(self):
1397 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1398
1399 open_fds = set()
1400
1401 for x in range(5):
1402 fds = os.pipe()
1403 self.addCleanup(os.close, fds[0])
1404 self.addCleanup(os.close, fds[1])
1405 open_fds.update(fds)
1406
1407 for fd in open_fds:
1408 p = subprocess.Popen([sys.executable, fd_status],
1409 stdout=subprocess.PIPE, close_fds=True,
1410 pass_fds=(fd, ))
1411 output, ignored = p.communicate()
1412
1413 remaining_fds = set(map(int, output.split(b',')))
1414 to_be_closed = open_fds - {fd}
1415
1416 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1417 self.assertFalse(remaining_fds & to_be_closed,
1418 "fd to be closed passed")
1419
1420 # pass_fds overrides close_fds with a warning.
1421 with self.assertWarns(RuntimeWarning) as context:
1422 self.assertFalse(subprocess.call(
1423 [sys.executable, "-c", "import sys; sys.exit(0)"],
1424 close_fds=False, pass_fds=(fd, )))
1425 self.assertIn('overriding close_fds', str(context.warning))
1426
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001427 def test_stdout_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 stdout=inout, stdin=inout)
1431 p.wait()
1432
1433 def test_stdout_stderr_are_single_inout_fd(self):
1434 with io.open(os.devnull, "r+") as inout:
1435 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1436 stdout=inout, stderr=inout)
1437 p.wait()
1438
1439 def test_stderr_stdin_are_single_inout_fd(self):
1440 with io.open(os.devnull, "r+") as inout:
1441 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1442 stderr=inout, stdin=inout)
1443 p.wait()
1444
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001445 def test_wait_when_sigchild_ignored(self):
1446 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1447 sigchild_ignore = support.findfile("sigchild_ignore.py",
1448 subdir="subprocessdata")
1449 p = subprocess.Popen([sys.executable, sigchild_ignore],
1450 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1451 stdout, stderr = p.communicate()
1452 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001453 " non-zero with this error:\n%s" %
1454 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001455
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001456 def test_select_unbuffered(self):
1457 # Issue #11459: bufsize=0 should really set the pipes as
1458 # unbuffered (and therefore let select() work properly).
1459 select = support.import_module("select")
1460 p = subprocess.Popen([sys.executable, "-c",
1461 'import sys;'
1462 'sys.stdout.write("apple")'],
1463 stdout=subprocess.PIPE,
1464 bufsize=0)
1465 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001466 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001467 try:
1468 self.assertEqual(f.read(4), b"appl")
1469 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1470 finally:
1471 p.wait()
1472
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001473 def test_zombie_fast_process_del(self):
1474 # Issue #12650: on Unix, if Popen.__del__() was called before the
1475 # process exited, it wouldn't be added to subprocess._active, and would
1476 # remain a zombie.
1477 # spawn a Popen, and delete its reference before it exits
1478 p = subprocess.Popen([sys.executable, "-c",
1479 'import sys, time;'
1480 'time.sleep(0.2)'],
1481 stdout=subprocess.PIPE,
1482 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001483 self.addCleanup(p.stdout.close)
1484 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001485 ident = id(p)
1486 pid = p.pid
1487 del p
1488 # check that p is in the active processes list
1489 self.assertIn(ident, [id(o) for o in subprocess._active])
1490
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001491 def test_leak_fast_process_del_killed(self):
1492 # Issue #12650: on Unix, if Popen.__del__() was called before the
1493 # process exited, and the process got killed by a signal, it would never
1494 # be removed from subprocess._active, which triggered a FD and memory
1495 # leak.
1496 # spawn a Popen, delete its reference and kill it
1497 p = subprocess.Popen([sys.executable, "-c",
1498 'import time;'
1499 'time.sleep(3)'],
1500 stdout=subprocess.PIPE,
1501 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001502 self.addCleanup(p.stdout.close)
1503 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001504 ident = id(p)
1505 pid = p.pid
1506 del p
1507 os.kill(pid, signal.SIGKILL)
1508 # check that p is in the active processes list
1509 self.assertIn(ident, [id(o) for o in subprocess._active])
1510
1511 # let some time for the process to exit, and create a new Popen: this
1512 # should trigger the wait() of p
1513 time.sleep(0.2)
1514 with self.assertRaises(EnvironmentError) as c:
1515 with subprocess.Popen(['nonexisting_i_hope'],
1516 stdout=subprocess.PIPE,
1517 stderr=subprocess.PIPE) as proc:
1518 pass
1519 # p should have been wait()ed on, and removed from the _active list
1520 self.assertRaises(OSError, os.waitpid, pid, 0)
1521 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1522
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001523
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001524@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001525class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001526
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001527 def test_startupinfo(self):
1528 # startupinfo argument
1529 # We uses hardcoded constants, because we do not want to
1530 # depend on win32all.
1531 STARTF_USESHOWWINDOW = 1
1532 SW_MAXIMIZE = 3
1533 startupinfo = subprocess.STARTUPINFO()
1534 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1535 startupinfo.wShowWindow = SW_MAXIMIZE
1536 # Since Python is a console process, it won't be affected
1537 # by wShowWindow, but the argument should be silently
1538 # ignored
1539 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001540 startupinfo=startupinfo)
1541
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001542 def test_creationflags(self):
1543 # creationflags argument
1544 CREATE_NEW_CONSOLE = 16
1545 sys.stderr.write(" a DOS box should flash briefly ...\n")
1546 subprocess.call(sys.executable +
1547 ' -c "import time; time.sleep(0.25)"',
1548 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001549
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001550 def test_invalid_args(self):
1551 # invalid arguments should raise ValueError
1552 self.assertRaises(ValueError, subprocess.call,
1553 [sys.executable, "-c",
1554 "import sys; sys.exit(47)"],
1555 preexec_fn=lambda: 1)
1556 self.assertRaises(ValueError, subprocess.call,
1557 [sys.executable, "-c",
1558 "import sys; sys.exit(47)"],
1559 stdout=subprocess.PIPE,
1560 close_fds=True)
1561
1562 def test_close_fds(self):
1563 # close file descriptors
1564 rc = subprocess.call([sys.executable, "-c",
1565 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001566 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001567 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001568
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001569 def test_shell_sequence(self):
1570 # Run command through the shell (sequence)
1571 newenv = os.environ.copy()
1572 newenv["FRUIT"] = "physalis"
1573 p = subprocess.Popen(["set"], shell=1,
1574 stdout=subprocess.PIPE,
1575 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001576 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001577 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001578
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001579 def test_shell_string(self):
1580 # Run command through the shell (string)
1581 newenv = os.environ.copy()
1582 newenv["FRUIT"] = "physalis"
1583 p = subprocess.Popen("set", shell=1,
1584 stdout=subprocess.PIPE,
1585 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001586 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001587 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001588
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001589 def test_call_string(self):
1590 # call() function with string argument on Windows
1591 rc = subprocess.call(sys.executable +
1592 ' -c "import sys; sys.exit(47)"')
1593 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001594
Florent Xicluna4886d242010-03-08 13:27:26 +00001595 def _kill_process(self, method, *args):
1596 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001597 p = subprocess.Popen([sys.executable, "-c", """if 1:
1598 import sys, time
1599 sys.stdout.write('x\\n')
1600 sys.stdout.flush()
1601 time.sleep(30)
1602 """],
1603 stdin=subprocess.PIPE,
1604 stdout=subprocess.PIPE,
1605 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001606 self.addCleanup(p.stdout.close)
1607 self.addCleanup(p.stderr.close)
1608 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001609 # Wait for the interpreter to be completely initialized before
1610 # sending any signal.
1611 p.stdout.read(1)
1612 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001613 _, stderr = p.communicate()
1614 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001615 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001616 self.assertNotEqual(returncode, 0)
1617
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001618 def _kill_dead_process(self, method, *args):
1619 p = subprocess.Popen([sys.executable, "-c", """if 1:
1620 import sys, time
1621 sys.stdout.write('x\\n')
1622 sys.stdout.flush()
1623 sys.exit(42)
1624 """],
1625 stdin=subprocess.PIPE,
1626 stdout=subprocess.PIPE,
1627 stderr=subprocess.PIPE)
1628 self.addCleanup(p.stdout.close)
1629 self.addCleanup(p.stderr.close)
1630 self.addCleanup(p.stdin.close)
1631 # Wait for the interpreter to be completely initialized before
1632 # sending any signal.
1633 p.stdout.read(1)
1634 # The process should end after this
1635 time.sleep(1)
1636 # This shouldn't raise even though the child is now dead
1637 getattr(p, method)(*args)
1638 _, stderr = p.communicate()
1639 self.assertStderrEqual(stderr, b'')
1640 rc = p.wait()
1641 self.assertEqual(rc, 42)
1642
Florent Xicluna4886d242010-03-08 13:27:26 +00001643 def test_send_signal(self):
1644 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001645
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001646 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001647 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001648
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001649 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001650 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001651
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001652 def test_send_signal_dead(self):
1653 self._kill_dead_process('send_signal', signal.SIGTERM)
1654
1655 def test_kill_dead(self):
1656 self._kill_dead_process('kill')
1657
1658 def test_terminate_dead(self):
1659 self._kill_dead_process('terminate')
1660
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001661
Brett Cannona23810f2008-05-26 19:04:21 +00001662# The module says:
1663# "NB This only works (and is only relevant) for UNIX."
1664#
1665# Actually, getoutput should work on any platform with an os.popen, but
1666# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001667@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001668class CommandTests(unittest.TestCase):
1669 def test_getoutput(self):
1670 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1671 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1672 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001673
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001674 # we use mkdtemp in the next line to create an empty directory
1675 # under our exclusive control; from that, we can invent a pathname
1676 # that we _know_ won't exist. This is guaranteed to fail.
1677 dir = None
1678 try:
1679 dir = tempfile.mkdtemp()
1680 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001681
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001682 status, output = subprocess.getstatusoutput('cat ' + name)
1683 self.assertNotEqual(status, 0)
1684 finally:
1685 if dir is not None:
1686 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001687
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001688
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001689@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1690 "poll system call not supported")
1691class ProcessTestCaseNoPoll(ProcessTestCase):
1692 def setUp(self):
1693 subprocess._has_poll = False
1694 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001695
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001696 def tearDown(self):
1697 subprocess._has_poll = True
1698 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001699
1700
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001701@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1702 "_posixsubprocess extension module not found.")
1703class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001704 @classmethod
1705 def setUpClass(cls):
1706 global subprocess
1707 assert subprocess._posixsubprocess
1708 # Reimport subprocess while forcing _posixsubprocess to not exist.
1709 with support.check_warnings(('.*_posixsubprocess .* not being used.*',
1710 RuntimeWarning)):
1711 subprocess = support.import_fresh_module(
1712 'subprocess', blocked=['_posixsubprocess'])
1713 assert not subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001714
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001715 @classmethod
1716 def tearDownClass(cls):
1717 global subprocess
1718 # Reimport subprocess as it should be, restoring order to the universe.
1719 subprocess = support.import_fresh_module('subprocess')
1720 assert subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001721
1722
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001723class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001724 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001725 def test_eintr_retry_call(self):
1726 record_calls = []
1727 def fake_os_func(*args):
1728 record_calls.append(args)
1729 if len(record_calls) == 2:
1730 raise OSError(errno.EINTR, "fake interrupted system call")
1731 return tuple(reversed(args))
1732
1733 self.assertEqual((999, 256),
1734 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1735 self.assertEqual([(256, 999)], record_calls)
1736 # This time there will be an EINTR so it will loop once.
1737 self.assertEqual((666,),
1738 subprocess._eintr_retry_call(fake_os_func, 666))
1739 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1740
1741
Tim Golden126c2962010-08-11 14:20:40 +00001742@unittest.skipUnless(mswindows, "Windows-specific tests")
1743class CommandsWithSpaces (BaseTestCase):
1744
1745 def setUp(self):
1746 super().setUp()
1747 f, fname = mkstemp(".py", "te st")
1748 self.fname = fname.lower ()
1749 os.write(f, b"import sys;"
1750 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1751 )
1752 os.close(f)
1753
1754 def tearDown(self):
1755 os.remove(self.fname)
1756 super().tearDown()
1757
1758 def with_spaces(self, *args, **kwargs):
1759 kwargs['stdout'] = subprocess.PIPE
1760 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001761 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001762 self.assertEqual(
1763 p.stdout.read ().decode("mbcs"),
1764 "2 [%r, 'ab cd']" % self.fname
1765 )
1766
1767 def test_shell_string_with_spaces(self):
1768 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001769 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1770 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001771
1772 def test_shell_sequence_with_spaces(self):
1773 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001774 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001775
1776 def test_noshell_string_with_spaces(self):
1777 # call() function with string argument with spaces on Windows
1778 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1779 "ab cd"))
1780
1781 def test_noshell_sequence_with_spaces(self):
1782 # call() function with sequence argument with spaces on Windows
1783 self.with_spaces([sys.executable, self.fname, "ab cd"])
1784
Brian Curtin79cdb662010-12-03 02:46:02 +00001785
Georg Brandla86b2622012-02-20 21:34:57 +01001786class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001787
1788 def test_pipe(self):
1789 with subprocess.Popen([sys.executable, "-c",
1790 "import sys;"
1791 "sys.stdout.write('stdout');"
1792 "sys.stderr.write('stderr');"],
1793 stdout=subprocess.PIPE,
1794 stderr=subprocess.PIPE) as proc:
1795 self.assertEqual(proc.stdout.read(), b"stdout")
1796 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1797
1798 self.assertTrue(proc.stdout.closed)
1799 self.assertTrue(proc.stderr.closed)
1800
1801 def test_returncode(self):
1802 with subprocess.Popen([sys.executable, "-c",
1803 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smithc9557af2011-05-11 22:18:23 -07001804 pass
1805 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001806 self.assertEqual(proc.returncode, 100)
1807
1808 def test_communicate_stdin(self):
1809 with subprocess.Popen([sys.executable, "-c",
1810 "import sys;"
1811 "sys.exit(sys.stdin.read() == 'context')"],
1812 stdin=subprocess.PIPE) as proc:
1813 proc.communicate(b"context")
1814 self.assertEqual(proc.returncode, 1)
1815
1816 def test_invalid_args(self):
1817 with self.assertRaises(EnvironmentError) as c:
1818 with subprocess.Popen(['nonexisting_i_hope'],
1819 stdout=subprocess.PIPE,
1820 stderr=subprocess.PIPE) as proc:
1821 pass
1822
1823 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1824 raise c.exception
1825
1826
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001827def test_main():
1828 unit_tests = (ProcessTestCase,
1829 POSIXProcessTestCase,
1830 Win32ProcessTestCase,
1831 ProcessTestCasePOSIXPurePython,
1832 CommandTests,
1833 ProcessTestCaseNoPoll,
1834 HelperFunctionTests,
1835 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001836 ContextManagerTests,
1837 )
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001838
1839 support.run_unittest(*unit_tests)
1840 support.reap_children()
1841
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001842if __name__ == "__main__":
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001843 unittest.main()