blob: 5e6c40f033dad157fffe85472967fa59b218b75d [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
6import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00007import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008import tempfile
9import time
Tim Peters3761e8d2004-10-13 04:07:12 +000010import re
Ezio Melotti184bdfb2010-02-18 09:37:05 +000011import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000012import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000013import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040014import shutil
Gregory P. Smith32ec9da2010-03-19 16:53:08 +000015try:
16 import gc
17except ImportError:
18 gc = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000019
20mswindows = (sys.platform == "win32")
21
22#
23# Depends on the following external programs: Python
24#
25
26if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000027 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
28 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000029else:
30 SETBINARY = ''
31
Florent Xiclunab1e94e82010-02-27 22:12:37 +000032
33try:
34 mkstemp = tempfile.mkstemp
35except AttributeError:
36 # tempfile.mkstemp is not available
37 def mkstemp():
38 """Replacement for mkstemp, calling mktemp."""
39 fname = tempfile.mktemp()
40 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
41
Tim Peters3761e8d2004-10-13 04:07:12 +000042
Florent Xiclunac049d872010-03-27 22:47:23 +000043class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000044 def setUp(self):
45 # Try to minimize the number of children we have so this test
46 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000047 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000048
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000049 def tearDown(self):
50 for inst in subprocess._active:
51 inst.wait()
52 subprocess._cleanup()
53 self.assertFalse(subprocess._active, "subprocess._active not empty")
54
Florent Xiclunab1e94e82010-02-27 22:12:37 +000055 def assertStderrEqual(self, stderr, expected, msg=None):
56 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
57 # shutdown time. That frustrates tests trying to check stderr produced
58 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000059 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040060 # strip_python_stderr also strips whitespace, so we do too.
61 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000062 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000063
Florent Xiclunac049d872010-03-27 22:47:23 +000064
65class ProcessTestCase(BaseTestCase):
66
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000067 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000068 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000069 rc = subprocess.call([sys.executable, "-c",
70 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000071 self.assertEqual(rc, 47)
72
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040073 def test_call_timeout(self):
74 # call() function with timeout argument; we want to test that the child
75 # process gets killed when the timeout expires. If the child isn't
76 # killed, this call will deadlock since subprocess.call waits for the
77 # child.
78 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
79 [sys.executable, "-c", "while True: pass"],
80 timeout=0.1)
81
Peter Astrand454f7672005-01-01 09:36:35 +000082 def test_check_call_zero(self):
83 # check_call() function with zero return code
84 rc = subprocess.check_call([sys.executable, "-c",
85 "import sys; sys.exit(0)"])
86 self.assertEqual(rc, 0)
87
88 def test_check_call_nonzero(self):
89 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000090 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000091 subprocess.check_call([sys.executable, "-c",
92 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000093 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000094
Georg Brandlf9734072008-12-07 15:30:06 +000095 def test_check_output(self):
96 # check_output() function with zero return code
97 output = subprocess.check_output(
98 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000099 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000100
101 def test_check_output_nonzero(self):
102 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000103 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000104 subprocess.check_output(
105 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000106 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000107
108 def test_check_output_stderr(self):
109 # check_output() function stderr redirected to stdout
110 output = subprocess.check_output(
111 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
112 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000113 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000114
115 def test_check_output_stdout_arg(self):
116 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000117 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000118 output = subprocess.check_output(
119 [sys.executable, "-c", "print('will not be run')"],
120 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000121 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000122 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000123
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400124 def test_check_output_timeout(self):
125 # check_output() function with timeout arg
126 with self.assertRaises(subprocess.TimeoutExpired) as c:
127 output = subprocess.check_output(
128 [sys.executable, "-c",
129 "import sys; sys.stdout.write('BDFL')\n"
130 "sys.stdout.flush()\n"
131 "while True: pass"],
Reid Kleckner80b92d12011-03-14 13:34:12 -0400132 timeout=1.5)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400133 self.fail("Expected TimeoutExpired.")
134 self.assertEqual(c.exception.output, b'BDFL')
135
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000136 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000137 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000138 newenv = os.environ.copy()
139 newenv["FRUIT"] = "banana"
140 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000141 'import sys, os;'
142 'sys.exit(os.getenv("FRUIT")=="banana")'],
143 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000144 self.assertEqual(rc, 1)
145
146 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000147 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000148 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000149 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000150 self.addCleanup(p.stdout.close)
151 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000152 p.wait()
153 self.assertEqual(p.stdin, None)
154
155 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000156 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000157 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000158 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000159 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000160 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000161 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000162 self.addCleanup(p.stdin.close)
163 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000164 p.wait()
165 self.assertEqual(p.stdout, None)
166
167 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000168 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000169 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000170 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000171 self.addCleanup(p.stdout.close)
172 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000173 p.wait()
174 self.assertEqual(p.stderr, None)
175
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000176 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000177 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000178 p = subprocess.Popen(["somethingyoudonthave", "-c",
179 "import sys; sys.exit(47)"],
180 executable=sys.executable, cwd=python_dir)
181 p.wait()
182 self.assertEqual(p.returncode, 47)
183
184 @unittest.skipIf(sysconfig.is_python_build(),
185 "need an installed Python. See #7774")
186 def test_executable_without_cwd(self):
187 # For a normal installation, it should work without 'cwd'
188 # argument. For test runs in the build directory, see #7774.
189 p = subprocess.Popen(["somethingyoudonthave", "-c",
190 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000191 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000192 p.wait()
193 self.assertEqual(p.returncode, 47)
194
195 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000196 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000197 p = subprocess.Popen([sys.executable, "-c",
198 'import sys; sys.exit(sys.stdin.read() == "pear")'],
199 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000200 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000201 p.stdin.close()
202 p.wait()
203 self.assertEqual(p.returncode, 1)
204
205 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000206 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000207 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000208 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000209 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000210 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000211 os.lseek(d, 0, 0)
212 p = subprocess.Popen([sys.executable, "-c",
213 'import sys; sys.exit(sys.stdin.read() == "pear")'],
214 stdin=d)
215 p.wait()
216 self.assertEqual(p.returncode, 1)
217
218 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000219 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000220 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000221 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000222 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223 tf.seek(0)
224 p = subprocess.Popen([sys.executable, "-c",
225 'import sys; sys.exit(sys.stdin.read() == "pear")'],
226 stdin=tf)
227 p.wait()
228 self.assertEqual(p.returncode, 1)
229
230 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000231 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000232 p = subprocess.Popen([sys.executable, "-c",
233 'import sys; sys.stdout.write("orange")'],
234 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000235 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000236 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000237
238 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000239 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000240 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000241 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 d = tf.fileno()
243 p = subprocess.Popen([sys.executable, "-c",
244 'import sys; sys.stdout.write("orange")'],
245 stdout=d)
246 p.wait()
247 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000248 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000249
250 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000251 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000252 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000253 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000254 p = subprocess.Popen([sys.executable, "-c",
255 'import sys; sys.stdout.write("orange")'],
256 stdout=tf)
257 p.wait()
258 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000259 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000260
261 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000262 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263 p = subprocess.Popen([sys.executable, "-c",
264 'import sys; sys.stderr.write("strawberry")'],
265 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000266 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000267 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268
269 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000270 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000271 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000272 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000273 d = tf.fileno()
274 p = subprocess.Popen([sys.executable, "-c",
275 'import sys; sys.stderr.write("strawberry")'],
276 stderr=d)
277 p.wait()
278 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000279 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000280
281 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000282 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000283 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000284 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285 p = subprocess.Popen([sys.executable, "-c",
286 'import sys; sys.stderr.write("strawberry")'],
287 stderr=tf)
288 p.wait()
289 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000290 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291
292 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000293 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000295 'import sys;'
296 'sys.stdout.write("apple");'
297 'sys.stdout.flush();'
298 'sys.stderr.write("orange")'],
299 stdout=subprocess.PIPE,
300 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000301 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000302 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000303
304 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000305 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000307 self.addCleanup(tf.close)
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=tf,
314 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000315 p.wait()
316 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000317 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318
Thomas Wouters89f507f2006-12-13 04:49:30 +0000319 def test_stdout_filedes_of_stdout(self):
320 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000321 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000323 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000324
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000325 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000326 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000327 # We cannot use os.path.realpath to canonicalize the path,
328 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
329 cwd = os.getcwd()
330 os.chdir(tmpdir)
331 tmpdir = os.getcwd()
332 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000333 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000334 'import sys,os;'
335 'sys.stdout.write(os.getcwd())'],
336 stdout=subprocess.PIPE,
337 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000338 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000339 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000340 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
341 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000342
343 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000344 newenv = os.environ.copy()
345 newenv["FRUIT"] = "orange"
346 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000347 'import sys,os;'
348 'sys.stdout.write(os.getenv("FRUIT"))'],
349 stdout=subprocess.PIPE,
350 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000351 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000352 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000353
Peter Astrandcbac93c2005-03-03 20:24:28 +0000354 def test_communicate_stdin(self):
355 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000356 'import sys;'
357 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000358 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000359 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000360 self.assertEqual(p.returncode, 1)
361
362 def test_communicate_stdout(self):
363 p = subprocess.Popen([sys.executable, "-c",
364 'import sys; sys.stdout.write("pineapple")'],
365 stdout=subprocess.PIPE)
366 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000367 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000368 self.assertEqual(stderr, None)
369
370 def test_communicate_stderr(self):
371 p = subprocess.Popen([sys.executable, "-c",
372 'import sys; sys.stderr.write("pineapple")'],
373 stderr=subprocess.PIPE)
374 (stdout, stderr) = p.communicate()
375 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000376 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000377
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000378 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000379 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000380 'import sys,os;'
381 'sys.stderr.write("pineapple");'
382 'sys.stdout.write(sys.stdin.read())'],
383 stdin=subprocess.PIPE,
384 stdout=subprocess.PIPE,
385 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000386 self.addCleanup(p.stdout.close)
387 self.addCleanup(p.stderr.close)
388 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000389 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000390 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000391 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000392
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400393 def test_communicate_timeout(self):
394 p = subprocess.Popen([sys.executable, "-c",
395 'import sys,os,time;'
396 'sys.stderr.write("pineapple\\n");'
397 'time.sleep(1);'
398 'sys.stderr.write("pear\\n");'
399 'sys.stdout.write(sys.stdin.read())'],
400 universal_newlines=True,
401 stdin=subprocess.PIPE,
402 stdout=subprocess.PIPE,
403 stderr=subprocess.PIPE)
404 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
405 timeout=0.3)
406 # Make sure we can keep waiting for it, and that we get the whole output
407 # after it completes.
408 (stdout, stderr) = p.communicate()
409 self.assertEqual(stdout, "banana")
410 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
411
412 def test_communicate_timeout_large_ouput(self):
413 # Test a expring timeout while the child is outputting lots of data.
414 p = subprocess.Popen([sys.executable, "-c",
415 'import sys,os,time;'
416 'sys.stdout.write("a" * (64 * 1024));'
417 'time.sleep(0.2);'
418 'sys.stdout.write("a" * (64 * 1024));'
419 'time.sleep(0.2);'
420 'sys.stdout.write("a" * (64 * 1024));'
421 'time.sleep(0.2);'
422 'sys.stdout.write("a" * (64 * 1024));'],
423 stdout=subprocess.PIPE)
424 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
425 (stdout, _) = p.communicate()
426 self.assertEqual(len(stdout), 4 * 64 * 1024)
427
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000428 # Test for the fd leak reported in http://bugs.python.org/issue2791.
429 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000430 for stdin_pipe in (False, True):
431 for stdout_pipe in (False, True):
432 for stderr_pipe in (False, True):
433 options = {}
434 if stdin_pipe:
435 options['stdin'] = subprocess.PIPE
436 if stdout_pipe:
437 options['stdout'] = subprocess.PIPE
438 if stderr_pipe:
439 options['stderr'] = subprocess.PIPE
440 if not options:
441 continue
442 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
443 p.communicate()
444 if p.stdin is not None:
445 self.assertTrue(p.stdin.closed)
446 if p.stdout is not None:
447 self.assertTrue(p.stdout.closed)
448 if p.stderr is not None:
449 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000450
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000451 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000452 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000453 p = subprocess.Popen([sys.executable, "-c",
454 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000455 (stdout, stderr) = p.communicate()
456 self.assertEqual(stdout, None)
457 self.assertEqual(stderr, None)
458
459 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000460 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000461 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000462 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463 x, y = os.pipe()
464 if mswindows:
465 pipe_buf = 512
466 else:
467 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
468 os.close(x)
469 os.close(y)
470 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000471 'import sys,os;'
472 'sys.stdout.write(sys.stdin.read(47));'
473 'sys.stderr.write("xyz"*%d);'
474 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
475 stdin=subprocess.PIPE,
476 stdout=subprocess.PIPE,
477 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000478 self.addCleanup(p.stdout.close)
479 self.addCleanup(p.stderr.close)
480 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000481 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482 (stdout, stderr) = p.communicate(string_to_write)
483 self.assertEqual(stdout, string_to_write)
484
485 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000486 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000487 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000488 'import sys,os;'
489 'sys.stdout.write(sys.stdin.read())'],
490 stdin=subprocess.PIPE,
491 stdout=subprocess.PIPE,
492 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000493 self.addCleanup(p.stdout.close)
494 self.addCleanup(p.stderr.close)
495 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000496 p.stdin.write(b"banana")
497 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000498 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000499 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000500
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000503 'import sys,os;' + SETBINARY +
504 'sys.stdout.write("line1\\n");'
505 'sys.stdout.flush();'
506 'sys.stdout.write("line2\\n");'
507 'sys.stdout.flush();'
508 'sys.stdout.write("line3\\r\\n");'
509 'sys.stdout.flush();'
510 'sys.stdout.write("line4\\r");'
511 'sys.stdout.flush();'
512 'sys.stdout.write("\\nline5");'
513 'sys.stdout.flush();'
514 'sys.stdout.write("\\nline6");'],
515 stdout=subprocess.PIPE,
516 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000517 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000519 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520
521 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000522 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000524 'import sys,os;' + SETBINARY +
525 'sys.stdout.write("line1\\n");'
526 'sys.stdout.flush();'
527 'sys.stdout.write("line2\\n");'
528 'sys.stdout.flush();'
529 'sys.stdout.write("line3\\r\\n");'
530 'sys.stdout.flush();'
531 'sys.stdout.write("line4\\r");'
532 'sys.stdout.flush();'
533 'sys.stdout.write("\\nline5");'
534 'sys.stdout.flush();'
535 'sys.stdout.write("\\nline6");'],
536 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
537 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000538 self.addCleanup(p.stdout.close)
539 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000541 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542
543 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000544 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000545 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000546 max_handles = 1026 # too much for most UNIX systems
547 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000548 max_handles = 2050 # too much for (at least some) Windows setups
549 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400550 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000551 try:
552 for i in range(max_handles):
553 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400554 tmpfile = os.path.join(tmpdir, support.TESTFN)
555 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000556 except OSError as e:
557 if e.errno != errno.EMFILE:
558 raise
559 break
560 else:
561 self.skipTest("failed to reach the file descriptor limit "
562 "(tried %d)" % max_handles)
563 # Close a couple of them (should be enough for a subprocess)
564 for i in range(10):
565 os.close(handles.pop())
566 # Loop creating some subprocesses. If one of them leaks some fds,
567 # the next loop iteration will fail by reaching the max fd limit.
568 for i in range(15):
569 p = subprocess.Popen([sys.executable, "-c",
570 "import sys;"
571 "sys.stdout.write(sys.stdin.read())"],
572 stdin=subprocess.PIPE,
573 stdout=subprocess.PIPE,
574 stderr=subprocess.PIPE)
575 data = p.communicate(b"lime")[0]
576 self.assertEqual(data, b"lime")
577 finally:
578 for h in handles:
579 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400580 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000581
582 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000583 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
584 '"a b c" d e')
585 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
586 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000587 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
588 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
590 'a\\\\\\b "de fg" h')
591 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
592 'a\\\\\\"b c d')
593 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
594 '"a\\\\b c" d e')
595 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
596 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000597 self.assertEqual(subprocess.list2cmdline(['ab', '']),
598 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000599
600
601 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000602 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000603 "-c", "import time; time.sleep(1)"])
604 count = 0
605 while p.poll() is None:
606 time.sleep(0.1)
607 count += 1
608 # We expect that the poll loop probably went around about 10 times,
609 # but, based on system scheduling we can't control, it's possible
610 # poll() never returned None. It "should be" very rare that it
611 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000612 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000613 # Subsequent invocations should just return the returncode
614 self.assertEqual(p.poll(), 0)
615
616
617 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000618 p = subprocess.Popen([sys.executable,
619 "-c", "import time; time.sleep(2)"])
620 self.assertEqual(p.wait(), 0)
621 # Subsequent invocations should just return the returncode
622 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000623
Peter Astrand738131d2004-11-30 21:04:45 +0000624
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400625 def test_wait_timeout(self):
626 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400627 "-c", "import time; time.sleep(0.1)"])
628 self.assertRaises(subprocess.TimeoutExpired, p.wait, timeout=0.01)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400629 self.assertEqual(p.wait(timeout=2), 0)
630
631
Peter Astrand738131d2004-11-30 21:04:45 +0000632 def test_invalid_bufsize(self):
633 # an invalid type of the bufsize argument should raise
634 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000635 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000636 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000637
Guido van Rossum46a05a72007-06-07 21:56:45 +0000638 def test_bufsize_is_none(self):
639 # bufsize=None should be the same as bufsize=0.
640 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
641 self.assertEqual(p.wait(), 0)
642 # Again with keyword arg
643 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
644 self.assertEqual(p.wait(), 0)
645
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000646 def test_leaking_fds_on_error(self):
647 # see bug #5179: Popen leaks file descriptors to PIPEs if
648 # the child fails to execute; this will eventually exhaust
649 # the maximum number of open fds. 1024 seems a very common
650 # value for that limit, but Windows has 2048, so we loop
651 # 1024 times (each call leaked two fds).
652 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000653 # Windows raises IOError. Others raise OSError.
654 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000655 subprocess.Popen(['nonexisting_i_hope'],
656 stdout=subprocess.PIPE,
657 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400658 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400659 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000660 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000661
Victor Stinnerb3693582010-05-21 20:13:12 +0000662 def test_issue8780(self):
663 # Ensure that stdout is inherited from the parent
664 # if stdout=PIPE is not used
665 code = ';'.join((
666 'import subprocess, sys',
667 'retcode = subprocess.call('
668 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
669 'assert retcode == 0'))
670 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000671 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000672
Tim Goldenaf5ac392010-08-06 13:03:56 +0000673 def test_handles_closed_on_exception(self):
674 # If CreateProcess exits with an error, ensure the
675 # duplicate output handles are released
676 ifhandle, ifname = mkstemp()
677 ofhandle, ofname = mkstemp()
678 efhandle, efname = mkstemp()
679 try:
680 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
681 stderr=efhandle)
682 except OSError:
683 os.close(ifhandle)
684 os.remove(ifname)
685 os.close(ofhandle)
686 os.remove(ofname)
687 os.close(efhandle)
688 os.remove(efname)
689 self.assertFalse(os.path.exists(ifname))
690 self.assertFalse(os.path.exists(ofname))
691 self.assertFalse(os.path.exists(efname))
692
Tim Peterse718f612004-10-12 21:51:32 +0000693
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000694# context manager
695class _SuppressCoreFiles(object):
696 """Try to prevent core files from being created."""
697 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000698
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000699 def __enter__(self):
700 """Try to save previous ulimit, then set it to (0, 0)."""
701 try:
702 import resource
703 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
704 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
705 except (ImportError, ValueError, resource.error):
706 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000707
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000708 if sys.platform == 'darwin':
709 # Check if the 'Crash Reporter' on OSX was configured
710 # in 'Developer' mode and warn that it will get triggered
711 # when it is.
712 #
713 # This assumes that this context manager is used in tests
714 # that might trigger the next manager.
715 value = subprocess.Popen(['/usr/bin/defaults', 'read',
716 'com.apple.CrashReporter', 'DialogType'],
717 stdout=subprocess.PIPE).communicate()[0]
718 if value.strip() == b'developer':
719 print("this tests triggers the Crash Reporter, "
720 "that is intentional", end='')
721 sys.stdout.flush()
722
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000723 def __exit__(self, *args):
724 """Return core file behavior to default."""
725 if self.old_limit is None:
726 return
727 try:
728 import resource
729 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
730 except (ImportError, ValueError, resource.error):
731 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000732
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000733
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000734@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000735class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000736
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000737 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000738 nonexistent_dir = "/_this/pa.th/does/not/exist"
739 try:
740 os.chdir(nonexistent_dir)
741 except OSError as e:
742 # This avoids hard coding the errno value or the OS perror()
743 # string and instead capture the exception that we want to see
744 # below for comparison.
745 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000746 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000747 else:
748 self.fail("chdir to nonexistant directory %s succeeded." %
749 nonexistent_dir)
750
751 # Error in the child re-raised in the parent.
752 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000753 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000754 cwd=nonexistent_dir)
755 except OSError as e:
756 # Test that the child process chdir failure actually makes
757 # it up to the parent process as the correct exception.
758 self.assertEqual(desired_exception.errno, e.errno)
759 self.assertEqual(desired_exception.strerror, e.strerror)
760 else:
761 self.fail("Expected OSError: %s" % desired_exception)
762
763 def test_restore_signals(self):
764 # Code coverage for both values of restore_signals to make sure it
765 # at least does not blow up.
766 # A test for behavior would be complex. Contributions welcome.
767 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
768 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
769
770 def test_start_new_session(self):
771 # For code coverage of calling setsid(). We don't care if we get an
772 # EPERM error from it depending on the test execution environment, that
773 # still indicates that it was called.
774 try:
775 output = subprocess.check_output(
776 [sys.executable, "-c",
777 "import os; print(os.getpgid(os.getpid()))"],
778 start_new_session=True)
779 except OSError as e:
780 if e.errno != errno.EPERM:
781 raise
782 else:
783 parent_pgid = os.getpgid(os.getpid())
784 child_pgid = int(output)
785 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000786
787 def test_run_abort(self):
788 # returncode handles signal termination
789 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000790 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000791 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000792 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000793 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000794
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000795 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000796 # DISCLAIMER: Setting environment variables is *not* a good use
797 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000798 p = subprocess.Popen([sys.executable, "-c",
799 'import sys,os;'
800 'sys.stdout.write(os.getenv("FRUIT"))'],
801 stdout=subprocess.PIPE,
802 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000803 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000804 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000805
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000806 def test_preexec_exception(self):
807 def raise_it():
808 raise ValueError("What if two swallows carried a coconut?")
809 try:
810 p = subprocess.Popen([sys.executable, "-c", ""],
811 preexec_fn=raise_it)
812 except RuntimeError as e:
813 self.assertTrue(
814 subprocess._posixsubprocess,
815 "Expected a ValueError from the preexec_fn")
816 except ValueError as e:
817 self.assertIn("coconut", e.args[0])
818 else:
819 self.fail("Exception raised by preexec_fn did not make it "
820 "to the parent process.")
821
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000822 @unittest.skipUnless(gc, "Requires a gc module.")
823 def test_preexec_gc_module_failure(self):
824 # This tests the code that disables garbage collection if the child
825 # process will execute any Python.
826 def raise_runtime_error():
827 raise RuntimeError("this shouldn't escape")
828 enabled = gc.isenabled()
829 orig_gc_disable = gc.disable
830 orig_gc_isenabled = gc.isenabled
831 try:
832 gc.disable()
833 self.assertFalse(gc.isenabled())
834 subprocess.call([sys.executable, '-c', ''],
835 preexec_fn=lambda: None)
836 self.assertFalse(gc.isenabled(),
837 "Popen enabled gc when it shouldn't.")
838
839 gc.enable()
840 self.assertTrue(gc.isenabled())
841 subprocess.call([sys.executable, '-c', ''],
842 preexec_fn=lambda: None)
843 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
844
845 gc.disable = raise_runtime_error
846 self.assertRaises(RuntimeError, subprocess.Popen,
847 [sys.executable, '-c', ''],
848 preexec_fn=lambda: None)
849
850 del gc.isenabled # force an AttributeError
851 self.assertRaises(AttributeError, subprocess.Popen,
852 [sys.executable, '-c', ''],
853 preexec_fn=lambda: None)
854 finally:
855 gc.disable = orig_gc_disable
856 gc.isenabled = orig_gc_isenabled
857 if not enabled:
858 gc.disable()
859
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000860 def test_args_string(self):
861 # args is a string
862 fd, fname = mkstemp()
863 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000864 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000865 fobj.write("#!/bin/sh\n")
866 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
867 sys.executable)
868 os.chmod(fname, 0o700)
869 p = subprocess.Popen(fname)
870 p.wait()
871 os.remove(fname)
872 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000873
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000874 def test_invalid_args(self):
875 # invalid arguments should raise ValueError
876 self.assertRaises(ValueError, subprocess.call,
877 [sys.executable, "-c",
878 "import sys; sys.exit(47)"],
879 startupinfo=47)
880 self.assertRaises(ValueError, subprocess.call,
881 [sys.executable, "-c",
882 "import sys; sys.exit(47)"],
883 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000884
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000885 def test_shell_sequence(self):
886 # Run command through the shell (sequence)
887 newenv = os.environ.copy()
888 newenv["FRUIT"] = "apple"
889 p = subprocess.Popen(["echo $FRUIT"], shell=1,
890 stdout=subprocess.PIPE,
891 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000892 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000893 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000894
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000895 def test_shell_string(self):
896 # Run command through the shell (string)
897 newenv = os.environ.copy()
898 newenv["FRUIT"] = "apple"
899 p = subprocess.Popen("echo $FRUIT", shell=1,
900 stdout=subprocess.PIPE,
901 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000902 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000903 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000904
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000905 def test_call_string(self):
906 # call() function with string argument on UNIX
907 fd, fname = mkstemp()
908 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000909 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000910 fobj.write("#!/bin/sh\n")
911 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
912 sys.executable)
913 os.chmod(fname, 0o700)
914 rc = subprocess.call(fname)
915 os.remove(fname)
916 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000917
Stefan Krah9542cc62010-07-19 14:20:53 +0000918 def test_specific_shell(self):
919 # Issue #9265: Incorrect name passed as arg[0].
920 shells = []
921 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
922 for name in ['bash', 'ksh']:
923 sh = os.path.join(prefix, name)
924 if os.path.isfile(sh):
925 shells.append(sh)
926 if not shells: # Will probably work for any shell but csh.
927 self.skipTest("bash or ksh required for this test")
928 sh = '/bin/sh'
929 if os.path.isfile(sh) and not os.path.islink(sh):
930 # Test will fail if /bin/sh is a symlink to csh.
931 shells.append(sh)
932 for sh in shells:
933 p = subprocess.Popen("echo $0", executable=sh, shell=True,
934 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000935 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000936 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
937
Florent Xicluna4886d242010-03-08 13:27:26 +0000938 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000939 # Do not inherit file handles from the parent.
940 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000941 p = subprocess.Popen([sys.executable, "-c", """if 1:
942 import sys, time
943 sys.stdout.write('x\\n')
944 sys.stdout.flush()
945 time.sleep(30)
946 """],
947 close_fds=True,
948 stdin=subprocess.PIPE,
949 stdout=subprocess.PIPE,
950 stderr=subprocess.PIPE)
951 # Wait for the interpreter to be completely initialized before
952 # sending any signal.
953 p.stdout.read(1)
954 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000955 return p
956
957 def test_send_signal(self):
958 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000959 _, stderr = p.communicate()
960 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000961 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000962
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000963 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000964 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000965 _, stderr = p.communicate()
966 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000967 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000968
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000969 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000970 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000971 _, stderr = p.communicate()
972 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000973 self.assertEqual(p.wait(), -signal.SIGTERM)
974
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000975 def check_close_std_fds(self, fds):
976 # Issue #9905: test that subprocess pipes still work properly with
977 # some standard fds closed
978 stdin = 0
979 newfds = []
980 for a in fds:
981 b = os.dup(a)
982 newfds.append(b)
983 if a == 0:
984 stdin = b
985 try:
986 for fd in fds:
987 os.close(fd)
988 out, err = subprocess.Popen([sys.executable, "-c",
989 'import sys;'
990 'sys.stdout.write("apple");'
991 'sys.stdout.flush();'
992 'sys.stderr.write("orange")'],
993 stdin=stdin,
994 stdout=subprocess.PIPE,
995 stderr=subprocess.PIPE).communicate()
996 err = support.strip_python_stderr(err)
997 self.assertEqual((out, err), (b'apple', b'orange'))
998 finally:
999 for b, a in zip(newfds, fds):
1000 os.dup2(b, a)
1001 for b in newfds:
1002 os.close(b)
1003
1004 def test_close_fd_0(self):
1005 self.check_close_std_fds([0])
1006
1007 def test_close_fd_1(self):
1008 self.check_close_std_fds([1])
1009
1010 def test_close_fd_2(self):
1011 self.check_close_std_fds([2])
1012
1013 def test_close_fds_0_1(self):
1014 self.check_close_std_fds([0, 1])
1015
1016 def test_close_fds_0_2(self):
1017 self.check_close_std_fds([0, 2])
1018
1019 def test_close_fds_1_2(self):
1020 self.check_close_std_fds([1, 2])
1021
1022 def test_close_fds_0_1_2(self):
1023 # Issue #10806: test that subprocess pipes still work properly with
1024 # all standard fds closed.
1025 self.check_close_std_fds([0, 1, 2])
1026
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001027 def test_remapping_std_fds(self):
1028 # open up some temporary files
1029 temps = [mkstemp() for i in range(3)]
1030 try:
1031 temp_fds = [fd for fd, fname in temps]
1032
1033 # unlink the files -- we won't need to reopen them
1034 for fd, fname in temps:
1035 os.unlink(fname)
1036
1037 # write some data to what will become stdin, and rewind
1038 os.write(temp_fds[1], b"STDIN")
1039 os.lseek(temp_fds[1], 0, 0)
1040
1041 # move the standard file descriptors out of the way
1042 saved_fds = [os.dup(fd) for fd in range(3)]
1043 try:
1044 # duplicate the file objects over the standard fd's
1045 for fd, temp_fd in enumerate(temp_fds):
1046 os.dup2(temp_fd, fd)
1047
1048 # now use those files in the "wrong" order, so that subprocess
1049 # has to rearrange them in the child
1050 p = subprocess.Popen([sys.executable, "-c",
1051 'import sys; got = sys.stdin.read();'
1052 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1053 stdin=temp_fds[1],
1054 stdout=temp_fds[2],
1055 stderr=temp_fds[0])
1056 p.wait()
1057 finally:
1058 # restore the original fd's underneath sys.stdin, etc.
1059 for std, saved in enumerate(saved_fds):
1060 os.dup2(saved, std)
1061 os.close(saved)
1062
1063 for fd in temp_fds:
1064 os.lseek(fd, 0, 0)
1065
1066 out = os.read(temp_fds[2], 1024)
1067 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1068 self.assertEqual(out, b"got STDIN")
1069 self.assertEqual(err, b"err")
1070
1071 finally:
1072 for fd in temp_fds:
1073 os.close(fd)
1074
Victor Stinner13bb71c2010-04-23 21:41:56 +00001075 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001076 def prepare():
1077 raise ValueError("surrogate:\uDCff")
1078
1079 try:
1080 subprocess.call(
1081 [sys.executable, "-c", "pass"],
1082 preexec_fn=prepare)
1083 except ValueError as err:
1084 # Pure Python implementations keeps the message
1085 self.assertIsNone(subprocess._posixsubprocess)
1086 self.assertEqual(str(err), "surrogate:\uDCff")
1087 except RuntimeError as err:
1088 # _posixsubprocess uses a default message
1089 self.assertIsNotNone(subprocess._posixsubprocess)
1090 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1091 else:
1092 self.fail("Expected ValueError or RuntimeError")
1093
Victor Stinner13bb71c2010-04-23 21:41:56 +00001094 def test_undecodable_env(self):
1095 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001096 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001097 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001098 env = os.environ.copy()
1099 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001100 # Use C locale to get ascii for the locale encoding to force
1101 # surrogate-escaping of \xFF in the child process; otherwise it can
1102 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001103 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001104 stdout = subprocess.check_output(
1105 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001106 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001107 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001108 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001109
1110 # test bytes
1111 key = key.encode("ascii", "surrogateescape")
1112 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001113 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001114 env = os.environ.copy()
1115 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001116 stdout = subprocess.check_output(
1117 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001118 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001119 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001120 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001121
Victor Stinnerb745a742010-05-18 17:17:23 +00001122 def test_bytes_program(self):
1123 abs_program = os.fsencode(sys.executable)
1124 path, program = os.path.split(sys.executable)
1125 program = os.fsencode(program)
1126
1127 # absolute bytes path
1128 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001129 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001130
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001131 # absolute bytes path as a string
1132 cmd = b"'" + abs_program + b"' -c pass"
1133 exitcode = subprocess.call(cmd, shell=True)
1134 self.assertEqual(exitcode, 0)
1135
Victor Stinnerb745a742010-05-18 17:17:23 +00001136 # bytes program, unicode PATH
1137 env = os.environ.copy()
1138 env["PATH"] = path
1139 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001140 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001141
1142 # bytes program, bytes PATH
1143 envb = os.environb.copy()
1144 envb[b"PATH"] = os.fsencode(path)
1145 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001146 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001147
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001148 def test_pipe_cloexec(self):
1149 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1150 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1151
1152 p1 = subprocess.Popen([sys.executable, sleeper],
1153 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1154 stderr=subprocess.PIPE, close_fds=False)
1155
1156 self.addCleanup(p1.communicate, b'')
1157
1158 p2 = subprocess.Popen([sys.executable, fd_status],
1159 stdout=subprocess.PIPE, close_fds=False)
1160
1161 output, error = p2.communicate()
1162 result_fds = set(map(int, output.split(b',')))
1163 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1164 p1.stderr.fileno()])
1165
1166 self.assertFalse(result_fds & unwanted_fds,
1167 "Expected no fds from %r to be open in child, "
1168 "found %r" %
1169 (unwanted_fds, result_fds & unwanted_fds))
1170
1171 def test_pipe_cloexec_real_tools(self):
1172 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1173 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1174
1175 subdata = b'zxcvbn'
1176 data = subdata * 4 + b'\n'
1177
1178 p1 = subprocess.Popen([sys.executable, qcat],
1179 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1180 close_fds=False)
1181
1182 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1183 stdin=p1.stdout, stdout=subprocess.PIPE,
1184 close_fds=False)
1185
1186 self.addCleanup(p1.wait)
1187 self.addCleanup(p2.wait)
1188 self.addCleanup(p1.terminate)
1189 self.addCleanup(p2.terminate)
1190
1191 p1.stdin.write(data)
1192 p1.stdin.close()
1193
1194 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1195
1196 self.assertTrue(readfiles, "The child hung")
1197 self.assertEqual(p2.stdout.read(), data)
1198
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001199 p1.stdout.close()
1200 p2.stdout.close()
1201
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001202 def test_close_fds(self):
1203 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1204
1205 fds = os.pipe()
1206 self.addCleanup(os.close, fds[0])
1207 self.addCleanup(os.close, fds[1])
1208
1209 open_fds = set(fds)
1210
1211 p = subprocess.Popen([sys.executable, fd_status],
1212 stdout=subprocess.PIPE, close_fds=False)
1213 output, ignored = p.communicate()
1214 remaining_fds = set(map(int, output.split(b',')))
1215
1216 self.assertEqual(remaining_fds & open_fds, open_fds,
1217 "Some fds were closed")
1218
1219 p = subprocess.Popen([sys.executable, fd_status],
1220 stdout=subprocess.PIPE, close_fds=True)
1221 output, ignored = p.communicate()
1222 remaining_fds = set(map(int, output.split(b',')))
1223
1224 self.assertFalse(remaining_fds & open_fds,
1225 "Some fds were left open")
1226 self.assertIn(1, remaining_fds, "Subprocess failed")
1227
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001228 def test_pass_fds(self):
1229 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1230
1231 open_fds = set()
1232
1233 for x in range(5):
1234 fds = os.pipe()
1235 self.addCleanup(os.close, fds[0])
1236 self.addCleanup(os.close, fds[1])
1237 open_fds.update(fds)
1238
1239 for fd in open_fds:
1240 p = subprocess.Popen([sys.executable, fd_status],
1241 stdout=subprocess.PIPE, close_fds=True,
1242 pass_fds=(fd, ))
1243 output, ignored = p.communicate()
1244
1245 remaining_fds = set(map(int, output.split(b',')))
1246 to_be_closed = open_fds - {fd}
1247
1248 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1249 self.assertFalse(remaining_fds & to_be_closed,
1250 "fd to be closed passed")
1251
1252 # pass_fds overrides close_fds with a warning.
1253 with self.assertWarns(RuntimeWarning) as context:
1254 self.assertFalse(subprocess.call(
1255 [sys.executable, "-c", "import sys; sys.exit(0)"],
1256 close_fds=False, pass_fds=(fd, )))
1257 self.assertIn('overriding close_fds', str(context.warning))
1258
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001259 def test_wait_when_sigchild_ignored(self):
1260 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1261 sigchild_ignore = support.findfile("sigchild_ignore.py",
1262 subdir="subprocessdata")
1263 p = subprocess.Popen([sys.executable, sigchild_ignore],
1264 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1265 stdout, stderr = p.communicate()
1266 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001267 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001268 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001269
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001270
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001271@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001272class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001273
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001274 def test_startupinfo(self):
1275 # startupinfo argument
1276 # We uses hardcoded constants, because we do not want to
1277 # depend on win32all.
1278 STARTF_USESHOWWINDOW = 1
1279 SW_MAXIMIZE = 3
1280 startupinfo = subprocess.STARTUPINFO()
1281 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1282 startupinfo.wShowWindow = SW_MAXIMIZE
1283 # Since Python is a console process, it won't be affected
1284 # by wShowWindow, but the argument should be silently
1285 # ignored
1286 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001287 startupinfo=startupinfo)
1288
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001289 def test_creationflags(self):
1290 # creationflags argument
1291 CREATE_NEW_CONSOLE = 16
1292 sys.stderr.write(" a DOS box should flash briefly ...\n")
1293 subprocess.call(sys.executable +
1294 ' -c "import time; time.sleep(0.25)"',
1295 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001296
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001297 def test_invalid_args(self):
1298 # invalid arguments should raise ValueError
1299 self.assertRaises(ValueError, subprocess.call,
1300 [sys.executable, "-c",
1301 "import sys; sys.exit(47)"],
1302 preexec_fn=lambda: 1)
1303 self.assertRaises(ValueError, subprocess.call,
1304 [sys.executable, "-c",
1305 "import sys; sys.exit(47)"],
1306 stdout=subprocess.PIPE,
1307 close_fds=True)
1308
1309 def test_close_fds(self):
1310 # close file descriptors
1311 rc = subprocess.call([sys.executable, "-c",
1312 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001313 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001314 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001315
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001316 def test_shell_sequence(self):
1317 # Run command through the shell (sequence)
1318 newenv = os.environ.copy()
1319 newenv["FRUIT"] = "physalis"
1320 p = subprocess.Popen(["set"], shell=1,
1321 stdout=subprocess.PIPE,
1322 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001323 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001324 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001325
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001326 def test_shell_string(self):
1327 # Run command through the shell (string)
1328 newenv = os.environ.copy()
1329 newenv["FRUIT"] = "physalis"
1330 p = subprocess.Popen("set", shell=1,
1331 stdout=subprocess.PIPE,
1332 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001333 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001334 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001335
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001336 def test_call_string(self):
1337 # call() function with string argument on Windows
1338 rc = subprocess.call(sys.executable +
1339 ' -c "import sys; sys.exit(47)"')
1340 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001341
Florent Xicluna4886d242010-03-08 13:27:26 +00001342 def _kill_process(self, method, *args):
1343 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001344 p = subprocess.Popen([sys.executable, "-c", """if 1:
1345 import sys, time
1346 sys.stdout.write('x\\n')
1347 sys.stdout.flush()
1348 time.sleep(30)
1349 """],
1350 stdin=subprocess.PIPE,
1351 stdout=subprocess.PIPE,
1352 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001353 self.addCleanup(p.stdout.close)
1354 self.addCleanup(p.stderr.close)
1355 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001356 # Wait for the interpreter to be completely initialized before
1357 # sending any signal.
1358 p.stdout.read(1)
1359 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001360 _, stderr = p.communicate()
1361 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001362 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001363 self.assertNotEqual(returncode, 0)
1364
1365 def test_send_signal(self):
1366 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001367
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001368 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001369 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001370
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001371 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001372 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001373
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001374
Brett Cannona23810f2008-05-26 19:04:21 +00001375# The module says:
1376# "NB This only works (and is only relevant) for UNIX."
1377#
1378# Actually, getoutput should work on any platform with an os.popen, but
1379# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001380@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001381class CommandTests(unittest.TestCase):
1382 def test_getoutput(self):
1383 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1384 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1385 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001386
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001387 # we use mkdtemp in the next line to create an empty directory
1388 # under our exclusive control; from that, we can invent a pathname
1389 # that we _know_ won't exist. This is guaranteed to fail.
1390 dir = None
1391 try:
1392 dir = tempfile.mkdtemp()
1393 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001394
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001395 status, output = subprocess.getstatusoutput('cat ' + name)
1396 self.assertNotEqual(status, 0)
1397 finally:
1398 if dir is not None:
1399 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001400
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001401
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001402@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1403 "poll system call not supported")
1404class ProcessTestCaseNoPoll(ProcessTestCase):
1405 def setUp(self):
1406 subprocess._has_poll = False
1407 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001408
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001409 def tearDown(self):
1410 subprocess._has_poll = True
1411 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001412
1413
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001414@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1415 "_posixsubprocess extension module not found.")
1416class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
1417 def setUp(self):
1418 subprocess._posixsubprocess = None
1419 ProcessTestCase.setUp(self)
1420 POSIXProcessTestCase.setUp(self)
1421
1422 def tearDown(self):
1423 subprocess._posixsubprocess = sys.modules['_posixsubprocess']
1424 POSIXProcessTestCase.tearDown(self)
1425 ProcessTestCase.tearDown(self)
1426
1427
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001428class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001429 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001430 def test_eintr_retry_call(self):
1431 record_calls = []
1432 def fake_os_func(*args):
1433 record_calls.append(args)
1434 if len(record_calls) == 2:
1435 raise OSError(errno.EINTR, "fake interrupted system call")
1436 return tuple(reversed(args))
1437
1438 self.assertEqual((999, 256),
1439 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1440 self.assertEqual([(256, 999)], record_calls)
1441 # This time there will be an EINTR so it will loop once.
1442 self.assertEqual((666,),
1443 subprocess._eintr_retry_call(fake_os_func, 666))
1444 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1445
1446
Tim Golden126c2962010-08-11 14:20:40 +00001447@unittest.skipUnless(mswindows, "Windows-specific tests")
1448class CommandsWithSpaces (BaseTestCase):
1449
1450 def setUp(self):
1451 super().setUp()
1452 f, fname = mkstemp(".py", "te st")
1453 self.fname = fname.lower ()
1454 os.write(f, b"import sys;"
1455 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1456 )
1457 os.close(f)
1458
1459 def tearDown(self):
1460 os.remove(self.fname)
1461 super().tearDown()
1462
1463 def with_spaces(self, *args, **kwargs):
1464 kwargs['stdout'] = subprocess.PIPE
1465 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001466 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001467 self.assertEqual(
1468 p.stdout.read ().decode("mbcs"),
1469 "2 [%r, 'ab cd']" % self.fname
1470 )
1471
1472 def test_shell_string_with_spaces(self):
1473 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001474 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1475 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001476
1477 def test_shell_sequence_with_spaces(self):
1478 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001479 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001480
1481 def test_noshell_string_with_spaces(self):
1482 # call() function with string argument with spaces on Windows
1483 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1484 "ab cd"))
1485
1486 def test_noshell_sequence_with_spaces(self):
1487 # call() function with sequence argument with spaces on Windows
1488 self.with_spaces([sys.executable, self.fname, "ab cd"])
1489
Brian Curtin79cdb662010-12-03 02:46:02 +00001490
1491class ContextManagerTests(ProcessTestCase):
1492
1493 def test_pipe(self):
1494 with subprocess.Popen([sys.executable, "-c",
1495 "import sys;"
1496 "sys.stdout.write('stdout');"
1497 "sys.stderr.write('stderr');"],
1498 stdout=subprocess.PIPE,
1499 stderr=subprocess.PIPE) as proc:
1500 self.assertEqual(proc.stdout.read(), b"stdout")
1501 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1502
1503 self.assertTrue(proc.stdout.closed)
1504 self.assertTrue(proc.stderr.closed)
1505
1506 def test_returncode(self):
1507 with subprocess.Popen([sys.executable, "-c",
1508 "import sys; sys.exit(100)"]) as proc:
1509 proc.wait()
1510 self.assertEqual(proc.returncode, 100)
1511
1512 def test_communicate_stdin(self):
1513 with subprocess.Popen([sys.executable, "-c",
1514 "import sys;"
1515 "sys.exit(sys.stdin.read() == 'context')"],
1516 stdin=subprocess.PIPE) as proc:
1517 proc.communicate(b"context")
1518 self.assertEqual(proc.returncode, 1)
1519
1520 def test_invalid_args(self):
1521 with self.assertRaises(EnvironmentError) as c:
1522 with subprocess.Popen(['nonexisting_i_hope'],
1523 stdout=subprocess.PIPE,
1524 stderr=subprocess.PIPE) as proc:
1525 pass
1526
1527 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1528 raise c.exception
1529
1530
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001531def test_main():
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001532 unit_tests = (ProcessTestCase,
1533 POSIXProcessTestCase,
1534 Win32ProcessTestCase,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001535 ProcessTestCasePOSIXPurePython,
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001536 CommandTests,
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001537 ProcessTestCaseNoPoll,
Tim Golden126c2962010-08-11 14:20:40 +00001538 HelperFunctionTests,
Brian Curtin79cdb662010-12-03 02:46:02 +00001539 CommandsWithSpaces,
Gregory P. Smithf5604852010-12-13 06:45:02 +00001540 ContextManagerTests)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001541
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001542 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +00001543 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001544
1545if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +00001546 test_main()