blob: 31565432b0cd63591775e6c53ce244038f441726 [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",
130 "import sys; sys.stdout.write('BDFL')\n"
131 "sys.stdout.flush()\n"
132 "while True: pass"],
Reid Kleckner80b92d12011-03-14 13:34:12 -0400133 timeout=1.5)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400134 self.fail("Expected TimeoutExpired.")
135 self.assertEqual(c.exception.output, b'BDFL')
136
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000137 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000138 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000139 newenv = os.environ.copy()
140 newenv["FRUIT"] = "banana"
141 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000142 'import sys, os;'
143 'sys.exit(os.getenv("FRUIT")=="banana")'],
144 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145 self.assertEqual(rc, 1)
146
147 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000148 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000149 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000150 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000151 self.addCleanup(p.stdout.close)
152 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000153 p.wait()
154 self.assertEqual(p.stdin, None)
155
156 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000157 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000158 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000159 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000160 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000161 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000162 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000163 self.addCleanup(p.stdin.close)
164 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165 p.wait()
166 self.assertEqual(p.stdout, None)
167
168 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000169 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000170 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000171 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000172 self.addCleanup(p.stdout.close)
173 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000174 p.wait()
175 self.assertEqual(p.stderr, None)
176
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000177 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000178 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000179 p = subprocess.Popen(["somethingyoudonthave", "-c",
180 "import sys; sys.exit(47)"],
181 executable=sys.executable, cwd=python_dir)
182 p.wait()
183 self.assertEqual(p.returncode, 47)
184
185 @unittest.skipIf(sysconfig.is_python_build(),
186 "need an installed Python. See #7774")
187 def test_executable_without_cwd(self):
188 # For a normal installation, it should work without 'cwd'
189 # argument. For test runs in the build directory, see #7774.
190 p = subprocess.Popen(["somethingyoudonthave", "-c",
191 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000192 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000193 p.wait()
194 self.assertEqual(p.returncode, 47)
195
196 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000197 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000198 p = subprocess.Popen([sys.executable, "-c",
199 'import sys; sys.exit(sys.stdin.read() == "pear")'],
200 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000201 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000202 p.stdin.close()
203 p.wait()
204 self.assertEqual(p.returncode, 1)
205
206 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000207 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000208 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000209 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000211 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000212 os.lseek(d, 0, 0)
213 p = subprocess.Popen([sys.executable, "-c",
214 'import sys; sys.exit(sys.stdin.read() == "pear")'],
215 stdin=d)
216 p.wait()
217 self.assertEqual(p.returncode, 1)
218
219 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000220 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000221 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000222 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000223 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000224 tf.seek(0)
225 p = subprocess.Popen([sys.executable, "-c",
226 'import sys; sys.exit(sys.stdin.read() == "pear")'],
227 stdin=tf)
228 p.wait()
229 self.assertEqual(p.returncode, 1)
230
231 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000232 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233 p = subprocess.Popen([sys.executable, "-c",
234 'import sys; sys.stdout.write("orange")'],
235 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000236 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000237 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238
239 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000240 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000241 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000242 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000243 d = tf.fileno()
244 p = subprocess.Popen([sys.executable, "-c",
245 'import sys; sys.stdout.write("orange")'],
246 stdout=d)
247 p.wait()
248 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000249 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000250
251 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000252 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000253 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000254 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000255 p = subprocess.Popen([sys.executable, "-c",
256 'import sys; sys.stdout.write("orange")'],
257 stdout=tf)
258 p.wait()
259 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000260 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000261
262 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000263 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000264 p = subprocess.Popen([sys.executable, "-c",
265 'import sys; sys.stderr.write("strawberry")'],
266 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000267 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000268 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269
270 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000271 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000272 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000273 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274 d = tf.fileno()
275 p = subprocess.Popen([sys.executable, "-c",
276 'import sys; sys.stderr.write("strawberry")'],
277 stderr=d)
278 p.wait()
279 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000280 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281
282 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000283 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000284 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000285 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000286 p = subprocess.Popen([sys.executable, "-c",
287 'import sys; sys.stderr.write("strawberry")'],
288 stderr=tf)
289 p.wait()
290 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000291 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000292
293 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000294 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000295 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000296 'import sys;'
297 'sys.stdout.write("apple");'
298 'sys.stdout.flush();'
299 'sys.stderr.write("orange")'],
300 stdout=subprocess.PIPE,
301 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000302 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000303 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000304
305 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000306 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000307 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000308 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000310 'import sys;'
311 'sys.stdout.write("apple");'
312 'sys.stdout.flush();'
313 'sys.stderr.write("orange")'],
314 stdout=tf,
315 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000316 p.wait()
317 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000318 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000319
Thomas Wouters89f507f2006-12-13 04:49:30 +0000320 def test_stdout_filedes_of_stdout(self):
321 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000322 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000323 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000324 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000325
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200326 def test_stdout_devnull(self):
327 p = subprocess.Popen([sys.executable, "-c",
328 'for i in range(10240):'
329 'print("x" * 1024)'],
330 stdout=subprocess.DEVNULL)
331 p.wait()
332 self.assertEqual(p.stdout, None)
333
334 def test_stderr_devnull(self):
335 p = subprocess.Popen([sys.executable, "-c",
336 'import sys\n'
337 'for i in range(10240):'
338 'sys.stderr.write("x" * 1024)'],
339 stderr=subprocess.DEVNULL)
340 p.wait()
341 self.assertEqual(p.stderr, None)
342
343 def test_stdin_devnull(self):
344 p = subprocess.Popen([sys.executable, "-c",
345 'import sys;'
346 'sys.stdin.read(1)'],
347 stdin=subprocess.DEVNULL)
348 p.wait()
349 self.assertEqual(p.stdin, None)
350
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000351 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000352 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000353 # We cannot use os.path.realpath to canonicalize the path,
354 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
355 cwd = os.getcwd()
356 os.chdir(tmpdir)
357 tmpdir = os.getcwd()
358 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000359 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000360 'import sys,os;'
361 'sys.stdout.write(os.getcwd())'],
362 stdout=subprocess.PIPE,
363 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000364 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000365 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000366 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
367 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000368
369 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370 newenv = os.environ.copy()
371 newenv["FRUIT"] = "orange"
372 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000373 'import sys,os;'
374 'sys.stdout.write(os.getenv("FRUIT"))'],
375 stdout=subprocess.PIPE,
376 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000377 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000378 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000379
Peter Astrandcbac93c2005-03-03 20:24:28 +0000380 def test_communicate_stdin(self):
381 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000382 'import sys;'
383 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000384 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000385 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000386 self.assertEqual(p.returncode, 1)
387
388 def test_communicate_stdout(self):
389 p = subprocess.Popen([sys.executable, "-c",
390 'import sys; sys.stdout.write("pineapple")'],
391 stdout=subprocess.PIPE)
392 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000393 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000394 self.assertEqual(stderr, None)
395
396 def test_communicate_stderr(self):
397 p = subprocess.Popen([sys.executable, "-c",
398 'import sys; sys.stderr.write("pineapple")'],
399 stderr=subprocess.PIPE)
400 (stdout, stderr) = p.communicate()
401 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000402 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000403
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000404 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000405 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000406 'import sys,os;'
407 'sys.stderr.write("pineapple");'
408 'sys.stdout.write(sys.stdin.read())'],
409 stdin=subprocess.PIPE,
410 stdout=subprocess.PIPE,
411 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000412 self.addCleanup(p.stdout.close)
413 self.addCleanup(p.stderr.close)
414 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000415 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000416 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000417 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000418
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400419 def test_communicate_timeout(self):
420 p = subprocess.Popen([sys.executable, "-c",
421 'import sys,os,time;'
422 'sys.stderr.write("pineapple\\n");'
423 'time.sleep(1);'
424 'sys.stderr.write("pear\\n");'
425 'sys.stdout.write(sys.stdin.read())'],
426 universal_newlines=True,
427 stdin=subprocess.PIPE,
428 stdout=subprocess.PIPE,
429 stderr=subprocess.PIPE)
430 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
431 timeout=0.3)
432 # Make sure we can keep waiting for it, and that we get the whole output
433 # after it completes.
434 (stdout, stderr) = p.communicate()
435 self.assertEqual(stdout, "banana")
436 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
437
438 def test_communicate_timeout_large_ouput(self):
439 # Test a expring timeout while the child is outputting lots of data.
440 p = subprocess.Popen([sys.executable, "-c",
441 'import sys,os,time;'
442 'sys.stdout.write("a" * (64 * 1024));'
443 'time.sleep(0.2);'
444 'sys.stdout.write("a" * (64 * 1024));'
445 'time.sleep(0.2);'
446 'sys.stdout.write("a" * (64 * 1024));'
447 'time.sleep(0.2);'
448 'sys.stdout.write("a" * (64 * 1024));'],
449 stdout=subprocess.PIPE)
450 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
451 (stdout, _) = p.communicate()
452 self.assertEqual(len(stdout), 4 * 64 * 1024)
453
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000454 # Test for the fd leak reported in http://bugs.python.org/issue2791.
455 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000456 for stdin_pipe in (False, True):
457 for stdout_pipe in (False, True):
458 for stderr_pipe in (False, True):
459 options = {}
460 if stdin_pipe:
461 options['stdin'] = subprocess.PIPE
462 if stdout_pipe:
463 options['stdout'] = subprocess.PIPE
464 if stderr_pipe:
465 options['stderr'] = subprocess.PIPE
466 if not options:
467 continue
468 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
469 p.communicate()
470 if p.stdin is not None:
471 self.assertTrue(p.stdin.closed)
472 if p.stdout is not None:
473 self.assertTrue(p.stdout.closed)
474 if p.stderr is not None:
475 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000476
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000477 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000478 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000479 p = subprocess.Popen([sys.executable, "-c",
480 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481 (stdout, stderr) = p.communicate()
482 self.assertEqual(stdout, None)
483 self.assertEqual(stderr, None)
484
485 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000486 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000487 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000488 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 x, y = os.pipe()
490 if mswindows:
491 pipe_buf = 512
492 else:
493 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
494 os.close(x)
495 os.close(y)
496 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000497 'import sys,os;'
498 'sys.stdout.write(sys.stdin.read(47));'
499 'sys.stderr.write("xyz"*%d);'
500 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
501 stdin=subprocess.PIPE,
502 stdout=subprocess.PIPE,
503 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000504 self.addCleanup(p.stdout.close)
505 self.addCleanup(p.stderr.close)
506 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000507 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000508 (stdout, stderr) = p.communicate(string_to_write)
509 self.assertEqual(stdout, string_to_write)
510
511 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000512 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000513 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000514 'import sys,os;'
515 'sys.stdout.write(sys.stdin.read())'],
516 stdin=subprocess.PIPE,
517 stdout=subprocess.PIPE,
518 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000519 self.addCleanup(p.stdout.close)
520 self.addCleanup(p.stderr.close)
521 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000522 p.stdin.write(b"banana")
523 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000524 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000525 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000526
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000529 'import sys,os;' + SETBINARY +
530 'sys.stdout.write("line1\\n");'
531 'sys.stdout.flush();'
532 'sys.stdout.write("line2\\n");'
533 'sys.stdout.flush();'
534 'sys.stdout.write("line3\\r\\n");'
535 'sys.stdout.flush();'
536 'sys.stdout.write("line4\\r");'
537 'sys.stdout.flush();'
538 'sys.stdout.write("\\nline5");'
539 'sys.stdout.flush();'
540 'sys.stdout.write("\\nline6");'],
541 stdout=subprocess.PIPE,
542 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000543 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000544 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000545 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546
547 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000548 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000550 'import sys,os;' + SETBINARY +
551 'sys.stdout.write("line1\\n");'
552 'sys.stdout.flush();'
553 'sys.stdout.write("line2\\n");'
554 'sys.stdout.flush();'
555 'sys.stdout.write("line3\\r\\n");'
556 'sys.stdout.flush();'
557 'sys.stdout.write("line4\\r");'
558 'sys.stdout.flush();'
559 'sys.stdout.write("\\nline5");'
560 'sys.stdout.flush();'
561 'sys.stdout.write("\\nline6");'],
562 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
563 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000564 self.addCleanup(p.stdout.close)
565 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000566 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000567 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568
569 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000570 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000571 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000572 max_handles = 1026 # too much for most UNIX systems
573 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000574 max_handles = 2050 # too much for (at least some) Windows setups
575 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400576 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000577 try:
578 for i in range(max_handles):
579 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400580 tmpfile = os.path.join(tmpdir, support.TESTFN)
581 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000582 except OSError as e:
583 if e.errno != errno.EMFILE:
584 raise
585 break
586 else:
587 self.skipTest("failed to reach the file descriptor limit "
588 "(tried %d)" % max_handles)
589 # Close a couple of them (should be enough for a subprocess)
590 for i in range(10):
591 os.close(handles.pop())
592 # Loop creating some subprocesses. If one of them leaks some fds,
593 # the next loop iteration will fail by reaching the max fd limit.
594 for i in range(15):
595 p = subprocess.Popen([sys.executable, "-c",
596 "import sys;"
597 "sys.stdout.write(sys.stdin.read())"],
598 stdin=subprocess.PIPE,
599 stdout=subprocess.PIPE,
600 stderr=subprocess.PIPE)
601 data = p.communicate(b"lime")[0]
602 self.assertEqual(data, b"lime")
603 finally:
604 for h in handles:
605 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400606 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000607
608 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000609 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
610 '"a b c" d e')
611 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
612 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000613 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
614 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000615 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
616 'a\\\\\\b "de fg" h')
617 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
618 'a\\\\\\"b c d')
619 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
620 '"a\\\\b c" d e')
621 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
622 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000623 self.assertEqual(subprocess.list2cmdline(['ab', '']),
624 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000625
626
627 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000628 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000629 "-c", "import time; time.sleep(1)"])
630 count = 0
631 while p.poll() is None:
632 time.sleep(0.1)
633 count += 1
634 # We expect that the poll loop probably went around about 10 times,
635 # but, based on system scheduling we can't control, it's possible
636 # poll() never returned None. It "should be" very rare that it
637 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000638 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000639 # Subsequent invocations should just return the returncode
640 self.assertEqual(p.poll(), 0)
641
642
643 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000644 p = subprocess.Popen([sys.executable,
645 "-c", "import time; time.sleep(2)"])
646 self.assertEqual(p.wait(), 0)
647 # Subsequent invocations should just return the returncode
648 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000649
Peter Astrand738131d2004-11-30 21:04:45 +0000650
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400651 def test_wait_timeout(self):
652 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400653 "-c", "import time; time.sleep(0.1)"])
654 self.assertRaises(subprocess.TimeoutExpired, p.wait, timeout=0.01)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400655 self.assertEqual(p.wait(timeout=2), 0)
656
657
Peter Astrand738131d2004-11-30 21:04:45 +0000658 def test_invalid_bufsize(self):
659 # an invalid type of the bufsize argument should raise
660 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000661 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000662 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000663
Guido van Rossum46a05a72007-06-07 21:56:45 +0000664 def test_bufsize_is_none(self):
665 # bufsize=None should be the same as bufsize=0.
666 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
667 self.assertEqual(p.wait(), 0)
668 # Again with keyword arg
669 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
670 self.assertEqual(p.wait(), 0)
671
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000672 def test_leaking_fds_on_error(self):
673 # see bug #5179: Popen leaks file descriptors to PIPEs if
674 # the child fails to execute; this will eventually exhaust
675 # the maximum number of open fds. 1024 seems a very common
676 # value for that limit, but Windows has 2048, so we loop
677 # 1024 times (each call leaked two fds).
678 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000679 # Windows raises IOError. Others raise OSError.
680 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000681 subprocess.Popen(['nonexisting_i_hope'],
682 stdout=subprocess.PIPE,
683 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400684 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400685 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000686 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000687
Victor Stinnerb3693582010-05-21 20:13:12 +0000688 def test_issue8780(self):
689 # Ensure that stdout is inherited from the parent
690 # if stdout=PIPE is not used
691 code = ';'.join((
692 'import subprocess, sys',
693 'retcode = subprocess.call('
694 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
695 'assert retcode == 0'))
696 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000697 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000698
Tim Goldenaf5ac392010-08-06 13:03:56 +0000699 def test_handles_closed_on_exception(self):
700 # If CreateProcess exits with an error, ensure the
701 # duplicate output handles are released
702 ifhandle, ifname = mkstemp()
703 ofhandle, ofname = mkstemp()
704 efhandle, efname = mkstemp()
705 try:
706 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
707 stderr=efhandle)
708 except OSError:
709 os.close(ifhandle)
710 os.remove(ifname)
711 os.close(ofhandle)
712 os.remove(ofname)
713 os.close(efhandle)
714 os.remove(efname)
715 self.assertFalse(os.path.exists(ifname))
716 self.assertFalse(os.path.exists(ofname))
717 self.assertFalse(os.path.exists(efname))
718
Tim Peterse718f612004-10-12 21:51:32 +0000719
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000720# context manager
721class _SuppressCoreFiles(object):
722 """Try to prevent core files from being created."""
723 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000724
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000725 def __enter__(self):
726 """Try to save previous ulimit, then set it to (0, 0)."""
727 try:
728 import resource
729 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
730 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
731 except (ImportError, ValueError, resource.error):
732 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000733
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000734 if sys.platform == 'darwin':
735 # Check if the 'Crash Reporter' on OSX was configured
736 # in 'Developer' mode and warn that it will get triggered
737 # when it is.
738 #
739 # This assumes that this context manager is used in tests
740 # that might trigger the next manager.
741 value = subprocess.Popen(['/usr/bin/defaults', 'read',
742 'com.apple.CrashReporter', 'DialogType'],
743 stdout=subprocess.PIPE).communicate()[0]
744 if value.strip() == b'developer':
745 print("this tests triggers the Crash Reporter, "
746 "that is intentional", end='')
747 sys.stdout.flush()
748
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000749 def __exit__(self, *args):
750 """Return core file behavior to default."""
751 if self.old_limit is None:
752 return
753 try:
754 import resource
755 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
756 except (ImportError, ValueError, resource.error):
757 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000758
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000759
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000760@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000761class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000762
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000763 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000764 nonexistent_dir = "/_this/pa.th/does/not/exist"
765 try:
766 os.chdir(nonexistent_dir)
767 except OSError as e:
768 # This avoids hard coding the errno value or the OS perror()
769 # string and instead capture the exception that we want to see
770 # below for comparison.
771 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000772 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000773 else:
774 self.fail("chdir to nonexistant directory %s succeeded." %
775 nonexistent_dir)
776
777 # Error in the child re-raised in the parent.
778 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000779 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000780 cwd=nonexistent_dir)
781 except OSError as e:
782 # Test that the child process chdir failure actually makes
783 # it up to the parent process as the correct exception.
784 self.assertEqual(desired_exception.errno, e.errno)
785 self.assertEqual(desired_exception.strerror, e.strerror)
786 else:
787 self.fail("Expected OSError: %s" % desired_exception)
788
789 def test_restore_signals(self):
790 # Code coverage for both values of restore_signals to make sure it
791 # at least does not blow up.
792 # A test for behavior would be complex. Contributions welcome.
793 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
794 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
795
796 def test_start_new_session(self):
797 # For code coverage of calling setsid(). We don't care if we get an
798 # EPERM error from it depending on the test execution environment, that
799 # still indicates that it was called.
800 try:
801 output = subprocess.check_output(
802 [sys.executable, "-c",
803 "import os; print(os.getpgid(os.getpid()))"],
804 start_new_session=True)
805 except OSError as e:
806 if e.errno != errno.EPERM:
807 raise
808 else:
809 parent_pgid = os.getpgid(os.getpid())
810 child_pgid = int(output)
811 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000812
813 def test_run_abort(self):
814 # returncode handles signal termination
815 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000816 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000817 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000818 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000819 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000820
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000821 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000822 # DISCLAIMER: Setting environment variables is *not* a good use
823 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000824 p = subprocess.Popen([sys.executable, "-c",
825 'import sys,os;'
826 'sys.stdout.write(os.getenv("FRUIT"))'],
827 stdout=subprocess.PIPE,
828 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000829 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000830 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000831
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000832 def test_preexec_exception(self):
833 def raise_it():
834 raise ValueError("What if two swallows carried a coconut?")
835 try:
836 p = subprocess.Popen([sys.executable, "-c", ""],
837 preexec_fn=raise_it)
838 except RuntimeError as e:
839 self.assertTrue(
840 subprocess._posixsubprocess,
841 "Expected a ValueError from the preexec_fn")
842 except ValueError as e:
843 self.assertIn("coconut", e.args[0])
844 else:
845 self.fail("Exception raised by preexec_fn did not make it "
846 "to the parent process.")
847
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000848 @unittest.skipUnless(gc, "Requires a gc module.")
849 def test_preexec_gc_module_failure(self):
850 # This tests the code that disables garbage collection if the child
851 # process will execute any Python.
852 def raise_runtime_error():
853 raise RuntimeError("this shouldn't escape")
854 enabled = gc.isenabled()
855 orig_gc_disable = gc.disable
856 orig_gc_isenabled = gc.isenabled
857 try:
858 gc.disable()
859 self.assertFalse(gc.isenabled())
860 subprocess.call([sys.executable, '-c', ''],
861 preexec_fn=lambda: None)
862 self.assertFalse(gc.isenabled(),
863 "Popen enabled gc when it shouldn't.")
864
865 gc.enable()
866 self.assertTrue(gc.isenabled())
867 subprocess.call([sys.executable, '-c', ''],
868 preexec_fn=lambda: None)
869 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
870
871 gc.disable = raise_runtime_error
872 self.assertRaises(RuntimeError, subprocess.Popen,
873 [sys.executable, '-c', ''],
874 preexec_fn=lambda: None)
875
876 del gc.isenabled # force an AttributeError
877 self.assertRaises(AttributeError, subprocess.Popen,
878 [sys.executable, '-c', ''],
879 preexec_fn=lambda: None)
880 finally:
881 gc.disable = orig_gc_disable
882 gc.isenabled = orig_gc_isenabled
883 if not enabled:
884 gc.disable()
885
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000886 def test_args_string(self):
887 # args is a string
888 fd, fname = mkstemp()
889 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000890 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000891 fobj.write("#!/bin/sh\n")
892 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
893 sys.executable)
894 os.chmod(fname, 0o700)
895 p = subprocess.Popen(fname)
896 p.wait()
897 os.remove(fname)
898 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000899
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000900 def test_invalid_args(self):
901 # invalid arguments should raise ValueError
902 self.assertRaises(ValueError, subprocess.call,
903 [sys.executable, "-c",
904 "import sys; sys.exit(47)"],
905 startupinfo=47)
906 self.assertRaises(ValueError, subprocess.call,
907 [sys.executable, "-c",
908 "import sys; sys.exit(47)"],
909 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000910
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000911 def test_shell_sequence(self):
912 # Run command through the shell (sequence)
913 newenv = os.environ.copy()
914 newenv["FRUIT"] = "apple"
915 p = subprocess.Popen(["echo $FRUIT"], shell=1,
916 stdout=subprocess.PIPE,
917 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000918 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000919 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000920
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000921 def test_shell_string(self):
922 # Run command through the shell (string)
923 newenv = os.environ.copy()
924 newenv["FRUIT"] = "apple"
925 p = subprocess.Popen("echo $FRUIT", shell=1,
926 stdout=subprocess.PIPE,
927 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000928 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000929 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000930
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000931 def test_call_string(self):
932 # call() function with string argument on UNIX
933 fd, fname = mkstemp()
934 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000935 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000936 fobj.write("#!/bin/sh\n")
937 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
938 sys.executable)
939 os.chmod(fname, 0o700)
940 rc = subprocess.call(fname)
941 os.remove(fname)
942 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000943
Stefan Krah9542cc62010-07-19 14:20:53 +0000944 def test_specific_shell(self):
945 # Issue #9265: Incorrect name passed as arg[0].
946 shells = []
947 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
948 for name in ['bash', 'ksh']:
949 sh = os.path.join(prefix, name)
950 if os.path.isfile(sh):
951 shells.append(sh)
952 if not shells: # Will probably work for any shell but csh.
953 self.skipTest("bash or ksh required for this test")
954 sh = '/bin/sh'
955 if os.path.isfile(sh) and not os.path.islink(sh):
956 # Test will fail if /bin/sh is a symlink to csh.
957 shells.append(sh)
958 for sh in shells:
959 p = subprocess.Popen("echo $0", executable=sh, shell=True,
960 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000961 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000962 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
963
Florent Xicluna4886d242010-03-08 13:27:26 +0000964 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000965 # Do not inherit file handles from the parent.
966 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000967 p = subprocess.Popen([sys.executable, "-c", """if 1:
968 import sys, time
969 sys.stdout.write('x\\n')
970 sys.stdout.flush()
971 time.sleep(30)
972 """],
973 close_fds=True,
974 stdin=subprocess.PIPE,
975 stdout=subprocess.PIPE,
976 stderr=subprocess.PIPE)
977 # Wait for the interpreter to be completely initialized before
978 # sending any signal.
979 p.stdout.read(1)
980 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000981 return p
982
983 def test_send_signal(self):
984 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000985 _, stderr = p.communicate()
986 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000987 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000988
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000989 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000990 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000991 _, stderr = p.communicate()
992 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000993 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000994
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000995 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000996 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000997 _, stderr = p.communicate()
998 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000999 self.assertEqual(p.wait(), -signal.SIGTERM)
1000
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001001 def check_close_std_fds(self, fds):
1002 # Issue #9905: test that subprocess pipes still work properly with
1003 # some standard fds closed
1004 stdin = 0
1005 newfds = []
1006 for a in fds:
1007 b = os.dup(a)
1008 newfds.append(b)
1009 if a == 0:
1010 stdin = b
1011 try:
1012 for fd in fds:
1013 os.close(fd)
1014 out, err = subprocess.Popen([sys.executable, "-c",
1015 'import sys;'
1016 'sys.stdout.write("apple");'
1017 'sys.stdout.flush();'
1018 'sys.stderr.write("orange")'],
1019 stdin=stdin,
1020 stdout=subprocess.PIPE,
1021 stderr=subprocess.PIPE).communicate()
1022 err = support.strip_python_stderr(err)
1023 self.assertEqual((out, err), (b'apple', b'orange'))
1024 finally:
1025 for b, a in zip(newfds, fds):
1026 os.dup2(b, a)
1027 for b in newfds:
1028 os.close(b)
1029
1030 def test_close_fd_0(self):
1031 self.check_close_std_fds([0])
1032
1033 def test_close_fd_1(self):
1034 self.check_close_std_fds([1])
1035
1036 def test_close_fd_2(self):
1037 self.check_close_std_fds([2])
1038
1039 def test_close_fds_0_1(self):
1040 self.check_close_std_fds([0, 1])
1041
1042 def test_close_fds_0_2(self):
1043 self.check_close_std_fds([0, 2])
1044
1045 def test_close_fds_1_2(self):
1046 self.check_close_std_fds([1, 2])
1047
1048 def test_close_fds_0_1_2(self):
1049 # Issue #10806: test that subprocess pipes still work properly with
1050 # all standard fds closed.
1051 self.check_close_std_fds([0, 1, 2])
1052
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001053 def test_remapping_std_fds(self):
1054 # open up some temporary files
1055 temps = [mkstemp() for i in range(3)]
1056 try:
1057 temp_fds = [fd for fd, fname in temps]
1058
1059 # unlink the files -- we won't need to reopen them
1060 for fd, fname in temps:
1061 os.unlink(fname)
1062
1063 # write some data to what will become stdin, and rewind
1064 os.write(temp_fds[1], b"STDIN")
1065 os.lseek(temp_fds[1], 0, 0)
1066
1067 # move the standard file descriptors out of the way
1068 saved_fds = [os.dup(fd) for fd in range(3)]
1069 try:
1070 # duplicate the file objects over the standard fd's
1071 for fd, temp_fd in enumerate(temp_fds):
1072 os.dup2(temp_fd, fd)
1073
1074 # now use those files in the "wrong" order, so that subprocess
1075 # has to rearrange them in the child
1076 p = subprocess.Popen([sys.executable, "-c",
1077 'import sys; got = sys.stdin.read();'
1078 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1079 stdin=temp_fds[1],
1080 stdout=temp_fds[2],
1081 stderr=temp_fds[0])
1082 p.wait()
1083 finally:
1084 # restore the original fd's underneath sys.stdin, etc.
1085 for std, saved in enumerate(saved_fds):
1086 os.dup2(saved, std)
1087 os.close(saved)
1088
1089 for fd in temp_fds:
1090 os.lseek(fd, 0, 0)
1091
1092 out = os.read(temp_fds[2], 1024)
1093 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1094 self.assertEqual(out, b"got STDIN")
1095 self.assertEqual(err, b"err")
1096
1097 finally:
1098 for fd in temp_fds:
1099 os.close(fd)
1100
Victor Stinner13bb71c2010-04-23 21:41:56 +00001101 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001102 def prepare():
1103 raise ValueError("surrogate:\uDCff")
1104
1105 try:
1106 subprocess.call(
1107 [sys.executable, "-c", "pass"],
1108 preexec_fn=prepare)
1109 except ValueError as err:
1110 # Pure Python implementations keeps the message
1111 self.assertIsNone(subprocess._posixsubprocess)
1112 self.assertEqual(str(err), "surrogate:\uDCff")
1113 except RuntimeError as err:
1114 # _posixsubprocess uses a default message
1115 self.assertIsNotNone(subprocess._posixsubprocess)
1116 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1117 else:
1118 self.fail("Expected ValueError or RuntimeError")
1119
Victor Stinner13bb71c2010-04-23 21:41:56 +00001120 def test_undecodable_env(self):
1121 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001122 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001123 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001124 env = os.environ.copy()
1125 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001126 # Use C locale to get ascii for the locale encoding to force
1127 # surrogate-escaping of \xFF in the child process; otherwise it can
1128 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001129 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001130 stdout = subprocess.check_output(
1131 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001132 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001133 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001134 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001135
1136 # test bytes
1137 key = key.encode("ascii", "surrogateescape")
1138 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001139 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001140 env = os.environ.copy()
1141 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001142 stdout = subprocess.check_output(
1143 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001144 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001145 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001146 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001147
Victor Stinnerb745a742010-05-18 17:17:23 +00001148 def test_bytes_program(self):
1149 abs_program = os.fsencode(sys.executable)
1150 path, program = os.path.split(sys.executable)
1151 program = os.fsencode(program)
1152
1153 # absolute bytes path
1154 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001155 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001156
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001157 # absolute bytes path as a string
1158 cmd = b"'" + abs_program + b"' -c pass"
1159 exitcode = subprocess.call(cmd, shell=True)
1160 self.assertEqual(exitcode, 0)
1161
Victor Stinnerb745a742010-05-18 17:17:23 +00001162 # bytes program, unicode PATH
1163 env = os.environ.copy()
1164 env["PATH"] = path
1165 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001166 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001167
1168 # bytes program, bytes PATH
1169 envb = os.environb.copy()
1170 envb[b"PATH"] = os.fsencode(path)
1171 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001172 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001173
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001174 def test_pipe_cloexec(self):
1175 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1176 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1177
1178 p1 = subprocess.Popen([sys.executable, sleeper],
1179 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1180 stderr=subprocess.PIPE, close_fds=False)
1181
1182 self.addCleanup(p1.communicate, b'')
1183
1184 p2 = subprocess.Popen([sys.executable, fd_status],
1185 stdout=subprocess.PIPE, close_fds=False)
1186
1187 output, error = p2.communicate()
1188 result_fds = set(map(int, output.split(b',')))
1189 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1190 p1.stderr.fileno()])
1191
1192 self.assertFalse(result_fds & unwanted_fds,
1193 "Expected no fds from %r to be open in child, "
1194 "found %r" %
1195 (unwanted_fds, result_fds & unwanted_fds))
1196
1197 def test_pipe_cloexec_real_tools(self):
1198 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1199 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1200
1201 subdata = b'zxcvbn'
1202 data = subdata * 4 + b'\n'
1203
1204 p1 = subprocess.Popen([sys.executable, qcat],
1205 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1206 close_fds=False)
1207
1208 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1209 stdin=p1.stdout, stdout=subprocess.PIPE,
1210 close_fds=False)
1211
1212 self.addCleanup(p1.wait)
1213 self.addCleanup(p2.wait)
1214 self.addCleanup(p1.terminate)
1215 self.addCleanup(p2.terminate)
1216
1217 p1.stdin.write(data)
1218 p1.stdin.close()
1219
1220 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1221
1222 self.assertTrue(readfiles, "The child hung")
1223 self.assertEqual(p2.stdout.read(), data)
1224
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001225 p1.stdout.close()
1226 p2.stdout.close()
1227
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001228 def test_close_fds(self):
1229 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1230
1231 fds = os.pipe()
1232 self.addCleanup(os.close, fds[0])
1233 self.addCleanup(os.close, fds[1])
1234
1235 open_fds = set(fds)
1236
1237 p = subprocess.Popen([sys.executable, fd_status],
1238 stdout=subprocess.PIPE, close_fds=False)
1239 output, ignored = p.communicate()
1240 remaining_fds = set(map(int, output.split(b',')))
1241
1242 self.assertEqual(remaining_fds & open_fds, open_fds,
1243 "Some fds were closed")
1244
1245 p = subprocess.Popen([sys.executable, fd_status],
1246 stdout=subprocess.PIPE, close_fds=True)
1247 output, ignored = p.communicate()
1248 remaining_fds = set(map(int, output.split(b',')))
1249
1250 self.assertFalse(remaining_fds & open_fds,
1251 "Some fds were left open")
1252 self.assertIn(1, remaining_fds, "Subprocess failed")
1253
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001254 def test_pass_fds(self):
1255 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1256
1257 open_fds = set()
1258
1259 for x in range(5):
1260 fds = os.pipe()
1261 self.addCleanup(os.close, fds[0])
1262 self.addCleanup(os.close, fds[1])
1263 open_fds.update(fds)
1264
1265 for fd in open_fds:
1266 p = subprocess.Popen([sys.executable, fd_status],
1267 stdout=subprocess.PIPE, close_fds=True,
1268 pass_fds=(fd, ))
1269 output, ignored = p.communicate()
1270
1271 remaining_fds = set(map(int, output.split(b',')))
1272 to_be_closed = open_fds - {fd}
1273
1274 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1275 self.assertFalse(remaining_fds & to_be_closed,
1276 "fd to be closed passed")
1277
1278 # pass_fds overrides close_fds with a warning.
1279 with self.assertWarns(RuntimeWarning) as context:
1280 self.assertFalse(subprocess.call(
1281 [sys.executable, "-c", "import sys; sys.exit(0)"],
1282 close_fds=False, pass_fds=(fd, )))
1283 self.assertIn('overriding close_fds', str(context.warning))
1284
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001285 def test_stdout_stdin_are_single_inout_fd(self):
1286 with io.open(os.devnull, "r+") as inout:
1287 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1288 stdout=inout, stdin=inout)
1289 p.wait()
1290
1291 def test_stdout_stderr_are_single_inout_fd(self):
1292 with io.open(os.devnull, "r+") as inout:
1293 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1294 stdout=inout, stderr=inout)
1295 p.wait()
1296
1297 def test_stderr_stdin_are_single_inout_fd(self):
1298 with io.open(os.devnull, "r+") as inout:
1299 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1300 stderr=inout, stdin=inout)
1301 p.wait()
1302
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001303 def test_wait_when_sigchild_ignored(self):
1304 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1305 sigchild_ignore = support.findfile("sigchild_ignore.py",
1306 subdir="subprocessdata")
1307 p = subprocess.Popen([sys.executable, sigchild_ignore],
1308 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1309 stdout, stderr = p.communicate()
1310 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001311 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001312 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001313
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001314
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001315@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001316class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001317
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001318 def test_startupinfo(self):
1319 # startupinfo argument
1320 # We uses hardcoded constants, because we do not want to
1321 # depend on win32all.
1322 STARTF_USESHOWWINDOW = 1
1323 SW_MAXIMIZE = 3
1324 startupinfo = subprocess.STARTUPINFO()
1325 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1326 startupinfo.wShowWindow = SW_MAXIMIZE
1327 # Since Python is a console process, it won't be affected
1328 # by wShowWindow, but the argument should be silently
1329 # ignored
1330 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001331 startupinfo=startupinfo)
1332
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001333 def test_creationflags(self):
1334 # creationflags argument
1335 CREATE_NEW_CONSOLE = 16
1336 sys.stderr.write(" a DOS box should flash briefly ...\n")
1337 subprocess.call(sys.executable +
1338 ' -c "import time; time.sleep(0.25)"',
1339 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001340
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001341 def test_invalid_args(self):
1342 # invalid arguments should raise ValueError
1343 self.assertRaises(ValueError, subprocess.call,
1344 [sys.executable, "-c",
1345 "import sys; sys.exit(47)"],
1346 preexec_fn=lambda: 1)
1347 self.assertRaises(ValueError, subprocess.call,
1348 [sys.executable, "-c",
1349 "import sys; sys.exit(47)"],
1350 stdout=subprocess.PIPE,
1351 close_fds=True)
1352
1353 def test_close_fds(self):
1354 # close file descriptors
1355 rc = subprocess.call([sys.executable, "-c",
1356 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001357 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001358 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001359
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001360 def test_shell_sequence(self):
1361 # Run command through the shell (sequence)
1362 newenv = os.environ.copy()
1363 newenv["FRUIT"] = "physalis"
1364 p = subprocess.Popen(["set"], shell=1,
1365 stdout=subprocess.PIPE,
1366 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001367 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001368 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001369
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001370 def test_shell_string(self):
1371 # Run command through the shell (string)
1372 newenv = os.environ.copy()
1373 newenv["FRUIT"] = "physalis"
1374 p = subprocess.Popen("set", shell=1,
1375 stdout=subprocess.PIPE,
1376 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001377 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001378 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001379
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001380 def test_call_string(self):
1381 # call() function with string argument on Windows
1382 rc = subprocess.call(sys.executable +
1383 ' -c "import sys; sys.exit(47)"')
1384 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001385
Florent Xicluna4886d242010-03-08 13:27:26 +00001386 def _kill_process(self, method, *args):
1387 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001388 p = subprocess.Popen([sys.executable, "-c", """if 1:
1389 import sys, time
1390 sys.stdout.write('x\\n')
1391 sys.stdout.flush()
1392 time.sleep(30)
1393 """],
1394 stdin=subprocess.PIPE,
1395 stdout=subprocess.PIPE,
1396 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001397 self.addCleanup(p.stdout.close)
1398 self.addCleanup(p.stderr.close)
1399 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001400 # Wait for the interpreter to be completely initialized before
1401 # sending any signal.
1402 p.stdout.read(1)
1403 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001404 _, stderr = p.communicate()
1405 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001406 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001407 self.assertNotEqual(returncode, 0)
1408
1409 def test_send_signal(self):
1410 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001411
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001412 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001413 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001414
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001415 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001416 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001417
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001418
Brett Cannona23810f2008-05-26 19:04:21 +00001419# The module says:
1420# "NB This only works (and is only relevant) for UNIX."
1421#
1422# Actually, getoutput should work on any platform with an os.popen, but
1423# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001424@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001425class CommandTests(unittest.TestCase):
1426 def test_getoutput(self):
1427 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1428 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1429 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001430
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001431 # we use mkdtemp in the next line to create an empty directory
1432 # under our exclusive control; from that, we can invent a pathname
1433 # that we _know_ won't exist. This is guaranteed to fail.
1434 dir = None
1435 try:
1436 dir = tempfile.mkdtemp()
1437 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001438
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001439 status, output = subprocess.getstatusoutput('cat ' + name)
1440 self.assertNotEqual(status, 0)
1441 finally:
1442 if dir is not None:
1443 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001444
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001445
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001446@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1447 "poll system call not supported")
1448class ProcessTestCaseNoPoll(ProcessTestCase):
1449 def setUp(self):
1450 subprocess._has_poll = False
1451 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001452
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001453 def tearDown(self):
1454 subprocess._has_poll = True
1455 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001456
1457
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001458@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1459 "_posixsubprocess extension module not found.")
1460class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
1461 def setUp(self):
1462 subprocess._posixsubprocess = None
1463 ProcessTestCase.setUp(self)
1464 POSIXProcessTestCase.setUp(self)
1465
1466 def tearDown(self):
1467 subprocess._posixsubprocess = sys.modules['_posixsubprocess']
1468 POSIXProcessTestCase.tearDown(self)
1469 ProcessTestCase.tearDown(self)
1470
1471
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001472class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001473 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001474 def test_eintr_retry_call(self):
1475 record_calls = []
1476 def fake_os_func(*args):
1477 record_calls.append(args)
1478 if len(record_calls) == 2:
1479 raise OSError(errno.EINTR, "fake interrupted system call")
1480 return tuple(reversed(args))
1481
1482 self.assertEqual((999, 256),
1483 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1484 self.assertEqual([(256, 999)], record_calls)
1485 # This time there will be an EINTR so it will loop once.
1486 self.assertEqual((666,),
1487 subprocess._eintr_retry_call(fake_os_func, 666))
1488 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1489
1490
Tim Golden126c2962010-08-11 14:20:40 +00001491@unittest.skipUnless(mswindows, "Windows-specific tests")
1492class CommandsWithSpaces (BaseTestCase):
1493
1494 def setUp(self):
1495 super().setUp()
1496 f, fname = mkstemp(".py", "te st")
1497 self.fname = fname.lower ()
1498 os.write(f, b"import sys;"
1499 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1500 )
1501 os.close(f)
1502
1503 def tearDown(self):
1504 os.remove(self.fname)
1505 super().tearDown()
1506
1507 def with_spaces(self, *args, **kwargs):
1508 kwargs['stdout'] = subprocess.PIPE
1509 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001510 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001511 self.assertEqual(
1512 p.stdout.read ().decode("mbcs"),
1513 "2 [%r, 'ab cd']" % self.fname
1514 )
1515
1516 def test_shell_string_with_spaces(self):
1517 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001518 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1519 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001520
1521 def test_shell_sequence_with_spaces(self):
1522 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001523 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001524
1525 def test_noshell_string_with_spaces(self):
1526 # call() function with string argument with spaces on Windows
1527 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1528 "ab cd"))
1529
1530 def test_noshell_sequence_with_spaces(self):
1531 # call() function with sequence argument with spaces on Windows
1532 self.with_spaces([sys.executable, self.fname, "ab cd"])
1533
Brian Curtin79cdb662010-12-03 02:46:02 +00001534
1535class ContextManagerTests(ProcessTestCase):
1536
1537 def test_pipe(self):
1538 with subprocess.Popen([sys.executable, "-c",
1539 "import sys;"
1540 "sys.stdout.write('stdout');"
1541 "sys.stderr.write('stderr');"],
1542 stdout=subprocess.PIPE,
1543 stderr=subprocess.PIPE) as proc:
1544 self.assertEqual(proc.stdout.read(), b"stdout")
1545 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1546
1547 self.assertTrue(proc.stdout.closed)
1548 self.assertTrue(proc.stderr.closed)
1549
1550 def test_returncode(self):
1551 with subprocess.Popen([sys.executable, "-c",
1552 "import sys; sys.exit(100)"]) as proc:
1553 proc.wait()
1554 self.assertEqual(proc.returncode, 100)
1555
1556 def test_communicate_stdin(self):
1557 with subprocess.Popen([sys.executable, "-c",
1558 "import sys;"
1559 "sys.exit(sys.stdin.read() == 'context')"],
1560 stdin=subprocess.PIPE) as proc:
1561 proc.communicate(b"context")
1562 self.assertEqual(proc.returncode, 1)
1563
1564 def test_invalid_args(self):
1565 with self.assertRaises(EnvironmentError) as c:
1566 with subprocess.Popen(['nonexisting_i_hope'],
1567 stdout=subprocess.PIPE,
1568 stderr=subprocess.PIPE) as proc:
1569 pass
1570
1571 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1572 raise c.exception
1573
1574
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001575def test_main():
1576 unit_tests = (ProcessTestCase,
1577 POSIXProcessTestCase,
1578 Win32ProcessTestCase,
1579 ProcessTestCasePOSIXPurePython,
1580 CommandTests,
1581 ProcessTestCaseNoPoll,
1582 HelperFunctionTests,
1583 CommandsWithSpaces,
1584 ContextManagerTests)
1585
1586 support.run_unittest(*unit_tests)
1587 support.reap_children()
1588
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001589if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001590 unittest.main()