blob: d58108157ec762bf9b6319f1db8763054965d907 [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):
138 python_dir = os.path.dirname(os.path.realpath(sys.executable))
139 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 Xiclunab1e94e82010-02-27 22:12:37 +0000651 def test_send_signal(self):
652 p = subprocess.Popen([sys.executable, "-c", "input()"])
Christian Heimesa342c012008-04-20 21:01:16 +0000653
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000654 # Let the process initialize correctly (Issue #3137)
Florent Xicluna129226d2010-03-05 00:52:00 +0000655 time.sleep(0.1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000656 self.assertIs(p.poll(), None)
Florent Xicluna129226d2010-03-05 00:52:00 +0000657 count, maxcount = 0, 3
658 # Retry if the process do not receive the SIGINT signal.
659 while count < maxcount and p.poll() is None:
660 p.send_signal(signal.SIGINT)
661 time.sleep(0.1)
662 count += 1
663 if p.poll() is None:
664 raise support.TestFailed("the subprocess did not receive "
665 "the signal SIGINT")
666 elif count > 1:
667 print("p.send_signal(SIGINT) succeeded "
668 "after {} attempts".format(count), file=sys.stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000669 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000670
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000671 def test_kill(self):
672 p = subprocess.Popen([sys.executable, "-c", "input()"])
Christian Heimesa342c012008-04-20 21:01:16 +0000673
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000674 self.assertIs(p.poll(), None)
675 p.kill()
676 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000677
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000678 def test_terminate(self):
679 p = subprocess.Popen([sys.executable, "-c", "input()"])
680
681 self.assertIs(p.poll(), None)
682 p.terminate()
683 self.assertEqual(p.wait(), -signal.SIGTERM)
684
685
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000686@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000687class Win32ProcessTestCase(unittest.TestCase):
688 def setUp(self):
689 # Try to minimize the number of children we have so this test
690 # doesn't crash on some buildbots (Alphas in particular).
691 support.reap_children()
692
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000693 def tearDown(self):
694 for inst in subprocess._active:
695 inst.wait()
696 subprocess._cleanup()
697 self.assertFalse(subprocess._active, "subprocess._active not empty")
698
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000699 def test_startupinfo(self):
700 # startupinfo argument
701 # We uses hardcoded constants, because we do not want to
702 # depend on win32all.
703 STARTF_USESHOWWINDOW = 1
704 SW_MAXIMIZE = 3
705 startupinfo = subprocess.STARTUPINFO()
706 startupinfo.dwFlags = STARTF_USESHOWWINDOW
707 startupinfo.wShowWindow = SW_MAXIMIZE
708 # Since Python is a console process, it won't be affected
709 # by wShowWindow, but the argument should be silently
710 # ignored
711 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000712 startupinfo=startupinfo)
713
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000714 def test_creationflags(self):
715 # creationflags argument
716 CREATE_NEW_CONSOLE = 16
717 sys.stderr.write(" a DOS box should flash briefly ...\n")
718 subprocess.call(sys.executable +
719 ' -c "import time; time.sleep(0.25)"',
720 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000721
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000722 def test_invalid_args(self):
723 # invalid arguments should raise ValueError
724 self.assertRaises(ValueError, subprocess.call,
725 [sys.executable, "-c",
726 "import sys; sys.exit(47)"],
727 preexec_fn=lambda: 1)
728 self.assertRaises(ValueError, subprocess.call,
729 [sys.executable, "-c",
730 "import sys; sys.exit(47)"],
731 stdout=subprocess.PIPE,
732 close_fds=True)
733
734 def test_close_fds(self):
735 # close file descriptors
736 rc = subprocess.call([sys.executable, "-c",
737 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000739 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000740
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000741 def test_shell_sequence(self):
742 # Run command through the shell (sequence)
743 newenv = os.environ.copy()
744 newenv["FRUIT"] = "physalis"
745 p = subprocess.Popen(["set"], shell=1,
746 stdout=subprocess.PIPE,
747 env=newenv)
748 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +0000749
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000750 def test_shell_string(self):
751 # Run command through the shell (string)
752 newenv = os.environ.copy()
753 newenv["FRUIT"] = "physalis"
754 p = subprocess.Popen("set", shell=1,
755 stdout=subprocess.PIPE,
756 env=newenv)
757 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000758
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000759 def test_call_string(self):
760 # call() function with string argument on Windows
761 rc = subprocess.call(sys.executable +
762 ' -c "import sys; sys.exit(47)"')
763 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000765 def test_send_signal(self):
766 p = subprocess.Popen([sys.executable, "-c", "input()"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000767
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000768 self.assertIs(p.poll(), None)
769 p.send_signal(signal.SIGTERM)
770 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000771
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000772 def test_kill(self):
773 p = subprocess.Popen([sys.executable, "-c", "input()"])
Christian Heimesa342c012008-04-20 21:01:16 +0000774
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000775 self.assertIs(p.poll(), None)
776 p.kill()
777 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000778
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000779 def test_terminate(self):
780 p = subprocess.Popen([sys.executable, "-c", "input()"])
Christian Heimesa342c012008-04-20 21:01:16 +0000781
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000782 self.assertIs(p.poll(), None)
783 p.terminate()
784 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000785
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000786
Brett Cannona23810f2008-05-26 19:04:21 +0000787# The module says:
788# "NB This only works (and is only relevant) for UNIX."
789#
790# Actually, getoutput should work on any platform with an os.popen, but
791# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000792@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000793class CommandTests(unittest.TestCase):
794 def test_getoutput(self):
795 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
796 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
797 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +0000798
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000799 # we use mkdtemp in the next line to create an empty directory
800 # under our exclusive control; from that, we can invent a pathname
801 # that we _know_ won't exist. This is guaranteed to fail.
802 dir = None
803 try:
804 dir = tempfile.mkdtemp()
805 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +0000806
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000807 status, output = subprocess.getstatusoutput('cat ' + name)
808 self.assertNotEqual(status, 0)
809 finally:
810 if dir is not None:
811 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +0000812
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000813
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000814@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
815 "poll system call not supported")
816class ProcessTestCaseNoPoll(ProcessTestCase):
817 def setUp(self):
818 subprocess._has_poll = False
819 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000820
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000821 def tearDown(self):
822 subprocess._has_poll = True
823 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000824
825
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000826class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +0000827 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000828 def test_eintr_retry_call(self):
829 record_calls = []
830 def fake_os_func(*args):
831 record_calls.append(args)
832 if len(record_calls) == 2:
833 raise OSError(errno.EINTR, "fake interrupted system call")
834 return tuple(reversed(args))
835
836 self.assertEqual((999, 256),
837 subprocess._eintr_retry_call(fake_os_func, 256, 999))
838 self.assertEqual([(256, 999)], record_calls)
839 # This time there will be an EINTR so it will loop once.
840 self.assertEqual((666,),
841 subprocess._eintr_retry_call(fake_os_func, 666))
842 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
843
844
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000845def test_main():
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000846 unit_tests = (ProcessTestCase,
847 POSIXProcessTestCase,
848 Win32ProcessTestCase,
849 CommandTests,
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000850 ProcessTestCaseNoPoll,
851 HelperFunctionTests)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000852
Florent Xicluna129226d2010-03-05 00:52:00 +0000853 unit_tests = (POSIXProcessTestCase,)
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000854 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +0000855 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000856
857if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +0000858 test_main()