blob: 685fabe6976e992d04c16fb2bbe00108de286d2e [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 Xiclunab1e94e82010-02-27 22:12:37 +000042 def assertStderrEqual(self, stderr, expected, msg=None):
43 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
44 # shutdown time. That frustrates tests trying to check stderr produced
45 # from a spawned Python process.
46 actual = re.sub("\[\d+ refs\]\r?\n?$", "", stderr.decode()).encode()
47 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000048
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000049 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000050 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000051 rc = subprocess.call([sys.executable, "-c",
52 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000053 self.assertEqual(rc, 47)
54
Peter Astrand454f7672005-01-01 09:36:35 +000055 def test_check_call_zero(self):
56 # check_call() function with zero return code
57 rc = subprocess.check_call([sys.executable, "-c",
58 "import sys; sys.exit(0)"])
59 self.assertEqual(rc, 0)
60
61 def test_check_call_nonzero(self):
62 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000063 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000064 subprocess.check_call([sys.executable, "-c",
65 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000066 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000067
Georg Brandlf9734072008-12-07 15:30:06 +000068 def test_check_output(self):
69 # check_output() function with zero return code
70 output = subprocess.check_output(
71 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000072 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000073
74 def test_check_output_nonzero(self):
75 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000076 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +000077 subprocess.check_output(
78 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000079 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +000080
81 def test_check_output_stderr(self):
82 # check_output() function stderr redirected to stdout
83 output = subprocess.check_output(
84 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
85 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +000086 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000087
88 def test_check_output_stdout_arg(self):
89 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +000090 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +000091 output = subprocess.check_output(
92 [sys.executable, "-c", "print('will not be run')"],
93 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +000094 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +000095 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +000096
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000097 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +000098 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000099 newenv = os.environ.copy()
100 newenv["FRUIT"] = "banana"
101 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000102 'import sys, os;'
103 'sys.exit(os.getenv("FRUIT")=="banana")'],
104 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000105 self.assertEqual(rc, 1)
106
107 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000108 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000109 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000110 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
111 p.wait()
112 self.assertEqual(p.stdin, None)
113
114 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000115 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000116 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000117 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000118 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000119 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000120 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000121 p.wait()
122 self.assertEqual(p.stdout, None)
123
124 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000125 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000126 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000127 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
128 p.wait()
129 self.assertEqual(p.stderr, None)
130
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000131 def test_executable_with_cwd(self):
132 python_dir = os.path.dirname(os.path.realpath(sys.executable))
133 p = subprocess.Popen(["somethingyoudonthave", "-c",
134 "import sys; sys.exit(47)"],
135 executable=sys.executable, cwd=python_dir)
136 p.wait()
137 self.assertEqual(p.returncode, 47)
138
139 @unittest.skipIf(sysconfig.is_python_build(),
140 "need an installed Python. See #7774")
141 def test_executable_without_cwd(self):
142 # For a normal installation, it should work without 'cwd'
143 # argument. For test runs in the build directory, see #7774.
144 p = subprocess.Popen(["somethingyoudonthave", "-c",
145 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000146 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000147 p.wait()
148 self.assertEqual(p.returncode, 47)
149
150 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000151 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000152 p = subprocess.Popen([sys.executable, "-c",
153 'import sys; sys.exit(sys.stdin.read() == "pear")'],
154 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000155 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000156 p.stdin.close()
157 p.wait()
158 self.assertEqual(p.returncode, 1)
159
160 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000161 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000162 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000163 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000164 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165 os.lseek(d, 0, 0)
166 p = subprocess.Popen([sys.executable, "-c",
167 'import sys; sys.exit(sys.stdin.read() == "pear")'],
168 stdin=d)
169 p.wait()
170 self.assertEqual(p.returncode, 1)
171
172 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000173 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000174 tf = tempfile.TemporaryFile()
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000175 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000176 tf.seek(0)
177 p = subprocess.Popen([sys.executable, "-c",
178 'import sys; sys.exit(sys.stdin.read() == "pear")'],
179 stdin=tf)
180 p.wait()
181 self.assertEqual(p.returncode, 1)
182
183 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000184 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000185 p = subprocess.Popen([sys.executable, "-c",
186 'import sys; sys.stdout.write("orange")'],
187 stdout=subprocess.PIPE)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000188 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189
190 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000191 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000192 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000193 d = tf.fileno()
194 p = subprocess.Popen([sys.executable, "-c",
195 'import sys; sys.stdout.write("orange")'],
196 stdout=d)
197 p.wait()
198 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000199 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000200
201 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000202 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000203 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000204 p = subprocess.Popen([sys.executable, "-c",
205 'import sys; sys.stdout.write("orange")'],
206 stdout=tf)
207 p.wait()
208 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000209 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210
211 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000212 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000213 p = subprocess.Popen([sys.executable, "-c",
214 'import sys; sys.stderr.write("strawberry")'],
215 stderr=subprocess.PIPE)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000216 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000217
218 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000219 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000220 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000221 d = tf.fileno()
222 p = subprocess.Popen([sys.executable, "-c",
223 'import sys; sys.stderr.write("strawberry")'],
224 stderr=d)
225 p.wait()
226 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000227 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000228
229 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000230 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000231 tf = tempfile.TemporaryFile()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000232 p = subprocess.Popen([sys.executable, "-c",
233 'import sys; sys.stderr.write("strawberry")'],
234 stderr=tf)
235 p.wait()
236 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000237 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238
239 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000240 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000241 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000242 'import sys;'
243 'sys.stdout.write("apple");'
244 'sys.stdout.flush();'
245 'sys.stderr.write("orange")'],
246 stdout=subprocess.PIPE,
247 stderr=subprocess.STDOUT)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000248 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000249
250 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000251 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000252 tf = tempfile.TemporaryFile()
253 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000254 'import sys;'
255 'sys.stdout.write("apple");'
256 'sys.stdout.flush();'
257 'sys.stderr.write("orange")'],
258 stdout=tf,
259 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000260 p.wait()
261 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000262 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263
Thomas Wouters89f507f2006-12-13 04:49:30 +0000264 def test_stdout_filedes_of_stdout(self):
265 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000266 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000267 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000268 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000269
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000271 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000272 # We cannot use os.path.realpath to canonicalize the path,
273 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
274 cwd = os.getcwd()
275 os.chdir(tmpdir)
276 tmpdir = os.getcwd()
277 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000278 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000279 'import sys,os;'
280 'sys.stdout.write(os.getcwd())'],
281 stdout=subprocess.PIPE,
282 cwd=tmpdir)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000283 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000284 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
285 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000286
287 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000288 newenv = os.environ.copy()
289 newenv["FRUIT"] = "orange"
290 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000291 'import sys,os;'
292 'sys.stdout.write(os.getenv("FRUIT"))'],
293 stdout=subprocess.PIPE,
294 env=newenv)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000295 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296
Peter Astrandcbac93c2005-03-03 20:24:28 +0000297 def test_communicate_stdin(self):
298 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000299 'import sys;'
300 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000301 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000302 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000303 self.assertEqual(p.returncode, 1)
304
305 def test_communicate_stdout(self):
306 p = subprocess.Popen([sys.executable, "-c",
307 'import sys; sys.stdout.write("pineapple")'],
308 stdout=subprocess.PIPE)
309 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000310 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000311 self.assertEqual(stderr, None)
312
313 def test_communicate_stderr(self):
314 p = subprocess.Popen([sys.executable, "-c",
315 'import sys; sys.stderr.write("pineapple")'],
316 stderr=subprocess.PIPE)
317 (stdout, stderr) = p.communicate()
318 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000319 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000320
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000321 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000322 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000323 'import sys,os;'
324 'sys.stderr.write("pineapple");'
325 'sys.stdout.write(sys.stdin.read())'],
326 stdin=subprocess.PIPE,
327 stdout=subprocess.PIPE,
328 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000329 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000330 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000331 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000332
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000333 # This test is Linux specific for simplicity to at least have
334 # some coverage. It is not a platform specific bug.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000335 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
336 "Linux specific")
337 # Test for the fd leak reported in http://bugs.python.org/issue2791.
338 def test_communicate_pipe_fd_leak(self):
339 fd_directory = '/proc/%d/fd' % os.getpid()
340 num_fds_before_popen = len(os.listdir(fd_directory))
341 p = subprocess.Popen([sys.executable, "-c", "print()"],
342 stdout=subprocess.PIPE)
343 p.communicate()
344 num_fds_after_communicate = len(os.listdir(fd_directory))
345 del p
346 num_fds_after_destruction = len(os.listdir(fd_directory))
347 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
348 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000349
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000350 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000351 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000352 p = subprocess.Popen([sys.executable, "-c",
353 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354 (stdout, stderr) = p.communicate()
355 self.assertEqual(stdout, None)
356 self.assertEqual(stderr, None)
357
358 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000359 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000360 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000361 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362 x, y = os.pipe()
363 if mswindows:
364 pipe_buf = 512
365 else:
366 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
367 os.close(x)
368 os.close(y)
369 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000370 'import sys,os;'
371 'sys.stdout.write(sys.stdin.read(47));'
372 'sys.stderr.write("xyz"*%d);'
373 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
374 stdin=subprocess.PIPE,
375 stdout=subprocess.PIPE,
376 stderr=subprocess.PIPE)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000377 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000378 (stdout, stderr) = p.communicate(string_to_write)
379 self.assertEqual(stdout, string_to_write)
380
381 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000382 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000383 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000384 'import sys,os;'
385 'sys.stdout.write(sys.stdin.read())'],
386 stdin=subprocess.PIPE,
387 stdout=subprocess.PIPE,
388 stderr=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000389 p.stdin.write(b"banana")
390 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000391 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000392 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000393
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000394 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000395 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000396 'import sys,os;' + SETBINARY +
397 'sys.stdout.write("line1\\n");'
398 'sys.stdout.flush();'
399 'sys.stdout.write("line2\\n");'
400 'sys.stdout.flush();'
401 'sys.stdout.write("line3\\r\\n");'
402 'sys.stdout.flush();'
403 'sys.stdout.write("line4\\r");'
404 'sys.stdout.flush();'
405 'sys.stdout.write("\\nline5");'
406 'sys.stdout.flush();'
407 'sys.stdout.write("\\nline6");'],
408 stdout=subprocess.PIPE,
409 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000410 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000411 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000412
413 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000414 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000415 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000416 'import sys,os;' + SETBINARY +
417 'sys.stdout.write("line1\\n");'
418 'sys.stdout.flush();'
419 'sys.stdout.write("line2\\n");'
420 'sys.stdout.flush();'
421 'sys.stdout.write("line3\\r\\n");'
422 'sys.stdout.flush();'
423 'sys.stdout.write("line4\\r");'
424 'sys.stdout.flush();'
425 'sys.stdout.write("\\nline5");'
426 'sys.stdout.flush();'
427 'sys.stdout.write("\\nline6");'],
428 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
429 universal_newlines=1)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000430 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000431 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000432
433 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000434 # Make sure we leak no resources
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000435 if (not hasattr(support, "is_resource_enabled") or
436 support.is_resource_enabled("subprocess") and not mswindows):
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000437 max_handles = 1026 # too much for most UNIX systems
438 else:
Tim Peterseba28be2005-03-28 01:08:02 +0000439 max_handles = 65
Fredrik Lundh9e29fc52004-10-13 07:54:54 +0000440 for i in range(max_handles):
Tim Peters3b01a702004-10-12 22:19:32 +0000441 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000442 "import sys;"
443 "sys.stdout.write(sys.stdin.read())"],
444 stdin=subprocess.PIPE,
445 stdout=subprocess.PIPE,
446 stderr=subprocess.PIPE)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000447 data = p.communicate(b"lime")[0]
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000448 self.assertEqual(data, b"lime")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449
450
451 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
453 '"a b c" d e')
454 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
455 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000456 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
457 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000458 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
459 'a\\\\\\b "de fg" h')
460 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
461 'a\\\\\\"b c d')
462 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
463 '"a\\\\b c" d e')
464 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
465 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000466 self.assertEqual(subprocess.list2cmdline(['ab', '']),
467 'ab ""')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000468 self.assertEqual(subprocess.list2cmdline(['echo', 'foo|bar']),
469 'echo "foo|bar"')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470
471
472 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000473 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000474 "-c", "import time; time.sleep(1)"])
475 count = 0
476 while p.poll() is None:
477 time.sleep(0.1)
478 count += 1
479 # We expect that the poll loop probably went around about 10 times,
480 # but, based on system scheduling we can't control, it's possible
481 # poll() never returned None. It "should be" very rare that it
482 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000483 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484 # Subsequent invocations should just return the returncode
485 self.assertEqual(p.poll(), 0)
486
487
488 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 p = subprocess.Popen([sys.executable,
490 "-c", "import time; time.sleep(2)"])
491 self.assertEqual(p.wait(), 0)
492 # Subsequent invocations should just return the returncode
493 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000494
Peter Astrand738131d2004-11-30 21:04:45 +0000495
496 def test_invalid_bufsize(self):
497 # an invalid type of the bufsize argument should raise
498 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000499 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000500 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000501
Guido van Rossum46a05a72007-06-07 21:56:45 +0000502 def test_bufsize_is_none(self):
503 # bufsize=None should be the same as bufsize=0.
504 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
505 self.assertEqual(p.wait(), 0)
506 # Again with keyword arg
507 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
508 self.assertEqual(p.wait(), 0)
509
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000510 def test_leaking_fds_on_error(self):
511 # see bug #5179: Popen leaks file descriptors to PIPEs if
512 # the child fails to execute; this will eventually exhaust
513 # the maximum number of open fds. 1024 seems a very common
514 # value for that limit, but Windows has 2048, so we loop
515 # 1024 times (each call leaked two fds).
516 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000517 # Windows raises IOError. Others raise OSError.
518 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000519 subprocess.Popen(['nonexisting_i_hope'],
520 stdout=subprocess.PIPE,
521 stderr=subprocess.PIPE)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000522 if c.exception.errno != 2: # ignore "no such file"
523 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000524
Tim Peterse718f612004-10-12 21:51:32 +0000525
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000526# context manager
527class _SuppressCoreFiles(object):
528 """Try to prevent core files from being created."""
529 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000530
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000531 def __enter__(self):
532 """Try to save previous ulimit, then set it to (0, 0)."""
533 try:
534 import resource
535 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
536 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
537 except (ImportError, ValueError, resource.error):
538 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000539
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000540 def __exit__(self, *args):
541 """Return core file behavior to default."""
542 if self.old_limit is None:
543 return
544 try:
545 import resource
546 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
547 except (ImportError, ValueError, resource.error):
548 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000550
551@unittest.skipIf(sys.platform == "win32", "POSIX specific tests")
552class POSIXProcessTestCase(unittest.TestCase):
553 def setUp(self):
554 # Try to minimize the number of children we have so this test
555 # doesn't crash on some buildbots (Alphas in particular).
556 support.reap_children()
557
558 def test_exceptions(self):
559 # caught & re-raised exceptions
560 with self.assertRaises(OSError) as c:
561 p = subprocess.Popen([sys.executable, "-c", ""],
562 cwd="/this/path/does/not/exist")
563 # The attribute child_traceback should contain "os.chdir" somewhere.
564 self.assertIn("os.chdir", c.exception.child_traceback)
565
566 def test_run_abort(self):
567 # returncode handles signal termination
568 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000569 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000570 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000571 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000572 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000573
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000574 def test_preexec(self):
575 # preexec function
576 p = subprocess.Popen([sys.executable, "-c",
577 'import sys,os;'
578 'sys.stdout.write(os.getenv("FRUIT"))'],
579 stdout=subprocess.PIPE,
580 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
581 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000582
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000583 def test_args_string(self):
584 # args is a string
585 fd, fname = mkstemp()
586 # reopen in text mode
587 with open(fd, "w") as fobj:
588 fobj.write("#!/bin/sh\n")
589 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
590 sys.executable)
591 os.chmod(fname, 0o700)
592 p = subprocess.Popen(fname)
593 p.wait()
594 os.remove(fname)
595 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000597 def test_invalid_args(self):
598 # invalid arguments should raise ValueError
599 self.assertRaises(ValueError, subprocess.call,
600 [sys.executable, "-c",
601 "import sys; sys.exit(47)"],
602 startupinfo=47)
603 self.assertRaises(ValueError, subprocess.call,
604 [sys.executable, "-c",
605 "import sys; sys.exit(47)"],
606 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000607
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000608 def test_shell_sequence(self):
609 # Run command through the shell (sequence)
610 newenv = os.environ.copy()
611 newenv["FRUIT"] = "apple"
612 p = subprocess.Popen(["echo $FRUIT"], shell=1,
613 stdout=subprocess.PIPE,
614 env=newenv)
615 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000617 def test_shell_string(self):
618 # Run command through the shell (string)
619 newenv = os.environ.copy()
620 newenv["FRUIT"] = "apple"
621 p = subprocess.Popen("echo $FRUIT", shell=1,
622 stdout=subprocess.PIPE,
623 env=newenv)
624 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000625
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000626 def test_call_string(self):
627 # call() function with string argument on UNIX
628 fd, fname = mkstemp()
629 # reopen in text mode
630 with open(fd, "w") as fobj:
631 fobj.write("#!/bin/sh\n")
632 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
633 sys.executable)
634 os.chmod(fname, 0o700)
635 rc = subprocess.call(fname)
636 os.remove(fname)
637 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000638
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000639 @unittest.skip("See issue #2777")
640 def test_send_signal(self):
641 p = subprocess.Popen([sys.executable, "-c", "input()"])
Christian Heimesa342c012008-04-20 21:01:16 +0000642
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000643 self.assertIs(p.poll(), None)
644 p.send_signal(signal.SIGINT)
645 self.assertIsNot(p.wait(), None)
Christian Heimesa342c012008-04-20 21:01:16 +0000646
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000647 @unittest.skip("See issue #2777")
648 def test_kill(self):
649 p = subprocess.Popen([sys.executable, "-c", "input()"])
Christian Heimesa342c012008-04-20 21:01:16 +0000650
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000651 self.assertIs(p.poll(), None)
652 p.kill()
653 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000654
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000655 @unittest.skip("See issue #2777")
656 def test_terminate(self):
657 p = subprocess.Popen([sys.executable, "-c", "input()"])
658
659 self.assertIs(p.poll(), None)
660 p.terminate()
661 self.assertEqual(p.wait(), -signal.SIGTERM)
662
663
664@unittest.skipUnless(sys.platform == "win32", "Windows specific tests")
665class Win32ProcessTestCase(unittest.TestCase):
666 def setUp(self):
667 # Try to minimize the number of children we have so this test
668 # doesn't crash on some buildbots (Alphas in particular).
669 support.reap_children()
670
671 def test_startupinfo(self):
672 # startupinfo argument
673 # We uses hardcoded constants, because we do not want to
674 # depend on win32all.
675 STARTF_USESHOWWINDOW = 1
676 SW_MAXIMIZE = 3
677 startupinfo = subprocess.STARTUPINFO()
678 startupinfo.dwFlags = STARTF_USESHOWWINDOW
679 startupinfo.wShowWindow = SW_MAXIMIZE
680 # Since Python is a console process, it won't be affected
681 # by wShowWindow, but the argument should be silently
682 # ignored
683 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000684 startupinfo=startupinfo)
685
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000686 def test_creationflags(self):
687 # creationflags argument
688 CREATE_NEW_CONSOLE = 16
689 sys.stderr.write(" a DOS box should flash briefly ...\n")
690 subprocess.call(sys.executable +
691 ' -c "import time; time.sleep(0.25)"',
692 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000693
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000694 def test_invalid_args(self):
695 # invalid arguments should raise ValueError
696 self.assertRaises(ValueError, subprocess.call,
697 [sys.executable, "-c",
698 "import sys; sys.exit(47)"],
699 preexec_fn=lambda: 1)
700 self.assertRaises(ValueError, subprocess.call,
701 [sys.executable, "-c",
702 "import sys; sys.exit(47)"],
703 stdout=subprocess.PIPE,
704 close_fds=True)
705
706 def test_close_fds(self):
707 # close file descriptors
708 rc = subprocess.call([sys.executable, "-c",
709 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000710 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000711 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000712
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000713 def test_shell_sequence(self):
714 # Run command through the shell (sequence)
715 newenv = os.environ.copy()
716 newenv["FRUIT"] = "physalis"
717 p = subprocess.Popen(["set"], shell=1,
718 stdout=subprocess.PIPE,
719 env=newenv)
720 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +0000721
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000722 def test_shell_string(self):
723 # Run command through the shell (string)
724 newenv = os.environ.copy()
725 newenv["FRUIT"] = "physalis"
726 p = subprocess.Popen("set", shell=1,
727 stdout=subprocess.PIPE,
728 env=newenv)
729 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000731 def test_call_string(self):
732 # call() function with string argument on Windows
733 rc = subprocess.call(sys.executable +
734 ' -c "import sys; sys.exit(47)"')
735 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000736
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000737 @unittest.skip("See issue #2777")
738 def test_send_signal(self):
739 p = subprocess.Popen([sys.executable, "-c", "input()"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000740
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000741 self.assertIs(p.poll(), None)
742 p.send_signal(signal.SIGTERM)
743 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000744
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000745 @unittest.skip("See issue #2777")
746 def test_kill(self):
747 p = subprocess.Popen([sys.executable, "-c", "input()"])
Christian Heimesa342c012008-04-20 21:01:16 +0000748
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000749 self.assertIs(p.poll(), None)
750 p.kill()
751 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000752
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000753 @unittest.skip("See issue #2777")
754 def test_terminate(self):
755 p = subprocess.Popen([sys.executable, "-c", "input()"])
Christian Heimesa342c012008-04-20 21:01:16 +0000756
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000757 self.assertIs(p.poll(), None)
758 p.terminate()
759 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000760
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000761
Brett Cannona23810f2008-05-26 19:04:21 +0000762# The module says:
763# "NB This only works (and is only relevant) for UNIX."
764#
765# Actually, getoutput should work on any platform with an os.popen, but
766# I'll take the comment as given, and skip this suite.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000767@unittest.skipUnless(os.name != 'posix', "only relevant for UNIX")
768class CommandTests(unittest.TestCase):
769 def test_getoutput(self):
770 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
771 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
772 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +0000773
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000774 # we use mkdtemp in the next line to create an empty directory
775 # under our exclusive control; from that, we can invent a pathname
776 # that we _know_ won't exist. This is guaranteed to fail.
777 dir = None
778 try:
779 dir = tempfile.mkdtemp()
780 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +0000781
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000782 status, output = subprocess.getstatusoutput('cat ' + name)
783 self.assertNotEqual(status, 0)
784 finally:
785 if dir is not None:
786 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +0000787
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000788
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000789@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
790 "poll system call not supported")
791class ProcessTestCaseNoPoll(ProcessTestCase):
792 def setUp(self):
793 subprocess._has_poll = False
794 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000795
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000796 def tearDown(self):
797 subprocess._has_poll = True
798 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000799
800
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000801class HelperFunctionTests(unittest.TestCase):
802 def test_eintr_retry_call(self):
803 record_calls = []
804 def fake_os_func(*args):
805 record_calls.append(args)
806 if len(record_calls) == 2:
807 raise OSError(errno.EINTR, "fake interrupted system call")
808 return tuple(reversed(args))
809
810 self.assertEqual((999, 256),
811 subprocess._eintr_retry_call(fake_os_func, 256, 999))
812 self.assertEqual([(256, 999)], record_calls)
813 # This time there will be an EINTR so it will loop once.
814 self.assertEqual((666,),
815 subprocess._eintr_retry_call(fake_os_func, 666))
816 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
817
818
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000819def test_main():
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000820 unit_tests = (ProcessTestCase,
821 POSIXProcessTestCase,
822 Win32ProcessTestCase,
823 CommandTests,
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000824 ProcessTestCaseNoPoll,
825 HelperFunctionTests)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000826
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000827 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +0000828 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000829
830if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +0000831 test_main()