blob: dc57c46b4569ca7325d305a77c0017f89783fc91 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
2from test import test_support
3import subprocess
4import sys
5import signal
6import os
Gregory P. Smithcce211f2010-03-01 00:05:08 +00007import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008import tempfile
9import time
Tim Peters3761e8d2004-10-13 04:07:12 +000010import re
Ezio Melotti8f6a2872010-02-10 21:40:33 +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 Xicluna98e3fc32010-02-27 19:20:50 +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):
Neal Norwitzb15ac312006-06-29 04:10:08 +000037 def setUp(self):
Tim Peters38ff36c2006-06-30 06:18:39 +000038 # Try to minimize the number of children we have so this test
39 # doesn't crash on some buildbots (Alphas in particular).
Florent Xicluna98e3fc32010-02-27 19:20:50 +000040 test_support.reap_children()
Neal Norwitzb15ac312006-06-29 04:10:08 +000041
Florent Xiclunaab5e17f2010-03-04 21:31:58 +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 Xicluna98e3fc32010-02-27 19:20:50 +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(r"\[\d+ refs\]\r?\n?$", "", stderr)
53 self.assertEqual(actual, expected, msg)
Neal Norwitzb15ac312006-06-29 04:10:08 +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 Xicluna98e3fc32010-02-27 19:20:50 +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 Xicluna98e3fc32010-02-27 19:20:50 +000072 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000073
Gregory P. Smith26576802008-12-05 02:27:01 +000074 def test_check_output(self):
75 # check_output() function with zero return code
76 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +000077 [sys.executable, "-c", "print 'BDFL'"])
Ezio Melottiaa980582010-01-23 23:04:36 +000078 self.assertIn('BDFL', output)
Gregory P. Smith97f49f42008-12-04 20:21:09 +000079
Gregory P. Smith26576802008-12-05 02:27:01 +000080 def test_check_output_nonzero(self):
Gregory P. Smith97f49f42008-12-04 20:21:09 +000081 # check_call() function with non-zero return code
Florent Xicluna98e3fc32010-02-27 19:20:50 +000082 with self.assertRaises(subprocess.CalledProcessError) as c:
Gregory P. Smith26576802008-12-05 02:27:01 +000083 subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +000084 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xicluna98e3fc32010-02-27 19:20:50 +000085 self.assertEqual(c.exception.returncode, 5)
Gregory P. Smith97f49f42008-12-04 20:21:09 +000086
Gregory P. Smith26576802008-12-05 02:27:01 +000087 def test_check_output_stderr(self):
88 # check_output() function stderr redirected to stdout
89 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +000090 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
91 stderr=subprocess.STDOUT)
Ezio Melottiaa980582010-01-23 23:04:36 +000092 self.assertIn('BDFL', output)
Gregory P. Smith97f49f42008-12-04 20:21:09 +000093
Gregory P. Smith26576802008-12-05 02:27:01 +000094 def test_check_output_stdout_arg(self):
95 # check_output() function stderr redirected to stdout
Florent Xicluna98e3fc32010-02-27 19:20:50 +000096 with self.assertRaises(ValueError) as c:
Gregory P. Smith26576802008-12-05 02:27:01 +000097 output = subprocess.check_output(
Gregory P. Smith97f49f42008-12-04 20:21:09 +000098 [sys.executable, "-c", "print 'will not be run'"],
99 stdout=sys.stdout)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000100 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000101 self.assertIn('stdout', c.exception.args[0])
Gregory P. Smith97f49f42008-12-04 20:21:09 +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",
Florent Xiclunabab22a72010-03-04 19:40:48 +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
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000115 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
116 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",
Tim Peters4052fe52004-10-13 03:29:54 +0000123 'print " this bit of output is from a '
124 'test of stdout in a different '
125 'process ..."'],
126 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
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000132 p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
133 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
134 p.wait()
135 self.assertEqual(p.stderr, None)
136
Ezio Melotti8f6a2872010-02-10 21:40:33 +0000137 def test_executable_with_cwd(self):
Florent Xicluna63763702010-03-11 01:50:48 +0000138 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti8f6a2872010-02-10 21:40:33 +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)
161 p.stdin.write("pear")
162 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()
170 os.write(d, "pear")
171 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()
181 tf.write("pear")
182 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)
194 self.assertEqual(p.stdout.read(), "orange")
195
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)
205 self.assertEqual(os.read(d, 1024), "orange")
206
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)
215 self.assertEqual(tf.read(), "orange")
216
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 Xicluna98e3fc32010-02-27 19:20:50 +0000222 self.assertStderrEqual(p.stderr.read(), "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 Xicluna98e3fc32010-02-27 19:20:50 +0000233 self.assertStderrEqual(os.read(d, 1024), "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 Xicluna98e3fc32010-02-27 19:20:50 +0000243 self.assertStderrEqual(tf.read(), "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",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000248 'import sys;'
249 'sys.stdout.write("apple");'
250 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251 'sys.stderr.write("orange")'],
252 stdout=subprocess.PIPE,
253 stderr=subprocess.STDOUT)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000254 self.assertStderrEqual(p.stdout.read(), "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",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000260 'import sys;'
261 'sys.stdout.write("apple");'
262 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263 'sys.stderr.write("orange")'],
264 stdout=tf,
265 stderr=tf)
266 p.wait()
267 tf.seek(0)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000268 self.assertStderrEqual(tf.read(), "appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269
Gustavo Niemeyerc36bede2006-09-07 00:48:33 +0000270 def test_stdout_filedes_of_stdout(self):
271 # stdout is set to 1 (#1531862).
272 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), '.\n'))"
273 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000274 self.assertEqual(rc, 2)
Gustavo Niemeyerc36bede2006-09-07 00:48:33 +0000275
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276 def test_cwd(self):
Guido van Rossume9a0e882007-12-20 17:28:10 +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",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000285 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000286 'sys.stdout.write(os.getcwd())'],
287 stdout=subprocess.PIPE,
288 cwd=tmpdir)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000289 normcase = os.path.normcase
290 self.assertEqual(normcase(p.stdout.read()), normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291
292 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293 newenv = os.environ.copy()
294 newenv["FRUIT"] = "orange"
295 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000296 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000297 'sys.stdout.write(os.getenv("FRUIT"))'],
298 stdout=subprocess.PIPE,
299 env=newenv)
300 self.assertEqual(p.stdout.read(), "orange")
301
Peter Astrandcbac93c2005-03-03 20:24:28 +0000302 def test_communicate_stdin(self):
303 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000304 'import sys;'
305 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000306 stdin=subprocess.PIPE)
307 p.communicate("pear")
308 self.assertEqual(p.returncode, 1)
309
310 def test_communicate_stdout(self):
311 p = subprocess.Popen([sys.executable, "-c",
312 'import sys; sys.stdout.write("pineapple")'],
313 stdout=subprocess.PIPE)
314 (stdout, stderr) = p.communicate()
315 self.assertEqual(stdout, "pineapple")
316 self.assertEqual(stderr, None)
317
318 def test_communicate_stderr(self):
319 p = subprocess.Popen([sys.executable, "-c",
320 'import sys; sys.stderr.write("pineapple")'],
321 stderr=subprocess.PIPE)
322 (stdout, stderr) = p.communicate()
323 self.assertEqual(stdout, None)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000324 self.assertStderrEqual(stderr, "pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000325
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000326 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000327 p = subprocess.Popen([sys.executable, "-c",
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000328 'import sys,os;'
329 'sys.stderr.write("pineapple");'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000330 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000331 stdin=subprocess.PIPE,
332 stdout=subprocess.PIPE,
333 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334 (stdout, stderr) = p.communicate("banana")
335 self.assertEqual(stdout, "banana")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000336 self.assertStderrEqual(stderr, "pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000337
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000338 # This test is Linux specific for simplicity to at least have
339 # some coverage. It is not a platform specific bug.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000340 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
341 "Linux specific")
342 # Test for the fd leak reported in http://bugs.python.org/issue2791.
343 def test_communicate_pipe_fd_leak(self):
344 fd_directory = '/proc/%d/fd' % os.getpid()
345 num_fds_before_popen = len(os.listdir(fd_directory))
346 p = subprocess.Popen([sys.executable, "-c", "print()"],
347 stdout=subprocess.PIPE)
348 p.communicate()
349 num_fds_after_communicate = len(os.listdir(fd_directory))
350 del p
351 num_fds_after_destruction = len(os.listdir(fd_directory))
352 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
353 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000354
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000355 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000356 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000357 p = subprocess.Popen([sys.executable, "-c",
358 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000359 (stdout, stderr) = p.communicate()
360 self.assertEqual(stdout, None)
361 self.assertEqual(stderr, None)
362
363 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000364 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000365 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000366 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000367 x, y = os.pipe()
368 if mswindows:
369 pipe_buf = 512
370 else:
371 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
372 os.close(x)
373 os.close(y)
374 p = subprocess.Popen([sys.executable, "-c",
Tim Peterse718f612004-10-12 21:51:32 +0000375 'import sys,os;'
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000376 'sys.stdout.write(sys.stdin.read(47));'
377 'sys.stderr.write("xyz"*%d);'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000378 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
Tim Peters3b01a702004-10-12 22:19:32 +0000379 stdin=subprocess.PIPE,
380 stdout=subprocess.PIPE,
381 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000382 string_to_write = "abc"*pipe_buf
383 (stdout, stderr) = p.communicate(string_to_write)
384 self.assertEqual(stdout, string_to_write)
385
386 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000387 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000388 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000389 'import sys,os;'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390 'sys.stdout.write(sys.stdin.read())'],
Tim Peters3b01a702004-10-12 22:19:32 +0000391 stdin=subprocess.PIPE,
392 stdout=subprocess.PIPE,
393 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000394 p.stdin.write("banana")
395 (stdout, stderr) = p.communicate("split")
396 self.assertEqual(stdout, "bananasplit")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000397 self.assertStderrEqual(stderr, "")
Tim Peterse718f612004-10-12 21:51:32 +0000398
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000399 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000400 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000401 'import sys,os;' + SETBINARY +
402 'sys.stdout.write("line1\\n");'
403 'sys.stdout.flush();'
404 'sys.stdout.write("line2\\r");'
405 'sys.stdout.flush();'
406 'sys.stdout.write("line3\\r\\n");'
407 'sys.stdout.flush();'
408 'sys.stdout.write("line4\\r");'
409 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000410 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000411 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000412 'sys.stdout.write("\\nline6");'],
413 stdout=subprocess.PIPE,
414 universal_newlines=1)
415 stdout = p.stdout.read()
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000416 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000417 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000418 self.assertEqual(stdout,
419 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000420 else:
421 # Interpreter without universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000422 self.assertEqual(stdout,
423 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424
425 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000426 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000427 p = subprocess.Popen([sys.executable, "-c",
Tim Peters3b01a702004-10-12 22:19:32 +0000428 'import sys,os;' + SETBINARY +
429 'sys.stdout.write("line1\\n");'
430 'sys.stdout.flush();'
431 'sys.stdout.write("line2\\r");'
432 'sys.stdout.flush();'
433 'sys.stdout.write("line3\\r\\n");'
434 'sys.stdout.flush();'
435 'sys.stdout.write("line4\\r");'
436 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000437 'sys.stdout.write("\\nline5");'
Tim Peters3b01a702004-10-12 22:19:32 +0000438 'sys.stdout.flush();'
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000439 'sys.stdout.write("\\nline6");'],
440 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
441 universal_newlines=1)
442 (stdout, stderr) = p.communicate()
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000443 if hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 # Interpreter with universal newline support
Tim Peters3b01a702004-10-12 22:19:32 +0000445 self.assertEqual(stdout,
446 "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000447 else:
448 # Interpreter without universal newline support
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000449 self.assertEqual(stdout,
450 "line1\nline2\rline3\r\nline4\r\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000451
452 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000453 # Make sure we leak no resources
Peter Astrandd6b24302006-06-22 20:06:46 +0000454 if not hasattr(test_support, "is_resource_enabled") \
455 or test_support.is_resource_enabled("subprocess") and not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000456 max_handles = 1026 # too much for most UNIX systems
457 else:
Tim Peterseba28be2005-03-28 01:08:02 +0000458 max_handles = 65
Fredrik Lundh9e29fc52004-10-13 07:54:54 +0000459 for i in range(max_handles):
Tim Peters3b01a702004-10-12 22:19:32 +0000460 p = subprocess.Popen([sys.executable, "-c",
461 "import sys;sys.stdout.write(sys.stdin.read())"],
462 stdin=subprocess.PIPE,
463 stdout=subprocess.PIPE,
464 stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000465 data = p.communicate("lime")[0]
466 self.assertEqual(data, "lime")
467
468
469 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
471 '"a b c" d e')
472 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
473 'ab\\"c \\ d')
Gregory P. Smithe047e6d2008-01-19 20:49:02 +0000474 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
475 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
477 'a\\\\\\b "de fg" h')
478 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
479 'a\\\\\\"b c d')
480 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
481 '"a\\\\b c" d e')
482 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
483 '"a\\\\b\\ c" d e')
Peter Astrand10514a72007-01-13 22:35:35 +0000484 self.assertEqual(subprocess.list2cmdline(['ab', '']),
485 'ab ""')
Gregory P. Smith70eb2f92008-01-19 22:49:37 +0000486 self.assertEqual(subprocess.list2cmdline(['echo', 'foo|bar']),
487 'echo "foo|bar"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488
489
490 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000491 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000492 "-c", "import time; time.sleep(1)"])
493 count = 0
494 while p.poll() is None:
495 time.sleep(0.1)
496 count += 1
497 # We expect that the poll loop probably went around about 10 times,
498 # but, based on system scheduling we can't control, it's possible
499 # poll() never returned None. It "should be" very rare that it
500 # didn't go around at least twice.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000501 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502 # Subsequent invocations should just return the returncode
503 self.assertEqual(p.poll(), 0)
504
505
506 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507 p = subprocess.Popen([sys.executable,
508 "-c", "import time; time.sleep(2)"])
509 self.assertEqual(p.wait(), 0)
510 # Subsequent invocations should just return the returncode
511 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000512
Peter Astrand738131d2004-11-30 21:04:45 +0000513
514 def test_invalid_bufsize(self):
515 # an invalid type of the bufsize argument should raise
516 # TypeError.
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000517 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000518 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000519
Georg Brandlf3715d22009-02-14 17:01:36 +0000520 def test_leaking_fds_on_error(self):
521 # see bug #5179: Popen leaks file descriptors to PIPEs if
522 # the child fails to execute; this will eventually exhaust
523 # the maximum number of open fds. 1024 seems a very common
524 # value for that limit, but Windows has 2048, so we loop
525 # 1024 times (each call leaked two fds).
526 for i in range(1024):
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000527 # Windows raises IOError. Others raise OSError.
528 with self.assertRaises(EnvironmentError) as c:
Georg Brandlf3715d22009-02-14 17:01:36 +0000529 subprocess.Popen(['nonexisting_i_hope'],
530 stdout=subprocess.PIPE,
531 stderr=subprocess.PIPE)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000532 if c.exception.errno != 2: # ignore "no such file"
533 raise c.exception
Georg Brandlf3715d22009-02-14 17:01:36 +0000534
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000535
536# context manager
537class _SuppressCoreFiles(object):
538 """Try to prevent core files from being created."""
539 old_limit = None
540
541 def __enter__(self):
542 """Try to save previous ulimit, then set it to (0, 0)."""
543 try:
544 import resource
545 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
546 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
547 except (ImportError, ValueError, resource.error):
548 pass
549
550 def __exit__(self, *args):
551 """Return core file behavior to default."""
552 if self.old_limit is None:
553 return
554 try:
555 import resource
556 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
557 except (ImportError, ValueError, resource.error):
558 pass
559
560
Florent Xiclunabab22a72010-03-04 19:40:48 +0000561@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000562class POSIXProcessTestCase(unittest.TestCase):
563 def setUp(self):
564 # Try to minimize the number of children we have so this test
565 # doesn't crash on some buildbots (Alphas in particular).
566 test_support.reap_children()
567
Florent Xiclunaab5e17f2010-03-04 21:31:58 +0000568 def tearDown(self):
569 for inst in subprocess._active:
570 inst.wait()
571 subprocess._cleanup()
572 self.assertFalse(subprocess._active, "subprocess._active not empty")
573
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000574 def test_exceptions(self):
575 # caught & re-raised exceptions
576 with self.assertRaises(OSError) as c:
577 p = subprocess.Popen([sys.executable, "-c", ""],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578 cwd="/this/path/does/not/exist")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000579 # The attribute child_traceback should contain "os.chdir" somewhere.
580 self.assertIn("os.chdir", c.exception.child_traceback)
Tim Peterse718f612004-10-12 21:51:32 +0000581
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000582 def test_run_abort(self):
583 # returncode handles signal termination
584 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000585 p = subprocess.Popen([sys.executable, "-c",
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000586 "import os; os.abort()"])
587 p.wait()
588 self.assertEqual(-p.returncode, signal.SIGABRT)
589
590 def test_preexec(self):
591 # preexec function
592 p = subprocess.Popen([sys.executable, "-c",
593 "import sys, os;"
594 "sys.stdout.write(os.getenv('FRUIT'))"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000595 stdout=subprocess.PIPE,
596 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000597 self.assertEqual(p.stdout.read(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000599 def test_args_string(self):
600 # args is a string
601 f, fname = mkstemp()
602 os.write(f, "#!/bin/sh\n")
603 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
604 sys.executable)
605 os.close(f)
606 os.chmod(fname, 0o700)
607 p = subprocess.Popen(fname)
608 p.wait()
609 os.remove(fname)
610 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000611
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000612 def test_invalid_args(self):
613 # invalid arguments should raise ValueError
614 self.assertRaises(ValueError, subprocess.call,
615 [sys.executable, "-c",
616 "import sys; sys.exit(47)"],
617 startupinfo=47)
618 self.assertRaises(ValueError, subprocess.call,
619 [sys.executable, "-c",
620 "import sys; sys.exit(47)"],
621 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000622
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000623 def test_shell_sequence(self):
624 # Run command through the shell (sequence)
625 newenv = os.environ.copy()
626 newenv["FRUIT"] = "apple"
627 p = subprocess.Popen(["echo $FRUIT"], shell=1,
628 stdout=subprocess.PIPE,
629 env=newenv)
630 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000632 def test_shell_string(self):
633 # Run command through the shell (string)
634 newenv = os.environ.copy()
635 newenv["FRUIT"] = "apple"
636 p = subprocess.Popen("echo $FRUIT", shell=1,
637 stdout=subprocess.PIPE,
638 env=newenv)
639 self.assertEqual(p.stdout.read().strip(), "apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000640
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000641 def test_call_string(self):
642 # call() function with string argument on UNIX
643 f, fname = mkstemp()
644 os.write(f, "#!/bin/sh\n")
645 os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
646 sys.executable)
647 os.close(f)
648 os.chmod(fname, 0700)
649 rc = subprocess.call(fname)
650 os.remove(fname)
651 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000652
Florent Xiclunac0838642010-03-07 15:27:39 +0000653 def _kill_process(self, method, *args):
Florent Xiclunacecef392010-03-05 19:31:21 +0000654 # Do not inherit file handles from the parent.
655 # It should fix failures on some platforms.
656 p = subprocess.Popen([sys.executable, "-c", "input()"], close_fds=True,
Florent Xiclunac0838642010-03-07 15:27:39 +0000657 stdin=subprocess.PIPE)
Christian Heimese74c8f22008-04-19 02:23:57 +0000658
Florent Xiclunac0838642010-03-07 15:27:39 +0000659 # Let the process initialize (Issue #3137)
Florent Xicluna80e0e2d2010-03-05 00:47:40 +0000660 time.sleep(0.1)
Florent Xiclunac0838642010-03-07 15:27:39 +0000661 # The process should not terminate prematurely
Florent Xiclunad6935632010-03-05 01:05:55 +0000662 self.assertIsNone(p.poll())
Florent Xiclunac0838642010-03-07 15:27:39 +0000663 # Retry if the process do not receive the signal.
Florent Xicluna80e0e2d2010-03-05 00:47:40 +0000664 count, maxcount = 0, 3
Florent Xicluna80e0e2d2010-03-05 00:47:40 +0000665 while count < maxcount and p.poll() is None:
Florent Xiclunac0838642010-03-07 15:27:39 +0000666 getattr(p, method)(*args)
Florent Xicluna80e0e2d2010-03-05 00:47:40 +0000667 time.sleep(0.1)
668 count += 1
Florent Xiclunac0838642010-03-07 15:27:39 +0000669
670 self.assertIsNotNone(p.poll(), "the subprocess did not terminate")
Florent Xiclunad6935632010-03-05 01:05:55 +0000671 if count > 1:
Florent Xiclunac0838642010-03-07 15:27:39 +0000672 print >>sys.stderr, ("p.{}{} succeeded after "
673 "{} attempts".format(method, args, count))
674 return p
675
676 def test_send_signal(self):
677 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xicluna78fd5212010-02-27 21:15:27 +0000678 self.assertNotEqual(p.wait(), 0)
Christian Heimese74c8f22008-04-19 02:23:57 +0000679
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000680 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000681 p = self._kill_process('kill')
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000682 self.assertEqual(p.wait(), -signal.SIGKILL)
Christian Heimese74c8f22008-04-19 02:23:57 +0000683
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000684 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000685 p = self._kill_process('terminate')
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000686 self.assertEqual(p.wait(), -signal.SIGTERM)
Tim Peterse718f612004-10-12 21:51:32 +0000687
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000688
Florent Xiclunabab22a72010-03-04 19:40:48 +0000689@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000690class Win32ProcessTestCase(unittest.TestCase):
691 def setUp(self):
692 # Try to minimize the number of children we have so this test
693 # doesn't crash on some buildbots (Alphas in particular).
694 test_support.reap_children()
695
Florent Xiclunaab5e17f2010-03-04 21:31:58 +0000696 def tearDown(self):
697 for inst in subprocess._active:
698 inst.wait()
699 subprocess._cleanup()
700 self.assertFalse(subprocess._active, "subprocess._active not empty")
701
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000702 def test_startupinfo(self):
703 # startupinfo argument
704 # We uses hardcoded constants, because we do not want to
705 # depend on win32all.
706 STARTF_USESHOWWINDOW = 1
707 SW_MAXIMIZE = 3
708 startupinfo = subprocess.STARTUPINFO()
709 startupinfo.dwFlags = STARTF_USESHOWWINDOW
710 startupinfo.wShowWindow = SW_MAXIMIZE
711 # Since Python is a console process, it won't be affected
712 # by wShowWindow, but the argument should be silently
713 # ignored
714 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000715 startupinfo=startupinfo)
716
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000717 def test_creationflags(self):
718 # creationflags argument
719 CREATE_NEW_CONSOLE = 16
720 sys.stderr.write(" a DOS box should flash briefly ...\n")
721 subprocess.call(sys.executable +
722 ' -c "import time; time.sleep(0.25)"',
723 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000724
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000725 def test_invalid_args(self):
726 # invalid arguments should raise ValueError
727 self.assertRaises(ValueError, subprocess.call,
728 [sys.executable, "-c",
729 "import sys; sys.exit(47)"],
730 preexec_fn=lambda: 1)
731 self.assertRaises(ValueError, subprocess.call,
732 [sys.executable, "-c",
733 "import sys; sys.exit(47)"],
734 stdout=subprocess.PIPE,
735 close_fds=True)
736
737 def test_close_fds(self):
738 # close file descriptors
739 rc = subprocess.call([sys.executable, "-c",
740 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000741 close_fds=True)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000742 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000743
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000744 def test_shell_sequence(self):
745 # Run command through the shell (sequence)
746 newenv = os.environ.copy()
747 newenv["FRUIT"] = "physalis"
748 p = subprocess.Popen(["set"], shell=1,
749 stdout=subprocess.PIPE,
750 env=newenv)
751 self.assertIn("physalis", p.stdout.read())
Peter Astrand81a191b2007-05-26 22:18:20 +0000752
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000753 def test_shell_string(self):
754 # Run command through the shell (string)
755 newenv = os.environ.copy()
756 newenv["FRUIT"] = "physalis"
757 p = subprocess.Popen("set", shell=1,
758 stdout=subprocess.PIPE,
759 env=newenv)
760 self.assertIn("physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000761
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000762 def test_call_string(self):
763 # call() function with string argument on Windows
764 rc = subprocess.call(sys.executable +
765 ' -c "import sys; sys.exit(47)"')
766 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000767
Florent Xiclunac0838642010-03-07 15:27:39 +0000768 def _kill_process(self, method, *args):
Florent Xicluna400efc22010-03-07 17:12:23 +0000769 # Some win32 buildbot raises EOFError if stdin is inherited
770 p = subprocess.Popen([sys.executable, "-c", "input()"],
771 stdin=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772
Florent Xiclunafaf17532010-03-08 10:59:33 +0000773 # Let the process initialize (Issue #3137)
Florent Xiclunac0838642010-03-07 15:27:39 +0000774 time.sleep(0.1)
775 # The process should not terminate prematurely
776 self.assertIsNone(p.poll())
777 # Retry if the process do not receive the signal.
778 count, maxcount = 0, 3
779 while count < maxcount and p.poll() is None:
780 getattr(p, method)(*args)
781 time.sleep(0.1)
782 count += 1
783
784 returncode = p.poll()
785 self.assertIsNotNone(returncode, "the subprocess did not terminate")
786 if count > 1:
787 print >>sys.stderr, ("p.{}{} succeeded after "
788 "{} attempts".format(method, args, count))
Florent Xiclunac0838642010-03-07 15:27:39 +0000789 self.assertEqual(p.wait(), returncode)
Florent Xiclunafaf17532010-03-08 10:59:33 +0000790 self.assertNotEqual(returncode, 0)
Florent Xiclunac0838642010-03-07 15:27:39 +0000791
792 def test_send_signal(self):
793 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimese74c8f22008-04-19 02:23:57 +0000794
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000795 def test_kill(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000796 self._kill_process('kill')
Christian Heimese74c8f22008-04-19 02:23:57 +0000797
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000798 def test_terminate(self):
Florent Xiclunac0838642010-03-07 15:27:39 +0000799 self._kill_process('terminate')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000800
Gregory P. Smithdd7ca242009-07-04 01:49:29 +0000801
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000802@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
803 "poll system call not supported")
804class ProcessTestCaseNoPoll(ProcessTestCase):
805 def setUp(self):
806 subprocess._has_poll = False
807 ProcessTestCase.setUp(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +0000808
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000809 def tearDown(self):
810 subprocess._has_poll = True
811 ProcessTestCase.tearDown(self)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +0000812
813
Gregory P. Smithcce211f2010-03-01 00:05:08 +0000814class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithc1baf4a2010-03-01 02:53:24 +0000815 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smithcce211f2010-03-01 00:05:08 +0000816 def test_eintr_retry_call(self):
817 record_calls = []
818 def fake_os_func(*args):
819 record_calls.append(args)
820 if len(record_calls) == 2:
821 raise OSError(errno.EINTR, "fake interrupted system call")
822 return tuple(reversed(args))
823
824 self.assertEqual((999, 256),
825 subprocess._eintr_retry_call(fake_os_func, 256, 999))
826 self.assertEqual([(256, 999)], record_calls)
827 # This time there will be an EINTR so it will loop once.
828 self.assertEqual((666,),
829 subprocess._eintr_retry_call(fake_os_func, 666))
830 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
831
832
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000833def test_main():
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000834 unit_tests = (ProcessTestCase,
835 POSIXProcessTestCase,
836 Win32ProcessTestCase,
Gregory P. Smithcce211f2010-03-01 00:05:08 +0000837 ProcessTestCaseNoPoll,
838 HelperFunctionTests)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000839
Gregory P. Smithdd7ca242009-07-04 01:49:29 +0000840 test_support.run_unittest(*unit_tests)
Florent Xicluna98e3fc32010-02-27 19:20:50 +0000841 test_support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000842
843if __name__ == "__main__":
844 test_main()