blob: 432d324749764ca7bacc1ac244fdb987947cdc6b [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. Smith112bb3a2011-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
Gregory P. Smith32ec9da2010-03-19 16:53:08 +000016try:
17 import gc
18except ImportError:
19 gc = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000020
21mswindows = (sys.platform == "win32")
22
23#
24# Depends on the following external programs: Python
25#
26
27if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000028 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
29 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000030else:
31 SETBINARY = ''
32
Florent Xiclunab1e94e82010-02-27 22:12:37 +000033
34try:
35 mkstemp = tempfile.mkstemp
36except AttributeError:
37 # tempfile.mkstemp is not available
38 def mkstemp():
39 """Replacement for mkstemp, calling mktemp."""
40 fname = tempfile.mktemp()
41 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
42
Tim Peters3761e8d2004-10-13 04:07:12 +000043
Florent Xiclunac049d872010-03-27 22:47:23 +000044class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045 def setUp(self):
46 # Try to minimize the number of children we have so this test
47 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000048 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000050 def tearDown(self):
51 for inst in subprocess._active:
52 inst.wait()
53 subprocess._cleanup()
54 self.assertFalse(subprocess._active, "subprocess._active not empty")
55
Florent Xiclunab1e94e82010-02-27 22:12:37 +000056 def assertStderrEqual(self, stderr, expected, msg=None):
57 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
58 # shutdown time. That frustrates tests trying to check stderr produced
59 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000060 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040061 # strip_python_stderr also strips whitespace, so we do too.
62 expected = expected.strip()
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
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040074 def test_call_timeout(self):
75 # call() function with timeout argument; we want to test that the child
76 # process gets killed when the timeout expires. If the child isn't
77 # killed, this call will deadlock since subprocess.call waits for the
78 # child.
79 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
80 [sys.executable, "-c", "while True: pass"],
81 timeout=0.1)
82
Peter Astrand454f7672005-01-01 09:36:35 +000083 def test_check_call_zero(self):
84 # check_call() function with zero return code
85 rc = subprocess.check_call([sys.executable, "-c",
86 "import sys; sys.exit(0)"])
87 self.assertEqual(rc, 0)
88
89 def test_check_call_nonzero(self):
90 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000091 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000092 subprocess.check_call([sys.executable, "-c",
93 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000094 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000095
Georg Brandlf9734072008-12-07 15:30:06 +000096 def test_check_output(self):
97 # check_output() function with zero return code
98 output = subprocess.check_output(
99 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000100 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000101
102 def test_check_output_nonzero(self):
103 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000104 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000105 subprocess.check_output(
106 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000107 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000108
109 def test_check_output_stderr(self):
110 # check_output() function stderr redirected to stdout
111 output = subprocess.check_output(
112 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
113 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000114 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000115
116 def test_check_output_stdout_arg(self):
117 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000118 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000119 output = subprocess.check_output(
120 [sys.executable, "-c", "print('will not be run')"],
121 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000122 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000123 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000124
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400125 def test_check_output_timeout(self):
126 # check_output() function with timeout arg
127 with self.assertRaises(subprocess.TimeoutExpired) as c:
128 output = subprocess.check_output(
129 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200130 "import sys, time\n"
131 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400132 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200133 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400134 # Some heavily loaded buildbots (sparc Debian 3.x) require
135 # this much time to start and print.
136 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400137 self.fail("Expected TimeoutExpired.")
138 self.assertEqual(c.exception.output, b'BDFL')
139
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000141 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000142 newenv = os.environ.copy()
143 newenv["FRUIT"] = "banana"
144 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000145 'import sys, os;'
146 'sys.exit(os.getenv("FRUIT")=="banana")'],
147 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000148 self.assertEqual(rc, 1)
149
Victor Stinner87b9bc32011-06-01 00:57:47 +0200150 def test_invalid_args(self):
151 # Popen() called with invalid arguments should raise TypeError
152 # but Popen.__del__ should not complain (issue #12085)
153 with support.captured_stderr() as s:
154 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
155 argcount = subprocess.Popen.__init__.__code__.co_argcount
156 too_many_args = [0] * (argcount + 1)
157 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
158 self.assertEqual(s.getvalue(), '')
159
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000160 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000161 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000162 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000163 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000164 self.addCleanup(p.stdout.close)
165 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000166 p.wait()
167 self.assertEqual(p.stdin, None)
168
169 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000170 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000171 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000172 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000173 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000174 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000175 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000176 self.addCleanup(p.stdin.close)
177 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000178 p.wait()
179 self.assertEqual(p.stdout, None)
180
181 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000182 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000183 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000184 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000185 self.addCleanup(p.stdout.close)
186 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000187 p.wait()
188 self.assertEqual(p.stderr, None)
189
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000190 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000191 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000192 p = subprocess.Popen(["somethingyoudonthave", "-c",
193 "import sys; sys.exit(47)"],
194 executable=sys.executable, cwd=python_dir)
195 p.wait()
196 self.assertEqual(p.returncode, 47)
197
198 @unittest.skipIf(sysconfig.is_python_build(),
199 "need an installed Python. See #7774")
200 def test_executable_without_cwd(self):
201 # For a normal installation, it should work without 'cwd'
202 # argument. For test runs in the build directory, see #7774.
203 p = subprocess.Popen(["somethingyoudonthave", "-c",
204 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000205 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000206 p.wait()
207 self.assertEqual(p.returncode, 47)
208
209 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000210 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000211 p = subprocess.Popen([sys.executable, "-c",
212 'import sys; sys.exit(sys.stdin.read() == "pear")'],
213 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000214 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000215 p.stdin.close()
216 p.wait()
217 self.assertEqual(p.returncode, 1)
218
219 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000220 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000221 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000222 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000224 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000225 os.lseek(d, 0, 0)
226 p = subprocess.Popen([sys.executable, "-c",
227 'import sys; sys.exit(sys.stdin.read() == "pear")'],
228 stdin=d)
229 p.wait()
230 self.assertEqual(p.returncode, 1)
231
232 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000233 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000234 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000235 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000236 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000237 tf.seek(0)
238 p = subprocess.Popen([sys.executable, "-c",
239 'import sys; sys.exit(sys.stdin.read() == "pear")'],
240 stdin=tf)
241 p.wait()
242 self.assertEqual(p.returncode, 1)
243
244 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000245 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000246 p = subprocess.Popen([sys.executable, "-c",
247 'import sys; sys.stdout.write("orange")'],
248 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000249 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000250 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251
252 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000253 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000254 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000255 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000256 d = tf.fileno()
257 p = subprocess.Popen([sys.executable, "-c",
258 'import sys; sys.stdout.write("orange")'],
259 stdout=d)
260 p.wait()
261 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000262 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263
264 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000265 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000266 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000267 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268 p = subprocess.Popen([sys.executable, "-c",
269 'import sys; sys.stdout.write("orange")'],
270 stdout=tf)
271 p.wait()
272 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000273 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274
275 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000276 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000277 p = subprocess.Popen([sys.executable, "-c",
278 'import sys; sys.stderr.write("strawberry")'],
279 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000280 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000281 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282
283 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000284 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000285 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000286 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000287 d = tf.fileno()
288 p = subprocess.Popen([sys.executable, "-c",
289 'import sys; sys.stderr.write("strawberry")'],
290 stderr=d)
291 p.wait()
292 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000293 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294
295 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000296 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000297 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000298 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000299 p = subprocess.Popen([sys.executable, "-c",
300 'import sys; sys.stderr.write("strawberry")'],
301 stderr=tf)
302 p.wait()
303 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000304 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000305
306 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000307 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000309 'import sys;'
310 'sys.stdout.write("apple");'
311 'sys.stdout.flush();'
312 'sys.stderr.write("orange")'],
313 stdout=subprocess.PIPE,
314 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000315 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000316 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000317
318 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000319 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000320 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000321 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000322 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000323 'import sys;'
324 'sys.stdout.write("apple");'
325 'sys.stdout.flush();'
326 'sys.stderr.write("orange")'],
327 stdout=tf,
328 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000329 p.wait()
330 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000331 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000332
Thomas Wouters89f507f2006-12-13 04:49:30 +0000333 def test_stdout_filedes_of_stdout(self):
334 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000335 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000336 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000337 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000338
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200339 def test_stdout_devnull(self):
340 p = subprocess.Popen([sys.executable, "-c",
341 'for i in range(10240):'
342 'print("x" * 1024)'],
343 stdout=subprocess.DEVNULL)
344 p.wait()
345 self.assertEqual(p.stdout, None)
346
347 def test_stderr_devnull(self):
348 p = subprocess.Popen([sys.executable, "-c",
349 'import sys\n'
350 'for i in range(10240):'
351 'sys.stderr.write("x" * 1024)'],
352 stderr=subprocess.DEVNULL)
353 p.wait()
354 self.assertEqual(p.stderr, None)
355
356 def test_stdin_devnull(self):
357 p = subprocess.Popen([sys.executable, "-c",
358 'import sys;'
359 'sys.stdin.read(1)'],
360 stdin=subprocess.DEVNULL)
361 p.wait()
362 self.assertEqual(p.stdin, None)
363
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000364 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000365 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000366 # We cannot use os.path.realpath to canonicalize the path,
367 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
368 cwd = os.getcwd()
369 os.chdir(tmpdir)
370 tmpdir = os.getcwd()
371 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000372 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000373 'import sys,os;'
374 'sys.stdout.write(os.getcwd())'],
375 stdout=subprocess.PIPE,
376 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000377 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000378 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000379 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
380 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000381
382 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000383 newenv = os.environ.copy()
384 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200385 with subprocess.Popen([sys.executable, "-c",
386 'import sys,os;'
387 'sys.stdout.write(os.getenv("FRUIT"))'],
388 stdout=subprocess.PIPE,
389 env=newenv) as p:
390 stdout, stderr = p.communicate()
391 self.assertEqual(stdout, b"orange")
392
Victor Stinner62d51182011-06-23 01:02:25 +0200393 # Windows requires at least the SYSTEMROOT environment variable to start
394 # Python
395 @unittest.skipIf(sys.platform == 'win32',
396 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200397 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200398 'the python library cannot be loaded '
399 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200400 def test_empty_env(self):
401 with subprocess.Popen([sys.executable, "-c",
402 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200403 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200404 stdout=subprocess.PIPE,
405 env={}) as p:
406 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200407 self.assertIn(stdout.strip(),
408 (b"[]",
409 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
410 # environment
411 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000412
Peter Astrandcbac93c2005-03-03 20:24:28 +0000413 def test_communicate_stdin(self):
414 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000415 'import sys;'
416 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000417 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000418 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000419 self.assertEqual(p.returncode, 1)
420
421 def test_communicate_stdout(self):
422 p = subprocess.Popen([sys.executable, "-c",
423 'import sys; sys.stdout.write("pineapple")'],
424 stdout=subprocess.PIPE)
425 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000426 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000427 self.assertEqual(stderr, None)
428
429 def test_communicate_stderr(self):
430 p = subprocess.Popen([sys.executable, "-c",
431 'import sys; sys.stderr.write("pineapple")'],
432 stderr=subprocess.PIPE)
433 (stdout, stderr) = p.communicate()
434 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000435 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000436
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000437 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000439 'import sys,os;'
440 'sys.stderr.write("pineapple");'
441 'sys.stdout.write(sys.stdin.read())'],
442 stdin=subprocess.PIPE,
443 stdout=subprocess.PIPE,
444 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000445 self.addCleanup(p.stdout.close)
446 self.addCleanup(p.stderr.close)
447 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000448 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000449 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000450 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000451
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400452 def test_communicate_timeout(self):
453 p = subprocess.Popen([sys.executable, "-c",
454 'import sys,os,time;'
455 'sys.stderr.write("pineapple\\n");'
456 'time.sleep(1);'
457 'sys.stderr.write("pear\\n");'
458 'sys.stdout.write(sys.stdin.read())'],
459 universal_newlines=True,
460 stdin=subprocess.PIPE,
461 stdout=subprocess.PIPE,
462 stderr=subprocess.PIPE)
463 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
464 timeout=0.3)
465 # Make sure we can keep waiting for it, and that we get the whole output
466 # after it completes.
467 (stdout, stderr) = p.communicate()
468 self.assertEqual(stdout, "banana")
469 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
470
471 def test_communicate_timeout_large_ouput(self):
472 # Test a expring timeout while the child is outputting lots of data.
473 p = subprocess.Popen([sys.executable, "-c",
474 'import sys,os,time;'
475 'sys.stdout.write("a" * (64 * 1024));'
476 'time.sleep(0.2);'
477 'sys.stdout.write("a" * (64 * 1024));'
478 'time.sleep(0.2);'
479 'sys.stdout.write("a" * (64 * 1024));'
480 'time.sleep(0.2);'
481 'sys.stdout.write("a" * (64 * 1024));'],
482 stdout=subprocess.PIPE)
483 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
484 (stdout, _) = p.communicate()
485 self.assertEqual(len(stdout), 4 * 64 * 1024)
486
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000487 # Test for the fd leak reported in http://bugs.python.org/issue2791.
488 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000489 for stdin_pipe in (False, True):
490 for stdout_pipe in (False, True):
491 for stderr_pipe in (False, True):
492 options = {}
493 if stdin_pipe:
494 options['stdin'] = subprocess.PIPE
495 if stdout_pipe:
496 options['stdout'] = subprocess.PIPE
497 if stderr_pipe:
498 options['stderr'] = subprocess.PIPE
499 if not options:
500 continue
501 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
502 p.communicate()
503 if p.stdin is not None:
504 self.assertTrue(p.stdin.closed)
505 if p.stdout is not None:
506 self.assertTrue(p.stdout.closed)
507 if p.stderr is not None:
508 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000509
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000510 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000511 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000512 p = subprocess.Popen([sys.executable, "-c",
513 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514 (stdout, stderr) = p.communicate()
515 self.assertEqual(stdout, None)
516 self.assertEqual(stderr, None)
517
518 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000519 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000521 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523 os.close(x)
524 os.close(y)
525 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000526 'import sys,os;'
527 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200528 'sys.stderr.write("x" * %d);'
529 'sys.stdout.write(sys.stdin.read())' %
530 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000531 stdin=subprocess.PIPE,
532 stdout=subprocess.PIPE,
533 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000534 self.addCleanup(p.stdout.close)
535 self.addCleanup(p.stderr.close)
536 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200537 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000538 (stdout, stderr) = p.communicate(string_to_write)
539 self.assertEqual(stdout, string_to_write)
540
541 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000542 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000544 'import sys,os;'
545 'sys.stdout.write(sys.stdin.read())'],
546 stdin=subprocess.PIPE,
547 stdout=subprocess.PIPE,
548 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000549 self.addCleanup(p.stdout.close)
550 self.addCleanup(p.stderr.close)
551 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000552 p.stdin.write(b"banana")
553 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000554 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000555 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000556
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000557 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000559 'import sys,os;' + SETBINARY +
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200560 'sys.stdout.write(sys.stdin.readline());'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000561 'sys.stdout.flush();'
562 'sys.stdout.write("line2\\n");'
563 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200564 'sys.stdout.write(sys.stdin.read());'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000565 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200566 'sys.stdout.write("line4\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000567 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200568 'sys.stdout.write("line5\\r\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000569 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200570 'sys.stdout.write("line6\\r");'
571 'sys.stdout.flush();'
572 'sys.stdout.write("\\nline7");'
573 'sys.stdout.flush();'
574 'sys.stdout.write("\\nline8");'],
575 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000576 stdout=subprocess.PIPE,
577 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200578 p.stdin.write("line1\n")
579 self.assertEqual(p.stdout.readline(), "line1\n")
580 p.stdin.write("line3\n")
581 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000582 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200583 self.assertEqual(p.stdout.readline(),
584 "line2\n")
585 self.assertEqual(p.stdout.read(6),
586 "line3\n")
587 self.assertEqual(p.stdout.read(),
588 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589
590 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000591 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000592 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000593 'import sys,os;' + SETBINARY +
Guido van Rossum98297ee2007-11-06 21:34:58 +0000594 'sys.stdout.write("line2\\n");'
595 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200596 'sys.stdout.write("line4\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000597 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200598 'sys.stdout.write("line5\\r\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000599 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200600 'sys.stdout.write("line6\\r");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000601 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200602 'sys.stdout.write("\\nline7");'
603 'sys.stdout.flush();'
604 'sys.stdout.write("\\nline8");'],
605 stderr=subprocess.PIPE,
606 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000607 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000608 self.addCleanup(p.stdout.close)
609 self.addCleanup(p.stderr.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200610 # BUG: can't give a non-empty stdin because it breaks both the
611 # select- and poll-based communicate() implementations.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000612 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200613 self.assertEqual(stdout,
614 "line2\nline4\nline5\nline6\nline7\nline8")
615
616 def test_universal_newlines_communicate_stdin(self):
617 # universal newlines through communicate(), with only stdin
618 p = subprocess.Popen([sys.executable, "-c",
619 'import sys,os;' + SETBINARY + '''\nif True:
620 s = sys.stdin.readline()
621 assert s == "line1\\n", repr(s)
622 s = sys.stdin.read()
623 assert s == "line3\\n", repr(s)
624 '''],
625 stdin=subprocess.PIPE,
626 universal_newlines=1)
627 (stdout, stderr) = p.communicate("line1\nline3\n")
628 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000629
630 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000631 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000632 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000633 max_handles = 1026 # too much for most UNIX systems
634 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000635 max_handles = 2050 # too much for (at least some) Windows setups
636 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400637 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000638 try:
639 for i in range(max_handles):
640 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400641 tmpfile = os.path.join(tmpdir, support.TESTFN)
642 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000643 except OSError as e:
644 if e.errno != errno.EMFILE:
645 raise
646 break
647 else:
648 self.skipTest("failed to reach the file descriptor limit "
649 "(tried %d)" % max_handles)
650 # Close a couple of them (should be enough for a subprocess)
651 for i in range(10):
652 os.close(handles.pop())
653 # Loop creating some subprocesses. If one of them leaks some fds,
654 # the next loop iteration will fail by reaching the max fd limit.
655 for i in range(15):
656 p = subprocess.Popen([sys.executable, "-c",
657 "import sys;"
658 "sys.stdout.write(sys.stdin.read())"],
659 stdin=subprocess.PIPE,
660 stdout=subprocess.PIPE,
661 stderr=subprocess.PIPE)
662 data = p.communicate(b"lime")[0]
663 self.assertEqual(data, b"lime")
664 finally:
665 for h in handles:
666 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400667 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000668
669 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000670 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
671 '"a b c" d e')
672 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
673 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000674 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
675 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000676 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
677 'a\\\\\\b "de fg" h')
678 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
679 'a\\\\\\"b c d')
680 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
681 '"a\\\\b c" d e')
682 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
683 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000684 self.assertEqual(subprocess.list2cmdline(['ab', '']),
685 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000686
687
688 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000689 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000690 "-c", "import time; time.sleep(1)"])
691 count = 0
692 while p.poll() is None:
693 time.sleep(0.1)
694 count += 1
695 # We expect that the poll loop probably went around about 10 times,
696 # but, based on system scheduling we can't control, it's possible
697 # poll() never returned None. It "should be" very rare that it
698 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000699 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000700 # Subsequent invocations should just return the returncode
701 self.assertEqual(p.poll(), 0)
702
703
704 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000705 p = subprocess.Popen([sys.executable,
706 "-c", "import time; time.sleep(2)"])
707 self.assertEqual(p.wait(), 0)
708 # Subsequent invocations should just return the returncode
709 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000710
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400711 def test_wait_timeout(self):
712 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400713 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400714 with self.assertRaises(subprocess.TimeoutExpired) as c:
715 p.wait(timeout=0.01)
716 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400717 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
718 # time to start.
719 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400720
Peter Astrand738131d2004-11-30 21:04:45 +0000721 def test_invalid_bufsize(self):
722 # an invalid type of the bufsize argument should raise
723 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000724 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000725 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000726
Guido van Rossum46a05a72007-06-07 21:56:45 +0000727 def test_bufsize_is_none(self):
728 # bufsize=None should be the same as bufsize=0.
729 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
730 self.assertEqual(p.wait(), 0)
731 # Again with keyword arg
732 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
733 self.assertEqual(p.wait(), 0)
734
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000735 def test_leaking_fds_on_error(self):
736 # see bug #5179: Popen leaks file descriptors to PIPEs if
737 # the child fails to execute; this will eventually exhaust
738 # the maximum number of open fds. 1024 seems a very common
739 # value for that limit, but Windows has 2048, so we loop
740 # 1024 times (each call leaked two fds).
741 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000742 # Windows raises IOError. Others raise OSError.
743 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000744 subprocess.Popen(['nonexisting_i_hope'],
745 stdout=subprocess.PIPE,
746 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400747 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400748 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000749 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000750
Victor Stinnerb3693582010-05-21 20:13:12 +0000751 def test_issue8780(self):
752 # Ensure that stdout is inherited from the parent
753 # if stdout=PIPE is not used
754 code = ';'.join((
755 'import subprocess, sys',
756 'retcode = subprocess.call('
757 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
758 'assert retcode == 0'))
759 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000760 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000761
Tim Goldenaf5ac392010-08-06 13:03:56 +0000762 def test_handles_closed_on_exception(self):
763 # If CreateProcess exits with an error, ensure the
764 # duplicate output handles are released
765 ifhandle, ifname = mkstemp()
766 ofhandle, ofname = mkstemp()
767 efhandle, efname = mkstemp()
768 try:
769 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
770 stderr=efhandle)
771 except OSError:
772 os.close(ifhandle)
773 os.remove(ifname)
774 os.close(ofhandle)
775 os.remove(ofname)
776 os.close(efhandle)
777 os.remove(efname)
778 self.assertFalse(os.path.exists(ifname))
779 self.assertFalse(os.path.exists(ofname))
780 self.assertFalse(os.path.exists(efname))
781
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200782 def test_communicate_epipe(self):
783 # Issue 10963: communicate() should hide EPIPE
784 p = subprocess.Popen([sys.executable, "-c", 'pass'],
785 stdin=subprocess.PIPE,
786 stdout=subprocess.PIPE,
787 stderr=subprocess.PIPE)
788 self.addCleanup(p.stdout.close)
789 self.addCleanup(p.stderr.close)
790 self.addCleanup(p.stdin.close)
791 p.communicate(b"x" * 2**20)
792
793 def test_communicate_epipe_only_stdin(self):
794 # Issue 10963: communicate() should hide EPIPE
795 p = subprocess.Popen([sys.executable, "-c", 'pass'],
796 stdin=subprocess.PIPE)
797 self.addCleanup(p.stdin.close)
798 time.sleep(2)
799 p.communicate(b"x" * 2**20)
800
Victor Stinner1848db82011-07-05 14:49:46 +0200801 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
802 "Requires signal.SIGALRM")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200803 def test_communicate_eintr(self):
804 # Issue #12493: communicate() should handle EINTR
805 def handler(signum, frame):
806 pass
807 old_handler = signal.signal(signal.SIGALRM, handler)
808 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
809
810 # the process is running for 2 seconds
811 args = [sys.executable, "-c", 'import time; time.sleep(2)']
812 for stream in ('stdout', 'stderr'):
813 kw = {stream: subprocess.PIPE}
814 with subprocess.Popen(args, **kw) as process:
815 signal.alarm(1)
816 # communicate() will be interrupted by SIGALRM
817 process.communicate()
818
Tim Peterse718f612004-10-12 21:51:32 +0000819
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000820# context manager
821class _SuppressCoreFiles(object):
822 """Try to prevent core files from being created."""
823 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000824
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000825 def __enter__(self):
826 """Try to save previous ulimit, then set it to (0, 0)."""
827 try:
828 import resource
829 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
830 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
831 except (ImportError, ValueError, resource.error):
832 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000833
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000834 if sys.platform == 'darwin':
835 # Check if the 'Crash Reporter' on OSX was configured
836 # in 'Developer' mode and warn that it will get triggered
837 # when it is.
838 #
839 # This assumes that this context manager is used in tests
840 # that might trigger the next manager.
841 value = subprocess.Popen(['/usr/bin/defaults', 'read',
842 'com.apple.CrashReporter', 'DialogType'],
843 stdout=subprocess.PIPE).communicate()[0]
844 if value.strip() == b'developer':
845 print("this tests triggers the Crash Reporter, "
846 "that is intentional", end='')
847 sys.stdout.flush()
848
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000849 def __exit__(self, *args):
850 """Return core file behavior to default."""
851 if self.old_limit is None:
852 return
853 try:
854 import resource
855 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
856 except (ImportError, ValueError, resource.error):
857 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000859
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000860@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000861class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000862
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000863 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000864 nonexistent_dir = "/_this/pa.th/does/not/exist"
865 try:
866 os.chdir(nonexistent_dir)
867 except OSError as e:
868 # This avoids hard coding the errno value or the OS perror()
869 # string and instead capture the exception that we want to see
870 # below for comparison.
871 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000872 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000873 else:
874 self.fail("chdir to nonexistant directory %s succeeded." %
875 nonexistent_dir)
876
877 # Error in the child re-raised in the parent.
878 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000879 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000880 cwd=nonexistent_dir)
881 except OSError as e:
882 # Test that the child process chdir failure actually makes
883 # it up to the parent process as the correct exception.
884 self.assertEqual(desired_exception.errno, e.errno)
885 self.assertEqual(desired_exception.strerror, e.strerror)
886 else:
887 self.fail("Expected OSError: %s" % desired_exception)
888
889 def test_restore_signals(self):
890 # Code coverage for both values of restore_signals to make sure it
891 # at least does not blow up.
892 # A test for behavior would be complex. Contributions welcome.
893 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
894 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
895
896 def test_start_new_session(self):
897 # For code coverage of calling setsid(). We don't care if we get an
898 # EPERM error from it depending on the test execution environment, that
899 # still indicates that it was called.
900 try:
901 output = subprocess.check_output(
902 [sys.executable, "-c",
903 "import os; print(os.getpgid(os.getpid()))"],
904 start_new_session=True)
905 except OSError as e:
906 if e.errno != errno.EPERM:
907 raise
908 else:
909 parent_pgid = os.getpgid(os.getpid())
910 child_pgid = int(output)
911 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000912
913 def test_run_abort(self):
914 # returncode handles signal termination
915 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000916 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000917 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000918 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000919 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000920
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000921 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000922 # DISCLAIMER: Setting environment variables is *not* a good use
923 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000924 p = subprocess.Popen([sys.executable, "-c",
925 'import sys,os;'
926 'sys.stdout.write(os.getenv("FRUIT"))'],
927 stdout=subprocess.PIPE,
928 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000929 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000930 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000932 def test_preexec_exception(self):
933 def raise_it():
934 raise ValueError("What if two swallows carried a coconut?")
935 try:
936 p = subprocess.Popen([sys.executable, "-c", ""],
937 preexec_fn=raise_it)
938 except RuntimeError as e:
939 self.assertTrue(
940 subprocess._posixsubprocess,
941 "Expected a ValueError from the preexec_fn")
942 except ValueError as e:
943 self.assertIn("coconut", e.args[0])
944 else:
945 self.fail("Exception raised by preexec_fn did not make it "
946 "to the parent process.")
947
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000948 @unittest.skipUnless(gc, "Requires a gc module.")
949 def test_preexec_gc_module_failure(self):
950 # This tests the code that disables garbage collection if the child
951 # process will execute any Python.
952 def raise_runtime_error():
953 raise RuntimeError("this shouldn't escape")
954 enabled = gc.isenabled()
955 orig_gc_disable = gc.disable
956 orig_gc_isenabled = gc.isenabled
957 try:
958 gc.disable()
959 self.assertFalse(gc.isenabled())
960 subprocess.call([sys.executable, '-c', ''],
961 preexec_fn=lambda: None)
962 self.assertFalse(gc.isenabled(),
963 "Popen enabled gc when it shouldn't.")
964
965 gc.enable()
966 self.assertTrue(gc.isenabled())
967 subprocess.call([sys.executable, '-c', ''],
968 preexec_fn=lambda: None)
969 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
970
971 gc.disable = raise_runtime_error
972 self.assertRaises(RuntimeError, subprocess.Popen,
973 [sys.executable, '-c', ''],
974 preexec_fn=lambda: None)
975
976 del gc.isenabled # force an AttributeError
977 self.assertRaises(AttributeError, subprocess.Popen,
978 [sys.executable, '-c', ''],
979 preexec_fn=lambda: None)
980 finally:
981 gc.disable = orig_gc_disable
982 gc.isenabled = orig_gc_isenabled
983 if not enabled:
984 gc.disable()
985
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000986 def test_args_string(self):
987 # args is a string
988 fd, fname = mkstemp()
989 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000990 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000991 fobj.write("#!/bin/sh\n")
992 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
993 sys.executable)
994 os.chmod(fname, 0o700)
995 p = subprocess.Popen(fname)
996 p.wait()
997 os.remove(fname)
998 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000999
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001000 def test_invalid_args(self):
1001 # invalid arguments should raise ValueError
1002 self.assertRaises(ValueError, subprocess.call,
1003 [sys.executable, "-c",
1004 "import sys; sys.exit(47)"],
1005 startupinfo=47)
1006 self.assertRaises(ValueError, subprocess.call,
1007 [sys.executable, "-c",
1008 "import sys; sys.exit(47)"],
1009 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001010
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001011 def test_shell_sequence(self):
1012 # Run command through the shell (sequence)
1013 newenv = os.environ.copy()
1014 newenv["FRUIT"] = "apple"
1015 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1016 stdout=subprocess.PIPE,
1017 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001018 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001019 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001020
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001021 def test_shell_string(self):
1022 # Run command through the shell (string)
1023 newenv = os.environ.copy()
1024 newenv["FRUIT"] = "apple"
1025 p = subprocess.Popen("echo $FRUIT", shell=1,
1026 stdout=subprocess.PIPE,
1027 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001028 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001029 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001030
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001031 def test_call_string(self):
1032 # call() function with string argument on UNIX
1033 fd, fname = mkstemp()
1034 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001035 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001036 fobj.write("#!/bin/sh\n")
1037 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1038 sys.executable)
1039 os.chmod(fname, 0o700)
1040 rc = subprocess.call(fname)
1041 os.remove(fname)
1042 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001043
Stefan Krah9542cc62010-07-19 14:20:53 +00001044 def test_specific_shell(self):
1045 # Issue #9265: Incorrect name passed as arg[0].
1046 shells = []
1047 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1048 for name in ['bash', 'ksh']:
1049 sh = os.path.join(prefix, name)
1050 if os.path.isfile(sh):
1051 shells.append(sh)
1052 if not shells: # Will probably work for any shell but csh.
1053 self.skipTest("bash or ksh required for this test")
1054 sh = '/bin/sh'
1055 if os.path.isfile(sh) and not os.path.islink(sh):
1056 # Test will fail if /bin/sh is a symlink to csh.
1057 shells.append(sh)
1058 for sh in shells:
1059 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1060 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001061 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001062 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1063
Florent Xicluna4886d242010-03-08 13:27:26 +00001064 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001065 # Do not inherit file handles from the parent.
1066 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001067 p = subprocess.Popen([sys.executable, "-c", """if 1:
1068 import sys, time
1069 sys.stdout.write('x\\n')
1070 sys.stdout.flush()
1071 time.sleep(30)
1072 """],
1073 close_fds=True,
1074 stdin=subprocess.PIPE,
1075 stdout=subprocess.PIPE,
1076 stderr=subprocess.PIPE)
1077 # Wait for the interpreter to be completely initialized before
1078 # sending any signal.
1079 p.stdout.read(1)
1080 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001081 return p
1082
1083 def test_send_signal(self):
1084 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001085 _, stderr = p.communicate()
1086 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001087 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001088
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001089 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001090 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001091 _, stderr = p.communicate()
1092 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001093 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001094
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001095 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001096 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001097 _, stderr = p.communicate()
1098 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001099 self.assertEqual(p.wait(), -signal.SIGTERM)
1100
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001101 def check_close_std_fds(self, fds):
1102 # Issue #9905: test that subprocess pipes still work properly with
1103 # some standard fds closed
1104 stdin = 0
1105 newfds = []
1106 for a in fds:
1107 b = os.dup(a)
1108 newfds.append(b)
1109 if a == 0:
1110 stdin = b
1111 try:
1112 for fd in fds:
1113 os.close(fd)
1114 out, err = subprocess.Popen([sys.executable, "-c",
1115 'import sys;'
1116 'sys.stdout.write("apple");'
1117 'sys.stdout.flush();'
1118 'sys.stderr.write("orange")'],
1119 stdin=stdin,
1120 stdout=subprocess.PIPE,
1121 stderr=subprocess.PIPE).communicate()
1122 err = support.strip_python_stderr(err)
1123 self.assertEqual((out, err), (b'apple', b'orange'))
1124 finally:
1125 for b, a in zip(newfds, fds):
1126 os.dup2(b, a)
1127 for b in newfds:
1128 os.close(b)
1129
1130 def test_close_fd_0(self):
1131 self.check_close_std_fds([0])
1132
1133 def test_close_fd_1(self):
1134 self.check_close_std_fds([1])
1135
1136 def test_close_fd_2(self):
1137 self.check_close_std_fds([2])
1138
1139 def test_close_fds_0_1(self):
1140 self.check_close_std_fds([0, 1])
1141
1142 def test_close_fds_0_2(self):
1143 self.check_close_std_fds([0, 2])
1144
1145 def test_close_fds_1_2(self):
1146 self.check_close_std_fds([1, 2])
1147
1148 def test_close_fds_0_1_2(self):
1149 # Issue #10806: test that subprocess pipes still work properly with
1150 # all standard fds closed.
1151 self.check_close_std_fds([0, 1, 2])
1152
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001153 def test_remapping_std_fds(self):
1154 # open up some temporary files
1155 temps = [mkstemp() for i in range(3)]
1156 try:
1157 temp_fds = [fd for fd, fname in temps]
1158
1159 # unlink the files -- we won't need to reopen them
1160 for fd, fname in temps:
1161 os.unlink(fname)
1162
1163 # write some data to what will become stdin, and rewind
1164 os.write(temp_fds[1], b"STDIN")
1165 os.lseek(temp_fds[1], 0, 0)
1166
1167 # move the standard file descriptors out of the way
1168 saved_fds = [os.dup(fd) for fd in range(3)]
1169 try:
1170 # duplicate the file objects over the standard fd's
1171 for fd, temp_fd in enumerate(temp_fds):
1172 os.dup2(temp_fd, fd)
1173
1174 # now use those files in the "wrong" order, so that subprocess
1175 # has to rearrange them in the child
1176 p = subprocess.Popen([sys.executable, "-c",
1177 'import sys; got = sys.stdin.read();'
1178 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1179 stdin=temp_fds[1],
1180 stdout=temp_fds[2],
1181 stderr=temp_fds[0])
1182 p.wait()
1183 finally:
1184 # restore the original fd's underneath sys.stdin, etc.
1185 for std, saved in enumerate(saved_fds):
1186 os.dup2(saved, std)
1187 os.close(saved)
1188
1189 for fd in temp_fds:
1190 os.lseek(fd, 0, 0)
1191
1192 out = os.read(temp_fds[2], 1024)
1193 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1194 self.assertEqual(out, b"got STDIN")
1195 self.assertEqual(err, b"err")
1196
1197 finally:
1198 for fd in temp_fds:
1199 os.close(fd)
1200
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001201 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1202 # open up some temporary files
1203 temps = [mkstemp() for i in range(3)]
1204 temp_fds = [fd for fd, fname in temps]
1205 try:
1206 # unlink the files -- we won't need to reopen them
1207 for fd, fname in temps:
1208 os.unlink(fname)
1209
1210 # save a copy of the standard file descriptors
1211 saved_fds = [os.dup(fd) for fd in range(3)]
1212 try:
1213 # duplicate the temp files over the standard fd's 0, 1, 2
1214 for fd, temp_fd in enumerate(temp_fds):
1215 os.dup2(temp_fd, fd)
1216
1217 # write some data to what will become stdin, and rewind
1218 os.write(stdin_no, b"STDIN")
1219 os.lseek(stdin_no, 0, 0)
1220
1221 # now use those files in the given order, so that subprocess
1222 # has to rearrange them in the child
1223 p = subprocess.Popen([sys.executable, "-c",
1224 'import sys; got = sys.stdin.read();'
1225 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1226 stdin=stdin_no,
1227 stdout=stdout_no,
1228 stderr=stderr_no)
1229 p.wait()
1230
1231 for fd in temp_fds:
1232 os.lseek(fd, 0, 0)
1233
1234 out = os.read(stdout_no, 1024)
1235 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1236 finally:
1237 for std, saved in enumerate(saved_fds):
1238 os.dup2(saved, std)
1239 os.close(saved)
1240
1241 self.assertEqual(out, b"got STDIN")
1242 self.assertEqual(err, b"err")
1243
1244 finally:
1245 for fd in temp_fds:
1246 os.close(fd)
1247
1248 # When duping fds, if there arises a situation where one of the fds is
1249 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1250 # This tests all combinations of this.
1251 def test_swap_fds(self):
1252 self.check_swap_fds(0, 1, 2)
1253 self.check_swap_fds(0, 2, 1)
1254 self.check_swap_fds(1, 0, 2)
1255 self.check_swap_fds(1, 2, 0)
1256 self.check_swap_fds(2, 0, 1)
1257 self.check_swap_fds(2, 1, 0)
1258
Victor Stinner13bb71c2010-04-23 21:41:56 +00001259 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001260 def prepare():
1261 raise ValueError("surrogate:\uDCff")
1262
1263 try:
1264 subprocess.call(
1265 [sys.executable, "-c", "pass"],
1266 preexec_fn=prepare)
1267 except ValueError as err:
1268 # Pure Python implementations keeps the message
1269 self.assertIsNone(subprocess._posixsubprocess)
1270 self.assertEqual(str(err), "surrogate:\uDCff")
1271 except RuntimeError as err:
1272 # _posixsubprocess uses a default message
1273 self.assertIsNotNone(subprocess._posixsubprocess)
1274 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1275 else:
1276 self.fail("Expected ValueError or RuntimeError")
1277
Victor Stinner13bb71c2010-04-23 21:41:56 +00001278 def test_undecodable_env(self):
1279 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001280 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001281 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001282 env = os.environ.copy()
1283 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001284 # Use C locale to get ascii for the locale encoding to force
1285 # surrogate-escaping of \xFF in the child process; otherwise it can
1286 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001287 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001288 stdout = subprocess.check_output(
1289 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001290 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001291 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001292 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001293
1294 # test bytes
1295 key = key.encode("ascii", "surrogateescape")
1296 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001297 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001298 env = os.environ.copy()
1299 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001300 stdout = subprocess.check_output(
1301 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001302 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001303 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001304 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001305
Victor Stinnerb745a742010-05-18 17:17:23 +00001306 def test_bytes_program(self):
1307 abs_program = os.fsencode(sys.executable)
1308 path, program = os.path.split(sys.executable)
1309 program = os.fsencode(program)
1310
1311 # absolute bytes path
1312 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001313 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001314
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001315 # absolute bytes path as a string
1316 cmd = b"'" + abs_program + b"' -c pass"
1317 exitcode = subprocess.call(cmd, shell=True)
1318 self.assertEqual(exitcode, 0)
1319
Victor Stinnerb745a742010-05-18 17:17:23 +00001320 # bytes program, unicode PATH
1321 env = os.environ.copy()
1322 env["PATH"] = path
1323 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001324 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001325
1326 # bytes program, bytes PATH
1327 envb = os.environb.copy()
1328 envb[b"PATH"] = os.fsencode(path)
1329 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001330 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001331
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001332 def test_pipe_cloexec(self):
1333 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1334 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1335
1336 p1 = subprocess.Popen([sys.executable, sleeper],
1337 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1338 stderr=subprocess.PIPE, close_fds=False)
1339
1340 self.addCleanup(p1.communicate, b'')
1341
1342 p2 = subprocess.Popen([sys.executable, fd_status],
1343 stdout=subprocess.PIPE, close_fds=False)
1344
1345 output, error = p2.communicate()
1346 result_fds = set(map(int, output.split(b',')))
1347 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1348 p1.stderr.fileno()])
1349
1350 self.assertFalse(result_fds & unwanted_fds,
1351 "Expected no fds from %r to be open in child, "
1352 "found %r" %
1353 (unwanted_fds, result_fds & unwanted_fds))
1354
1355 def test_pipe_cloexec_real_tools(self):
1356 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1357 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1358
1359 subdata = b'zxcvbn'
1360 data = subdata * 4 + b'\n'
1361
1362 p1 = subprocess.Popen([sys.executable, qcat],
1363 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1364 close_fds=False)
1365
1366 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1367 stdin=p1.stdout, stdout=subprocess.PIPE,
1368 close_fds=False)
1369
1370 self.addCleanup(p1.wait)
1371 self.addCleanup(p2.wait)
1372 self.addCleanup(p1.terminate)
1373 self.addCleanup(p2.terminate)
1374
1375 p1.stdin.write(data)
1376 p1.stdin.close()
1377
1378 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1379
1380 self.assertTrue(readfiles, "The child hung")
1381 self.assertEqual(p2.stdout.read(), data)
1382
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001383 p1.stdout.close()
1384 p2.stdout.close()
1385
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001386 def test_close_fds(self):
1387 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1388
1389 fds = os.pipe()
1390 self.addCleanup(os.close, fds[0])
1391 self.addCleanup(os.close, fds[1])
1392
1393 open_fds = set(fds)
1394
1395 p = subprocess.Popen([sys.executable, fd_status],
1396 stdout=subprocess.PIPE, close_fds=False)
1397 output, ignored = p.communicate()
1398 remaining_fds = set(map(int, output.split(b',')))
1399
1400 self.assertEqual(remaining_fds & open_fds, open_fds,
1401 "Some fds were closed")
1402
1403 p = subprocess.Popen([sys.executable, fd_status],
1404 stdout=subprocess.PIPE, close_fds=True)
1405 output, ignored = p.communicate()
1406 remaining_fds = set(map(int, output.split(b',')))
1407
1408 self.assertFalse(remaining_fds & open_fds,
1409 "Some fds were left open")
1410 self.assertIn(1, remaining_fds, "Subprocess failed")
1411
Victor Stinner88701e22011-06-01 13:13:04 +02001412 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1413 # descriptor of a pipe closed in the parent process is valid in the
1414 # child process according to fstat(), but the mode of the file
1415 # descriptor is invalid, and read or write raise an error.
1416 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001417 def test_pass_fds(self):
1418 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1419
1420 open_fds = set()
1421
1422 for x in range(5):
1423 fds = os.pipe()
1424 self.addCleanup(os.close, fds[0])
1425 self.addCleanup(os.close, fds[1])
1426 open_fds.update(fds)
1427
1428 for fd in open_fds:
1429 p = subprocess.Popen([sys.executable, fd_status],
1430 stdout=subprocess.PIPE, close_fds=True,
1431 pass_fds=(fd, ))
1432 output, ignored = p.communicate()
1433
1434 remaining_fds = set(map(int, output.split(b',')))
1435 to_be_closed = open_fds - {fd}
1436
1437 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1438 self.assertFalse(remaining_fds & to_be_closed,
1439 "fd to be closed passed")
1440
1441 # pass_fds overrides close_fds with a warning.
1442 with self.assertWarns(RuntimeWarning) as context:
1443 self.assertFalse(subprocess.call(
1444 [sys.executable, "-c", "import sys; sys.exit(0)"],
1445 close_fds=False, pass_fds=(fd, )))
1446 self.assertIn('overriding close_fds', str(context.warning))
1447
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001448 def test_stdout_stdin_are_single_inout_fd(self):
1449 with io.open(os.devnull, "r+") as inout:
1450 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1451 stdout=inout, stdin=inout)
1452 p.wait()
1453
1454 def test_stdout_stderr_are_single_inout_fd(self):
1455 with io.open(os.devnull, "r+") as inout:
1456 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1457 stdout=inout, stderr=inout)
1458 p.wait()
1459
1460 def test_stderr_stdin_are_single_inout_fd(self):
1461 with io.open(os.devnull, "r+") as inout:
1462 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1463 stderr=inout, stdin=inout)
1464 p.wait()
1465
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001466 def test_wait_when_sigchild_ignored(self):
1467 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1468 sigchild_ignore = support.findfile("sigchild_ignore.py",
1469 subdir="subprocessdata")
1470 p = subprocess.Popen([sys.executable, sigchild_ignore],
1471 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1472 stdout, stderr = p.communicate()
1473 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001474 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001475 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001476
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001477 def test_select_unbuffered(self):
1478 # Issue #11459: bufsize=0 should really set the pipes as
1479 # unbuffered (and therefore let select() work properly).
1480 select = support.import_module("select")
1481 p = subprocess.Popen([sys.executable, "-c",
1482 'import sys;'
1483 'sys.stdout.write("apple")'],
1484 stdout=subprocess.PIPE,
1485 bufsize=0)
1486 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001487 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001488 try:
1489 self.assertEqual(f.read(4), b"appl")
1490 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1491 finally:
1492 p.wait()
1493
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001494 def test_zombie_fast_process_del(self):
1495 # Issue #12650: on Unix, if Popen.__del__() was called before the
1496 # process exited, it wouldn't be added to subprocess._active, and would
1497 # remain a zombie.
1498 # spawn a Popen, and delete its reference before it exits
1499 p = subprocess.Popen([sys.executable, "-c",
1500 'import sys, time;'
1501 'time.sleep(0.2)'],
1502 stdout=subprocess.PIPE,
1503 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001504 self.addCleanup(p.stdout.close)
1505 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001506 ident = id(p)
1507 pid = p.pid
1508 del p
1509 # check that p is in the active processes list
1510 self.assertIn(ident, [id(o) for o in subprocess._active])
1511
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001512 def test_leak_fast_process_del_killed(self):
1513 # Issue #12650: on Unix, if Popen.__del__() was called before the
1514 # process exited, and the process got killed by a signal, it would never
1515 # be removed from subprocess._active, which triggered a FD and memory
1516 # leak.
1517 # spawn a Popen, delete its reference and kill it
1518 p = subprocess.Popen([sys.executable, "-c",
1519 'import time;'
1520 'time.sleep(3)'],
1521 stdout=subprocess.PIPE,
1522 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001523 self.addCleanup(p.stdout.close)
1524 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001525 ident = id(p)
1526 pid = p.pid
1527 del p
1528 os.kill(pid, signal.SIGKILL)
1529 # check that p is in the active processes list
1530 self.assertIn(ident, [id(o) for o in subprocess._active])
1531
1532 # let some time for the process to exit, and create a new Popen: this
1533 # should trigger the wait() of p
1534 time.sleep(0.2)
1535 with self.assertRaises(EnvironmentError) as c:
1536 with subprocess.Popen(['nonexisting_i_hope'],
1537 stdout=subprocess.PIPE,
1538 stderr=subprocess.PIPE) as proc:
1539 pass
1540 # p should have been wait()ed on, and removed from the _active list
1541 self.assertRaises(OSError, os.waitpid, pid, 0)
1542 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1543
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001544
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001545@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001546class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001547
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001548 def test_startupinfo(self):
1549 # startupinfo argument
1550 # We uses hardcoded constants, because we do not want to
1551 # depend on win32all.
1552 STARTF_USESHOWWINDOW = 1
1553 SW_MAXIMIZE = 3
1554 startupinfo = subprocess.STARTUPINFO()
1555 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1556 startupinfo.wShowWindow = SW_MAXIMIZE
1557 # Since Python is a console process, it won't be affected
1558 # by wShowWindow, but the argument should be silently
1559 # ignored
1560 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001561 startupinfo=startupinfo)
1562
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001563 def test_creationflags(self):
1564 # creationflags argument
1565 CREATE_NEW_CONSOLE = 16
1566 sys.stderr.write(" a DOS box should flash briefly ...\n")
1567 subprocess.call(sys.executable +
1568 ' -c "import time; time.sleep(0.25)"',
1569 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001570
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001571 def test_invalid_args(self):
1572 # invalid arguments should raise ValueError
1573 self.assertRaises(ValueError, subprocess.call,
1574 [sys.executable, "-c",
1575 "import sys; sys.exit(47)"],
1576 preexec_fn=lambda: 1)
1577 self.assertRaises(ValueError, subprocess.call,
1578 [sys.executable, "-c",
1579 "import sys; sys.exit(47)"],
1580 stdout=subprocess.PIPE,
1581 close_fds=True)
1582
1583 def test_close_fds(self):
1584 # close file descriptors
1585 rc = subprocess.call([sys.executable, "-c",
1586 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001587 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001588 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001589
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001590 def test_shell_sequence(self):
1591 # Run command through the shell (sequence)
1592 newenv = os.environ.copy()
1593 newenv["FRUIT"] = "physalis"
1594 p = subprocess.Popen(["set"], shell=1,
1595 stdout=subprocess.PIPE,
1596 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001597 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001598 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001599
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001600 def test_shell_string(self):
1601 # Run command through the shell (string)
1602 newenv = os.environ.copy()
1603 newenv["FRUIT"] = "physalis"
1604 p = subprocess.Popen("set", shell=1,
1605 stdout=subprocess.PIPE,
1606 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001607 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001608 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001609
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001610 def test_call_string(self):
1611 # call() function with string argument on Windows
1612 rc = subprocess.call(sys.executable +
1613 ' -c "import sys; sys.exit(47)"')
1614 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001615
Florent Xicluna4886d242010-03-08 13:27:26 +00001616 def _kill_process(self, method, *args):
1617 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001618 p = subprocess.Popen([sys.executable, "-c", """if 1:
1619 import sys, time
1620 sys.stdout.write('x\\n')
1621 sys.stdout.flush()
1622 time.sleep(30)
1623 """],
1624 stdin=subprocess.PIPE,
1625 stdout=subprocess.PIPE,
1626 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001627 self.addCleanup(p.stdout.close)
1628 self.addCleanup(p.stderr.close)
1629 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001630 # Wait for the interpreter to be completely initialized before
1631 # sending any signal.
1632 p.stdout.read(1)
1633 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001634 _, stderr = p.communicate()
1635 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001636 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001637 self.assertNotEqual(returncode, 0)
1638
1639 def test_send_signal(self):
1640 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001641
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001642 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001643 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001644
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001645 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001646 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001647
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001648
Brett Cannona23810f2008-05-26 19:04:21 +00001649# The module says:
1650# "NB This only works (and is only relevant) for UNIX."
1651#
1652# Actually, getoutput should work on any platform with an os.popen, but
1653# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001654@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001655class CommandTests(unittest.TestCase):
1656 def test_getoutput(self):
1657 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1658 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1659 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001660
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001661 # we use mkdtemp in the next line to create an empty directory
1662 # under our exclusive control; from that, we can invent a pathname
1663 # that we _know_ won't exist. This is guaranteed to fail.
1664 dir = None
1665 try:
1666 dir = tempfile.mkdtemp()
1667 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001668
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001669 status, output = subprocess.getstatusoutput('cat ' + name)
1670 self.assertNotEqual(status, 0)
1671 finally:
1672 if dir is not None:
1673 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001674
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001675
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001676@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1677 "poll system call not supported")
1678class ProcessTestCaseNoPoll(ProcessTestCase):
1679 def setUp(self):
1680 subprocess._has_poll = False
1681 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001682
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001683 def tearDown(self):
1684 subprocess._has_poll = True
1685 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001686
1687
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001688class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001689 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001690 def test_eintr_retry_call(self):
1691 record_calls = []
1692 def fake_os_func(*args):
1693 record_calls.append(args)
1694 if len(record_calls) == 2:
1695 raise OSError(errno.EINTR, "fake interrupted system call")
1696 return tuple(reversed(args))
1697
1698 self.assertEqual((999, 256),
1699 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1700 self.assertEqual([(256, 999)], record_calls)
1701 # This time there will be an EINTR so it will loop once.
1702 self.assertEqual((666,),
1703 subprocess._eintr_retry_call(fake_os_func, 666))
1704 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1705
1706
Tim Golden126c2962010-08-11 14:20:40 +00001707@unittest.skipUnless(mswindows, "Windows-specific tests")
1708class CommandsWithSpaces (BaseTestCase):
1709
1710 def setUp(self):
1711 super().setUp()
1712 f, fname = mkstemp(".py", "te st")
1713 self.fname = fname.lower ()
1714 os.write(f, b"import sys;"
1715 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1716 )
1717 os.close(f)
1718
1719 def tearDown(self):
1720 os.remove(self.fname)
1721 super().tearDown()
1722
1723 def with_spaces(self, *args, **kwargs):
1724 kwargs['stdout'] = subprocess.PIPE
1725 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001726 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001727 self.assertEqual(
1728 p.stdout.read ().decode("mbcs"),
1729 "2 [%r, 'ab cd']" % self.fname
1730 )
1731
1732 def test_shell_string_with_spaces(self):
1733 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001734 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1735 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001736
1737 def test_shell_sequence_with_spaces(self):
1738 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001739 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001740
1741 def test_noshell_string_with_spaces(self):
1742 # call() function with string argument with spaces on Windows
1743 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1744 "ab cd"))
1745
1746 def test_noshell_sequence_with_spaces(self):
1747 # call() function with sequence argument with spaces on Windows
1748 self.with_spaces([sys.executable, self.fname, "ab cd"])
1749
Brian Curtin79cdb662010-12-03 02:46:02 +00001750
1751class ContextManagerTests(ProcessTestCase):
1752
1753 def test_pipe(self):
1754 with subprocess.Popen([sys.executable, "-c",
1755 "import sys;"
1756 "sys.stdout.write('stdout');"
1757 "sys.stderr.write('stderr');"],
1758 stdout=subprocess.PIPE,
1759 stderr=subprocess.PIPE) as proc:
1760 self.assertEqual(proc.stdout.read(), b"stdout")
1761 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1762
1763 self.assertTrue(proc.stdout.closed)
1764 self.assertTrue(proc.stderr.closed)
1765
1766 def test_returncode(self):
1767 with subprocess.Popen([sys.executable, "-c",
1768 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07001769 pass
1770 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001771 self.assertEqual(proc.returncode, 100)
1772
1773 def test_communicate_stdin(self):
1774 with subprocess.Popen([sys.executable, "-c",
1775 "import sys;"
1776 "sys.exit(sys.stdin.read() == 'context')"],
1777 stdin=subprocess.PIPE) as proc:
1778 proc.communicate(b"context")
1779 self.assertEqual(proc.returncode, 1)
1780
1781 def test_invalid_args(self):
1782 with self.assertRaises(EnvironmentError) as c:
1783 with subprocess.Popen(['nonexisting_i_hope'],
1784 stdout=subprocess.PIPE,
1785 stderr=subprocess.PIPE) as proc:
1786 pass
1787
1788 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1789 raise c.exception
1790
1791
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001792def test_main():
1793 unit_tests = (ProcessTestCase,
1794 POSIXProcessTestCase,
1795 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001796 CommandTests,
1797 ProcessTestCaseNoPoll,
1798 HelperFunctionTests,
1799 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001800 ContextManagerTests,
1801 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001802
1803 support.run_unittest(*unit_tests)
1804 support.reap_children()
1805
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001806if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001807 unittest.main()