blob: dff9012cdee0ace52ee9bbfb0c100f3f364ddc3b [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
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000012
13mswindows = (sys.platform == "win32")
14
15#
16# Depends on the following external programs: Python
17#
18
19if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000020 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
21 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000022else:
23 SETBINARY = ''
24
Florent Xiclunab1e94e82010-02-27 22:12:37 +000025
26try:
27 mkstemp = tempfile.mkstemp
28except AttributeError:
29 # tempfile.mkstemp is not available
30 def mkstemp():
31 """Replacement for mkstemp, calling mktemp."""
32 fname = tempfile.mktemp()
33 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
34
Tim Peters3761e8d2004-10-13 04:07:12 +000035
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000036class ProcessTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000037 def setUp(self):
38 # Try to minimize the number of children we have so this test
39 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000040 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000041
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000042 def tearDown(self):
43 for inst in subprocess._active:
44 inst.wait()
45 subprocess._cleanup()
46 self.assertFalse(subprocess._active, "subprocess._active not empty")
47
Florent Xiclunab1e94e82010-02-27 22:12:37 +000048 def assertStderrEqual(self, stderr, expected, msg=None):
49 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
50 # shutdown time. That frustrates tests trying to check stderr produced
51 # from a spawned Python process.
52 actual = re.sub("\[\d+ refs\]\r?\n?$", "", stderr.decode()).encode()
53 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000055 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000056 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000057 rc = subprocess.call([sys.executable, "-c",
58 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000059 self.assertEqual(rc, 47)
60
Peter Astrand454f7672005-01-01 09:36:35 +000061 def test_check_call_zero(self):
62 # check_call() function with zero return code
63 rc = subprocess.check_call([sys.executable, "-c",
64 "import sys; sys.exit(0)"])
65 self.assertEqual(rc, 0)
66
67 def test_check_call_nonzero(self):
68 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000069 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000070 subprocess.check_call([sys.executable, "-c",
71 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000072 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000073
Georg Brandlf9734072008-12-07 15:30:06 +000074 def test_check_output(self):
75 # check_output() function with zero return code
76 output = subprocess.check_output(
77 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000078 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000079
80 def test_check_output_nonzero(self):
81 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000082 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +000083 subprocess.check_output(
84 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000085 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +000086
87 def test_check_output_stderr(self):
88 # check_output() function stderr redirected to stdout
89 output = subprocess.check_output(
90 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
91 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +000092 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000093
94 def test_check_output_stdout_arg(self):
95 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +000096 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +000097 output = subprocess.check_output(
98 [sys.executable, "-c", "print('will not be run')"],
99 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000100 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000101 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000102
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000103 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000104 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000105 newenv = os.environ.copy()
106 newenv["FRUIT"] = "banana"
107 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000108 'import sys, os;'
109 'sys.exit(os.getenv("FRUIT")=="banana")'],
110 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000111 self.assertEqual(rc, 1)
112
113 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000114 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000115 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000116 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
117 p.wait()
118 self.assertEqual(p.stdin, None)
119
120 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000121 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000122 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000123 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000124 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000125 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000126 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000127 p.wait()
128 self.assertEqual(p.stdout, None)
129
130 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000131 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000132 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000133 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
134 p.wait()
135 self.assertEqual(p.stderr, None)
136
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000137 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000138 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000139 p = subprocess.Popen(["somethingyoudonthave", "-c",
140 "import sys; sys.exit(47)"],
141 executable=sys.executable, cwd=python_dir)
142 p.wait()
143 self.assertEqual(p.returncode, 47)
144
145 @unittest.skipIf(sysconfig.is_python_build(),
146 "need an installed Python. See #7774")
147 def test_executable_without_cwd(self):
148 # For a normal installation, it should work without 'cwd'
149 # argument. For test runs in the build directory, see #7774.
150 p = subprocess.Popen(["somethingyoudonthave", "-c",
151 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000152 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000153 p.wait()
154 self.assertEqual(p.returncode, 47)
155
156 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000157 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000158 p = subprocess.Popen([sys.executable, "-c",
159 'import sys; sys.exit(sys.stdin.read() == "pear")'],
160 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000161 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000162 p.stdin.close()
163 p.wait()
164 self.assertEqual(p.returncode, 1)
165
166 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000167 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000168 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000169 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000170 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000171 os.lseek(d, 0, 0)
172 p = subprocess.Popen([sys.executable, "-c",
173 'import sys; sys.exit(sys.stdin.read() == "pear")'],
174 stdin=d)
175 p.wait()
176 self.assertEqual(p.returncode, 1)
177
178 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000179 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000180 tf = tempfile.TemporaryFile()
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000181 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000182 tf.seek(0)
183 p = subprocess.Popen([sys.executable, "-c",
184 'import sys; sys.exit(sys.stdin.read() == "pear")'],
185 stdin=tf)
186 p.wait()
187 self.assertEqual(p.returncode, 1)
188
189 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000190 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000191 p = subprocess.Popen([sys.executable, "-c",
192 'import sys; sys.stdout.write("orange")'],
193 stdout=subprocess.PIPE)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000194 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000195
196 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000197 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000198 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000199 d = tf.fileno()
200 p = subprocess.Popen([sys.executable, "-c",
201 'import sys; sys.stdout.write("orange")'],
202 stdout=d)
203 p.wait()
204 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000205 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000206
207 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000208 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000209 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210 p = subprocess.Popen([sys.executable, "-c",
211 'import sys; sys.stdout.write("orange")'],
212 stdout=tf)
213 p.wait()
214 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000215 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000216
217 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000218 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000219 p = subprocess.Popen([sys.executable, "-c",
220 'import sys; sys.stderr.write("strawberry")'],
221 stderr=subprocess.PIPE)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000222 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223
224 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000225 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000226 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 d = tf.fileno()
228 p = subprocess.Popen([sys.executable, "-c",
229 'import sys; sys.stderr.write("strawberry")'],
230 stderr=d)
231 p.wait()
232 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000233 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000234
235 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000236 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000237 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238 p = subprocess.Popen([sys.executable, "-c",
239 'import sys; sys.stderr.write("strawberry")'],
240 stderr=tf)
241 p.wait()
242 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000243 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244
245 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000246 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000248 'import sys;'
249 'sys.stdout.write("apple");'
250 'sys.stdout.flush();'
251 'sys.stderr.write("orange")'],
252 stdout=subprocess.PIPE,
253 stderr=subprocess.STDOUT)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000254 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000255
256 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000257 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000258 tf = tempfile.TemporaryFile()
259 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000260 'import sys;'
261 'sys.stdout.write("apple");'
262 'sys.stdout.flush();'
263 'sys.stderr.write("orange")'],
264 stdout=tf,
265 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000266 p.wait()
267 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000268 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269
Thomas Wouters89f507f2006-12-13 04:49:30 +0000270 def test_stdout_filedes_of_stdout(self):
271 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000272 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000273 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000274 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000275
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000277 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000278 # We cannot use os.path.realpath to canonicalize the path,
279 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
280 cwd = os.getcwd()
281 os.chdir(tmpdir)
282 tmpdir = os.getcwd()
283 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000284 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000285 'import sys,os;'
286 'sys.stdout.write(os.getcwd())'],
287 stdout=subprocess.PIPE,
288 cwd=tmpdir)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000289 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000290 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
291 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000292
293 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294 newenv = os.environ.copy()
295 newenv["FRUIT"] = "orange"
296 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000297 'import sys,os;'
298 'sys.stdout.write(os.getenv("FRUIT"))'],
299 stdout=subprocess.PIPE,
300 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000301 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000302
Peter Astrandcbac93c2005-03-03 20:24:28 +0000303 def test_communicate_stdin(self):
304 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000305 'import sys;'
306 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000307 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000308 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000309 self.assertEqual(p.returncode, 1)
310
311 def test_communicate_stdout(self):
312 p = subprocess.Popen([sys.executable, "-c",
313 'import sys; sys.stdout.write("pineapple")'],
314 stdout=subprocess.PIPE)
315 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000316 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000317 self.assertEqual(stderr, None)
318
319 def test_communicate_stderr(self):
320 p = subprocess.Popen([sys.executable, "-c",
321 'import sys; sys.stderr.write("pineapple")'],
322 stderr=subprocess.PIPE)
323 (stdout, stderr) = p.communicate()
324 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000325 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000326
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000327 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000328 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000329 'import sys,os;'
330 'sys.stderr.write("pineapple");'
331 'sys.stdout.write(sys.stdin.read())'],
332 stdin=subprocess.PIPE,
333 stdout=subprocess.PIPE,
334 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000335 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000336 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000337 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000338
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000339 # This test is Linux specific for simplicity to at least have
340 # some coverage. It is not a platform specific bug.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000341 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
342 "Linux specific")
343 # Test for the fd leak reported in http://bugs.python.org/issue2791.
344 def test_communicate_pipe_fd_leak(self):
345 fd_directory = '/proc/%d/fd' % os.getpid()
346 num_fds_before_popen = len(os.listdir(fd_directory))
347 p = subprocess.Popen([sys.executable, "-c", "print()"],
348 stdout=subprocess.PIPE)
349 p.communicate()
350 num_fds_after_communicate = len(os.listdir(fd_directory))
351 del p
352 num_fds_after_destruction = len(os.listdir(fd_directory))
353 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
354 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000355
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000356 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000357 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000358 p = subprocess.Popen([sys.executable, "-c",
359 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000360 (stdout, stderr) = p.communicate()
361 self.assertEqual(stdout, None)
362 self.assertEqual(stderr, None)
363
364 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000365 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000366 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000367 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000368 x, y = os.pipe()
369 if mswindows:
370 pipe_buf = 512
371 else:
372 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
373 os.close(x)
374 os.close(y)
375 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000376 'import sys,os;'
377 'sys.stdout.write(sys.stdin.read(47));'
378 'sys.stderr.write("xyz"*%d);'
379 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
380 stdin=subprocess.PIPE,
381 stdout=subprocess.PIPE,
382 stderr=subprocess.PIPE)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000383 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000384 (stdout, stderr) = p.communicate(string_to_write)
385 self.assertEqual(stdout, string_to_write)
386
387 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000388 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000389 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000390 'import sys,os;'
391 'sys.stdout.write(sys.stdin.read())'],
392 stdin=subprocess.PIPE,
393 stdout=subprocess.PIPE,
394 stderr=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000395 p.stdin.write(b"banana")
396 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000397 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000398 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000399
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000400 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000401 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000402 'import sys,os;' + SETBINARY +
403 'sys.stdout.write("line1\\n");'
404 'sys.stdout.flush();'
405 'sys.stdout.write("line2\\n");'
406 'sys.stdout.flush();'
407 'sys.stdout.write("line3\\r\\n");'
408 'sys.stdout.flush();'
409 'sys.stdout.write("line4\\r");'
410 'sys.stdout.flush();'
411 'sys.stdout.write("\\nline5");'
412 'sys.stdout.flush();'
413 'sys.stdout.write("\\nline6");'],
414 stdout=subprocess.PIPE,
415 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000417 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000418
419 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000420 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000421 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000422 'import sys,os;' + SETBINARY +
423 'sys.stdout.write("line1\\n");'
424 'sys.stdout.flush();'
425 'sys.stdout.write("line2\\n");'
426 'sys.stdout.flush();'
427 'sys.stdout.write("line3\\r\\n");'
428 'sys.stdout.flush();'
429 'sys.stdout.write("line4\\r");'
430 'sys.stdout.flush();'
431 'sys.stdout.write("\\nline5");'
432 'sys.stdout.flush();'
433 'sys.stdout.write("\\nline6");'],
434 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
435 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000436 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000437 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438
439 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000440 # Make sure we leak no resources
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000441 if (not hasattr(support, "is_resource_enabled") or
442 support.is_resource_enabled("subprocess") and not mswindows):
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000443 max_handles = 1026 # too much for most UNIX systems
444 else:
Tim Peterseba28be2005-03-28 01:08:02 +0000445 max_handles = 65
Fredrik Lundh9e29fc52004-10-13 07:54:54 +0000446 for i in range(max_handles):
Tim Peters3b01a702004-10-12 22:19:32 +0000447 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000448 "import sys;"
449 "sys.stdout.write(sys.stdin.read())"],
450 stdin=subprocess.PIPE,
451 stdout=subprocess.PIPE,
452 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000453 data = p.communicate(b"lime")[0]
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000454 self.assertEqual(data, b"lime")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000455
456
457 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000458 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
459 '"a b c" d e')
460 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
461 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000462 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
463 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
465 'a\\\\\\b "de fg" h')
466 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
467 'a\\\\\\"b c d')
468 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
469 '"a\\\\b c" d e')
470 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
471 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000472 self.assertEqual(subprocess.list2cmdline(['ab', '']),
473 'ab ""')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000474 self.assertEqual(subprocess.list2cmdline(['echo', 'foo|bar']),
475 'echo "foo|bar"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476
477
478 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000480 "-c", "import time; time.sleep(1)"])
481 count = 0
482 while p.poll() is None:
483 time.sleep(0.1)
484 count += 1
485 # We expect that the poll loop probably went around about 10 times,
486 # but, based on system scheduling we can't control, it's possible
487 # poll() never returned None. It "should be" very rare that it
488 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000489 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490 # Subsequent invocations should just return the returncode
491 self.assertEqual(p.poll(), 0)
492
493
494 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495 p = subprocess.Popen([sys.executable,
496 "-c", "import time; time.sleep(2)"])
497 self.assertEqual(p.wait(), 0)
498 # Subsequent invocations should just return the returncode
499 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000500
Peter Astrand738131d2004-11-30 21:04:45 +0000501
502 def test_invalid_bufsize(self):
503 # an invalid type of the bufsize argument should raise
504 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000505 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000506 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000507
Guido van Rossum46a05a72007-06-07 21:56:45 +0000508 def test_bufsize_is_none(self):
509 # bufsize=None should be the same as bufsize=0.
510 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
511 self.assertEqual(p.wait(), 0)
512 # Again with keyword arg
513 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
514 self.assertEqual(p.wait(), 0)
515
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000516 def test_leaking_fds_on_error(self):
517 # see bug #5179: Popen leaks file descriptors to PIPEs if
518 # the child fails to execute; this will eventually exhaust
519 # the maximum number of open fds. 1024 seems a very common
520 # value for that limit, but Windows has 2048, so we loop
521 # 1024 times (each call leaked two fds).
522 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000523 # Windows raises IOError. Others raise OSError.
524 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000525 subprocess.Popen(['nonexisting_i_hope'],
526 stdout=subprocess.PIPE,
527 stderr=subprocess.PIPE)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000528 if c.exception.errno != 2: # ignore "no such file"
529 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000530
Tim Peterse718f612004-10-12 21:51:32 +0000531
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000532# context manager
533class _SuppressCoreFiles(object):
534 """Try to prevent core files from being created."""
535 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000536
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000537 def __enter__(self):
538 """Try to save previous ulimit, then set it to (0, 0)."""
539 try:
540 import resource
541 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
542 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
543 except (ImportError, ValueError, resource.error):
544 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000545
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000546 def __exit__(self, *args):
547 """Return core file behavior to default."""
548 if self.old_limit is None:
549 return
550 try:
551 import resource
552 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
553 except (ImportError, ValueError, resource.error):
554 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000555
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000556
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000557@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000558class POSIXProcessTestCase(unittest.TestCase):
559 def setUp(self):
560 # Try to minimize the number of children we have so this test
561 # doesn't crash on some buildbots (Alphas in particular).
562 support.reap_children()
563
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000564 def tearDown(self):
565 for inst in subprocess._active:
566 inst.wait()
567 subprocess._cleanup()
568 self.assertFalse(subprocess._active, "subprocess._active not empty")
569
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000570 def test_exceptions(self):
571 # caught & re-raised exceptions
572 with self.assertRaises(OSError) as c:
573 p = subprocess.Popen([sys.executable, "-c", ""],
574 cwd="/this/path/does/not/exist")
575 # The attribute child_traceback should contain "os.chdir" somewhere.
576 self.assertIn("os.chdir", c.exception.child_traceback)
577
578 def test_run_abort(self):
579 # returncode handles signal termination
580 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000581 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000582 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000583 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000584 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000585
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000586 def test_preexec(self):
587 # preexec function
588 p = subprocess.Popen([sys.executable, "-c",
589 'import sys,os;'
590 'sys.stdout.write(os.getenv("FRUIT"))'],
591 stdout=subprocess.PIPE,
592 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
593 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000594
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000595 def test_args_string(self):
596 # args is a string
597 fd, fname = mkstemp()
598 # reopen in text mode
599 with open(fd, "w") as fobj:
600 fobj.write("#!/bin/sh\n")
601 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
602 sys.executable)
603 os.chmod(fname, 0o700)
604 p = subprocess.Popen(fname)
605 p.wait()
606 os.remove(fname)
607 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000608
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000609 def test_invalid_args(self):
610 # invalid arguments should raise ValueError
611 self.assertRaises(ValueError, subprocess.call,
612 [sys.executable, "-c",
613 "import sys; sys.exit(47)"],
614 startupinfo=47)
615 self.assertRaises(ValueError, subprocess.call,
616 [sys.executable, "-c",
617 "import sys; sys.exit(47)"],
618 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000620 def test_shell_sequence(self):
621 # Run command through the shell (sequence)
622 newenv = os.environ.copy()
623 newenv["FRUIT"] = "apple"
624 p = subprocess.Popen(["echo $FRUIT"], shell=1,
625 stdout=subprocess.PIPE,
626 env=newenv)
627 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000628
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000629 def test_shell_string(self):
630 # Run command through the shell (string)
631 newenv = os.environ.copy()
632 newenv["FRUIT"] = "apple"
633 p = subprocess.Popen("echo $FRUIT", shell=1,
634 stdout=subprocess.PIPE,
635 env=newenv)
636 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000637
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000638 def test_call_string(self):
639 # call() function with string argument on UNIX
640 fd, fname = mkstemp()
641 # reopen in text mode
642 with open(fd, "w") as fobj:
643 fobj.write("#!/bin/sh\n")
644 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
645 sys.executable)
646 os.chmod(fname, 0o700)
647 rc = subprocess.call(fname)
648 os.remove(fname)
649 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000650
Florent Xicluna4886d242010-03-08 13:27:26 +0000651 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000652 # Do not inherit file handles from the parent.
653 # It should fix failures on some platforms.
654 p = subprocess.Popen([sys.executable, "-c", "input()"], close_fds=True,
Florent Xicluna4886d242010-03-08 13:27:26 +0000655 stdin=subprocess.PIPE)
Christian Heimesa342c012008-04-20 21:01:16 +0000656
Florent Xicluna4886d242010-03-08 13:27:26 +0000657 # Let the process initialize (Issue #3137)
Florent Xicluna129226d2010-03-05 00:52:00 +0000658 time.sleep(0.1)
Florent Xicluna4886d242010-03-08 13:27:26 +0000659 # The process should not terminate prematurely
Florent Xiclunab8f22b12010-03-05 01:18:04 +0000660 self.assertIsNone(p.poll())
Florent Xicluna4886d242010-03-08 13:27:26 +0000661 # Retry if the process do not receive the signal.
Florent Xicluna129226d2010-03-05 00:52:00 +0000662 count, maxcount = 0, 3
Florent Xicluna129226d2010-03-05 00:52:00 +0000663 while count < maxcount and p.poll() is None:
Florent Xicluna4886d242010-03-08 13:27:26 +0000664 getattr(p, method)(*args)
Florent Xicluna129226d2010-03-05 00:52:00 +0000665 time.sleep(0.1)
666 count += 1
Florent Xicluna4886d242010-03-08 13:27:26 +0000667
668 self.assertIsNotNone(p.poll(), "the subprocess did not terminate")
Florent Xiclunab8f22b12010-03-05 01:18:04 +0000669 if count > 1:
Florent Xicluna4886d242010-03-08 13:27:26 +0000670 print("p.{}{} succeeded after "
671 "{} attempts".format(method, args, count), file=sys.stderr)
672 return p
673
674 def test_send_signal(self):
675 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000676 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000677
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000678 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000679 p = self._kill_process('kill')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000680 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000681
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000682 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000683 p = self._kill_process('terminate')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000684 self.assertEqual(p.wait(), -signal.SIGTERM)
685
686
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000687@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000688class Win32ProcessTestCase(unittest.TestCase):
689 def setUp(self):
690 # Try to minimize the number of children we have so this test
691 # doesn't crash on some buildbots (Alphas in particular).
692 support.reap_children()
693
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000694 def tearDown(self):
695 for inst in subprocess._active:
696 inst.wait()
697 subprocess._cleanup()
698 self.assertFalse(subprocess._active, "subprocess._active not empty")
699
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000700 def test_startupinfo(self):
701 # startupinfo argument
702 # We uses hardcoded constants, because we do not want to
703 # depend on win32all.
704 STARTF_USESHOWWINDOW = 1
705 SW_MAXIMIZE = 3
706 startupinfo = subprocess.STARTUPINFO()
707 startupinfo.dwFlags = STARTF_USESHOWWINDOW
708 startupinfo.wShowWindow = SW_MAXIMIZE
709 # Since Python is a console process, it won't be affected
710 # by wShowWindow, but the argument should be silently
711 # ignored
712 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000713 startupinfo=startupinfo)
714
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000715 def test_creationflags(self):
716 # creationflags argument
717 CREATE_NEW_CONSOLE = 16
718 sys.stderr.write(" a DOS box should flash briefly ...\n")
719 subprocess.call(sys.executable +
720 ' -c "import time; time.sleep(0.25)"',
721 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000722
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000723 def test_invalid_args(self):
724 # invalid arguments should raise ValueError
725 self.assertRaises(ValueError, subprocess.call,
726 [sys.executable, "-c",
727 "import sys; sys.exit(47)"],
728 preexec_fn=lambda: 1)
729 self.assertRaises(ValueError, subprocess.call,
730 [sys.executable, "-c",
731 "import sys; sys.exit(47)"],
732 stdout=subprocess.PIPE,
733 close_fds=True)
734
735 def test_close_fds(self):
736 # close file descriptors
737 rc = subprocess.call([sys.executable, "-c",
738 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000739 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000740 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000741
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000742 def test_shell_sequence(self):
743 # Run command through the shell (sequence)
744 newenv = os.environ.copy()
745 newenv["FRUIT"] = "physalis"
746 p = subprocess.Popen(["set"], shell=1,
747 stdout=subprocess.PIPE,
748 env=newenv)
749 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +0000750
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000751 def test_shell_string(self):
752 # Run command through the shell (string)
753 newenv = os.environ.copy()
754 newenv["FRUIT"] = "physalis"
755 p = subprocess.Popen("set", shell=1,
756 stdout=subprocess.PIPE,
757 env=newenv)
758 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000759
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000760 def test_call_string(self):
761 # call() function with string argument on Windows
762 rc = subprocess.call(sys.executable +
763 ' -c "import sys; sys.exit(47)"')
764 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000765
Florent Xicluna4886d242010-03-08 13:27:26 +0000766 def _kill_process(self, method, *args):
767 # Some win32 buildbot raises EOFError if stdin is inherited
768 p = subprocess.Popen([sys.executable, "-c", "input()"],
769 stdin=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000770
Florent Xicluna4886d242010-03-08 13:27:26 +0000771 # Let the process initialize (Issue #3137)
772 time.sleep(0.1)
773 # The process should not terminate prematurely
774 self.assertIsNone(p.poll())
775 # Retry if the process do not receive the signal.
776 count, maxcount = 0, 3
777 while count < maxcount and p.poll() is None:
778 getattr(p, method)(*args)
779 time.sleep(0.1)
780 count += 1
781
782 returncode = p.poll()
783 self.assertIsNotNone(returncode, "the subprocess did not terminate")
784 if count > 1:
785 print("p.{}{} succeeded after "
786 "{} attempts".format(method, args, count), file=sys.stderr)
787 self.assertEqual(p.wait(), returncode)
788 self.assertNotEqual(returncode, 0)
789
790 def test_send_signal(self):
791 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +0000792
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000793 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000794 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +0000795
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000796 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000797 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +0000798
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000799
Brett Cannona23810f2008-05-26 19:04:21 +0000800# The module says:
801# "NB This only works (and is only relevant) for UNIX."
802#
803# Actually, getoutput should work on any platform with an os.popen, but
804# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000805@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000806class CommandTests(unittest.TestCase):
807 def test_getoutput(self):
808 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
809 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
810 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +0000811
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000812 # we use mkdtemp in the next line to create an empty directory
813 # under our exclusive control; from that, we can invent a pathname
814 # that we _know_ won't exist. This is guaranteed to fail.
815 dir = None
816 try:
817 dir = tempfile.mkdtemp()
818 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +0000819
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000820 status, output = subprocess.getstatusoutput('cat ' + name)
821 self.assertNotEqual(status, 0)
822 finally:
823 if dir is not None:
824 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +0000825
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000826
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000827@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
828 "poll system call not supported")
829class ProcessTestCaseNoPoll(ProcessTestCase):
830 def setUp(self):
831 subprocess._has_poll = False
832 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000833
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000834 def tearDown(self):
835 subprocess._has_poll = True
836 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000837
838
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000839class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +0000840 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000841 def test_eintr_retry_call(self):
842 record_calls = []
843 def fake_os_func(*args):
844 record_calls.append(args)
845 if len(record_calls) == 2:
846 raise OSError(errno.EINTR, "fake interrupted system call")
847 return tuple(reversed(args))
848
849 self.assertEqual((999, 256),
850 subprocess._eintr_retry_call(fake_os_func, 256, 999))
851 self.assertEqual([(256, 999)], record_calls)
852 # This time there will be an EINTR so it will loop once.
853 self.assertEqual((666,),
854 subprocess._eintr_retry_call(fake_os_func, 666))
855 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
856
857
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858def test_main():
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000859 unit_tests = (ProcessTestCase,
860 POSIXProcessTestCase,
861 Win32ProcessTestCase,
862 CommandTests,
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000863 ProcessTestCaseNoPoll,
864 HelperFunctionTests)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000865
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000866 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +0000867 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000868
869if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +0000870 test_main()