blob: eb0f5d73abef04e43f902eb343a38868dc6d9685 [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. Smith32ec9da2010-03-19 16:53:08 +000012try:
13 import gc
14except ImportError:
15 gc = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000016
17mswindows = (sys.platform == "win32")
18
19#
20# Depends on the following external programs: Python
21#
22
23if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000024 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
25 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000026else:
27 SETBINARY = ''
28
Florent Xiclunab1e94e82010-02-27 22:12:37 +000029
30try:
31 mkstemp = tempfile.mkstemp
32except AttributeError:
33 # tempfile.mkstemp is not available
34 def mkstemp():
35 """Replacement for mkstemp, calling mktemp."""
36 fname = tempfile.mktemp()
37 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
38
Tim Peters3761e8d2004-10-13 04:07:12 +000039
Florent Xiclunac049d872010-03-27 22:47:23 +000040class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000041 def setUp(self):
42 # Try to minimize the number of children we have so this test
43 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000044 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000046 def tearDown(self):
47 for inst in subprocess._active:
48 inst.wait()
49 subprocess._cleanup()
50 self.assertFalse(subprocess._active, "subprocess._active not empty")
51
Florent Xiclunab1e94e82010-02-27 22:12:37 +000052 def assertStderrEqual(self, stderr, expected, msg=None):
53 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
54 # shutdown time. That frustrates tests trying to check stderr produced
55 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000056 actual = support.strip_python_stderr(stderr)
Florent Xiclunab1e94e82010-02-27 22:12:37 +000057 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000058
Florent Xiclunac049d872010-03-27 22:47:23 +000059
60class ProcessTestCase(BaseTestCase):
61
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000062 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000063 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000064 rc = subprocess.call([sys.executable, "-c",
65 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000066 self.assertEqual(rc, 47)
67
Peter Astrand454f7672005-01-01 09:36:35 +000068 def test_check_call_zero(self):
69 # check_call() function with zero return code
70 rc = subprocess.check_call([sys.executable, "-c",
71 "import sys; sys.exit(0)"])
72 self.assertEqual(rc, 0)
73
74 def test_check_call_nonzero(self):
75 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000076 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000077 subprocess.check_call([sys.executable, "-c",
78 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000079 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000080
Georg Brandlf9734072008-12-07 15:30:06 +000081 def test_check_output(self):
82 # check_output() function with zero return code
83 output = subprocess.check_output(
84 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000085 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000086
87 def test_check_output_nonzero(self):
88 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000089 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +000090 subprocess.check_output(
91 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000092 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +000093
94 def test_check_output_stderr(self):
95 # check_output() function stderr redirected to stdout
96 output = subprocess.check_output(
97 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
98 stderr=subprocess.STDOUT)
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_stdout_arg(self):
102 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000103 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000104 output = subprocess.check_output(
105 [sys.executable, "-c", "print('will not be run')"],
106 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000107 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000108 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000109
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000110 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000111 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000112 newenv = os.environ.copy()
113 newenv["FRUIT"] = "banana"
114 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000115 'import sys, os;'
116 'sys.exit(os.getenv("FRUIT")=="banana")'],
117 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000118 self.assertEqual(rc, 1)
119
120 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000121 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000122 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000123 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
124 p.wait()
125 self.assertEqual(p.stdin, None)
126
127 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000128 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000129 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000130 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000131 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000132 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000133 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000134 p.wait()
135 self.assertEqual(p.stdout, None)
136
137 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000138 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000139 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
141 p.wait()
142 self.assertEqual(p.stderr, None)
143
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000144 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000145 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000146 p = subprocess.Popen(["somethingyoudonthave", "-c",
147 "import sys; sys.exit(47)"],
148 executable=sys.executable, cwd=python_dir)
149 p.wait()
150 self.assertEqual(p.returncode, 47)
151
152 @unittest.skipIf(sysconfig.is_python_build(),
153 "need an installed Python. See #7774")
154 def test_executable_without_cwd(self):
155 # For a normal installation, it should work without 'cwd'
156 # argument. For test runs in the build directory, see #7774.
157 p = subprocess.Popen(["somethingyoudonthave", "-c",
158 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000159 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000160 p.wait()
161 self.assertEqual(p.returncode, 47)
162
163 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000164 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165 p = subprocess.Popen([sys.executable, "-c",
166 'import sys; sys.exit(sys.stdin.read() == "pear")'],
167 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000168 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000169 p.stdin.close()
170 p.wait()
171 self.assertEqual(p.returncode, 1)
172
173 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000174 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000175 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000176 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000177 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000178 os.lseek(d, 0, 0)
179 p = subprocess.Popen([sys.executable, "-c",
180 'import sys; sys.exit(sys.stdin.read() == "pear")'],
181 stdin=d)
182 p.wait()
183 self.assertEqual(p.returncode, 1)
184
185 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000186 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000187 tf = tempfile.TemporaryFile()
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000188 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 tf.seek(0)
190 p = subprocess.Popen([sys.executable, "-c",
191 'import sys; sys.exit(sys.stdin.read() == "pear")'],
192 stdin=tf)
193 p.wait()
194 self.assertEqual(p.returncode, 1)
195
196 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000197 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000198 p = subprocess.Popen([sys.executable, "-c",
199 'import sys; sys.stdout.write("orange")'],
200 stdout=subprocess.PIPE)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000201 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000202
203 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000204 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000205 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000206 d = tf.fileno()
207 p = subprocess.Popen([sys.executable, "-c",
208 'import sys; sys.stdout.write("orange")'],
209 stdout=d)
210 p.wait()
211 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000212 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000213
214 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000215 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000216 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000217 p = subprocess.Popen([sys.executable, "-c",
218 'import sys; sys.stdout.write("orange")'],
219 stdout=tf)
220 p.wait()
221 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000222 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223
224 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000225 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000226 p = subprocess.Popen([sys.executable, "-c",
227 'import sys; sys.stderr.write("strawberry")'],
228 stderr=subprocess.PIPE)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000229 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000230
231 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000232 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000233 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000234 d = tf.fileno()
235 p = subprocess.Popen([sys.executable, "-c",
236 'import sys; sys.stderr.write("strawberry")'],
237 stderr=d)
238 p.wait()
239 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000240 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000241
242 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000243 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000244 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 p = subprocess.Popen([sys.executable, "-c",
246 'import sys; sys.stderr.write("strawberry")'],
247 stderr=tf)
248 p.wait()
249 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000250 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251
252 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000253 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000254 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000255 'import sys;'
256 'sys.stdout.write("apple");'
257 'sys.stdout.flush();'
258 'sys.stderr.write("orange")'],
259 stdout=subprocess.PIPE,
260 stderr=subprocess.STDOUT)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000261 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262
263 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000264 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265 tf = tempfile.TemporaryFile()
266 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000267 'import sys;'
268 'sys.stdout.write("apple");'
269 'sys.stdout.flush();'
270 'sys.stderr.write("orange")'],
271 stdout=tf,
272 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000273 p.wait()
274 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000275 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276
Thomas Wouters89f507f2006-12-13 04:49:30 +0000277 def test_stdout_filedes_of_stdout(self):
278 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000279 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000280 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000281 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000282
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000283 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000284 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000285 # We cannot use os.path.realpath to canonicalize the path,
286 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
287 cwd = os.getcwd()
288 os.chdir(tmpdir)
289 tmpdir = os.getcwd()
290 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000292 'import sys,os;'
293 'sys.stdout.write(os.getcwd())'],
294 stdout=subprocess.PIPE,
295 cwd=tmpdir)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000296 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000297 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
298 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000299
300 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000301 newenv = os.environ.copy()
302 newenv["FRUIT"] = "orange"
303 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000304 'import sys,os;'
305 'sys.stdout.write(os.getenv("FRUIT"))'],
306 stdout=subprocess.PIPE,
307 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000308 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309
Peter Astrandcbac93c2005-03-03 20:24:28 +0000310 def test_communicate_stdin(self):
311 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000312 'import sys;'
313 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000314 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000315 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000316 self.assertEqual(p.returncode, 1)
317
318 def test_communicate_stdout(self):
319 p = subprocess.Popen([sys.executable, "-c",
320 'import sys; sys.stdout.write("pineapple")'],
321 stdout=subprocess.PIPE)
322 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000323 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000324 self.assertEqual(stderr, None)
325
326 def test_communicate_stderr(self):
327 p = subprocess.Popen([sys.executable, "-c",
328 'import sys; sys.stderr.write("pineapple")'],
329 stderr=subprocess.PIPE)
330 (stdout, stderr) = p.communicate()
331 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000332 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000333
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000335 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000336 'import sys,os;'
337 'sys.stderr.write("pineapple");'
338 'sys.stdout.write(sys.stdin.read())'],
339 stdin=subprocess.PIPE,
340 stdout=subprocess.PIPE,
341 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000342 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000343 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000344 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000345
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000346 # This test is Linux specific for simplicity to at least have
347 # some coverage. It is not a platform specific bug.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000348 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
349 "Linux specific")
350 # Test for the fd leak reported in http://bugs.python.org/issue2791.
351 def test_communicate_pipe_fd_leak(self):
352 fd_directory = '/proc/%d/fd' % os.getpid()
353 num_fds_before_popen = len(os.listdir(fd_directory))
354 p = subprocess.Popen([sys.executable, "-c", "print()"],
355 stdout=subprocess.PIPE)
356 p.communicate()
357 num_fds_after_communicate = len(os.listdir(fd_directory))
358 del p
359 num_fds_after_destruction = len(os.listdir(fd_directory))
360 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
361 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000362
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000363 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000364 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000365 p = subprocess.Popen([sys.executable, "-c",
366 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000367 (stdout, stderr) = p.communicate()
368 self.assertEqual(stdout, None)
369 self.assertEqual(stderr, None)
370
371 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000372 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000373 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000374 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000375 x, y = os.pipe()
376 if mswindows:
377 pipe_buf = 512
378 else:
379 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
380 os.close(x)
381 os.close(y)
382 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000383 'import sys,os;'
384 'sys.stdout.write(sys.stdin.read(47));'
385 'sys.stderr.write("xyz"*%d);'
386 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
387 stdin=subprocess.PIPE,
388 stdout=subprocess.PIPE,
389 stderr=subprocess.PIPE)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000390 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000391 (stdout, stderr) = p.communicate(string_to_write)
392 self.assertEqual(stdout, string_to_write)
393
394 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000395 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000396 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000397 'import sys,os;'
398 'sys.stdout.write(sys.stdin.read())'],
399 stdin=subprocess.PIPE,
400 stdout=subprocess.PIPE,
401 stderr=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000402 p.stdin.write(b"banana")
403 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000404 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000405 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000406
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000407 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000408 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000409 'import sys,os;' + SETBINARY +
410 'sys.stdout.write("line1\\n");'
411 'sys.stdout.flush();'
412 'sys.stdout.write("line2\\n");'
413 'sys.stdout.flush();'
414 'sys.stdout.write("line3\\r\\n");'
415 'sys.stdout.flush();'
416 'sys.stdout.write("line4\\r");'
417 'sys.stdout.flush();'
418 'sys.stdout.write("\\nline5");'
419 'sys.stdout.flush();'
420 'sys.stdout.write("\\nline6");'],
421 stdout=subprocess.PIPE,
422 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000424 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000425
426 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000427 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000428 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000429 'import sys,os;' + SETBINARY +
430 'sys.stdout.write("line1\\n");'
431 'sys.stdout.flush();'
432 'sys.stdout.write("line2\\n");'
433 'sys.stdout.flush();'
434 'sys.stdout.write("line3\\r\\n");'
435 'sys.stdout.flush();'
436 'sys.stdout.write("line4\\r");'
437 'sys.stdout.flush();'
438 'sys.stdout.write("\\nline5");'
439 'sys.stdout.flush();'
440 'sys.stdout.write("\\nline6");'],
441 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
442 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000443 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000444 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000445
446 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000447 # Make sure we leak no resources
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000448 if (not hasattr(support, "is_resource_enabled") or
449 support.is_resource_enabled("subprocess") and not mswindows):
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000450 max_handles = 1026 # too much for most UNIX systems
451 else:
Tim Peterseba28be2005-03-28 01:08:02 +0000452 max_handles = 65
Fredrik Lundh9e29fc52004-10-13 07:54:54 +0000453 for i in range(max_handles):
Tim Peters3b01a702004-10-12 22:19:32 +0000454 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000455 "import sys;"
456 "sys.stdout.write(sys.stdin.read())"],
457 stdin=subprocess.PIPE,
458 stdout=subprocess.PIPE,
459 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000460 data = p.communicate(b"lime")[0]
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000461 self.assertEqual(data, b"lime")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000462
463
464 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000465 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
466 '"a b c" d e')
467 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
468 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000469 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
470 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
472 'a\\\\\\b "de fg" h')
473 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
474 'a\\\\\\"b c d')
475 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
476 '"a\\\\b c" d e')
477 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
478 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000479 self.assertEqual(subprocess.list2cmdline(['ab', '']),
480 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481
482
483 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000485 "-c", "import time; time.sleep(1)"])
486 count = 0
487 while p.poll() is None:
488 time.sleep(0.1)
489 count += 1
490 # We expect that the poll loop probably went around about 10 times,
491 # but, based on system scheduling we can't control, it's possible
492 # poll() never returned None. It "should be" very rare that it
493 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000494 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495 # Subsequent invocations should just return the returncode
496 self.assertEqual(p.poll(), 0)
497
498
499 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500 p = subprocess.Popen([sys.executable,
501 "-c", "import time; time.sleep(2)"])
502 self.assertEqual(p.wait(), 0)
503 # Subsequent invocations should just return the returncode
504 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000505
Peter Astrand738131d2004-11-30 21:04:45 +0000506
507 def test_invalid_bufsize(self):
508 # an invalid type of the bufsize argument should raise
509 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000510 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000511 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000512
Guido van Rossum46a05a72007-06-07 21:56:45 +0000513 def test_bufsize_is_none(self):
514 # bufsize=None should be the same as bufsize=0.
515 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
516 self.assertEqual(p.wait(), 0)
517 # Again with keyword arg
518 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
519 self.assertEqual(p.wait(), 0)
520
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000521 def test_leaking_fds_on_error(self):
522 # see bug #5179: Popen leaks file descriptors to PIPEs if
523 # the child fails to execute; this will eventually exhaust
524 # the maximum number of open fds. 1024 seems a very common
525 # value for that limit, but Windows has 2048, so we loop
526 # 1024 times (each call leaked two fds).
527 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000528 # Windows raises IOError. Others raise OSError.
529 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000530 subprocess.Popen(['nonexisting_i_hope'],
531 stdout=subprocess.PIPE,
532 stderr=subprocess.PIPE)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000533 if c.exception.errno != 2: # ignore "no such file"
534 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000535
Victor Stinnerb3693582010-05-21 20:13:12 +0000536 def test_issue8780(self):
537 # Ensure that stdout is inherited from the parent
538 # if stdout=PIPE is not used
539 code = ';'.join((
540 'import subprocess, sys',
541 'retcode = subprocess.call('
542 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
543 'assert retcode == 0'))
544 output = subprocess.check_output([sys.executable, '-c', code])
545 self.assert_(output.startswith(b'Hello World!'), ascii(output))
546
Tim Peterse718f612004-10-12 21:51:32 +0000547
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000548# context manager
549class _SuppressCoreFiles(object):
550 """Try to prevent core files from being created."""
551 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000552
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000553 def __enter__(self):
554 """Try to save previous ulimit, then set it to (0, 0)."""
555 try:
556 import resource
557 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
558 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
559 except (ImportError, ValueError, resource.error):
560 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000561
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000562 if sys.platform == 'darwin':
563 # Check if the 'Crash Reporter' on OSX was configured
564 # in 'Developer' mode and warn that it will get triggered
565 # when it is.
566 #
567 # This assumes that this context manager is used in tests
568 # that might trigger the next manager.
569 value = subprocess.Popen(['/usr/bin/defaults', 'read',
570 'com.apple.CrashReporter', 'DialogType'],
571 stdout=subprocess.PIPE).communicate()[0]
572 if value.strip() == b'developer':
573 print("this tests triggers the Crash Reporter, "
574 "that is intentional", end='')
575 sys.stdout.flush()
576
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000577 def __exit__(self, *args):
578 """Return core file behavior to default."""
579 if self.old_limit is None:
580 return
581 try:
582 import resource
583 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
584 except (ImportError, ValueError, resource.error):
585 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000586
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000587
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000588@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000589class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000590
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000591 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000592 nonexistent_dir = "/_this/pa.th/does/not/exist"
593 try:
594 os.chdir(nonexistent_dir)
595 except OSError as e:
596 # This avoids hard coding the errno value or the OS perror()
597 # string and instead capture the exception that we want to see
598 # below for comparison.
599 desired_exception = e
600 else:
601 self.fail("chdir to nonexistant directory %s succeeded." %
602 nonexistent_dir)
603
604 # Error in the child re-raised in the parent.
605 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000606 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000607 cwd=nonexistent_dir)
608 except OSError as e:
609 # Test that the child process chdir failure actually makes
610 # it up to the parent process as the correct exception.
611 self.assertEqual(desired_exception.errno, e.errno)
612 self.assertEqual(desired_exception.strerror, e.strerror)
613 else:
614 self.fail("Expected OSError: %s" % desired_exception)
615
616 def test_restore_signals(self):
617 # Code coverage for both values of restore_signals to make sure it
618 # at least does not blow up.
619 # A test for behavior would be complex. Contributions welcome.
620 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
621 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
622
623 def test_start_new_session(self):
624 # For code coverage of calling setsid(). We don't care if we get an
625 # EPERM error from it depending on the test execution environment, that
626 # still indicates that it was called.
627 try:
628 output = subprocess.check_output(
629 [sys.executable, "-c",
630 "import os; print(os.getpgid(os.getpid()))"],
631 start_new_session=True)
632 except OSError as e:
633 if e.errno != errno.EPERM:
634 raise
635 else:
636 parent_pgid = os.getpgid(os.getpid())
637 child_pgid = int(output)
638 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000639
640 def test_run_abort(self):
641 # returncode handles signal termination
642 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000644 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000645 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000646 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000648 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000649 # DISCLAIMER: Setting environment variables is *not* a good use
650 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000651 p = subprocess.Popen([sys.executable, "-c",
652 'import sys,os;'
653 'sys.stdout.write(os.getenv("FRUIT"))'],
654 stdout=subprocess.PIPE,
655 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
656 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000657
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000658 def test_preexec_exception(self):
659 def raise_it():
660 raise ValueError("What if two swallows carried a coconut?")
661 try:
662 p = subprocess.Popen([sys.executable, "-c", ""],
663 preexec_fn=raise_it)
664 except RuntimeError as e:
665 self.assertTrue(
666 subprocess._posixsubprocess,
667 "Expected a ValueError from the preexec_fn")
668 except ValueError as e:
669 self.assertIn("coconut", e.args[0])
670 else:
671 self.fail("Exception raised by preexec_fn did not make it "
672 "to the parent process.")
673
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000674 @unittest.skipUnless(gc, "Requires a gc module.")
675 def test_preexec_gc_module_failure(self):
676 # This tests the code that disables garbage collection if the child
677 # process will execute any Python.
678 def raise_runtime_error():
679 raise RuntimeError("this shouldn't escape")
680 enabled = gc.isenabled()
681 orig_gc_disable = gc.disable
682 orig_gc_isenabled = gc.isenabled
683 try:
684 gc.disable()
685 self.assertFalse(gc.isenabled())
686 subprocess.call([sys.executable, '-c', ''],
687 preexec_fn=lambda: None)
688 self.assertFalse(gc.isenabled(),
689 "Popen enabled gc when it shouldn't.")
690
691 gc.enable()
692 self.assertTrue(gc.isenabled())
693 subprocess.call([sys.executable, '-c', ''],
694 preexec_fn=lambda: None)
695 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
696
697 gc.disable = raise_runtime_error
698 self.assertRaises(RuntimeError, subprocess.Popen,
699 [sys.executable, '-c', ''],
700 preexec_fn=lambda: None)
701
702 del gc.isenabled # force an AttributeError
703 self.assertRaises(AttributeError, subprocess.Popen,
704 [sys.executable, '-c', ''],
705 preexec_fn=lambda: None)
706 finally:
707 gc.disable = orig_gc_disable
708 gc.isenabled = orig_gc_isenabled
709 if not enabled:
710 gc.disable()
711
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000712 def test_args_string(self):
713 # args is a string
714 fd, fname = mkstemp()
715 # reopen in text mode
716 with open(fd, "w") as fobj:
717 fobj.write("#!/bin/sh\n")
718 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
719 sys.executable)
720 os.chmod(fname, 0o700)
721 p = subprocess.Popen(fname)
722 p.wait()
723 os.remove(fname)
724 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000725
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000726 def test_invalid_args(self):
727 # invalid arguments should raise ValueError
728 self.assertRaises(ValueError, subprocess.call,
729 [sys.executable, "-c",
730 "import sys; sys.exit(47)"],
731 startupinfo=47)
732 self.assertRaises(ValueError, subprocess.call,
733 [sys.executable, "-c",
734 "import sys; sys.exit(47)"],
735 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000736
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000737 def test_shell_sequence(self):
738 # Run command through the shell (sequence)
739 newenv = os.environ.copy()
740 newenv["FRUIT"] = "apple"
741 p = subprocess.Popen(["echo $FRUIT"], shell=1,
742 stdout=subprocess.PIPE,
743 env=newenv)
744 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000745
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000746 def test_shell_string(self):
747 # Run command through the shell (string)
748 newenv = os.environ.copy()
749 newenv["FRUIT"] = "apple"
750 p = subprocess.Popen("echo $FRUIT", shell=1,
751 stdout=subprocess.PIPE,
752 env=newenv)
753 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000754
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000755 def test_call_string(self):
756 # call() function with string argument on UNIX
757 fd, fname = mkstemp()
758 # reopen in text mode
759 with open(fd, "w") as fobj:
760 fobj.write("#!/bin/sh\n")
761 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
762 sys.executable)
763 os.chmod(fname, 0o700)
764 rc = subprocess.call(fname)
765 os.remove(fname)
766 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000767
Stefan Krah9542cc62010-07-19 14:20:53 +0000768 def test_specific_shell(self):
769 # Issue #9265: Incorrect name passed as arg[0].
770 shells = []
771 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
772 for name in ['bash', 'ksh']:
773 sh = os.path.join(prefix, name)
774 if os.path.isfile(sh):
775 shells.append(sh)
776 if not shells: # Will probably work for any shell but csh.
777 self.skipTest("bash or ksh required for this test")
778 sh = '/bin/sh'
779 if os.path.isfile(sh) and not os.path.islink(sh):
780 # Test will fail if /bin/sh is a symlink to csh.
781 shells.append(sh)
782 for sh in shells:
783 p = subprocess.Popen("echo $0", executable=sh, shell=True,
784 stdout=subprocess.PIPE)
785 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
786
Florent Xicluna4886d242010-03-08 13:27:26 +0000787 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000788 # Do not inherit file handles from the parent.
789 # It should fix failures on some platforms.
790 p = subprocess.Popen([sys.executable, "-c", "input()"], close_fds=True,
Florent Xiclunac049d872010-03-27 22:47:23 +0000791 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Christian Heimesa342c012008-04-20 21:01:16 +0000792
Florent Xicluna4886d242010-03-08 13:27:26 +0000793 # Let the process initialize (Issue #3137)
Florent Xicluna129226d2010-03-05 00:52:00 +0000794 time.sleep(0.1)
Florent Xicluna4886d242010-03-08 13:27:26 +0000795 # The process should not terminate prematurely
Florent Xiclunab8f22b12010-03-05 01:18:04 +0000796 self.assertIsNone(p.poll())
Florent Xicluna4886d242010-03-08 13:27:26 +0000797 # Retry if the process do not receive the signal.
Florent Xicluna129226d2010-03-05 00:52:00 +0000798 count, maxcount = 0, 3
Florent Xicluna129226d2010-03-05 00:52:00 +0000799 while count < maxcount and p.poll() is None:
Florent Xicluna4886d242010-03-08 13:27:26 +0000800 getattr(p, method)(*args)
Florent Xicluna129226d2010-03-05 00:52:00 +0000801 time.sleep(0.1)
802 count += 1
Florent Xicluna4886d242010-03-08 13:27:26 +0000803
804 self.assertIsNotNone(p.poll(), "the subprocess did not terminate")
Florent Xiclunab8f22b12010-03-05 01:18:04 +0000805 if count > 1:
Florent Xicluna4886d242010-03-08 13:27:26 +0000806 print("p.{}{} succeeded after "
807 "{} attempts".format(method, args, count), file=sys.stderr)
808 return p
809
810 def test_send_signal(self):
811 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000812 _, stderr = p.communicate()
813 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000814 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000815
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000816 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000817 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000818 _, stderr = p.communicate()
819 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000820 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000821
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000822 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000823 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000824 _, stderr = p.communicate()
825 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000826 self.assertEqual(p.wait(), -signal.SIGTERM)
827
Victor Stinner13bb71c2010-04-23 21:41:56 +0000828 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +0000829 def prepare():
830 raise ValueError("surrogate:\uDCff")
831
832 try:
833 subprocess.call(
834 [sys.executable, "-c", "pass"],
835 preexec_fn=prepare)
836 except ValueError as err:
837 # Pure Python implementations keeps the message
838 self.assertIsNone(subprocess._posixsubprocess)
839 self.assertEqual(str(err), "surrogate:\uDCff")
840 except RuntimeError as err:
841 # _posixsubprocess uses a default message
842 self.assertIsNotNone(subprocess._posixsubprocess)
843 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
844 else:
845 self.fail("Expected ValueError or RuntimeError")
846
Victor Stinner13bb71c2010-04-23 21:41:56 +0000847 def test_undecodable_env(self):
848 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +0000849 # test str with surrogates
850 script = "import os; print(repr(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000851 env = os.environ.copy()
852 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +0000853 stdout = subprocess.check_output(
854 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000855 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +0000856 stdout = stdout.rstrip(b'\n\r')
Victor Stinner84ae1182010-05-06 22:05:07 +0000857 self.assertEquals(stdout.decode('ascii'), repr(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +0000858
859 # test bytes
860 key = key.encode("ascii", "surrogateescape")
861 value = value.encode("ascii", "surrogateescape")
Victor Stinner84ae1182010-05-06 22:05:07 +0000862 script = "import os; print(repr(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000863 env = os.environ.copy()
864 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +0000865 stdout = subprocess.check_output(
866 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000867 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +0000868 stdout = stdout.rstrip(b'\n\r')
Victor Stinner84ae1182010-05-06 22:05:07 +0000869 self.assertEquals(stdout.decode('ascii'), repr(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +0000870
Victor Stinnerb745a742010-05-18 17:17:23 +0000871 def test_bytes_program(self):
872 abs_program = os.fsencode(sys.executable)
873 path, program = os.path.split(sys.executable)
874 program = os.fsencode(program)
875
876 # absolute bytes path
877 exitcode = subprocess.call([abs_program, "-c", "pass"])
878 self.assertEquals(exitcode, 0)
879
880 # bytes program, unicode PATH
881 env = os.environ.copy()
882 env["PATH"] = path
883 exitcode = subprocess.call([program, "-c", "pass"], env=env)
884 self.assertEquals(exitcode, 0)
885
886 # bytes program, bytes PATH
887 envb = os.environb.copy()
888 envb[b"PATH"] = os.fsencode(path)
889 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
890 self.assertEquals(exitcode, 0)
891
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000892
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000893@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000894class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000895
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000896 def test_startupinfo(self):
897 # startupinfo argument
898 # We uses hardcoded constants, because we do not want to
899 # depend on win32all.
900 STARTF_USESHOWWINDOW = 1
901 SW_MAXIMIZE = 3
902 startupinfo = subprocess.STARTUPINFO()
903 startupinfo.dwFlags = STARTF_USESHOWWINDOW
904 startupinfo.wShowWindow = SW_MAXIMIZE
905 # Since Python is a console process, it won't be affected
906 # by wShowWindow, but the argument should be silently
907 # ignored
908 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000909 startupinfo=startupinfo)
910
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000911 def test_creationflags(self):
912 # creationflags argument
913 CREATE_NEW_CONSOLE = 16
914 sys.stderr.write(" a DOS box should flash briefly ...\n")
915 subprocess.call(sys.executable +
916 ' -c "import time; time.sleep(0.25)"',
917 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000918
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000919 def test_invalid_args(self):
920 # invalid arguments should raise ValueError
921 self.assertRaises(ValueError, subprocess.call,
922 [sys.executable, "-c",
923 "import sys; sys.exit(47)"],
924 preexec_fn=lambda: 1)
925 self.assertRaises(ValueError, subprocess.call,
926 [sys.executable, "-c",
927 "import sys; sys.exit(47)"],
928 stdout=subprocess.PIPE,
929 close_fds=True)
930
931 def test_close_fds(self):
932 # close file descriptors
933 rc = subprocess.call([sys.executable, "-c",
934 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000935 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000936 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000937
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000938 def test_shell_sequence(self):
939 # Run command through the shell (sequence)
940 newenv = os.environ.copy()
941 newenv["FRUIT"] = "physalis"
942 p = subprocess.Popen(["set"], shell=1,
943 stdout=subprocess.PIPE,
944 env=newenv)
945 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +0000946
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000947 def test_shell_string(self):
948 # Run command through the shell (string)
949 newenv = os.environ.copy()
950 newenv["FRUIT"] = "physalis"
951 p = subprocess.Popen("set", shell=1,
952 stdout=subprocess.PIPE,
953 env=newenv)
954 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000955
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000956 def test_call_string(self):
957 # call() function with string argument on Windows
958 rc = subprocess.call(sys.executable +
959 ' -c "import sys; sys.exit(47)"')
960 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000961
Florent Xicluna4886d242010-03-08 13:27:26 +0000962 def _kill_process(self, method, *args):
963 # Some win32 buildbot raises EOFError if stdin is inherited
964 p = subprocess.Popen([sys.executable, "-c", "input()"],
Florent Xiclunac049d872010-03-27 22:47:23 +0000965 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000966
Florent Xicluna4886d242010-03-08 13:27:26 +0000967 # Let the process initialize (Issue #3137)
968 time.sleep(0.1)
969 # The process should not terminate prematurely
970 self.assertIsNone(p.poll())
971 # Retry if the process do not receive the signal.
972 count, maxcount = 0, 3
973 while count < maxcount and p.poll() is None:
974 getattr(p, method)(*args)
975 time.sleep(0.1)
976 count += 1
977
978 returncode = p.poll()
979 self.assertIsNotNone(returncode, "the subprocess did not terminate")
980 if count > 1:
981 print("p.{}{} succeeded after "
982 "{} attempts".format(method, args, count), file=sys.stderr)
Florent Xiclunac049d872010-03-27 22:47:23 +0000983 _, stderr = p.communicate()
984 self.assertStderrEqual(stderr, b'')
Florent Xicluna4886d242010-03-08 13:27:26 +0000985 self.assertEqual(p.wait(), returncode)
986 self.assertNotEqual(returncode, 0)
987
988 def test_send_signal(self):
989 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +0000990
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000991 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000992 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +0000993
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000994 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000995 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +0000996
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000997
Brett Cannona23810f2008-05-26 19:04:21 +0000998# The module says:
999# "NB This only works (and is only relevant) for UNIX."
1000#
1001# Actually, getoutput should work on any platform with an os.popen, but
1002# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001003@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001004class CommandTests(unittest.TestCase):
1005 def test_getoutput(self):
1006 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1007 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1008 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001009
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001010 # we use mkdtemp in the next line to create an empty directory
1011 # under our exclusive control; from that, we can invent a pathname
1012 # that we _know_ won't exist. This is guaranteed to fail.
1013 dir = None
1014 try:
1015 dir = tempfile.mkdtemp()
1016 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001017
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001018 status, output = subprocess.getstatusoutput('cat ' + name)
1019 self.assertNotEqual(status, 0)
1020 finally:
1021 if dir is not None:
1022 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001023
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001024
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001025@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1026 "poll system call not supported")
1027class ProcessTestCaseNoPoll(ProcessTestCase):
1028 def setUp(self):
1029 subprocess._has_poll = False
1030 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001031
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001032 def tearDown(self):
1033 subprocess._has_poll = True
1034 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001035
1036
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001037@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1038 "_posixsubprocess extension module not found.")
1039class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
1040 def setUp(self):
1041 subprocess._posixsubprocess = None
1042 ProcessTestCase.setUp(self)
1043 POSIXProcessTestCase.setUp(self)
1044
1045 def tearDown(self):
1046 subprocess._posixsubprocess = sys.modules['_posixsubprocess']
1047 POSIXProcessTestCase.tearDown(self)
1048 ProcessTestCase.tearDown(self)
1049
1050
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001051class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001052 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001053 def test_eintr_retry_call(self):
1054 record_calls = []
1055 def fake_os_func(*args):
1056 record_calls.append(args)
1057 if len(record_calls) == 2:
1058 raise OSError(errno.EINTR, "fake interrupted system call")
1059 return tuple(reversed(args))
1060
1061 self.assertEqual((999, 256),
1062 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1063 self.assertEqual([(256, 999)], record_calls)
1064 # This time there will be an EINTR so it will loop once.
1065 self.assertEqual((666,),
1066 subprocess._eintr_retry_call(fake_os_func, 666))
1067 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1068
1069
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001070def test_main():
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001071 unit_tests = (ProcessTestCase,
1072 POSIXProcessTestCase,
1073 Win32ProcessTestCase,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001074 ProcessTestCasePOSIXPurePython,
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001075 CommandTests,
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001076 ProcessTestCaseNoPoll,
1077 HelperFunctionTests)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001078
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001079 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +00001080 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001081
1082if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +00001083 test_main()