blob: 8759941a026db83bc242e1771d4a10797eae5fea [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003import subprocess
4import sys
5import signal
6import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00007import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008import tempfile
9import time
Tim Peters3761e8d2004-10-13 04:07:12 +000010import re
Ezio Melotti184bdfb2010-02-18 09:37:05 +000011import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000012import warnings
Gregory P. Smith32ec9da2010-03-19 16:53:08 +000013try:
14 import gc
15except ImportError:
16 gc = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000017
18mswindows = (sys.platform == "win32")
19
20#
21# Depends on the following external programs: Python
22#
23
24if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000025 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
26 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000027else:
28 SETBINARY = ''
29
Florent Xiclunab1e94e82010-02-27 22:12:37 +000030
31try:
32 mkstemp = tempfile.mkstemp
33except AttributeError:
34 # tempfile.mkstemp is not available
35 def mkstemp():
36 """Replacement for mkstemp, calling mktemp."""
37 fname = tempfile.mktemp()
38 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
39
Tim Peters3761e8d2004-10-13 04:07:12 +000040
Florent Xiclunac049d872010-03-27 22:47:23 +000041class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000042 def setUp(self):
43 # Try to minimize the number of children we have so this test
44 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000045 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000046
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000047 def tearDown(self):
48 for inst in subprocess._active:
49 inst.wait()
50 subprocess._cleanup()
51 self.assertFalse(subprocess._active, "subprocess._active not empty")
52
Florent Xiclunab1e94e82010-02-27 22:12:37 +000053 def assertStderrEqual(self, stderr, expected, msg=None):
54 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
55 # shutdown time. That frustrates tests trying to check stderr produced
56 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000057 actual = support.strip_python_stderr(stderr)
Florent Xiclunab1e94e82010-02-27 22:12:37 +000058 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059
Florent Xiclunac049d872010-03-27 22:47:23 +000060
Gregory P. Smithd23047b2010-12-04 09:10:44 +000061class DeprecationWarningTests(BaseTestCase):
62 def setUp(self):
63 BaseTestCase.setUp(self)
64 self._saved_warn = warnings.warn
65 self._warn_calls = []
66 warnings.warn = self._record_warn
67
68 def tearDown(self):
69 warnings.warn = self._saved_warn
70 BaseTestCase.tearDown(self)
71
72 def _record_warn(self, *args):
73 """A warnings.warn function that records calls."""
74 self._warn_calls.append(args)
75 self._saved_warn(*args)
76
77 def testCloseFdsWarning(self):
78 quick_process = [sys.executable, "-c", "import sys; sys.exit(0)"]
79 subprocess.call(quick_process, close_fds=True)
80 self.assertEqual([], self._warn_calls)
81 subprocess.call(quick_process, close_fds=False)
82 self.assertEqual([], self._warn_calls)
83 self.assertWarns(DeprecationWarning, subprocess.call, quick_process)
84 self.assertEqual(1, len(self._warn_calls))
85 self.assertIn('close_fds parameter was not specified',
86 self._warn_calls[0][0])
87
88
Florent Xiclunac049d872010-03-27 22:47:23 +000089class ProcessTestCase(BaseTestCase):
90
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000091 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000092 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000093 rc = subprocess.call([sys.executable, "-c",
94 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000095 self.assertEqual(rc, 47)
96
Peter Astrand454f7672005-01-01 09:36:35 +000097 def test_check_call_zero(self):
98 # check_call() function with zero return code
99 rc = subprocess.check_call([sys.executable, "-c",
100 "import sys; sys.exit(0)"])
101 self.assertEqual(rc, 0)
102
103 def test_check_call_nonzero(self):
104 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000105 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000106 subprocess.check_call([sys.executable, "-c",
107 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000108 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000109
Georg Brandlf9734072008-12-07 15:30:06 +0000110 def test_check_output(self):
111 # check_output() function with zero return code
112 output = subprocess.check_output(
113 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000114 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000115
116 def test_check_output_nonzero(self):
117 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000118 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000119 subprocess.check_output(
120 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000121 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000122
123 def test_check_output_stderr(self):
124 # check_output() function stderr redirected to stdout
125 output = subprocess.check_output(
126 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
127 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000128 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000129
130 def test_check_output_stdout_arg(self):
131 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000132 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000133 output = subprocess.check_output(
134 [sys.executable, "-c", "print('will not be run')"],
135 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000136 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000137 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000138
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000139 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000140 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000141 newenv = os.environ.copy()
142 newenv["FRUIT"] = "banana"
143 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000144 'import sys, os;'
145 'sys.exit(os.getenv("FRUIT")=="banana")'],
146 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000147 self.assertEqual(rc, 1)
148
149 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000150 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000151 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000152 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000153 self.addCleanup(p.stdout.close)
154 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000155 p.wait()
156 self.assertEqual(p.stdin, None)
157
158 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000159 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000160 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000161 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000162 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000163 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000164 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000165 self.addCleanup(p.stdin.close)
166 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000167 p.wait()
168 self.assertEqual(p.stdout, None)
169
170 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000171 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000172 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000173 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000174 self.addCleanup(p.stdout.close)
175 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000176 p.wait()
177 self.assertEqual(p.stderr, None)
178
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000179 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000180 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000181 p = subprocess.Popen(["somethingyoudonthave", "-c",
182 "import sys; sys.exit(47)"],
183 executable=sys.executable, cwd=python_dir)
184 p.wait()
185 self.assertEqual(p.returncode, 47)
186
187 @unittest.skipIf(sysconfig.is_python_build(),
188 "need an installed Python. See #7774")
189 def test_executable_without_cwd(self):
190 # For a normal installation, it should work without 'cwd'
191 # argument. For test runs in the build directory, see #7774.
192 p = subprocess.Popen(["somethingyoudonthave", "-c",
193 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000194 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000195 p.wait()
196 self.assertEqual(p.returncode, 47)
197
198 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000199 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000200 p = subprocess.Popen([sys.executable, "-c",
201 'import sys; sys.exit(sys.stdin.read() == "pear")'],
202 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000203 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000204 p.stdin.close()
205 p.wait()
206 self.assertEqual(p.returncode, 1)
207
208 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000209 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000210 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000211 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000212 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000213 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000214 os.lseek(d, 0, 0)
215 p = subprocess.Popen([sys.executable, "-c",
216 'import sys; sys.exit(sys.stdin.read() == "pear")'],
217 stdin=d)
218 p.wait()
219 self.assertEqual(p.returncode, 1)
220
221 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000222 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000224 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000225 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000226 tf.seek(0)
227 p = subprocess.Popen([sys.executable, "-c",
228 'import sys; sys.exit(sys.stdin.read() == "pear")'],
229 stdin=tf)
230 p.wait()
231 self.assertEqual(p.returncode, 1)
232
233 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000234 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000235 p = subprocess.Popen([sys.executable, "-c",
236 'import sys; sys.stdout.write("orange")'],
237 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000238 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000239 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000240
241 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000242 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000243 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000244 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 d = tf.fileno()
246 p = subprocess.Popen([sys.executable, "-c",
247 'import sys; sys.stdout.write("orange")'],
248 stdout=d)
249 p.wait()
250 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000251 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000252
253 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000254 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000255 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000256 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000257 p = subprocess.Popen([sys.executable, "-c",
258 'import sys; sys.stdout.write("orange")'],
259 stdout=tf)
260 p.wait()
261 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000262 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263
264 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000265 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000266 p = subprocess.Popen([sys.executable, "-c",
267 'import sys; sys.stderr.write("strawberry")'],
268 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000269 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000270 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271
272 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000273 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000274 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000275 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276 d = tf.fileno()
277 p = subprocess.Popen([sys.executable, "-c",
278 'import sys; sys.stderr.write("strawberry")'],
279 stderr=d)
280 p.wait()
281 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000282 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000283
284 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000285 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000286 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000287 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000288 p = subprocess.Popen([sys.executable, "-c",
289 'import sys; sys.stderr.write("strawberry")'],
290 stderr=tf)
291 p.wait()
292 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000293 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294
295 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000296 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000297 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000298 'import sys;'
299 'sys.stdout.write("apple");'
300 'sys.stdout.flush();'
301 'sys.stderr.write("orange")'],
302 stdout=subprocess.PIPE,
303 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000304 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000305 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306
307 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000308 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000310 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000311 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000312 'import sys;'
313 'sys.stdout.write("apple");'
314 'sys.stdout.flush();'
315 'sys.stderr.write("orange")'],
316 stdout=tf,
317 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318 p.wait()
319 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000320 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000321
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322 def test_stdout_filedes_of_stdout(self):
323 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000324 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000325 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000326 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000327
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000328 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000329 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000330 # We cannot use os.path.realpath to canonicalize the path,
331 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
332 cwd = os.getcwd()
333 os.chdir(tmpdir)
334 tmpdir = os.getcwd()
335 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000336 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000337 'import sys,os;'
338 'sys.stdout.write(os.getcwd())'],
339 stdout=subprocess.PIPE,
340 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000341 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000342 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000343 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
344 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000345
346 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000347 newenv = os.environ.copy()
348 newenv["FRUIT"] = "orange"
349 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000350 'import sys,os;'
351 'sys.stdout.write(os.getenv("FRUIT"))'],
352 stdout=subprocess.PIPE,
353 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000354 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000355 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000356
Peter Astrandcbac93c2005-03-03 20:24:28 +0000357 def test_communicate_stdin(self):
358 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000359 'import sys;'
360 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000361 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000362 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000363 self.assertEqual(p.returncode, 1)
364
365 def test_communicate_stdout(self):
366 p = subprocess.Popen([sys.executable, "-c",
367 'import sys; sys.stdout.write("pineapple")'],
368 stdout=subprocess.PIPE)
369 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000370 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000371 self.assertEqual(stderr, None)
372
373 def test_communicate_stderr(self):
374 p = subprocess.Popen([sys.executable, "-c",
375 'import sys; sys.stderr.write("pineapple")'],
376 stderr=subprocess.PIPE)
377 (stdout, stderr) = p.communicate()
378 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000379 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000380
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000381 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000382 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000383 'import sys,os;'
384 'sys.stderr.write("pineapple");'
385 'sys.stdout.write(sys.stdin.read())'],
386 stdin=subprocess.PIPE,
387 stdout=subprocess.PIPE,
388 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000389 self.addCleanup(p.stdout.close)
390 self.addCleanup(p.stderr.close)
391 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000392 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000393 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000394 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000395
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000396 # This test is Linux specific for simplicity to at least have
397 # some coverage. It is not a platform specific bug.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000398 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
399 "Linux specific")
400 # Test for the fd leak reported in http://bugs.python.org/issue2791.
401 def test_communicate_pipe_fd_leak(self):
402 fd_directory = '/proc/%d/fd' % os.getpid()
403 num_fds_before_popen = len(os.listdir(fd_directory))
404 p = subprocess.Popen([sys.executable, "-c", "print()"],
405 stdout=subprocess.PIPE)
406 p.communicate()
407 num_fds_after_communicate = len(os.listdir(fd_directory))
408 del p
409 num_fds_after_destruction = len(os.listdir(fd_directory))
410 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
411 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000412
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000414 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000415 p = subprocess.Popen([sys.executable, "-c",
416 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000417 (stdout, stderr) = p.communicate()
418 self.assertEqual(stdout, None)
419 self.assertEqual(stderr, None)
420
421 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000422 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000424 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000425 x, y = os.pipe()
426 if mswindows:
427 pipe_buf = 512
428 else:
429 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
430 os.close(x)
431 os.close(y)
432 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000433 'import sys,os;'
434 'sys.stdout.write(sys.stdin.read(47));'
435 'sys.stderr.write("xyz"*%d);'
436 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
437 stdin=subprocess.PIPE,
438 stdout=subprocess.PIPE,
439 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000440 self.addCleanup(p.stdout.close)
441 self.addCleanup(p.stderr.close)
442 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000443 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 (stdout, stderr) = p.communicate(string_to_write)
445 self.assertEqual(stdout, string_to_write)
446
447 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000448 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000450 'import sys,os;'
451 'sys.stdout.write(sys.stdin.read())'],
452 stdin=subprocess.PIPE,
453 stdout=subprocess.PIPE,
454 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000455 self.addCleanup(p.stdout.close)
456 self.addCleanup(p.stderr.close)
457 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000458 p.stdin.write(b"banana")
459 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000460 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000461 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000462
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000465 'import sys,os;' + SETBINARY +
466 'sys.stdout.write("line1\\n");'
467 'sys.stdout.flush();'
468 'sys.stdout.write("line2\\n");'
469 'sys.stdout.flush();'
470 'sys.stdout.write("line3\\r\\n");'
471 'sys.stdout.flush();'
472 'sys.stdout.write("line4\\r");'
473 'sys.stdout.flush();'
474 'sys.stdout.write("\\nline5");'
475 'sys.stdout.flush();'
476 'sys.stdout.write("\\nline6");'],
477 stdout=subprocess.PIPE,
478 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000479 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000480 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000481 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482
483 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000484 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000486 'import sys,os;' + SETBINARY +
487 'sys.stdout.write("line1\\n");'
488 'sys.stdout.flush();'
489 'sys.stdout.write("line2\\n");'
490 'sys.stdout.flush();'
491 'sys.stdout.write("line3\\r\\n");'
492 'sys.stdout.flush();'
493 'sys.stdout.write("line4\\r");'
494 'sys.stdout.flush();'
495 'sys.stdout.write("\\nline5");'
496 'sys.stdout.flush();'
497 'sys.stdout.write("\\nline6");'],
498 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
499 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000500 self.addCleanup(p.stdout.close)
501 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000503 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504
505 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000506 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000507 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000508 max_handles = 1026 # too much for most UNIX systems
509 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000510 max_handles = 2050 # too much for (at least some) Windows setups
511 handles = []
512 try:
513 for i in range(max_handles):
514 try:
515 handles.append(os.open(support.TESTFN,
516 os.O_WRONLY | os.O_CREAT))
517 except OSError as e:
518 if e.errno != errno.EMFILE:
519 raise
520 break
521 else:
522 self.skipTest("failed to reach the file descriptor limit "
523 "(tried %d)" % max_handles)
524 # Close a couple of them (should be enough for a subprocess)
525 for i in range(10):
526 os.close(handles.pop())
527 # Loop creating some subprocesses. If one of them leaks some fds,
528 # the next loop iteration will fail by reaching the max fd limit.
529 for i in range(15):
530 p = subprocess.Popen([sys.executable, "-c",
531 "import sys;"
532 "sys.stdout.write(sys.stdin.read())"],
533 stdin=subprocess.PIPE,
534 stdout=subprocess.PIPE,
535 stderr=subprocess.PIPE)
536 data = p.communicate(b"lime")[0]
537 self.assertEqual(data, b"lime")
538 finally:
539 for h in handles:
540 os.close(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000541
542 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
544 '"a b c" d e')
545 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
546 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000547 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
548 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
550 'a\\\\\\b "de fg" h')
551 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
552 'a\\\\\\"b c d')
553 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
554 '"a\\\\b c" d e')
555 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
556 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000557 self.assertEqual(subprocess.list2cmdline(['ab', '']),
558 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559
560
561 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000562 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000563 "-c", "import time; time.sleep(1)"])
564 count = 0
565 while p.poll() is None:
566 time.sleep(0.1)
567 count += 1
568 # We expect that the poll loop probably went around about 10 times,
569 # but, based on system scheduling we can't control, it's possible
570 # poll() never returned None. It "should be" very rare that it
571 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000572 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000573 # Subsequent invocations should just return the returncode
574 self.assertEqual(p.poll(), 0)
575
576
577 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578 p = subprocess.Popen([sys.executable,
579 "-c", "import time; time.sleep(2)"])
580 self.assertEqual(p.wait(), 0)
581 # Subsequent invocations should just return the returncode
582 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000583
Peter Astrand738131d2004-11-30 21:04:45 +0000584
585 def test_invalid_bufsize(self):
586 # an invalid type of the bufsize argument should raise
587 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000588 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000589 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000590
Guido van Rossum46a05a72007-06-07 21:56:45 +0000591 def test_bufsize_is_none(self):
592 # bufsize=None should be the same as bufsize=0.
593 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
594 self.assertEqual(p.wait(), 0)
595 # Again with keyword arg
596 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
597 self.assertEqual(p.wait(), 0)
598
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000599 def test_leaking_fds_on_error(self):
600 # see bug #5179: Popen leaks file descriptors to PIPEs if
601 # the child fails to execute; this will eventually exhaust
602 # the maximum number of open fds. 1024 seems a very common
603 # value for that limit, but Windows has 2048, so we loop
604 # 1024 times (each call leaked two fds).
605 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000606 # Windows raises IOError. Others raise OSError.
607 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000608 subprocess.Popen(['nonexisting_i_hope'],
609 stdout=subprocess.PIPE,
610 stderr=subprocess.PIPE)
Antoine Pitrou679e0f22010-09-18 17:56:02 +0000611 if c.exception.errno != errno.ENOENT: # ignore "no such file"
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000612 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000613
Victor Stinnerb3693582010-05-21 20:13:12 +0000614 def test_issue8780(self):
615 # Ensure that stdout is inherited from the parent
616 # if stdout=PIPE is not used
617 code = ';'.join((
618 'import subprocess, sys',
619 'retcode = subprocess.call('
620 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
621 'assert retcode == 0'))
622 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000623 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000624
Tim Goldenaf5ac392010-08-06 13:03:56 +0000625 def test_handles_closed_on_exception(self):
626 # If CreateProcess exits with an error, ensure the
627 # duplicate output handles are released
628 ifhandle, ifname = mkstemp()
629 ofhandle, ofname = mkstemp()
630 efhandle, efname = mkstemp()
631 try:
632 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
633 stderr=efhandle)
634 except OSError:
635 os.close(ifhandle)
636 os.remove(ifname)
637 os.close(ofhandle)
638 os.remove(ofname)
639 os.close(efhandle)
640 os.remove(efname)
641 self.assertFalse(os.path.exists(ifname))
642 self.assertFalse(os.path.exists(ofname))
643 self.assertFalse(os.path.exists(efname))
644
Tim Peterse718f612004-10-12 21:51:32 +0000645
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000646# context manager
647class _SuppressCoreFiles(object):
648 """Try to prevent core files from being created."""
649 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000650
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000651 def __enter__(self):
652 """Try to save previous ulimit, then set it to (0, 0)."""
653 try:
654 import resource
655 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
656 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
657 except (ImportError, ValueError, resource.error):
658 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000659
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000660 if sys.platform == 'darwin':
661 # Check if the 'Crash Reporter' on OSX was configured
662 # in 'Developer' mode and warn that it will get triggered
663 # when it is.
664 #
665 # This assumes that this context manager is used in tests
666 # that might trigger the next manager.
667 value = subprocess.Popen(['/usr/bin/defaults', 'read',
668 'com.apple.CrashReporter', 'DialogType'],
669 stdout=subprocess.PIPE).communicate()[0]
670 if value.strip() == b'developer':
671 print("this tests triggers the Crash Reporter, "
672 "that is intentional", end='')
673 sys.stdout.flush()
674
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000675 def __exit__(self, *args):
676 """Return core file behavior to default."""
677 if self.old_limit is None:
678 return
679 try:
680 import resource
681 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
682 except (ImportError, ValueError, resource.error):
683 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000684
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000685
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000686@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000687class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000688
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000689 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000690 nonexistent_dir = "/_this/pa.th/does/not/exist"
691 try:
692 os.chdir(nonexistent_dir)
693 except OSError as e:
694 # This avoids hard coding the errno value or the OS perror()
695 # string and instead capture the exception that we want to see
696 # below for comparison.
697 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000698 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000699 else:
700 self.fail("chdir to nonexistant directory %s succeeded." %
701 nonexistent_dir)
702
703 # Error in the child re-raised in the parent.
704 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000705 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000706 cwd=nonexistent_dir)
707 except OSError as e:
708 # Test that the child process chdir failure actually makes
709 # it up to the parent process as the correct exception.
710 self.assertEqual(desired_exception.errno, e.errno)
711 self.assertEqual(desired_exception.strerror, e.strerror)
712 else:
713 self.fail("Expected OSError: %s" % desired_exception)
714
715 def test_restore_signals(self):
716 # Code coverage for both values of restore_signals to make sure it
717 # at least does not blow up.
718 # A test for behavior would be complex. Contributions welcome.
719 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
720 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
721
722 def test_start_new_session(self):
723 # For code coverage of calling setsid(). We don't care if we get an
724 # EPERM error from it depending on the test execution environment, that
725 # still indicates that it was called.
726 try:
727 output = subprocess.check_output(
728 [sys.executable, "-c",
729 "import os; print(os.getpgid(os.getpid()))"],
730 start_new_session=True)
731 except OSError as e:
732 if e.errno != errno.EPERM:
733 raise
734 else:
735 parent_pgid = os.getpgid(os.getpid())
736 child_pgid = int(output)
737 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000738
739 def test_run_abort(self):
740 # returncode handles signal termination
741 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000742 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000743 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000744 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000745 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000746
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000747 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000748 # DISCLAIMER: Setting environment variables is *not* a good use
749 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000750 p = subprocess.Popen([sys.executable, "-c",
751 'import sys,os;'
752 'sys.stdout.write(os.getenv("FRUIT"))'],
753 stdout=subprocess.PIPE,
754 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000755 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000756 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000757
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000758 def test_preexec_exception(self):
759 def raise_it():
760 raise ValueError("What if two swallows carried a coconut?")
761 try:
762 p = subprocess.Popen([sys.executable, "-c", ""],
763 preexec_fn=raise_it)
764 except RuntimeError as e:
765 self.assertTrue(
766 subprocess._posixsubprocess,
767 "Expected a ValueError from the preexec_fn")
768 except ValueError as e:
769 self.assertIn("coconut", e.args[0])
770 else:
771 self.fail("Exception raised by preexec_fn did not make it "
772 "to the parent process.")
773
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000774 @unittest.skipUnless(gc, "Requires a gc module.")
775 def test_preexec_gc_module_failure(self):
776 # This tests the code that disables garbage collection if the child
777 # process will execute any Python.
778 def raise_runtime_error():
779 raise RuntimeError("this shouldn't escape")
780 enabled = gc.isenabled()
781 orig_gc_disable = gc.disable
782 orig_gc_isenabled = gc.isenabled
783 try:
784 gc.disable()
785 self.assertFalse(gc.isenabled())
786 subprocess.call([sys.executable, '-c', ''],
787 preexec_fn=lambda: None)
788 self.assertFalse(gc.isenabled(),
789 "Popen enabled gc when it shouldn't.")
790
791 gc.enable()
792 self.assertTrue(gc.isenabled())
793 subprocess.call([sys.executable, '-c', ''],
794 preexec_fn=lambda: None)
795 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
796
797 gc.disable = raise_runtime_error
798 self.assertRaises(RuntimeError, subprocess.Popen,
799 [sys.executable, '-c', ''],
800 preexec_fn=lambda: None)
801
802 del gc.isenabled # force an AttributeError
803 self.assertRaises(AttributeError, subprocess.Popen,
804 [sys.executable, '-c', ''],
805 preexec_fn=lambda: None)
806 finally:
807 gc.disable = orig_gc_disable
808 gc.isenabled = orig_gc_isenabled
809 if not enabled:
810 gc.disable()
811
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000812 def test_args_string(self):
813 # args is a string
814 fd, fname = mkstemp()
815 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000816 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000817 fobj.write("#!/bin/sh\n")
818 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
819 sys.executable)
820 os.chmod(fname, 0o700)
821 p = subprocess.Popen(fname)
822 p.wait()
823 os.remove(fname)
824 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000825
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000826 def test_invalid_args(self):
827 # invalid arguments should raise ValueError
828 self.assertRaises(ValueError, subprocess.call,
829 [sys.executable, "-c",
830 "import sys; sys.exit(47)"],
831 startupinfo=47)
832 self.assertRaises(ValueError, subprocess.call,
833 [sys.executable, "-c",
834 "import sys; sys.exit(47)"],
835 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000836
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000837 def test_shell_sequence(self):
838 # Run command through the shell (sequence)
839 newenv = os.environ.copy()
840 newenv["FRUIT"] = "apple"
841 p = subprocess.Popen(["echo $FRUIT"], shell=1,
842 stdout=subprocess.PIPE,
843 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000844 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000845 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000846
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000847 def test_shell_string(self):
848 # Run command through the shell (string)
849 newenv = os.environ.copy()
850 newenv["FRUIT"] = "apple"
851 p = subprocess.Popen("echo $FRUIT", shell=1,
852 stdout=subprocess.PIPE,
853 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000854 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000855 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000856
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000857 def test_call_string(self):
858 # call() function with string argument on UNIX
859 fd, fname = mkstemp()
860 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000861 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000862 fobj.write("#!/bin/sh\n")
863 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
864 sys.executable)
865 os.chmod(fname, 0o700)
866 rc = subprocess.call(fname)
867 os.remove(fname)
868 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000869
Stefan Krah9542cc62010-07-19 14:20:53 +0000870 def test_specific_shell(self):
871 # Issue #9265: Incorrect name passed as arg[0].
872 shells = []
873 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
874 for name in ['bash', 'ksh']:
875 sh = os.path.join(prefix, name)
876 if os.path.isfile(sh):
877 shells.append(sh)
878 if not shells: # Will probably work for any shell but csh.
879 self.skipTest("bash or ksh required for this test")
880 sh = '/bin/sh'
881 if os.path.isfile(sh) and not os.path.islink(sh):
882 # Test will fail if /bin/sh is a symlink to csh.
883 shells.append(sh)
884 for sh in shells:
885 p = subprocess.Popen("echo $0", executable=sh, shell=True,
886 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000887 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000888 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
889
Florent Xicluna4886d242010-03-08 13:27:26 +0000890 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000891 # Do not inherit file handles from the parent.
892 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000893 p = subprocess.Popen([sys.executable, "-c", """if 1:
894 import sys, time
895 sys.stdout.write('x\\n')
896 sys.stdout.flush()
897 time.sleep(30)
898 """],
899 close_fds=True,
900 stdin=subprocess.PIPE,
901 stdout=subprocess.PIPE,
902 stderr=subprocess.PIPE)
903 # Wait for the interpreter to be completely initialized before
904 # sending any signal.
905 p.stdout.read(1)
906 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000907 return p
908
909 def test_send_signal(self):
910 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000911 _, stderr = p.communicate()
912 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000913 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000914
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000915 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000916 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000917 _, stderr = p.communicate()
918 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000919 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000920
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000921 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000922 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000923 _, stderr = p.communicate()
924 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000925 self.assertEqual(p.wait(), -signal.SIGTERM)
926
Victor Stinner13bb71c2010-04-23 21:41:56 +0000927 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +0000928 def prepare():
929 raise ValueError("surrogate:\uDCff")
930
931 try:
932 subprocess.call(
933 [sys.executable, "-c", "pass"],
934 preexec_fn=prepare)
935 except ValueError as err:
936 # Pure Python implementations keeps the message
937 self.assertIsNone(subprocess._posixsubprocess)
938 self.assertEqual(str(err), "surrogate:\uDCff")
939 except RuntimeError as err:
940 # _posixsubprocess uses a default message
941 self.assertIsNotNone(subprocess._posixsubprocess)
942 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
943 else:
944 self.fail("Expected ValueError or RuntimeError")
945
Victor Stinner13bb71c2010-04-23 21:41:56 +0000946 def test_undecodable_env(self):
947 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +0000948 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +0000949 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000950 env = os.environ.copy()
951 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +0000952 # Use C locale to get ascii for the locale encoding to force
953 # surrogate-escaping of \xFF in the child process; otherwise it can
954 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +0000955 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +0000956 stdout = subprocess.check_output(
957 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000958 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +0000959 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000960 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +0000961
962 # test bytes
963 key = key.encode("ascii", "surrogateescape")
964 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +0000965 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000966 env = os.environ.copy()
967 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +0000968 stdout = subprocess.check_output(
969 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000970 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +0000971 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000972 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +0000973
Victor Stinnerb745a742010-05-18 17:17:23 +0000974 def test_bytes_program(self):
975 abs_program = os.fsencode(sys.executable)
976 path, program = os.path.split(sys.executable)
977 program = os.fsencode(program)
978
979 # absolute bytes path
980 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000981 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +0000982
983 # bytes program, unicode PATH
984 env = os.environ.copy()
985 env["PATH"] = path
986 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000987 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +0000988
989 # bytes program, bytes PATH
990 envb = os.environb.copy()
991 envb[b"PATH"] = os.fsencode(path)
992 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000993 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +0000994
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000995
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000996@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000997class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000998
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000999 def test_startupinfo(self):
1000 # startupinfo argument
1001 # We uses hardcoded constants, because we do not want to
1002 # depend on win32all.
1003 STARTF_USESHOWWINDOW = 1
1004 SW_MAXIMIZE = 3
1005 startupinfo = subprocess.STARTUPINFO()
1006 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1007 startupinfo.wShowWindow = SW_MAXIMIZE
1008 # Since Python is a console process, it won't be affected
1009 # by wShowWindow, but the argument should be silently
1010 # ignored
1011 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001012 startupinfo=startupinfo)
1013
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001014 def test_creationflags(self):
1015 # creationflags argument
1016 CREATE_NEW_CONSOLE = 16
1017 sys.stderr.write(" a DOS box should flash briefly ...\n")
1018 subprocess.call(sys.executable +
1019 ' -c "import time; time.sleep(0.25)"',
1020 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001021
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001022 def test_invalid_args(self):
1023 # invalid arguments should raise ValueError
1024 self.assertRaises(ValueError, subprocess.call,
1025 [sys.executable, "-c",
1026 "import sys; sys.exit(47)"],
1027 preexec_fn=lambda: 1)
1028 self.assertRaises(ValueError, subprocess.call,
1029 [sys.executable, "-c",
1030 "import sys; sys.exit(47)"],
1031 stdout=subprocess.PIPE,
1032 close_fds=True)
1033
1034 def test_close_fds(self):
1035 # close file descriptors
1036 rc = subprocess.call([sys.executable, "-c",
1037 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001038 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001039 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001040
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001041 def test_shell_sequence(self):
1042 # Run command through the shell (sequence)
1043 newenv = os.environ.copy()
1044 newenv["FRUIT"] = "physalis"
1045 p = subprocess.Popen(["set"], shell=1,
1046 stdout=subprocess.PIPE,
1047 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001048 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001049 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001050
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001051 def test_shell_string(self):
1052 # Run command through the shell (string)
1053 newenv = os.environ.copy()
1054 newenv["FRUIT"] = "physalis"
1055 p = subprocess.Popen("set", shell=1,
1056 stdout=subprocess.PIPE,
1057 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001058 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001059 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001060
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001061 def test_call_string(self):
1062 # call() function with string argument on Windows
1063 rc = subprocess.call(sys.executable +
1064 ' -c "import sys; sys.exit(47)"')
1065 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001066
Florent Xicluna4886d242010-03-08 13:27:26 +00001067 def _kill_process(self, method, *args):
1068 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001069 p = subprocess.Popen([sys.executable, "-c", """if 1:
1070 import sys, time
1071 sys.stdout.write('x\\n')
1072 sys.stdout.flush()
1073 time.sleep(30)
1074 """],
1075 stdin=subprocess.PIPE,
1076 stdout=subprocess.PIPE,
1077 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001078 self.addCleanup(p.stdout.close)
1079 self.addCleanup(p.stderr.close)
1080 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001081 # Wait for the interpreter to be completely initialized before
1082 # sending any signal.
1083 p.stdout.read(1)
1084 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001085 _, stderr = p.communicate()
1086 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001087 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001088 self.assertNotEqual(returncode, 0)
1089
1090 def test_send_signal(self):
1091 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001092
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001093 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001094 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001095
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001096 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001097 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001098
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001099
Brett Cannona23810f2008-05-26 19:04:21 +00001100# The module says:
1101# "NB This only works (and is only relevant) for UNIX."
1102#
1103# Actually, getoutput should work on any platform with an os.popen, but
1104# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001105@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001106class CommandTests(unittest.TestCase):
1107 def test_getoutput(self):
1108 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1109 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1110 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001111
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001112 # we use mkdtemp in the next line to create an empty directory
1113 # under our exclusive control; from that, we can invent a pathname
1114 # that we _know_ won't exist. This is guaranteed to fail.
1115 dir = None
1116 try:
1117 dir = tempfile.mkdtemp()
1118 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001119
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001120 status, output = subprocess.getstatusoutput('cat ' + name)
1121 self.assertNotEqual(status, 0)
1122 finally:
1123 if dir is not None:
1124 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001125
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001126
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001127@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1128 "poll system call not supported")
1129class ProcessTestCaseNoPoll(ProcessTestCase):
1130 def setUp(self):
1131 subprocess._has_poll = False
1132 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001133
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001134 def tearDown(self):
1135 subprocess._has_poll = True
1136 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001137
1138
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001139@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1140 "_posixsubprocess extension module not found.")
1141class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
1142 def setUp(self):
1143 subprocess._posixsubprocess = None
1144 ProcessTestCase.setUp(self)
1145 POSIXProcessTestCase.setUp(self)
1146
1147 def tearDown(self):
1148 subprocess._posixsubprocess = sys.modules['_posixsubprocess']
1149 POSIXProcessTestCase.tearDown(self)
1150 ProcessTestCase.tearDown(self)
1151
1152
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001153class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001154 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001155 def test_eintr_retry_call(self):
1156 record_calls = []
1157 def fake_os_func(*args):
1158 record_calls.append(args)
1159 if len(record_calls) == 2:
1160 raise OSError(errno.EINTR, "fake interrupted system call")
1161 return tuple(reversed(args))
1162
1163 self.assertEqual((999, 256),
1164 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1165 self.assertEqual([(256, 999)], record_calls)
1166 # This time there will be an EINTR so it will loop once.
1167 self.assertEqual((666,),
1168 subprocess._eintr_retry_call(fake_os_func, 666))
1169 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1170
1171
Tim Golden126c2962010-08-11 14:20:40 +00001172@unittest.skipUnless(mswindows, "Windows-specific tests")
1173class CommandsWithSpaces (BaseTestCase):
1174
1175 def setUp(self):
1176 super().setUp()
1177 f, fname = mkstemp(".py", "te st")
1178 self.fname = fname.lower ()
1179 os.write(f, b"import sys;"
1180 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1181 )
1182 os.close(f)
1183
1184 def tearDown(self):
1185 os.remove(self.fname)
1186 super().tearDown()
1187
1188 def with_spaces(self, *args, **kwargs):
1189 kwargs['stdout'] = subprocess.PIPE
1190 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001191 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001192 self.assertEqual(
1193 p.stdout.read ().decode("mbcs"),
1194 "2 [%r, 'ab cd']" % self.fname
1195 )
1196
1197 def test_shell_string_with_spaces(self):
1198 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001199 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1200 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001201
1202 def test_shell_sequence_with_spaces(self):
1203 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001204 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001205
1206 def test_noshell_string_with_spaces(self):
1207 # call() function with string argument with spaces on Windows
1208 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1209 "ab cd"))
1210
1211 def test_noshell_sequence_with_spaces(self):
1212 # call() function with sequence argument with spaces on Windows
1213 self.with_spaces([sys.executable, self.fname, "ab cd"])
1214
Brian Curtin79cdb662010-12-03 02:46:02 +00001215
1216class ContextManagerTests(ProcessTestCase):
1217
1218 def test_pipe(self):
1219 with subprocess.Popen([sys.executable, "-c",
1220 "import sys;"
1221 "sys.stdout.write('stdout');"
1222 "sys.stderr.write('stderr');"],
1223 stdout=subprocess.PIPE,
1224 stderr=subprocess.PIPE) as proc:
1225 self.assertEqual(proc.stdout.read(), b"stdout")
1226 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1227
1228 self.assertTrue(proc.stdout.closed)
1229 self.assertTrue(proc.stderr.closed)
1230
1231 def test_returncode(self):
1232 with subprocess.Popen([sys.executable, "-c",
1233 "import sys; sys.exit(100)"]) as proc:
1234 proc.wait()
1235 self.assertEqual(proc.returncode, 100)
1236
1237 def test_communicate_stdin(self):
1238 with subprocess.Popen([sys.executable, "-c",
1239 "import sys;"
1240 "sys.exit(sys.stdin.read() == 'context')"],
1241 stdin=subprocess.PIPE) as proc:
1242 proc.communicate(b"context")
1243 self.assertEqual(proc.returncode, 1)
1244
1245 def test_invalid_args(self):
1246 with self.assertRaises(EnvironmentError) as c:
1247 with subprocess.Popen(['nonexisting_i_hope'],
1248 stdout=subprocess.PIPE,
1249 stderr=subprocess.PIPE) as proc:
1250 pass
1251
1252 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1253 raise c.exception
1254
1255
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001256def test_main():
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001257 unit_tests = (ProcessTestCase,
1258 POSIXProcessTestCase,
1259 Win32ProcessTestCase,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001260 ProcessTestCasePOSIXPurePython,
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001261 CommandTests,
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001262 ProcessTestCaseNoPoll,
Tim Golden126c2962010-08-11 14:20:40 +00001263 HelperFunctionTests,
Brian Curtin79cdb662010-12-03 02:46:02 +00001264 CommandsWithSpaces,
Gregory P. Smithd23047b2010-12-04 09:10:44 +00001265 ContextManagerTests,
1266 DeprecationWarningTests)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001267
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001268 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +00001269 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001270
1271if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +00001272 test_main()