blob: f07f49052b4bba7b0791d0e269a94c62e3c4f562 [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):
Gregory P. Smithd23047b2010-12-04 09:10:44 +000062 def testCloseFdsWarning(self):
63 quick_process = [sys.executable, "-c", "import sys; sys.exit(0)"]
Gregory P. Smithb4162302010-12-04 09:59:52 +000064 with warnings.catch_warnings(record=True) as warnlist:
65 warnings.simplefilter("always")
66 subprocess.call(quick_process, close_fds=True)
67 self.assertEqual([], warnlist)
68 subprocess.call(quick_process, close_fds=False)
69 self.assertEqual([], warnlist)
70 with self.assertWarns(DeprecationWarning) as wm:
71 subprocess.Popen(quick_process).wait()
72 self.assertEqual(1, len(wm.warnings))
73 self.assertIn('close_fds parameter was not specified',
74 str(wm.warnings[0]))
Gregory P. Smithd23047b2010-12-04 09:10:44 +000075
76
Florent Xiclunac049d872010-03-27 22:47:23 +000077class ProcessTestCase(BaseTestCase):
78
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000079 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000080 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000081 rc = subprocess.call([sys.executable, "-c",
82 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000083 self.assertEqual(rc, 47)
84
Peter Astrand454f7672005-01-01 09:36:35 +000085 def test_check_call_zero(self):
86 # check_call() function with zero return code
87 rc = subprocess.check_call([sys.executable, "-c",
88 "import sys; sys.exit(0)"])
89 self.assertEqual(rc, 0)
90
91 def test_check_call_nonzero(self):
92 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000093 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000094 subprocess.check_call([sys.executable, "-c",
95 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000096 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000097
Georg Brandlf9734072008-12-07 15:30:06 +000098 def test_check_output(self):
99 # check_output() function with zero return code
100 output = subprocess.check_output(
101 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000102 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000103
104 def test_check_output_nonzero(self):
105 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000106 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000107 subprocess.check_output(
108 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000109 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000110
111 def test_check_output_stderr(self):
112 # check_output() function stderr redirected to stdout
113 output = subprocess.check_output(
114 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
115 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000116 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000117
118 def test_check_output_stdout_arg(self):
119 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000120 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000121 output = subprocess.check_output(
122 [sys.executable, "-c", "print('will not be run')"],
123 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000124 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000125 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000126
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000127 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000128 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000129 newenv = os.environ.copy()
130 newenv["FRUIT"] = "banana"
131 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000132 'import sys, os;'
133 'sys.exit(os.getenv("FRUIT")=="banana")'],
134 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000135 self.assertEqual(rc, 1)
136
137 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000138 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000139 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000141 self.addCleanup(p.stdout.close)
142 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000143 p.wait()
144 self.assertEqual(p.stdin, None)
145
146 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000147 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000148 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000149 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000150 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000151 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000152 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000153 self.addCleanup(p.stdin.close)
154 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000155 p.wait()
156 self.assertEqual(p.stdout, None)
157
158 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000159 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000160 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000161 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000162 self.addCleanup(p.stdout.close)
163 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000164 p.wait()
165 self.assertEqual(p.stderr, None)
166
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000167 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000168 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000169 p = subprocess.Popen(["somethingyoudonthave", "-c",
170 "import sys; sys.exit(47)"],
171 executable=sys.executable, cwd=python_dir)
172 p.wait()
173 self.assertEqual(p.returncode, 47)
174
175 @unittest.skipIf(sysconfig.is_python_build(),
176 "need an installed Python. See #7774")
177 def test_executable_without_cwd(self):
178 # For a normal installation, it should work without 'cwd'
179 # argument. For test runs in the build directory, see #7774.
180 p = subprocess.Popen(["somethingyoudonthave", "-c",
181 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000182 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000183 p.wait()
184 self.assertEqual(p.returncode, 47)
185
186 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000187 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000188 p = subprocess.Popen([sys.executable, "-c",
189 'import sys; sys.exit(sys.stdin.read() == "pear")'],
190 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000191 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000192 p.stdin.close()
193 p.wait()
194 self.assertEqual(p.returncode, 1)
195
196 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000197 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000198 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000199 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000200 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000201 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000202 os.lseek(d, 0, 0)
203 p = subprocess.Popen([sys.executable, "-c",
204 'import sys; sys.exit(sys.stdin.read() == "pear")'],
205 stdin=d)
206 p.wait()
207 self.assertEqual(p.returncode, 1)
208
209 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000210 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000211 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000212 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000213 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000214 tf.seek(0)
215 p = subprocess.Popen([sys.executable, "-c",
216 'import sys; sys.exit(sys.stdin.read() == "pear")'],
217 stdin=tf)
218 p.wait()
219 self.assertEqual(p.returncode, 1)
220
221 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000222 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223 p = subprocess.Popen([sys.executable, "-c",
224 'import sys; sys.stdout.write("orange")'],
225 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000226 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000227 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000228
229 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000230 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000231 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000232 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233 d = tf.fileno()
234 p = subprocess.Popen([sys.executable, "-c",
235 'import sys; sys.stdout.write("orange")'],
236 stdout=d)
237 p.wait()
238 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000239 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000240
241 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000242 # stdout is set to open file object
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 p = subprocess.Popen([sys.executable, "-c",
246 'import sys; sys.stdout.write("orange")'],
247 stdout=tf)
248 p.wait()
249 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000250 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251
252 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000253 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000254 p = subprocess.Popen([sys.executable, "-c",
255 'import sys; sys.stderr.write("strawberry")'],
256 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000257 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000258 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000259
260 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000261 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000262 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000263 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000264 d = tf.fileno()
265 p = subprocess.Popen([sys.executable, "-c",
266 'import sys; sys.stderr.write("strawberry")'],
267 stderr=d)
268 p.wait()
269 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000270 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271
272 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000273 # stderr is set to open file object
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 p = subprocess.Popen([sys.executable, "-c",
277 'import sys; sys.stderr.write("strawberry")'],
278 stderr=tf)
279 p.wait()
280 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000281 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282
283 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000284 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000286 'import sys;'
287 'sys.stdout.write("apple");'
288 'sys.stdout.flush();'
289 'sys.stderr.write("orange")'],
290 stdout=subprocess.PIPE,
291 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000292 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000293 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294
295 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000296 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000297 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000298 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000299 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000300 'import sys;'
301 'sys.stdout.write("apple");'
302 'sys.stdout.flush();'
303 'sys.stderr.write("orange")'],
304 stdout=tf,
305 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306 p.wait()
307 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000308 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309
Thomas Wouters89f507f2006-12-13 04:49:30 +0000310 def test_stdout_filedes_of_stdout(self):
311 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000312 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000313 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000314 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000315
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000316 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000317 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000318 # We cannot use os.path.realpath to canonicalize the path,
319 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
320 cwd = os.getcwd()
321 os.chdir(tmpdir)
322 tmpdir = os.getcwd()
323 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000324 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000325 'import sys,os;'
326 'sys.stdout.write(os.getcwd())'],
327 stdout=subprocess.PIPE,
328 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000329 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000330 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000331 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
332 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000333
334 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000335 newenv = os.environ.copy()
336 newenv["FRUIT"] = "orange"
337 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000338 'import sys,os;'
339 'sys.stdout.write(os.getenv("FRUIT"))'],
340 stdout=subprocess.PIPE,
341 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000342 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000343 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000344
Peter Astrandcbac93c2005-03-03 20:24:28 +0000345 def test_communicate_stdin(self):
346 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000347 'import sys;'
348 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000349 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000350 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000351 self.assertEqual(p.returncode, 1)
352
353 def test_communicate_stdout(self):
354 p = subprocess.Popen([sys.executable, "-c",
355 'import sys; sys.stdout.write("pineapple")'],
356 stdout=subprocess.PIPE)
357 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000358 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000359 self.assertEqual(stderr, None)
360
361 def test_communicate_stderr(self):
362 p = subprocess.Popen([sys.executable, "-c",
363 'import sys; sys.stderr.write("pineapple")'],
364 stderr=subprocess.PIPE)
365 (stdout, stderr) = p.communicate()
366 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000367 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000368
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000369 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000371 'import sys,os;'
372 'sys.stderr.write("pineapple");'
373 'sys.stdout.write(sys.stdin.read())'],
374 stdin=subprocess.PIPE,
375 stdout=subprocess.PIPE,
376 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000377 self.addCleanup(p.stdout.close)
378 self.addCleanup(p.stderr.close)
379 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000380 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000381 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000382 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000383
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000384 # This test is Linux specific for simplicity to at least have
385 # some coverage. It is not a platform specific bug.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000386 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
387 "Linux specific")
388 # Test for the fd leak reported in http://bugs.python.org/issue2791.
389 def test_communicate_pipe_fd_leak(self):
390 fd_directory = '/proc/%d/fd' % os.getpid()
391 num_fds_before_popen = len(os.listdir(fd_directory))
392 p = subprocess.Popen([sys.executable, "-c", "print()"],
393 stdout=subprocess.PIPE)
394 p.communicate()
395 num_fds_after_communicate = len(os.listdir(fd_directory))
396 del p
397 num_fds_after_destruction = len(os.listdir(fd_directory))
398 self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
399 self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000400
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000401 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000402 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000403 p = subprocess.Popen([sys.executable, "-c",
404 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000405 (stdout, stderr) = p.communicate()
406 self.assertEqual(stdout, None)
407 self.assertEqual(stderr, None)
408
409 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000410 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000411 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000412 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413 x, y = os.pipe()
414 if mswindows:
415 pipe_buf = 512
416 else:
417 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
418 os.close(x)
419 os.close(y)
420 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000421 'import sys,os;'
422 'sys.stdout.write(sys.stdin.read(47));'
423 'sys.stderr.write("xyz"*%d);'
424 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
425 stdin=subprocess.PIPE,
426 stdout=subprocess.PIPE,
427 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000428 self.addCleanup(p.stdout.close)
429 self.addCleanup(p.stderr.close)
430 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000431 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000432 (stdout, stderr) = p.communicate(string_to_write)
433 self.assertEqual(stdout, string_to_write)
434
435 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000436 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000437 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000438 'import sys,os;'
439 'sys.stdout.write(sys.stdin.read())'],
440 stdin=subprocess.PIPE,
441 stdout=subprocess.PIPE,
442 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000443 self.addCleanup(p.stdout.close)
444 self.addCleanup(p.stderr.close)
445 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000446 p.stdin.write(b"banana")
447 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000448 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000449 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000450
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000451 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000453 'import sys,os;' + SETBINARY +
454 'sys.stdout.write("line1\\n");'
455 'sys.stdout.flush();'
456 'sys.stdout.write("line2\\n");'
457 'sys.stdout.flush();'
458 'sys.stdout.write("line3\\r\\n");'
459 'sys.stdout.flush();'
460 'sys.stdout.write("line4\\r");'
461 'sys.stdout.flush();'
462 'sys.stdout.write("\\nline5");'
463 'sys.stdout.flush();'
464 'sys.stdout.write("\\nline6");'],
465 stdout=subprocess.PIPE,
466 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000467 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000469 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470
471 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000472 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000473 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000474 'import sys,os;' + SETBINARY +
475 'sys.stdout.write("line1\\n");'
476 'sys.stdout.flush();'
477 'sys.stdout.write("line2\\n");'
478 'sys.stdout.flush();'
479 'sys.stdout.write("line3\\r\\n");'
480 'sys.stdout.flush();'
481 'sys.stdout.write("line4\\r");'
482 'sys.stdout.flush();'
483 'sys.stdout.write("\\nline5");'
484 'sys.stdout.flush();'
485 'sys.stdout.write("\\nline6");'],
486 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
487 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000488 self.addCleanup(p.stdout.close)
489 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000491 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492
493 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000494 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000495 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000496 max_handles = 1026 # too much for most UNIX systems
497 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000498 max_handles = 2050 # too much for (at least some) Windows setups
499 handles = []
500 try:
501 for i in range(max_handles):
502 try:
503 handles.append(os.open(support.TESTFN,
504 os.O_WRONLY | os.O_CREAT))
505 except OSError as e:
506 if e.errno != errno.EMFILE:
507 raise
508 break
509 else:
510 self.skipTest("failed to reach the file descriptor limit "
511 "(tried %d)" % max_handles)
512 # Close a couple of them (should be enough for a subprocess)
513 for i in range(10):
514 os.close(handles.pop())
515 # Loop creating some subprocesses. If one of them leaks some fds,
516 # the next loop iteration will fail by reaching the max fd limit.
517 for i in range(15):
518 p = subprocess.Popen([sys.executable, "-c",
519 "import sys;"
520 "sys.stdout.write(sys.stdin.read())"],
521 stdin=subprocess.PIPE,
522 stdout=subprocess.PIPE,
523 stderr=subprocess.PIPE)
524 data = p.communicate(b"lime")[0]
525 self.assertEqual(data, b"lime")
526 finally:
527 for h in handles:
528 os.close(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000529
530 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
532 '"a b c" d e')
533 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
534 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000535 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
536 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
538 'a\\\\\\b "de fg" h')
539 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
540 'a\\\\\\"b c d')
541 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
542 '"a\\\\b c" d e')
543 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
544 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000545 self.assertEqual(subprocess.list2cmdline(['ab', '']),
546 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547
548
549 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000550 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000551 "-c", "import time; time.sleep(1)"])
552 count = 0
553 while p.poll() is None:
554 time.sleep(0.1)
555 count += 1
556 # We expect that the poll loop probably went around about 10 times,
557 # but, based on system scheduling we can't control, it's possible
558 # poll() never returned None. It "should be" very rare that it
559 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000560 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561 # Subsequent invocations should just return the returncode
562 self.assertEqual(p.poll(), 0)
563
564
565 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000566 p = subprocess.Popen([sys.executable,
567 "-c", "import time; time.sleep(2)"])
568 self.assertEqual(p.wait(), 0)
569 # Subsequent invocations should just return the returncode
570 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000571
Peter Astrand738131d2004-11-30 21:04:45 +0000572
573 def test_invalid_bufsize(self):
574 # an invalid type of the bufsize argument should raise
575 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000576 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000577 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000578
Guido van Rossum46a05a72007-06-07 21:56:45 +0000579 def test_bufsize_is_none(self):
580 # bufsize=None should be the same as bufsize=0.
581 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
582 self.assertEqual(p.wait(), 0)
583 # Again with keyword arg
584 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
585 self.assertEqual(p.wait(), 0)
586
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000587 def test_leaking_fds_on_error(self):
588 # see bug #5179: Popen leaks file descriptors to PIPEs if
589 # the child fails to execute; this will eventually exhaust
590 # the maximum number of open fds. 1024 seems a very common
591 # value for that limit, but Windows has 2048, so we loop
592 # 1024 times (each call leaked two fds).
593 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000594 # Windows raises IOError. Others raise OSError.
595 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000596 subprocess.Popen(['nonexisting_i_hope'],
597 stdout=subprocess.PIPE,
598 stderr=subprocess.PIPE)
Antoine Pitrou679e0f22010-09-18 17:56:02 +0000599 if c.exception.errno != errno.ENOENT: # ignore "no such file"
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000600 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000601
Victor Stinnerb3693582010-05-21 20:13:12 +0000602 def test_issue8780(self):
603 # Ensure that stdout is inherited from the parent
604 # if stdout=PIPE is not used
605 code = ';'.join((
606 'import subprocess, sys',
607 'retcode = subprocess.call('
608 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
609 'assert retcode == 0'))
610 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000611 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000612
Tim Goldenaf5ac392010-08-06 13:03:56 +0000613 def test_handles_closed_on_exception(self):
614 # If CreateProcess exits with an error, ensure the
615 # duplicate output handles are released
616 ifhandle, ifname = mkstemp()
617 ofhandle, ofname = mkstemp()
618 efhandle, efname = mkstemp()
619 try:
620 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
621 stderr=efhandle)
622 except OSError:
623 os.close(ifhandle)
624 os.remove(ifname)
625 os.close(ofhandle)
626 os.remove(ofname)
627 os.close(efhandle)
628 os.remove(efname)
629 self.assertFalse(os.path.exists(ifname))
630 self.assertFalse(os.path.exists(ofname))
631 self.assertFalse(os.path.exists(efname))
632
Tim Peterse718f612004-10-12 21:51:32 +0000633
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000634# context manager
635class _SuppressCoreFiles(object):
636 """Try to prevent core files from being created."""
637 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000638
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000639 def __enter__(self):
640 """Try to save previous ulimit, then set it to (0, 0)."""
641 try:
642 import resource
643 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
644 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
645 except (ImportError, ValueError, resource.error):
646 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000647
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000648 if sys.platform == 'darwin':
649 # Check if the 'Crash Reporter' on OSX was configured
650 # in 'Developer' mode and warn that it will get triggered
651 # when it is.
652 #
653 # This assumes that this context manager is used in tests
654 # that might trigger the next manager.
655 value = subprocess.Popen(['/usr/bin/defaults', 'read',
656 'com.apple.CrashReporter', 'DialogType'],
657 stdout=subprocess.PIPE).communicate()[0]
658 if value.strip() == b'developer':
659 print("this tests triggers the Crash Reporter, "
660 "that is intentional", end='')
661 sys.stdout.flush()
662
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000663 def __exit__(self, *args):
664 """Return core file behavior to default."""
665 if self.old_limit is None:
666 return
667 try:
668 import resource
669 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
670 except (ImportError, ValueError, resource.error):
671 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000672
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000673
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000674@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000675class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000676
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000677 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000678 nonexistent_dir = "/_this/pa.th/does/not/exist"
679 try:
680 os.chdir(nonexistent_dir)
681 except OSError as e:
682 # This avoids hard coding the errno value or the OS perror()
683 # string and instead capture the exception that we want to see
684 # below for comparison.
685 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000686 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000687 else:
688 self.fail("chdir to nonexistant directory %s succeeded." %
689 nonexistent_dir)
690
691 # Error in the child re-raised in the parent.
692 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000693 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000694 cwd=nonexistent_dir)
695 except OSError as e:
696 # Test that the child process chdir failure actually makes
697 # it up to the parent process as the correct exception.
698 self.assertEqual(desired_exception.errno, e.errno)
699 self.assertEqual(desired_exception.strerror, e.strerror)
700 else:
701 self.fail("Expected OSError: %s" % desired_exception)
702
703 def test_restore_signals(self):
704 # Code coverage for both values of restore_signals to make sure it
705 # at least does not blow up.
706 # A test for behavior would be complex. Contributions welcome.
707 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
708 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
709
710 def test_start_new_session(self):
711 # For code coverage of calling setsid(). We don't care if we get an
712 # EPERM error from it depending on the test execution environment, that
713 # still indicates that it was called.
714 try:
715 output = subprocess.check_output(
716 [sys.executable, "-c",
717 "import os; print(os.getpgid(os.getpid()))"],
718 start_new_session=True)
719 except OSError as e:
720 if e.errno != errno.EPERM:
721 raise
722 else:
723 parent_pgid = os.getpgid(os.getpid())
724 child_pgid = int(output)
725 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000726
727 def test_run_abort(self):
728 # returncode handles signal termination
729 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000731 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000732 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000733 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000735 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000736 # DISCLAIMER: Setting environment variables is *not* a good use
737 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000738 p = subprocess.Popen([sys.executable, "-c",
739 'import sys,os;'
740 'sys.stdout.write(os.getenv("FRUIT"))'],
741 stdout=subprocess.PIPE,
742 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000743 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000744 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000745
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000746 def test_preexec_exception(self):
747 def raise_it():
748 raise ValueError("What if two swallows carried a coconut?")
749 try:
750 p = subprocess.Popen([sys.executable, "-c", ""],
751 preexec_fn=raise_it)
752 except RuntimeError as e:
753 self.assertTrue(
754 subprocess._posixsubprocess,
755 "Expected a ValueError from the preexec_fn")
756 except ValueError as e:
757 self.assertIn("coconut", e.args[0])
758 else:
759 self.fail("Exception raised by preexec_fn did not make it "
760 "to the parent process.")
761
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000762 @unittest.skipUnless(gc, "Requires a gc module.")
763 def test_preexec_gc_module_failure(self):
764 # This tests the code that disables garbage collection if the child
765 # process will execute any Python.
766 def raise_runtime_error():
767 raise RuntimeError("this shouldn't escape")
768 enabled = gc.isenabled()
769 orig_gc_disable = gc.disable
770 orig_gc_isenabled = gc.isenabled
771 try:
772 gc.disable()
773 self.assertFalse(gc.isenabled())
774 subprocess.call([sys.executable, '-c', ''],
775 preexec_fn=lambda: None)
776 self.assertFalse(gc.isenabled(),
777 "Popen enabled gc when it shouldn't.")
778
779 gc.enable()
780 self.assertTrue(gc.isenabled())
781 subprocess.call([sys.executable, '-c', ''],
782 preexec_fn=lambda: None)
783 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
784
785 gc.disable = raise_runtime_error
786 self.assertRaises(RuntimeError, subprocess.Popen,
787 [sys.executable, '-c', ''],
788 preexec_fn=lambda: None)
789
790 del gc.isenabled # force an AttributeError
791 self.assertRaises(AttributeError, subprocess.Popen,
792 [sys.executable, '-c', ''],
793 preexec_fn=lambda: None)
794 finally:
795 gc.disable = orig_gc_disable
796 gc.isenabled = orig_gc_isenabled
797 if not enabled:
798 gc.disable()
799
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000800 def test_args_string(self):
801 # args is a string
802 fd, fname = mkstemp()
803 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000804 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000805 fobj.write("#!/bin/sh\n")
806 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
807 sys.executable)
808 os.chmod(fname, 0o700)
809 p = subprocess.Popen(fname)
810 p.wait()
811 os.remove(fname)
812 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000813
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000814 def test_invalid_args(self):
815 # invalid arguments should raise ValueError
816 self.assertRaises(ValueError, subprocess.call,
817 [sys.executable, "-c",
818 "import sys; sys.exit(47)"],
819 startupinfo=47)
820 self.assertRaises(ValueError, subprocess.call,
821 [sys.executable, "-c",
822 "import sys; sys.exit(47)"],
823 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000824
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000825 def test_shell_sequence(self):
826 # Run command through the shell (sequence)
827 newenv = os.environ.copy()
828 newenv["FRUIT"] = "apple"
829 p = subprocess.Popen(["echo $FRUIT"], shell=1,
830 stdout=subprocess.PIPE,
831 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000832 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000833 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000834
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000835 def test_shell_string(self):
836 # Run command through the shell (string)
837 newenv = os.environ.copy()
838 newenv["FRUIT"] = "apple"
839 p = subprocess.Popen("echo $FRUIT", shell=1,
840 stdout=subprocess.PIPE,
841 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000842 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000843 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000844
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000845 def test_call_string(self):
846 # call() function with string argument on UNIX
847 fd, fname = mkstemp()
848 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000849 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000850 fobj.write("#!/bin/sh\n")
851 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
852 sys.executable)
853 os.chmod(fname, 0o700)
854 rc = subprocess.call(fname)
855 os.remove(fname)
856 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000857
Stefan Krah9542cc62010-07-19 14:20:53 +0000858 def test_specific_shell(self):
859 # Issue #9265: Incorrect name passed as arg[0].
860 shells = []
861 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
862 for name in ['bash', 'ksh']:
863 sh = os.path.join(prefix, name)
864 if os.path.isfile(sh):
865 shells.append(sh)
866 if not shells: # Will probably work for any shell but csh.
867 self.skipTest("bash or ksh required for this test")
868 sh = '/bin/sh'
869 if os.path.isfile(sh) and not os.path.islink(sh):
870 # Test will fail if /bin/sh is a symlink to csh.
871 shells.append(sh)
872 for sh in shells:
873 p = subprocess.Popen("echo $0", executable=sh, shell=True,
874 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000875 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000876 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
877
Florent Xicluna4886d242010-03-08 13:27:26 +0000878 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000879 # Do not inherit file handles from the parent.
880 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000881 p = subprocess.Popen([sys.executable, "-c", """if 1:
882 import sys, time
883 sys.stdout.write('x\\n')
884 sys.stdout.flush()
885 time.sleep(30)
886 """],
887 close_fds=True,
888 stdin=subprocess.PIPE,
889 stdout=subprocess.PIPE,
890 stderr=subprocess.PIPE)
891 # Wait for the interpreter to be completely initialized before
892 # sending any signal.
893 p.stdout.read(1)
894 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000895 return p
896
897 def test_send_signal(self):
898 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000899 _, stderr = p.communicate()
900 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000901 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000902
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000903 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000904 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000905 _, stderr = p.communicate()
906 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000907 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000908
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000909 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000910 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000911 _, stderr = p.communicate()
912 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000913 self.assertEqual(p.wait(), -signal.SIGTERM)
914
Victor Stinner13bb71c2010-04-23 21:41:56 +0000915 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +0000916 def prepare():
917 raise ValueError("surrogate:\uDCff")
918
919 try:
920 subprocess.call(
921 [sys.executable, "-c", "pass"],
922 preexec_fn=prepare)
923 except ValueError as err:
924 # Pure Python implementations keeps the message
925 self.assertIsNone(subprocess._posixsubprocess)
926 self.assertEqual(str(err), "surrogate:\uDCff")
927 except RuntimeError as err:
928 # _posixsubprocess uses a default message
929 self.assertIsNotNone(subprocess._posixsubprocess)
930 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
931 else:
932 self.fail("Expected ValueError or RuntimeError")
933
Victor Stinner13bb71c2010-04-23 21:41:56 +0000934 def test_undecodable_env(self):
935 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +0000936 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +0000937 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000938 env = os.environ.copy()
939 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +0000940 # Use C locale to get ascii for the locale encoding to force
941 # surrogate-escaping of \xFF in the child process; otherwise it can
942 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +0000943 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +0000944 stdout = subprocess.check_output(
945 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000946 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +0000947 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000948 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +0000949
950 # test bytes
951 key = key.encode("ascii", "surrogateescape")
952 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +0000953 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +0000954 env = os.environ.copy()
955 env[key] = value
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
Victor Stinnerb745a742010-05-18 17:17:23 +0000962 def test_bytes_program(self):
963 abs_program = os.fsencode(sys.executable)
964 path, program = os.path.split(sys.executable)
965 program = os.fsencode(program)
966
967 # absolute bytes path
968 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000969 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +0000970
971 # bytes program, unicode PATH
972 env = os.environ.copy()
973 env["PATH"] = path
974 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000975 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +0000976
977 # bytes program, bytes PATH
978 envb = os.environb.copy()
979 envb[b"PATH"] = os.fsencode(path)
980 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000981 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +0000982
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000983
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000984@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000985class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000986
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000987 def test_startupinfo(self):
988 # startupinfo argument
989 # We uses hardcoded constants, because we do not want to
990 # depend on win32all.
991 STARTF_USESHOWWINDOW = 1
992 SW_MAXIMIZE = 3
993 startupinfo = subprocess.STARTUPINFO()
994 startupinfo.dwFlags = STARTF_USESHOWWINDOW
995 startupinfo.wShowWindow = SW_MAXIMIZE
996 # Since Python is a console process, it won't be affected
997 # by wShowWindow, but the argument should be silently
998 # ignored
999 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001000 startupinfo=startupinfo)
1001
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001002 def test_creationflags(self):
1003 # creationflags argument
1004 CREATE_NEW_CONSOLE = 16
1005 sys.stderr.write(" a DOS box should flash briefly ...\n")
1006 subprocess.call(sys.executable +
1007 ' -c "import time; time.sleep(0.25)"',
1008 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001009
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001010 def test_invalid_args(self):
1011 # invalid arguments should raise ValueError
1012 self.assertRaises(ValueError, subprocess.call,
1013 [sys.executable, "-c",
1014 "import sys; sys.exit(47)"],
1015 preexec_fn=lambda: 1)
1016 self.assertRaises(ValueError, subprocess.call,
1017 [sys.executable, "-c",
1018 "import sys; sys.exit(47)"],
1019 stdout=subprocess.PIPE,
1020 close_fds=True)
1021
1022 def test_close_fds(self):
1023 # close file descriptors
1024 rc = subprocess.call([sys.executable, "-c",
1025 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001026 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001027 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001028
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001029 def test_shell_sequence(self):
1030 # Run command through the shell (sequence)
1031 newenv = os.environ.copy()
1032 newenv["FRUIT"] = "physalis"
1033 p = subprocess.Popen(["set"], shell=1,
1034 stdout=subprocess.PIPE,
1035 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001036 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001037 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001038
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001039 def test_shell_string(self):
1040 # Run command through the shell (string)
1041 newenv = os.environ.copy()
1042 newenv["FRUIT"] = "physalis"
1043 p = subprocess.Popen("set", shell=1,
1044 stdout=subprocess.PIPE,
1045 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001046 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001047 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001048
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001049 def test_call_string(self):
1050 # call() function with string argument on Windows
1051 rc = subprocess.call(sys.executable +
1052 ' -c "import sys; sys.exit(47)"')
1053 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001054
Florent Xicluna4886d242010-03-08 13:27:26 +00001055 def _kill_process(self, method, *args):
1056 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001057 p = subprocess.Popen([sys.executable, "-c", """if 1:
1058 import sys, time
1059 sys.stdout.write('x\\n')
1060 sys.stdout.flush()
1061 time.sleep(30)
1062 """],
1063 stdin=subprocess.PIPE,
1064 stdout=subprocess.PIPE,
1065 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001066 self.addCleanup(p.stdout.close)
1067 self.addCleanup(p.stderr.close)
1068 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001069 # Wait for the interpreter to be completely initialized before
1070 # sending any signal.
1071 p.stdout.read(1)
1072 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001073 _, stderr = p.communicate()
1074 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001075 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001076 self.assertNotEqual(returncode, 0)
1077
1078 def test_send_signal(self):
1079 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001080
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001081 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001082 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001083
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001084 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001085 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001086
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001087
Brett Cannona23810f2008-05-26 19:04:21 +00001088# The module says:
1089# "NB This only works (and is only relevant) for UNIX."
1090#
1091# Actually, getoutput should work on any platform with an os.popen, but
1092# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001093@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001094class CommandTests(unittest.TestCase):
1095 def test_getoutput(self):
1096 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1097 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1098 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001099
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001100 # we use mkdtemp in the next line to create an empty directory
1101 # under our exclusive control; from that, we can invent a pathname
1102 # that we _know_ won't exist. This is guaranteed to fail.
1103 dir = None
1104 try:
1105 dir = tempfile.mkdtemp()
1106 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001107
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001108 status, output = subprocess.getstatusoutput('cat ' + name)
1109 self.assertNotEqual(status, 0)
1110 finally:
1111 if dir is not None:
1112 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001113
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001114
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001115@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1116 "poll system call not supported")
1117class ProcessTestCaseNoPoll(ProcessTestCase):
1118 def setUp(self):
1119 subprocess._has_poll = False
1120 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001121
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001122 def tearDown(self):
1123 subprocess._has_poll = True
1124 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001125
1126
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001127@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1128 "_posixsubprocess extension module not found.")
1129class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
1130 def setUp(self):
1131 subprocess._posixsubprocess = None
1132 ProcessTestCase.setUp(self)
1133 POSIXProcessTestCase.setUp(self)
1134
1135 def tearDown(self):
1136 subprocess._posixsubprocess = sys.modules['_posixsubprocess']
1137 POSIXProcessTestCase.tearDown(self)
1138 ProcessTestCase.tearDown(self)
1139
1140
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001141class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001142 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001143 def test_eintr_retry_call(self):
1144 record_calls = []
1145 def fake_os_func(*args):
1146 record_calls.append(args)
1147 if len(record_calls) == 2:
1148 raise OSError(errno.EINTR, "fake interrupted system call")
1149 return tuple(reversed(args))
1150
1151 self.assertEqual((999, 256),
1152 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1153 self.assertEqual([(256, 999)], record_calls)
1154 # This time there will be an EINTR so it will loop once.
1155 self.assertEqual((666,),
1156 subprocess._eintr_retry_call(fake_os_func, 666))
1157 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1158
1159
Tim Golden126c2962010-08-11 14:20:40 +00001160@unittest.skipUnless(mswindows, "Windows-specific tests")
1161class CommandsWithSpaces (BaseTestCase):
1162
1163 def setUp(self):
1164 super().setUp()
1165 f, fname = mkstemp(".py", "te st")
1166 self.fname = fname.lower ()
1167 os.write(f, b"import sys;"
1168 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1169 )
1170 os.close(f)
1171
1172 def tearDown(self):
1173 os.remove(self.fname)
1174 super().tearDown()
1175
1176 def with_spaces(self, *args, **kwargs):
1177 kwargs['stdout'] = subprocess.PIPE
1178 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001179 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001180 self.assertEqual(
1181 p.stdout.read ().decode("mbcs"),
1182 "2 [%r, 'ab cd']" % self.fname
1183 )
1184
1185 def test_shell_string_with_spaces(self):
1186 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001187 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1188 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001189
1190 def test_shell_sequence_with_spaces(self):
1191 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001192 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001193
1194 def test_noshell_string_with_spaces(self):
1195 # call() function with string argument with spaces on Windows
1196 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1197 "ab cd"))
1198
1199 def test_noshell_sequence_with_spaces(self):
1200 # call() function with sequence argument with spaces on Windows
1201 self.with_spaces([sys.executable, self.fname, "ab cd"])
1202
Brian Curtin79cdb662010-12-03 02:46:02 +00001203
1204class ContextManagerTests(ProcessTestCase):
1205
1206 def test_pipe(self):
1207 with subprocess.Popen([sys.executable, "-c",
1208 "import sys;"
1209 "sys.stdout.write('stdout');"
1210 "sys.stderr.write('stderr');"],
1211 stdout=subprocess.PIPE,
1212 stderr=subprocess.PIPE) as proc:
1213 self.assertEqual(proc.stdout.read(), b"stdout")
1214 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1215
1216 self.assertTrue(proc.stdout.closed)
1217 self.assertTrue(proc.stderr.closed)
1218
1219 def test_returncode(self):
1220 with subprocess.Popen([sys.executable, "-c",
1221 "import sys; sys.exit(100)"]) as proc:
1222 proc.wait()
1223 self.assertEqual(proc.returncode, 100)
1224
1225 def test_communicate_stdin(self):
1226 with subprocess.Popen([sys.executable, "-c",
1227 "import sys;"
1228 "sys.exit(sys.stdin.read() == 'context')"],
1229 stdin=subprocess.PIPE) as proc:
1230 proc.communicate(b"context")
1231 self.assertEqual(proc.returncode, 1)
1232
1233 def test_invalid_args(self):
1234 with self.assertRaises(EnvironmentError) as c:
1235 with subprocess.Popen(['nonexisting_i_hope'],
1236 stdout=subprocess.PIPE,
1237 stderr=subprocess.PIPE) as proc:
1238 pass
1239
1240 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1241 raise c.exception
1242
1243
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001244def test_main():
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001245 unit_tests = (ProcessTestCase,
1246 POSIXProcessTestCase,
1247 Win32ProcessTestCase,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001248 ProcessTestCasePOSIXPurePython,
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001249 CommandTests,
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001250 ProcessTestCaseNoPoll,
Tim Golden126c2962010-08-11 14:20:40 +00001251 HelperFunctionTests,
Brian Curtin79cdb662010-12-03 02:46:02 +00001252 CommandsWithSpaces,
Gregory P. Smithd23047b2010-12-04 09:10:44 +00001253 ContextManagerTests,
1254 DeprecationWarningTests)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001255
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001256 support.run_unittest(*unit_tests)
Brett Cannona23810f2008-05-26 19:04:21 +00001257 support.reap_children()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001258
1259if __name__ == "__main__":
Brett Cannona23810f2008-05-26 19:04:21 +00001260 test_main()