Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1 | import unittest |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1ef8c7e | 2016-06-04 00:22:17 +0000 | [diff] [blame] | 2 | from unittest import mock |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 3 | from test import support |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 4 | import subprocess |
| 5 | import sys |
| 6 | import signal |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 7 | import io |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 8 | import os |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 9 | import errno |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 10 | import tempfile |
| 11 | import time |
Charles-François Natali | 3a4586a | 2013-11-08 19:56:59 +0100 | [diff] [blame] | 12 | import selectors |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 13 | import sysconfig |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 14 | import select |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 15 | import shutil |
Benjamin Peterson | b870aa1 | 2011-12-10 12:44:25 -0500 | [diff] [blame] | 16 | import gc |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 17 | import textwrap |
Benjamin Peterson | 964561b | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 18 | |
| 19 | try: |
Antoine Pitrou | a839271 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 20 | import threading |
| 21 | except ImportError: |
| 22 | threading = None |
Benjamin Peterson | 964561b | 2011-12-10 12:31:42 -0500 | [diff] [blame] | 23 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 24 | mswindows = (sys.platform == "win32") |
| 25 | |
| 26 | # |
| 27 | # Depends on the following external programs: Python |
| 28 | # |
| 29 | |
| 30 | if mswindows: |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 31 | SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), ' |
| 32 | 'os.O_BINARY);') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 33 | else: |
| 34 | SETBINARY = '' |
| 35 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 36 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 37 | class BaseTestCase(unittest.TestCase): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 38 | def setUp(self): |
| 39 | # Try to minimize the number of children we have so this test |
| 40 | # doesn't crash on some buildbots (Alphas in particular). |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 41 | support.reap_children() |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 42 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 43 | def tearDown(self): |
| 44 | for inst in subprocess._active: |
| 45 | inst.wait() |
| 46 | subprocess._cleanup() |
| 47 | self.assertFalse(subprocess._active, "subprocess._active not empty") |
| 48 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 49 | def assertStderrEqual(self, stderr, expected, msg=None): |
| 50 | # In a debug build, stuff like "[6580 refs]" is printed to stderr at |
| 51 | # shutdown time. That frustrates tests trying to check stderr produced |
| 52 | # from a spawned Python process. |
Antoine Pitrou | 62f68ed | 2010-08-04 11:48:56 +0000 | [diff] [blame] | 53 | actual = support.strip_python_stderr(stderr) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 54 | # strip_python_stderr also strips whitespace, so we do too. |
| 55 | expected = expected.strip() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 56 | self.assertEqual(actual, expected, msg) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 57 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 58 | |
Gregory P. Smith | 3d8e776 | 2012-11-10 22:32:22 -0800 | [diff] [blame] | 59 | class PopenTestException(Exception): |
| 60 | pass |
| 61 | |
| 62 | |
| 63 | class PopenExecuteChildRaises(subprocess.Popen): |
| 64 | """Popen subclass for testing cleanup of subprocess.PIPE filehandles when |
| 65 | _execute_child fails. |
| 66 | """ |
| 67 | def _execute_child(self, *args, **kwargs): |
| 68 | raise PopenTestException("Forced Exception for Test") |
| 69 | |
| 70 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 71 | class ProcessTestCase(BaseTestCase): |
| 72 | |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 73 | def test_io_buffered_by_default(self): |
| 74 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 75 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 76 | stderr=subprocess.PIPE) |
| 77 | try: |
| 78 | self.assertIsInstance(p.stdin, io.BufferedIOBase) |
| 79 | self.assertIsInstance(p.stdout, io.BufferedIOBase) |
| 80 | self.assertIsInstance(p.stderr, io.BufferedIOBase) |
| 81 | finally: |
Gregory P. Smith | a1b9ed3 | 2013-03-23 11:54:22 -0700 | [diff] [blame] | 82 | p.stdin.close() |
| 83 | p.stdout.close() |
| 84 | p.stderr.close() |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 85 | p.wait() |
| 86 | |
| 87 | def test_io_unbuffered_works(self): |
| 88 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 89 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 90 | stderr=subprocess.PIPE, bufsize=0) |
| 91 | try: |
| 92 | self.assertIsInstance(p.stdin, io.RawIOBase) |
| 93 | self.assertIsInstance(p.stdout, io.RawIOBase) |
| 94 | self.assertIsInstance(p.stderr, io.RawIOBase) |
| 95 | finally: |
Gregory P. Smith | a1b9ed3 | 2013-03-23 11:54:22 -0700 | [diff] [blame] | 96 | p.stdin.close() |
| 97 | p.stdout.close() |
| 98 | p.stderr.close() |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 99 | p.wait() |
| 100 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 101 | def test_call_seq(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 102 | # call() function with sequence argument |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 103 | rc = subprocess.call([sys.executable, "-c", |
| 104 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 105 | self.assertEqual(rc, 47) |
| 106 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 107 | def test_call_timeout(self): |
| 108 | # call() function with timeout argument; we want to test that the child |
| 109 | # process gets killed when the timeout expires. If the child isn't |
| 110 | # killed, this call will deadlock since subprocess.call waits for the |
| 111 | # child. |
| 112 | self.assertRaises(subprocess.TimeoutExpired, subprocess.call, |
| 113 | [sys.executable, "-c", "while True: pass"], |
| 114 | timeout=0.1) |
| 115 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 116 | def test_check_call_zero(self): |
| 117 | # check_call() function with zero return code |
| 118 | rc = subprocess.check_call([sys.executable, "-c", |
| 119 | "import sys; sys.exit(0)"]) |
| 120 | self.assertEqual(rc, 0) |
| 121 | |
| 122 | def test_check_call_nonzero(self): |
| 123 | # check_call() function with non-zero return code |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 124 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 125 | subprocess.check_call([sys.executable, "-c", |
| 126 | "import sys; sys.exit(47)"]) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 127 | self.assertEqual(c.exception.returncode, 47) |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 128 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 129 | def test_check_output(self): |
| 130 | # check_output() function with zero return code |
| 131 | output = subprocess.check_output( |
| 132 | [sys.executable, "-c", "print('BDFL')"]) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 133 | self.assertIn(b'BDFL', output) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 134 | |
| 135 | def test_check_output_nonzero(self): |
| 136 | # check_call() function with non-zero return code |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 137 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 138 | subprocess.check_output( |
| 139 | [sys.executable, "-c", "import sys; sys.exit(5)"]) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 140 | self.assertEqual(c.exception.returncode, 5) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 141 | |
| 142 | def test_check_output_stderr(self): |
| 143 | # check_output() function stderr redirected to stdout |
| 144 | output = subprocess.check_output( |
| 145 | [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"], |
| 146 | stderr=subprocess.STDOUT) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 147 | self.assertIn(b'BDFL', output) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 148 | |
Serhiy Storchaka | fcd9f22 | 2013-04-22 20:20:54 +0300 | [diff] [blame] | 149 | def test_check_output_stdin_arg(self): |
| 150 | # check_output() can be called with stdin set to a file |
| 151 | tf = tempfile.TemporaryFile() |
| 152 | self.addCleanup(tf.close) |
| 153 | tf.write(b'pear') |
| 154 | tf.seek(0) |
| 155 | output = subprocess.check_output( |
| 156 | [sys.executable, "-c", |
| 157 | "import sys; sys.stdout.write(sys.stdin.read().upper())"], |
| 158 | stdin=tf) |
| 159 | self.assertIn(b'PEAR', output) |
| 160 | |
| 161 | def test_check_output_input_arg(self): |
| 162 | # check_output() can be called with input set to a string |
| 163 | output = subprocess.check_output( |
| 164 | [sys.executable, "-c", |
| 165 | "import sys; sys.stdout.write(sys.stdin.read().upper())"], |
| 166 | input=b'pear') |
| 167 | self.assertIn(b'PEAR', output) |
| 168 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 169 | def test_check_output_stdout_arg(self): |
Serhiy Storchaka | fcd9f22 | 2013-04-22 20:20:54 +0300 | [diff] [blame] | 170 | # check_output() refuses to accept 'stdout' argument |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 171 | with self.assertRaises(ValueError) as c: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 172 | output = subprocess.check_output( |
| 173 | [sys.executable, "-c", "print('will not be run')"], |
| 174 | stdout=sys.stdout) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 175 | self.fail("Expected ValueError when stdout arg supplied.") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 176 | self.assertIn('stdout', c.exception.args[0]) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 177 | |
Serhiy Storchaka | fcd9f22 | 2013-04-22 20:20:54 +0300 | [diff] [blame] | 178 | def test_check_output_stdin_with_input_arg(self): |
| 179 | # check_output() refuses to accept 'stdin' with 'input' |
| 180 | tf = tempfile.TemporaryFile() |
| 181 | self.addCleanup(tf.close) |
| 182 | tf.write(b'pear') |
| 183 | tf.seek(0) |
| 184 | with self.assertRaises(ValueError) as c: |
| 185 | output = subprocess.check_output( |
| 186 | [sys.executable, "-c", "print('will not be run')"], |
| 187 | stdin=tf, input=b'hare') |
| 188 | self.fail("Expected ValueError when stdin and input args supplied.") |
| 189 | self.assertIn('stdin', c.exception.args[0]) |
| 190 | self.assertIn('input', c.exception.args[0]) |
| 191 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 192 | def test_check_output_timeout(self): |
| 193 | # check_output() function with timeout arg |
| 194 | with self.assertRaises(subprocess.TimeoutExpired) as c: |
| 195 | output = subprocess.check_output( |
| 196 | [sys.executable, "-c", |
Victor Stinner | 149b1c7 | 2011-06-06 23:43:02 +0200 | [diff] [blame] | 197 | "import sys, time\n" |
| 198 | "sys.stdout.write('BDFL')\n" |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 199 | "sys.stdout.flush()\n" |
Victor Stinner | 149b1c7 | 2011-06-06 23:43:02 +0200 | [diff] [blame] | 200 | "time.sleep(3600)"], |
Reid Kleckner | da9ac72 | 2011-03-16 17:08:21 -0400 | [diff] [blame] | 201 | # Some heavily loaded buildbots (sparc Debian 3.x) require |
| 202 | # this much time to start and print. |
| 203 | timeout=3) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 204 | self.fail("Expected TimeoutExpired.") |
| 205 | self.assertEqual(c.exception.output, b'BDFL') |
| 206 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 207 | def test_call_kwargs(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 208 | # call() function with keyword args |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 209 | newenv = os.environ.copy() |
| 210 | newenv["FRUIT"] = "banana" |
| 211 | rc = subprocess.call([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 212 | 'import sys, os;' |
| 213 | 'sys.exit(os.getenv("FRUIT")=="banana")'], |
| 214 | env=newenv) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 215 | self.assertEqual(rc, 1) |
| 216 | |
Victor Stinner | 87b9bc3 | 2011-06-01 00:57:47 +0200 | [diff] [blame] | 217 | def test_invalid_args(self): |
| 218 | # Popen() called with invalid arguments should raise TypeError |
| 219 | # but Popen.__del__ should not complain (issue #12085) |
| 220 | with support.captured_stderr() as s: |
| 221 | self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1) |
| 222 | argcount = subprocess.Popen.__init__.__code__.co_argcount |
| 223 | too_many_args = [0] * (argcount + 1) |
| 224 | self.assertRaises(TypeError, subprocess.Popen, *too_many_args) |
| 225 | self.assertEqual(s.getvalue(), '') |
| 226 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 227 | def test_stdin_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 228 | # .stdin is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 229 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 230 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 231 | self.addCleanup(p.stdout.close) |
| 232 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 233 | p.wait() |
| 234 | self.assertEqual(p.stdin, None) |
| 235 | |
| 236 | def test_stdout_none(self): |
Ezio Melotti | 42a541b | 2013-03-11 05:53:34 +0200 | [diff] [blame] | 237 | # .stdout is None when not redirected, and the child's stdout will |
| 238 | # be inherited from the parent. In order to test this we run a |
| 239 | # subprocess in a subprocess: |
| 240 | # this_test |
| 241 | # \-- subprocess created by this test (parent) |
| 242 | # \-- subprocess created by the parent subprocess (child) |
| 243 | # The parent doesn't specify stdout, so the child will use the |
| 244 | # parent's stdout. This test checks that the message printed by the |
| 245 | # child goes to the parent stdout. The parent also checks that the |
| 246 | # child's stdout is None. See #11963. |
| 247 | code = ('import sys; from subprocess import Popen, PIPE;' |
| 248 | 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],' |
| 249 | ' stdin=PIPE, stderr=PIPE);' |
| 250 | 'p.wait(); assert p.stdout is None;') |
| 251 | p = subprocess.Popen([sys.executable, "-c", code], |
| 252 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 253 | self.addCleanup(p.stdout.close) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 254 | self.addCleanup(p.stderr.close) |
Ezio Melotti | 42a541b | 2013-03-11 05:53:34 +0200 | [diff] [blame] | 255 | out, err = p.communicate() |
| 256 | self.assertEqual(p.returncode, 0, err) |
| 257 | self.assertEqual(out.rstrip(), b'test_stdout_none') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 258 | |
| 259 | def test_stderr_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 260 | # .stderr is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 261 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 262 | stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
Brian Curtin | 3c6a951 | 2010-11-05 03:58:52 +0000 | [diff] [blame] | 263 | self.addCleanup(p.stdout.close) |
| 264 | self.addCleanup(p.stdin.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 265 | p.wait() |
| 266 | self.assertEqual(p.stderr, None) |
| 267 | |
Chris Jerdonek | 776cb19 | 2012-10-08 15:56:43 -0700 | [diff] [blame] | 268 | def _assert_python(self, pre_args, **kwargs): |
| 269 | # We include sys.exit() to prevent the test runner from hanging |
| 270 | # whenever python is found. |
| 271 | args = pre_args + ["import sys; sys.exit(47)"] |
| 272 | p = subprocess.Popen(args, **kwargs) |
| 273 | p.wait() |
| 274 | self.assertEqual(47, p.returncode) |
| 275 | |
| 276 | def test_executable(self): |
| 277 | # Check that the executable argument works. |
Chris Jerdonek | 86b0fb2 | 2012-10-09 13:17:49 -0700 | [diff] [blame] | 278 | # |
| 279 | # On Unix (non-Mac and non-Windows), Python looks at args[0] to |
| 280 | # determine where its standard library is, so we need the directory |
| 281 | # of args[0] to be valid for the Popen() call to Python to succeed. |
| 282 | # See also issue #16170 and issue #7774. |
| 283 | doesnotexist = os.path.join(os.path.dirname(sys.executable), |
| 284 | "doesnotexist") |
| 285 | self._assert_python([doesnotexist, "-c"], executable=sys.executable) |
Chris Jerdonek | 776cb19 | 2012-10-08 15:56:43 -0700 | [diff] [blame] | 286 | |
| 287 | def test_executable_takes_precedence(self): |
| 288 | # Check that the executable argument takes precedence over args[0]. |
| 289 | # |
| 290 | # Verify first that the call succeeds without the executable arg. |
| 291 | pre_args = [sys.executable, "-c"] |
| 292 | self._assert_python(pre_args) |
| 293 | self.assertRaises(FileNotFoundError, self._assert_python, pre_args, |
| 294 | executable="doesnotexist") |
| 295 | |
| 296 | @unittest.skipIf(mswindows, "executable argument replaces shell") |
| 297 | def test_executable_replaces_shell(self): |
| 298 | # Check that the executable argument replaces the default shell |
| 299 | # when shell=True. |
| 300 | self._assert_python([], executable=sys.executable, shell=True) |
| 301 | |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 302 | # For use in the test_cwd* tests below. |
| 303 | def _normalize_cwd(self, cwd): |
| 304 | # Normalize an expected cwd (for Tru64 support). |
| 305 | # We can't use os.path.realpath since it doesn't expand Tru64 {memb} |
| 306 | # strings. See bug #1063571. |
Serhiy Storchaka | 2a23adf | 2015-09-06 14:13:25 +0300 | [diff] [blame] | 307 | with support.change_cwd(cwd): |
| 308 | return os.getcwd() |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 309 | |
| 310 | # For use in the test_cwd* tests below. |
| 311 | def _split_python_path(self): |
| 312 | # Return normalized (python_dir, python_base). |
| 313 | python_path = os.path.realpath(sys.executable) |
| 314 | return os.path.split(python_path) |
| 315 | |
| 316 | # For use in the test_cwd* tests below. |
| 317 | def _assert_cwd(self, expected_cwd, python_arg, **kwargs): |
| 318 | # Invoke Python via Popen, and assert that (1) the call succeeds, |
| 319 | # and that (2) the current working directory of the child process |
| 320 | # matches *expected_cwd*. |
| 321 | p = subprocess.Popen([python_arg, "-c", |
| 322 | "import os, sys; " |
| 323 | "sys.stdout.write(os.getcwd()); " |
| 324 | "sys.exit(47)"], |
| 325 | stdout=subprocess.PIPE, |
| 326 | **kwargs) |
| 327 | self.addCleanup(p.stdout.close) |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 328 | p.wait() |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 329 | self.assertEqual(47, p.returncode) |
| 330 | normcase = os.path.normcase |
| 331 | self.assertEqual(normcase(expected_cwd), |
| 332 | normcase(p.stdout.read().decode("utf-8"))) |
| 333 | |
| 334 | def test_cwd(self): |
| 335 | # Check that cwd changes the cwd for the child process. |
| 336 | temp_dir = tempfile.gettempdir() |
| 337 | temp_dir = self._normalize_cwd(temp_dir) |
| 338 | self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir) |
| 339 | |
Chris Jerdonek | c2cd626 | 2012-09-30 09:45:00 -0700 | [diff] [blame] | 340 | @unittest.skipIf(mswindows, "pending resolution of issue #15533") |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 341 | def test_cwd_with_relative_arg(self): |
| 342 | # Check that Popen looks for args[0] relative to cwd if args[0] |
| 343 | # is relative. |
| 344 | python_dir, python_base = self._split_python_path() |
| 345 | rel_python = os.path.join(os.curdir, python_base) |
| 346 | with support.temp_cwd() as wrong_dir: |
| 347 | # Before calling with the correct cwd, confirm that the call fails |
| 348 | # without cwd and with the wrong cwd. |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 349 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 350 | [rel_python]) |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 351 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 352 | [rel_python], cwd=wrong_dir) |
| 353 | python_dir = self._normalize_cwd(python_dir) |
| 354 | self._assert_cwd(python_dir, rel_python, cwd=python_dir) |
| 355 | |
Chris Jerdonek | c2cd626 | 2012-09-30 09:45:00 -0700 | [diff] [blame] | 356 | @unittest.skipIf(mswindows, "pending resolution of issue #15533") |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 357 | def test_cwd_with_relative_executable(self): |
| 358 | # Check that Popen looks for executable relative to cwd if executable |
| 359 | # is relative (and that executable takes precedence over args[0]). |
| 360 | python_dir, python_base = self._split_python_path() |
| 361 | rel_python = os.path.join(os.curdir, python_base) |
| 362 | doesntexist = "somethingyoudonthave" |
| 363 | with support.temp_cwd() as wrong_dir: |
| 364 | # Before calling with the correct cwd, confirm that the call fails |
| 365 | # without cwd and with the wrong cwd. |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 366 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 367 | [doesntexist], executable=rel_python) |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 368 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 369 | [doesntexist], executable=rel_python, |
| 370 | cwd=wrong_dir) |
| 371 | python_dir = self._normalize_cwd(python_dir) |
| 372 | self._assert_cwd(python_dir, doesntexist, executable=rel_python, |
| 373 | cwd=python_dir) |
| 374 | |
| 375 | def test_cwd_with_absolute_arg(self): |
| 376 | # Check that Popen can find the executable when the cwd is wrong |
| 377 | # if args[0] is an absolute path. |
| 378 | python_dir, python_base = self._split_python_path() |
| 379 | abs_python = os.path.join(python_dir, python_base) |
| 380 | rel_python = os.path.join(os.curdir, python_base) |
Berker Peksag | ce64391 | 2015-05-06 06:33:17 +0300 | [diff] [blame] | 381 | with support.temp_dir() as wrong_dir: |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 382 | # Before calling with an absolute path, confirm that using a |
| 383 | # relative path fails. |
Chris Jerdonek | 28714c8 | 2012-09-30 02:15:37 -0700 | [diff] [blame] | 384 | self.assertRaises(FileNotFoundError, subprocess.Popen, |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 385 | [rel_python], cwd=wrong_dir) |
| 386 | wrong_dir = self._normalize_cwd(wrong_dir) |
| 387 | self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir) |
| 388 | |
Vinay Sajip | 7ded1f0 | 2012-05-26 03:45:29 +0100 | [diff] [blame] | 389 | @unittest.skipIf(sys.base_prefix != sys.prefix, |
| 390 | 'Test is not venv-compatible') |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 391 | def test_executable_with_cwd(self): |
Chris Jerdonek | ec3ea94 | 2012-09-30 00:10:28 -0700 | [diff] [blame] | 392 | python_dir, python_base = self._split_python_path() |
| 393 | python_dir = self._normalize_cwd(python_dir) |
| 394 | self._assert_cwd(python_dir, "somethingyoudonthave", |
| 395 | executable=sys.executable, cwd=python_dir) |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 396 | |
Vinay Sajip | 7ded1f0 | 2012-05-26 03:45:29 +0100 | [diff] [blame] | 397 | @unittest.skipIf(sys.base_prefix != sys.prefix, |
| 398 | 'Test is not venv-compatible') |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 399 | @unittest.skipIf(sysconfig.is_python_build(), |
| 400 | "need an installed Python. See #7774") |
| 401 | def test_executable_without_cwd(self): |
| 402 | # For a normal installation, it should work without 'cwd' |
| 403 | # argument. For test runs in the build directory, see #7774. |
Ned Deily | e92dfbf | 2013-08-02 18:02:21 -0700 | [diff] [blame] | 404 | self._assert_cwd(os.getcwd(), "somethingyoudonthave", |
| 405 | executable=sys.executable) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 406 | |
| 407 | def test_stdin_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 408 | # stdin redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 409 | p = subprocess.Popen([sys.executable, "-c", |
| 410 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 411 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 412 | p.stdin.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 413 | p.stdin.close() |
| 414 | p.wait() |
| 415 | self.assertEqual(p.returncode, 1) |
| 416 | |
| 417 | def test_stdin_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 418 | # stdin is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 419 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 420 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 421 | d = tf.fileno() |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 422 | os.write(d, b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 423 | os.lseek(d, 0, 0) |
| 424 | p = subprocess.Popen([sys.executable, "-c", |
| 425 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 426 | stdin=d) |
| 427 | p.wait() |
| 428 | self.assertEqual(p.returncode, 1) |
| 429 | |
| 430 | def test_stdin_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 431 | # stdin is set to open file object |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 432 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 433 | self.addCleanup(tf.close) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 434 | tf.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 435 | tf.seek(0) |
| 436 | p = subprocess.Popen([sys.executable, "-c", |
| 437 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 438 | stdin=tf) |
| 439 | p.wait() |
| 440 | self.assertEqual(p.returncode, 1) |
| 441 | |
| 442 | def test_stdout_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 443 | # stdout redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 444 | p = subprocess.Popen([sys.executable, "-c", |
| 445 | 'import sys; sys.stdout.write("orange")'], |
| 446 | stdout=subprocess.PIPE) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 447 | with p: |
| 448 | self.assertEqual(p.stdout.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 449 | |
| 450 | def test_stdout_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 451 | # stdout is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 452 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 453 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 454 | d = tf.fileno() |
| 455 | p = subprocess.Popen([sys.executable, "-c", |
| 456 | 'import sys; sys.stdout.write("orange")'], |
| 457 | stdout=d) |
| 458 | p.wait() |
| 459 | os.lseek(d, 0, 0) |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 460 | self.assertEqual(os.read(d, 1024), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 461 | |
| 462 | def test_stdout_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 463 | # stdout is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 464 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 465 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 466 | p = subprocess.Popen([sys.executable, "-c", |
| 467 | 'import sys; sys.stdout.write("orange")'], |
| 468 | stdout=tf) |
| 469 | p.wait() |
| 470 | tf.seek(0) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 471 | self.assertEqual(tf.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 472 | |
| 473 | def test_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 474 | # stderr redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 475 | p = subprocess.Popen([sys.executable, "-c", |
| 476 | 'import sys; sys.stderr.write("strawberry")'], |
| 477 | stderr=subprocess.PIPE) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 478 | with p: |
| 479 | self.assertStderrEqual(p.stderr.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 480 | |
| 481 | def test_stderr_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 482 | # stderr is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 483 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 484 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 485 | d = tf.fileno() |
| 486 | p = subprocess.Popen([sys.executable, "-c", |
| 487 | 'import sys; sys.stderr.write("strawberry")'], |
| 488 | stderr=d) |
| 489 | p.wait() |
| 490 | os.lseek(d, 0, 0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 491 | self.assertStderrEqual(os.read(d, 1024), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 492 | |
| 493 | def test_stderr_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 494 | # stderr is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 495 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 496 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 497 | p = subprocess.Popen([sys.executable, "-c", |
| 498 | 'import sys; sys.stderr.write("strawberry")'], |
| 499 | stderr=tf) |
| 500 | p.wait() |
| 501 | tf.seek(0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 502 | self.assertStderrEqual(tf.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 503 | |
Martin Panter | c763589 | 2016-05-13 01:54:44 +0000 | [diff] [blame] | 504 | def test_stderr_redirect_with_no_stdout_redirect(self): |
| 505 | # test stderr=STDOUT while stdout=None (not set) |
| 506 | |
| 507 | # - grandchild prints to stderr |
| 508 | # - child redirects grandchild's stderr to its stdout |
| 509 | # - the parent should get grandchild's stderr in child's stdout |
| 510 | p = subprocess.Popen([sys.executable, "-c", |
| 511 | 'import sys, subprocess;' |
| 512 | 'rc = subprocess.call([sys.executable, "-c",' |
| 513 | ' "import sys;"' |
| 514 | ' "sys.stderr.write(\'42\')"],' |
| 515 | ' stderr=subprocess.STDOUT);' |
| 516 | 'sys.exit(rc)'], |
| 517 | stdout=subprocess.PIPE, |
| 518 | stderr=subprocess.PIPE) |
| 519 | stdout, stderr = p.communicate() |
| 520 | #NOTE: stdout should get stderr from grandchild |
| 521 | self.assertStderrEqual(stdout, b'42') |
| 522 | self.assertStderrEqual(stderr, b'') # should be empty |
| 523 | self.assertEqual(p.returncode, 0) |
| 524 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 525 | def test_stdout_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 526 | # capture stdout and stderr to the same pipe |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 527 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 528 | 'import sys;' |
| 529 | 'sys.stdout.write("apple");' |
| 530 | 'sys.stdout.flush();' |
| 531 | 'sys.stderr.write("orange")'], |
| 532 | stdout=subprocess.PIPE, |
| 533 | stderr=subprocess.STDOUT) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 534 | with p: |
| 535 | self.assertStderrEqual(p.stdout.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 536 | |
| 537 | def test_stdout_stderr_file(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 538 | # capture stdout and stderr to the same open file |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 539 | tf = tempfile.TemporaryFile() |
Benjamin Peterson | cc221b2 | 2010-10-31 02:06:21 +0000 | [diff] [blame] | 540 | self.addCleanup(tf.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 541 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 542 | 'import sys;' |
| 543 | 'sys.stdout.write("apple");' |
| 544 | 'sys.stdout.flush();' |
| 545 | 'sys.stderr.write("orange")'], |
| 546 | stdout=tf, |
| 547 | stderr=tf) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 548 | p.wait() |
| 549 | tf.seek(0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 550 | self.assertStderrEqual(tf.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 551 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 552 | def test_stdout_filedes_of_stdout(self): |
| 553 | # stdout is set to 1 (#1531862). |
Ezio Melotti | 42a541b | 2013-03-11 05:53:34 +0200 | [diff] [blame] | 554 | # To avoid printing the text on stdout, we do something similar to |
| 555 | # test_stdout_none (see above). The parent subprocess calls the child |
| 556 | # subprocess passing stdout=1, and this test uses stdout=PIPE in |
| 557 | # order to capture and check the output of the parent. See #11963. |
| 558 | code = ('import sys, subprocess; ' |
| 559 | 'rc = subprocess.call([sys.executable, "-c", ' |
| 560 | ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), ' |
| 561 | 'b\'test with stdout=1\'))"], stdout=1); ' |
| 562 | 'assert rc == 18') |
| 563 | p = subprocess.Popen([sys.executable, "-c", code], |
| 564 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 565 | self.addCleanup(p.stdout.close) |
| 566 | self.addCleanup(p.stderr.close) |
| 567 | out, err = p.communicate() |
| 568 | self.assertEqual(p.returncode, 0, err) |
| 569 | self.assertEqual(out.rstrip(), b'test with stdout=1') |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 570 | |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 571 | def test_stdout_devnull(self): |
| 572 | p = subprocess.Popen([sys.executable, "-c", |
| 573 | 'for i in range(10240):' |
| 574 | 'print("x" * 1024)'], |
| 575 | stdout=subprocess.DEVNULL) |
| 576 | p.wait() |
| 577 | self.assertEqual(p.stdout, None) |
| 578 | |
| 579 | def test_stderr_devnull(self): |
| 580 | p = subprocess.Popen([sys.executable, "-c", |
| 581 | 'import sys\n' |
| 582 | 'for i in range(10240):' |
| 583 | 'sys.stderr.write("x" * 1024)'], |
| 584 | stderr=subprocess.DEVNULL) |
| 585 | p.wait() |
| 586 | self.assertEqual(p.stderr, None) |
| 587 | |
| 588 | def test_stdin_devnull(self): |
| 589 | p = subprocess.Popen([sys.executable, "-c", |
| 590 | 'import sys;' |
| 591 | 'sys.stdin.read(1)'], |
| 592 | stdin=subprocess.DEVNULL) |
| 593 | p.wait() |
| 594 | self.assertEqual(p.stdin, None) |
| 595 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 596 | def test_env(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 597 | newenv = os.environ.copy() |
| 598 | newenv["FRUIT"] = "orange" |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 599 | with subprocess.Popen([sys.executable, "-c", |
| 600 | 'import sys,os;' |
| 601 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 602 | stdout=subprocess.PIPE, |
| 603 | env=newenv) as p: |
| 604 | stdout, stderr = p.communicate() |
| 605 | self.assertEqual(stdout, b"orange") |
| 606 | |
Victor Stinner | 62d5118 | 2011-06-23 01:02:25 +0200 | [diff] [blame] | 607 | # Windows requires at least the SYSTEMROOT environment variable to start |
| 608 | # Python |
| 609 | @unittest.skipIf(sys.platform == 'win32', |
| 610 | 'cannot test an empty env on Windows') |
Victor Stinner | 237e5cb | 2011-06-22 21:28:43 +0200 | [diff] [blame] | 611 | @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None, |
Victor Stinner | 372309a | 2011-06-21 21:59:06 +0200 | [diff] [blame] | 612 | 'the python library cannot be loaded ' |
| 613 | 'with an empty environment') |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 614 | def test_empty_env(self): |
| 615 | with subprocess.Popen([sys.executable, "-c", |
| 616 | 'import os; ' |
Victor Stinner | 372309a | 2011-06-21 21:59:06 +0200 | [diff] [blame] | 617 | 'print(list(os.environ.keys()))'], |
Victor Stinner | f1512a2 | 2011-06-21 17:18:38 +0200 | [diff] [blame] | 618 | stdout=subprocess.PIPE, |
| 619 | env={}) as p: |
| 620 | stdout, stderr = p.communicate() |
Victor Stinner | 237e5cb | 2011-06-22 21:28:43 +0200 | [diff] [blame] | 621 | self.assertIn(stdout.strip(), |
| 622 | (b"[]", |
| 623 | # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty |
| 624 | # environment |
| 625 | b"['__CF_USER_TEXT_ENCODING']")) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 626 | |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 627 | def test_communicate_stdin(self): |
| 628 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 629 | 'import sys;' |
| 630 | 'sys.exit(sys.stdin.read() == "pear")'], |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 631 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 632 | p.communicate(b"pear") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 633 | self.assertEqual(p.returncode, 1) |
| 634 | |
| 635 | def test_communicate_stdout(self): |
| 636 | p = subprocess.Popen([sys.executable, "-c", |
| 637 | 'import sys; sys.stdout.write("pineapple")'], |
| 638 | stdout=subprocess.PIPE) |
| 639 | (stdout, stderr) = p.communicate() |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 640 | self.assertEqual(stdout, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 641 | self.assertEqual(stderr, None) |
| 642 | |
| 643 | def test_communicate_stderr(self): |
| 644 | p = subprocess.Popen([sys.executable, "-c", |
| 645 | 'import sys; sys.stderr.write("pineapple")'], |
| 646 | stderr=subprocess.PIPE) |
| 647 | (stdout, stderr) = p.communicate() |
| 648 | self.assertEqual(stdout, None) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 649 | self.assertStderrEqual(stderr, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 650 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 651 | def test_communicate(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 652 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 653 | 'import sys,os;' |
| 654 | 'sys.stderr.write("pineapple");' |
| 655 | 'sys.stdout.write(sys.stdin.read())'], |
| 656 | stdin=subprocess.PIPE, |
| 657 | stdout=subprocess.PIPE, |
| 658 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 659 | self.addCleanup(p.stdout.close) |
| 660 | self.addCleanup(p.stderr.close) |
| 661 | self.addCleanup(p.stdin.close) |
Georg Brandl | 1abcbf8 | 2008-07-01 19:28:43 +0000 | [diff] [blame] | 662 | (stdout, stderr) = p.communicate(b"banana") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 663 | self.assertEqual(stdout, b"banana") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 664 | self.assertStderrEqual(stderr, b"pineapple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 665 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 666 | def test_communicate_timeout(self): |
| 667 | p = subprocess.Popen([sys.executable, "-c", |
| 668 | 'import sys,os,time;' |
| 669 | 'sys.stderr.write("pineapple\\n");' |
| 670 | 'time.sleep(1);' |
| 671 | 'sys.stderr.write("pear\\n");' |
| 672 | 'sys.stdout.write(sys.stdin.read())'], |
| 673 | universal_newlines=True, |
| 674 | stdin=subprocess.PIPE, |
| 675 | stdout=subprocess.PIPE, |
| 676 | stderr=subprocess.PIPE) |
| 677 | self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana", |
| 678 | timeout=0.3) |
| 679 | # Make sure we can keep waiting for it, and that we get the whole output |
| 680 | # after it completes. |
| 681 | (stdout, stderr) = p.communicate() |
| 682 | self.assertEqual(stdout, "banana") |
| 683 | self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n") |
| 684 | |
| 685 | def test_communicate_timeout_large_ouput(self): |
Ross Lagerwall | 003c7a3 | 2012-02-12 09:02:01 +0200 | [diff] [blame] | 686 | # Test an expiring timeout while the child is outputting lots of data. |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 687 | p = subprocess.Popen([sys.executable, "-c", |
| 688 | 'import sys,os,time;' |
| 689 | 'sys.stdout.write("a" * (64 * 1024));' |
| 690 | 'time.sleep(0.2);' |
| 691 | 'sys.stdout.write("a" * (64 * 1024));' |
| 692 | 'time.sleep(0.2);' |
| 693 | 'sys.stdout.write("a" * (64 * 1024));' |
| 694 | 'time.sleep(0.2);' |
| 695 | 'sys.stdout.write("a" * (64 * 1024));'], |
| 696 | stdout=subprocess.PIPE) |
| 697 | self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4) |
| 698 | (stdout, _) = p.communicate() |
| 699 | self.assertEqual(len(stdout), 4 * 64 * 1024) |
| 700 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 701 | # Test for the fd leak reported in http://bugs.python.org/issue2791. |
| 702 | def test_communicate_pipe_fd_leak(self): |
Victor Stinner | 667d4b5 | 2010-12-25 22:40:32 +0000 | [diff] [blame] | 703 | for stdin_pipe in (False, True): |
| 704 | for stdout_pipe in (False, True): |
| 705 | for stderr_pipe in (False, True): |
| 706 | options = {} |
| 707 | if stdin_pipe: |
| 708 | options['stdin'] = subprocess.PIPE |
| 709 | if stdout_pipe: |
| 710 | options['stdout'] = subprocess.PIPE |
| 711 | if stderr_pipe: |
| 712 | options['stderr'] = subprocess.PIPE |
| 713 | if not options: |
| 714 | continue |
| 715 | p = subprocess.Popen((sys.executable, "-c", "pass"), **options) |
| 716 | p.communicate() |
| 717 | if p.stdin is not None: |
| 718 | self.assertTrue(p.stdin.closed) |
| 719 | if p.stdout is not None: |
| 720 | self.assertTrue(p.stdout.closed) |
| 721 | if p.stderr is not None: |
| 722 | self.assertTrue(p.stderr.closed) |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 723 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 724 | def test_communicate_returns(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 725 | # communicate() should return None if no redirection is active |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 726 | p = subprocess.Popen([sys.executable, "-c", |
| 727 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 728 | (stdout, stderr) = p.communicate() |
| 729 | self.assertEqual(stdout, None) |
| 730 | self.assertEqual(stderr, None) |
| 731 | |
| 732 | def test_communicate_pipe_buf(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 733 | # communicate() with writes larger than pipe_buf |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 734 | # This test will probably deadlock rather than fail, if |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 735 | # communicate() does not work properly. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 736 | x, y = os.pipe() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 737 | os.close(x) |
| 738 | os.close(y) |
| 739 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 740 | 'import sys,os;' |
| 741 | 'sys.stdout.write(sys.stdin.read(47));' |
Charles-François Natali | 2d51721 | 2011-05-29 16:36:44 +0200 | [diff] [blame] | 742 | 'sys.stderr.write("x" * %d);' |
| 743 | 'sys.stdout.write(sys.stdin.read())' % |
| 744 | support.PIPE_MAX_SIZE], |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 745 | stdin=subprocess.PIPE, |
| 746 | stdout=subprocess.PIPE, |
| 747 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 748 | self.addCleanup(p.stdout.close) |
| 749 | self.addCleanup(p.stderr.close) |
| 750 | self.addCleanup(p.stdin.close) |
Charles-François Natali | 2d51721 | 2011-05-29 16:36:44 +0200 | [diff] [blame] | 751 | string_to_write = b"a" * support.PIPE_MAX_SIZE |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 752 | (stdout, stderr) = p.communicate(string_to_write) |
| 753 | self.assertEqual(stdout, string_to_write) |
| 754 | |
| 755 | def test_writes_before_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 756 | # stdin.write before communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 757 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 758 | 'import sys,os;' |
| 759 | 'sys.stdout.write(sys.stdin.read())'], |
| 760 | stdin=subprocess.PIPE, |
| 761 | stdout=subprocess.PIPE, |
| 762 | stderr=subprocess.PIPE) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 763 | self.addCleanup(p.stdout.close) |
| 764 | self.addCleanup(p.stderr.close) |
| 765 | self.addCleanup(p.stdin.close) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 766 | p.stdin.write(b"banana") |
| 767 | (stdout, stderr) = p.communicate(b"split") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 768 | self.assertEqual(stdout, b"bananasplit") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 769 | self.assertStderrEqual(stderr, b"") |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 770 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 771 | def test_universal_newlines(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 772 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 773 | 'import sys,os;' + SETBINARY + |
Antoine Pitrou | ec2d269 | 2012-08-05 00:23:40 +0200 | [diff] [blame] | 774 | 'buf = sys.stdout.buffer;' |
| 775 | 'buf.write(sys.stdin.readline().encode());' |
| 776 | 'buf.flush();' |
| 777 | 'buf.write(b"line2\\n");' |
| 778 | 'buf.flush();' |
| 779 | 'buf.write(sys.stdin.read().encode());' |
| 780 | 'buf.flush();' |
| 781 | 'buf.write(b"line4\\n");' |
| 782 | 'buf.flush();' |
| 783 | 'buf.write(b"line5\\r\\n");' |
| 784 | 'buf.flush();' |
| 785 | 'buf.write(b"line6\\r");' |
| 786 | 'buf.flush();' |
| 787 | 'buf.write(b"\\nline7");' |
| 788 | 'buf.flush();' |
| 789 | 'buf.write(b"\\nline8");'], |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 790 | stdin=subprocess.PIPE, |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 791 | stdout=subprocess.PIPE, |
| 792 | universal_newlines=1) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 793 | with p: |
| 794 | p.stdin.write("line1\n") |
| 795 | p.stdin.flush() |
| 796 | self.assertEqual(p.stdout.readline(), "line1\n") |
| 797 | p.stdin.write("line3\n") |
| 798 | p.stdin.close() |
| 799 | self.addCleanup(p.stdout.close) |
| 800 | self.assertEqual(p.stdout.readline(), |
| 801 | "line2\n") |
| 802 | self.assertEqual(p.stdout.read(6), |
| 803 | "line3\n") |
| 804 | self.assertEqual(p.stdout.read(), |
| 805 | "line4\nline5\nline6\nline7\nline8") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 806 | |
| 807 | def test_universal_newlines_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 808 | # universal newlines through communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 809 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 810 | 'import sys,os;' + SETBINARY + |
Antoine Pitrou | ec2d269 | 2012-08-05 00:23:40 +0200 | [diff] [blame] | 811 | 'buf = sys.stdout.buffer;' |
| 812 | 'buf.write(b"line2\\n");' |
| 813 | 'buf.flush();' |
| 814 | 'buf.write(b"line4\\n");' |
| 815 | 'buf.flush();' |
| 816 | 'buf.write(b"line5\\r\\n");' |
| 817 | 'buf.flush();' |
| 818 | 'buf.write(b"line6\\r");' |
| 819 | 'buf.flush();' |
| 820 | 'buf.write(b"\\nline7");' |
| 821 | 'buf.flush();' |
| 822 | 'buf.write(b"\\nline8");'], |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 823 | stderr=subprocess.PIPE, |
| 824 | stdout=subprocess.PIPE, |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 825 | universal_newlines=1) |
Brian Curtin | 19a5379 | 2010-11-05 17:09:05 +0000 | [diff] [blame] | 826 | self.addCleanup(p.stdout.close) |
| 827 | self.addCleanup(p.stderr.close) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 828 | (stdout, stderr) = p.communicate() |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 829 | self.assertEqual(stdout, |
| 830 | "line2\nline4\nline5\nline6\nline7\nline8") |
| 831 | |
| 832 | def test_universal_newlines_communicate_stdin(self): |
| 833 | # universal newlines through communicate(), with only stdin |
| 834 | p = subprocess.Popen([sys.executable, "-c", |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 835 | 'import sys,os;' + SETBINARY + textwrap.dedent(''' |
| 836 | s = sys.stdin.readline() |
| 837 | assert s == "line1\\n", repr(s) |
| 838 | s = sys.stdin.read() |
| 839 | assert s == "line3\\n", repr(s) |
| 840 | ''')], |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 841 | stdin=subprocess.PIPE, |
| 842 | universal_newlines=1) |
| 843 | (stdout, stderr) = p.communicate("line1\nline3\n") |
| 844 | self.assertEqual(p.returncode, 0) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 845 | |
Andrew Svetlov | f376507 | 2012-08-14 18:35:17 +0300 | [diff] [blame] | 846 | def test_universal_newlines_communicate_input_none(self): |
| 847 | # Test communicate(input=None) with universal newlines. |
| 848 | # |
| 849 | # We set stdout to PIPE because, as of this writing, a different |
| 850 | # code path is tested when the number of pipes is zero or one. |
| 851 | p = subprocess.Popen([sys.executable, "-c", "pass"], |
| 852 | stdin=subprocess.PIPE, |
| 853 | stdout=subprocess.PIPE, |
| 854 | universal_newlines=True) |
| 855 | p.communicate() |
| 856 | self.assertEqual(p.returncode, 0) |
| 857 | |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 858 | def test_universal_newlines_communicate_stdin_stdout_stderr(self): |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 859 | # universal newlines through communicate(), with stdin, stdout, stderr |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 860 | p = subprocess.Popen([sys.executable, "-c", |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 861 | 'import sys,os;' + SETBINARY + textwrap.dedent(''' |
| 862 | s = sys.stdin.buffer.readline() |
| 863 | sys.stdout.buffer.write(s) |
| 864 | sys.stdout.buffer.write(b"line2\\r") |
| 865 | sys.stderr.buffer.write(b"eline2\\n") |
| 866 | s = sys.stdin.buffer.read() |
| 867 | sys.stdout.buffer.write(s) |
| 868 | sys.stdout.buffer.write(b"line4\\n") |
| 869 | sys.stdout.buffer.write(b"line5\\r\\n") |
| 870 | sys.stderr.buffer.write(b"eline6\\r") |
| 871 | sys.stderr.buffer.write(b"eline7\\r\\nz") |
| 872 | ''')], |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 873 | stdin=subprocess.PIPE, |
| 874 | stderr=subprocess.PIPE, |
| 875 | stdout=subprocess.PIPE, |
Andrew Svetlov | 47ec25d | 2012-08-19 16:25:37 +0300 | [diff] [blame] | 876 | universal_newlines=True) |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 877 | self.addCleanup(p.stdout.close) |
| 878 | self.addCleanup(p.stderr.close) |
| 879 | (stdout, stderr) = p.communicate("line1\nline3\n") |
| 880 | self.assertEqual(p.returncode, 0) |
Andrew Svetlov | 943c5b3 | 2012-08-16 20:17:47 +0300 | [diff] [blame] | 881 | self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout) |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 882 | # Python debug build push something like "[42442 refs]\n" |
| 883 | # to stderr at exit of subprocess. |
Andrew Svetlov | 943c5b3 | 2012-08-16 20:17:47 +0300 | [diff] [blame] | 884 | # Don't use assertStderrEqual because it strips CR and LF from output. |
| 885 | self.assertTrue(stderr.startswith("eline2\neline6\neline7\n")) |
Andrew Svetlov | 5395d2f | 2012-08-15 22:46:43 +0300 | [diff] [blame] | 886 | |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 887 | def test_universal_newlines_communicate_encodings(self): |
| 888 | # Check that universal newlines mode works for various encodings, |
| 889 | # in particular for encodings in the UTF-16 and UTF-32 families. |
| 890 | # See issue #15595. |
| 891 | # |
| 892 | # UTF-16 and UTF-32-BE are sufficient to check both with BOM and |
| 893 | # without, and UTF-16 and UTF-32. |
Antoine Pitrou | fd4722c | 2013-10-12 00:13:50 +0200 | [diff] [blame] | 894 | import _bootlocale |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 895 | for encoding in ['utf-16', 'utf-32-be']: |
Antoine Pitrou | fd4722c | 2013-10-12 00:13:50 +0200 | [diff] [blame] | 896 | old_getpreferredencoding = _bootlocale.getpreferredencoding |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 897 | # Indirectly via io.TextIOWrapper, Popen() defaults to |
| 898 | # locale.getpreferredencoding(False) and earlier in Python 3.2 to |
| 899 | # locale.getpreferredencoding(). |
| 900 | def getpreferredencoding(do_setlocale=True): |
| 901 | return encoding |
| 902 | code = ("import sys; " |
| 903 | r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" % |
| 904 | encoding) |
| 905 | args = [sys.executable, '-c', code] |
| 906 | try: |
Antoine Pitrou | fd4722c | 2013-10-12 00:13:50 +0200 | [diff] [blame] | 907 | _bootlocale.getpreferredencoding = getpreferredencoding |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 908 | # We set stdin to be non-None because, as of this writing, |
| 909 | # a different code path is used when the number of pipes is |
| 910 | # zero or one. |
| 911 | popen = subprocess.Popen(args, universal_newlines=True, |
| 912 | stdin=subprocess.PIPE, |
| 913 | stdout=subprocess.PIPE) |
| 914 | stdout, stderr = popen.communicate(input='') |
| 915 | finally: |
Antoine Pitrou | fd4722c | 2013-10-12 00:13:50 +0200 | [diff] [blame] | 916 | _bootlocale.getpreferredencoding = old_getpreferredencoding |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 917 | self.assertEqual(stdout, '1\n2\n3\n4') |
| 918 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 919 | def test_no_leaking(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 920 | # Make sure we leak no resources |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 921 | if not mswindows: |
Peter Astrand | f7f1bb7 | 2005-03-03 20:47:37 +0000 | [diff] [blame] | 922 | max_handles = 1026 # too much for most UNIX systems |
| 923 | else: |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 924 | max_handles = 2050 # too much for (at least some) Windows setups |
| 925 | handles = [] |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 926 | tmpdir = tempfile.mkdtemp() |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 927 | try: |
| 928 | for i in range(max_handles): |
| 929 | try: |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 930 | tmpfile = os.path.join(tmpdir, support.TESTFN) |
| 931 | handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT)) |
Antoine Pitrou | 8db3027 | 2010-09-18 22:38:48 +0000 | [diff] [blame] | 932 | except OSError as e: |
| 933 | if e.errno != errno.EMFILE: |
| 934 | raise |
| 935 | break |
| 936 | else: |
| 937 | self.skipTest("failed to reach the file descriptor limit " |
| 938 | "(tried %d)" % max_handles) |
| 939 | # Close a couple of them (should be enough for a subprocess) |
| 940 | for i in range(10): |
| 941 | os.close(handles.pop()) |
| 942 | # Loop creating some subprocesses. If one of them leaks some fds, |
| 943 | # the next loop iteration will fail by reaching the max fd limit. |
| 944 | for i in range(15): |
| 945 | p = subprocess.Popen([sys.executable, "-c", |
| 946 | "import sys;" |
| 947 | "sys.stdout.write(sys.stdin.read())"], |
| 948 | stdin=subprocess.PIPE, |
| 949 | stdout=subprocess.PIPE, |
| 950 | stderr=subprocess.PIPE) |
| 951 | data = p.communicate(b"lime")[0] |
| 952 | self.assertEqual(data, b"lime") |
| 953 | finally: |
| 954 | for h in handles: |
| 955 | os.close(h) |
Gregory P. Smith | 81ce685 | 2011-03-15 02:04:11 -0400 | [diff] [blame] | 956 | shutil.rmtree(tmpdir) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 957 | |
| 958 | def test_list2cmdline(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 959 | self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']), |
| 960 | '"a b c" d e') |
| 961 | self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']), |
| 962 | 'ab\\"c \\ d') |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 963 | self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']), |
| 964 | 'ab\\"c " \\\\" d') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 965 | self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']), |
| 966 | 'a\\\\\\b "de fg" h') |
| 967 | self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']), |
| 968 | 'a\\\\\\"b c d') |
| 969 | self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']), |
| 970 | '"a\\\\b c" d e') |
| 971 | self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']), |
| 972 | '"a\\\\b\\ c" d e') |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 973 | self.assertEqual(subprocess.list2cmdline(['ab', '']), |
| 974 | 'ab ""') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 975 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 976 | def test_poll(self): |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 977 | p = subprocess.Popen([sys.executable, "-c", |
Ross Lagerwall | e7ad419 | 2012-02-22 06:02:07 +0200 | [diff] [blame] | 978 | "import os; os.read(0, 1)"], |
| 979 | stdin=subprocess.PIPE) |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 980 | self.addCleanup(p.stdin.close) |
| 981 | self.assertIsNone(p.poll()) |
| 982 | os.write(p.stdin.fileno(), b'A') |
| 983 | p.wait() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 984 | # Subsequent invocations should just return the returncode |
| 985 | self.assertEqual(p.poll(), 0) |
| 986 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 987 | def test_wait(self): |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 988 | p = subprocess.Popen([sys.executable, "-c", "pass"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 989 | self.assertEqual(p.wait(), 0) |
| 990 | # Subsequent invocations should just return the returncode |
| 991 | self.assertEqual(p.wait(), 0) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 992 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 993 | def test_wait_timeout(self): |
| 994 | p = subprocess.Popen([sys.executable, |
Antoine Pitrou | dc49b2b | 2013-05-19 15:55:40 +0200 | [diff] [blame] | 995 | "-c", "import time; time.sleep(0.3)"]) |
Reid Kleckner | 2b228f0 | 2011-03-16 16:57:54 -0400 | [diff] [blame] | 996 | with self.assertRaises(subprocess.TimeoutExpired) as c: |
Antoine Pitrou | dc49b2b | 2013-05-19 15:55:40 +0200 | [diff] [blame] | 997 | p.wait(timeout=0.0001) |
| 998 | self.assertIn("0.0001", str(c.exception)) # For coverage of __str__. |
Reid Kleckner | da9ac72 | 2011-03-16 17:08:21 -0400 | [diff] [blame] | 999 | # Some heavily loaded buildbots (sparc Debian 3.x) require this much |
| 1000 | # time to start. |
| 1001 | self.assertEqual(p.wait(timeout=3), 0) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1002 | |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 1003 | def test_invalid_bufsize(self): |
| 1004 | # an invalid type of the bufsize argument should raise |
| 1005 | # TypeError. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1006 | with self.assertRaises(TypeError): |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 1007 | subprocess.Popen([sys.executable, "-c", "pass"], "orange") |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 1008 | |
Guido van Rossum | 46a05a7 | 2007-06-07 21:56:45 +0000 | [diff] [blame] | 1009 | def test_bufsize_is_none(self): |
| 1010 | # bufsize=None should be the same as bufsize=0. |
| 1011 | p = subprocess.Popen([sys.executable, "-c", "pass"], None) |
| 1012 | self.assertEqual(p.wait(), 0) |
| 1013 | # Again with keyword arg |
| 1014 | p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None) |
| 1015 | self.assertEqual(p.wait(), 0) |
| 1016 | |
Antoine Pitrou | afe8d06 | 2014-09-21 21:10:56 +0200 | [diff] [blame] | 1017 | def _test_bufsize_equal_one(self, line, expected, universal_newlines): |
| 1018 | # subprocess may deadlock with bufsize=1, see issue #21332 |
| 1019 | with subprocess.Popen([sys.executable, "-c", "import sys;" |
| 1020 | "sys.stdout.write(sys.stdin.readline());" |
| 1021 | "sys.stdout.flush()"], |
| 1022 | stdin=subprocess.PIPE, |
| 1023 | stdout=subprocess.PIPE, |
| 1024 | stderr=subprocess.DEVNULL, |
| 1025 | bufsize=1, |
| 1026 | universal_newlines=universal_newlines) as p: |
| 1027 | p.stdin.write(line) # expect that it flushes the line in text mode |
| 1028 | os.close(p.stdin.fileno()) # close it without flushing the buffer |
| 1029 | read_line = p.stdout.readline() |
| 1030 | try: |
| 1031 | p.stdin.close() |
| 1032 | except OSError: |
| 1033 | pass |
| 1034 | p.stdin = None |
| 1035 | self.assertEqual(p.returncode, 0) |
| 1036 | self.assertEqual(read_line, expected) |
| 1037 | |
| 1038 | def test_bufsize_equal_one_text_mode(self): |
| 1039 | # line is flushed in text mode with bufsize=1. |
| 1040 | # we should get the full line in return |
| 1041 | line = "line\n" |
| 1042 | self._test_bufsize_equal_one(line, line, universal_newlines=True) |
| 1043 | |
| 1044 | def test_bufsize_equal_one_binary_mode(self): |
| 1045 | # line is not flushed in binary mode with bufsize=1. |
| 1046 | # we should get empty response |
| 1047 | line = b'line' + os.linesep.encode() # assume ascii-based locale |
| 1048 | self._test_bufsize_equal_one(line, b'', universal_newlines=False) |
| 1049 | |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 1050 | def test_leaking_fds_on_error(self): |
| 1051 | # see bug #5179: Popen leaks file descriptors to PIPEs if |
| 1052 | # the child fails to execute; this will eventually exhaust |
| 1053 | # the maximum number of open fds. 1024 seems a very common |
| 1054 | # value for that limit, but Windows has 2048, so we loop |
| 1055 | # 1024 times (each call leaked two fds). |
| 1056 | for i in range(1024): |
Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 1057 | with self.assertRaises(OSError) as c: |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 1058 | subprocess.Popen(['nonexisting_i_hope'], |
| 1059 | stdout=subprocess.PIPE, |
| 1060 | stderr=subprocess.PIPE) |
R David Murray | 384069c | 2011-03-13 22:26:53 -0400 | [diff] [blame] | 1061 | # ignore errors that indicate the command was not found |
R David Murray | 6924bd7 | 2011-03-13 22:48:55 -0400 | [diff] [blame] | 1062 | if c.exception.errno not in (errno.ENOENT, errno.EACCES): |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1063 | raise c.exception |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 1064 | |
Antoine Pitrou | a839271 | 2013-08-30 23:38:13 +0200 | [diff] [blame] | 1065 | @unittest.skipIf(threading is None, "threading required") |
| 1066 | def test_double_close_on_error(self): |
| 1067 | # Issue #18851 |
| 1068 | fds = [] |
| 1069 | def open_fds(): |
| 1070 | for i in range(20): |
| 1071 | fds.extend(os.pipe()) |
| 1072 | time.sleep(0.001) |
| 1073 | t = threading.Thread(target=open_fds) |
| 1074 | t.start() |
| 1075 | try: |
| 1076 | with self.assertRaises(EnvironmentError): |
| 1077 | subprocess.Popen(['nonexisting_i_hope'], |
| 1078 | stdin=subprocess.PIPE, |
| 1079 | stdout=subprocess.PIPE, |
| 1080 | stderr=subprocess.PIPE) |
| 1081 | finally: |
| 1082 | t.join() |
| 1083 | exc = None |
| 1084 | for fd in fds: |
| 1085 | # If a double close occurred, some of those fds will |
| 1086 | # already have been closed by mistake, and os.close() |
| 1087 | # here will raise. |
| 1088 | try: |
| 1089 | os.close(fd) |
| 1090 | except OSError as e: |
| 1091 | exc = e |
| 1092 | if exc is not None: |
| 1093 | raise exc |
| 1094 | |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1095 | @unittest.skipIf(threading is None, "threading required") |
| 1096 | def test_threadsafe_wait(self): |
| 1097 | """Issue21291: Popen.wait() needs to be threadsafe for returncode.""" |
| 1098 | proc = subprocess.Popen([sys.executable, '-c', |
| 1099 | 'import time; time.sleep(12)']) |
| 1100 | self.assertEqual(proc.returncode, None) |
| 1101 | results = [] |
| 1102 | |
| 1103 | def kill_proc_timer_thread(): |
| 1104 | results.append(('thread-start-poll-result', proc.poll())) |
| 1105 | # terminate it from the thread and wait for the result. |
| 1106 | proc.kill() |
| 1107 | proc.wait() |
| 1108 | results.append(('thread-after-kill-and-wait', proc.returncode)) |
| 1109 | # this wait should be a no-op given the above. |
| 1110 | proc.wait() |
| 1111 | results.append(('thread-after-second-wait', proc.returncode)) |
| 1112 | |
| 1113 | # This is a timing sensitive test, the failure mode is |
| 1114 | # triggered when both the main thread and this thread are in |
| 1115 | # the wait() call at once. The delay here is to allow the |
| 1116 | # main thread to most likely be blocked in its wait() call. |
| 1117 | t = threading.Timer(0.2, kill_proc_timer_thread) |
| 1118 | t.start() |
| 1119 | |
Gregory P. Smith | ab2719f | 2014-04-23 08:38:36 -0700 | [diff] [blame] | 1120 | if mswindows: |
| 1121 | expected_errorcode = 1 |
| 1122 | else: |
| 1123 | # Should be -9 because of the proc.kill() from the thread. |
| 1124 | expected_errorcode = -9 |
| 1125 | |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1126 | # Wait for the process to finish; the thread should kill it |
| 1127 | # long before it finishes on its own. Supplying a timeout |
| 1128 | # triggers a different code path for better coverage. |
| 1129 | proc.wait(timeout=20) |
Gregory P. Smith | ab2719f | 2014-04-23 08:38:36 -0700 | [diff] [blame] | 1130 | self.assertEqual(proc.returncode, expected_errorcode, |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1131 | msg="unexpected result in wait from main thread") |
| 1132 | |
| 1133 | # This should be a no-op with no change in returncode. |
| 1134 | proc.wait() |
Gregory P. Smith | ab2719f | 2014-04-23 08:38:36 -0700 | [diff] [blame] | 1135 | self.assertEqual(proc.returncode, expected_errorcode, |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1136 | msg="unexpected result in second main wait.") |
| 1137 | |
| 1138 | t.join() |
| 1139 | # Ensure that all of the thread results are as expected. |
| 1140 | # When a race condition occurs in wait(), the returncode could |
| 1141 | # be set by the wrong thread that doesn't actually have it |
| 1142 | # leading to an incorrect value. |
| 1143 | self.assertEqual([('thread-start-poll-result', None), |
Gregory P. Smith | ab2719f | 2014-04-23 08:38:36 -0700 | [diff] [blame] | 1144 | ('thread-after-kill-and-wait', expected_errorcode), |
| 1145 | ('thread-after-second-wait', expected_errorcode)], |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1146 | results) |
| 1147 | |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 1148 | def test_issue8780(self): |
| 1149 | # Ensure that stdout is inherited from the parent |
| 1150 | # if stdout=PIPE is not used |
| 1151 | code = ';'.join(( |
| 1152 | 'import subprocess, sys', |
| 1153 | 'retcode = subprocess.call(' |
| 1154 | "[sys.executable, '-c', 'print(\"Hello World!\")'])", |
| 1155 | 'assert retcode == 0')) |
| 1156 | output = subprocess.check_output([sys.executable, '-c', code]) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1157 | self.assertTrue(output.startswith(b'Hello World!'), ascii(output)) |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 1158 | |
Tim Golden | af5ac39 | 2010-08-06 13:03:56 +0000 | [diff] [blame] | 1159 | def test_handles_closed_on_exception(self): |
| 1160 | # If CreateProcess exits with an error, ensure the |
| 1161 | # duplicate output handles are released |
Berker Peksag | 16a1f28 | 2015-09-28 13:33:14 +0300 | [diff] [blame] | 1162 | ifhandle, ifname = tempfile.mkstemp() |
| 1163 | ofhandle, ofname = tempfile.mkstemp() |
| 1164 | efhandle, efname = tempfile.mkstemp() |
Tim Golden | af5ac39 | 2010-08-06 13:03:56 +0000 | [diff] [blame] | 1165 | try: |
| 1166 | subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle, |
| 1167 | stderr=efhandle) |
| 1168 | except OSError: |
| 1169 | os.close(ifhandle) |
| 1170 | os.remove(ifname) |
| 1171 | os.close(ofhandle) |
| 1172 | os.remove(ofname) |
| 1173 | os.close(efhandle) |
| 1174 | os.remove(efname) |
| 1175 | self.assertFalse(os.path.exists(ifname)) |
| 1176 | self.assertFalse(os.path.exists(ofname)) |
| 1177 | self.assertFalse(os.path.exists(efname)) |
| 1178 | |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 1179 | def test_communicate_epipe(self): |
| 1180 | # Issue 10963: communicate() should hide EPIPE |
| 1181 | p = subprocess.Popen([sys.executable, "-c", 'pass'], |
| 1182 | stdin=subprocess.PIPE, |
| 1183 | stdout=subprocess.PIPE, |
| 1184 | stderr=subprocess.PIPE) |
| 1185 | self.addCleanup(p.stdout.close) |
| 1186 | self.addCleanup(p.stderr.close) |
| 1187 | self.addCleanup(p.stdin.close) |
| 1188 | p.communicate(b"x" * 2**20) |
| 1189 | |
| 1190 | def test_communicate_epipe_only_stdin(self): |
| 1191 | # Issue 10963: communicate() should hide EPIPE |
| 1192 | p = subprocess.Popen([sys.executable, "-c", 'pass'], |
| 1193 | stdin=subprocess.PIPE) |
| 1194 | self.addCleanup(p.stdin.close) |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1195 | p.wait() |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 1196 | p.communicate(b"x" * 2**20) |
| 1197 | |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1198 | @unittest.skipUnless(hasattr(signal, 'SIGUSR1'), |
| 1199 | "Requires signal.SIGUSR1") |
| 1200 | @unittest.skipUnless(hasattr(os, 'kill'), |
| 1201 | "Requires os.kill") |
| 1202 | @unittest.skipUnless(hasattr(os, 'getppid'), |
| 1203 | "Requires os.getppid") |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 1204 | def test_communicate_eintr(self): |
| 1205 | # Issue #12493: communicate() should handle EINTR |
| 1206 | def handler(signum, frame): |
| 1207 | pass |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1208 | old_handler = signal.signal(signal.SIGUSR1, handler) |
| 1209 | self.addCleanup(signal.signal, signal.SIGUSR1, old_handler) |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 1210 | |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1211 | args = [sys.executable, "-c", |
| 1212 | 'import os, signal;' |
| 1213 | 'os.kill(os.getppid(), signal.SIGUSR1)'] |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 1214 | for stream in ('stdout', 'stderr'): |
| 1215 | kw = {stream: subprocess.PIPE} |
| 1216 | with subprocess.Popen(args, **kw) as process: |
Ross Lagerwall | ab66d2a | 2012-02-12 09:01:30 +0200 | [diff] [blame] | 1217 | # communicate() will be interrupted by SIGUSR1 |
Victor Stinner | 2cfb6f3 | 2011-07-05 14:00:56 +0200 | [diff] [blame] | 1218 | process.communicate() |
| 1219 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1220 | |
Gregory P. Smith | 3d8e776 | 2012-11-10 22:32:22 -0800 | [diff] [blame] | 1221 | # This test is Linux-ish specific for simplicity to at least have |
| 1222 | # some coverage. It is not a platform specific bug. |
| 1223 | @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()), |
| 1224 | "Linux specific") |
| 1225 | def test_failed_child_execute_fd_leak(self): |
| 1226 | """Test for the fork() failure fd leak reported in issue16327.""" |
| 1227 | fd_directory = '/proc/%d/fd' % os.getpid() |
| 1228 | fds_before_popen = os.listdir(fd_directory) |
| 1229 | with self.assertRaises(PopenTestException): |
| 1230 | PopenExecuteChildRaises( |
| 1231 | [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE, |
| 1232 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 1233 | |
| 1234 | # NOTE: This test doesn't verify that the real _execute_child |
| 1235 | # does not close the file descriptors itself on the way out |
| 1236 | # during an exception. Code inspection has confirmed that. |
| 1237 | |
| 1238 | fds_after_exception = os.listdir(fd_directory) |
| 1239 | self.assertEqual(fds_before_popen, fds_after_exception) |
| 1240 | |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 1241 | |
| 1242 | class RunFuncTestCase(BaseTestCase): |
| 1243 | def run_python(self, code, **kwargs): |
| 1244 | """Run Python code in a subprocess using subprocess.run""" |
| 1245 | argv = [sys.executable, "-c", code] |
| 1246 | return subprocess.run(argv, **kwargs) |
| 1247 | |
| 1248 | def test_returncode(self): |
| 1249 | # call() function with sequence argument |
| 1250 | cp = self.run_python("import sys; sys.exit(47)") |
| 1251 | self.assertEqual(cp.returncode, 47) |
| 1252 | with self.assertRaises(subprocess.CalledProcessError): |
| 1253 | cp.check_returncode() |
| 1254 | |
| 1255 | def test_check(self): |
| 1256 | with self.assertRaises(subprocess.CalledProcessError) as c: |
| 1257 | self.run_python("import sys; sys.exit(47)", check=True) |
| 1258 | self.assertEqual(c.exception.returncode, 47) |
| 1259 | |
| 1260 | def test_check_zero(self): |
| 1261 | # check_returncode shouldn't raise when returncode is zero |
| 1262 | cp = self.run_python("import sys; sys.exit(0)", check=True) |
| 1263 | self.assertEqual(cp.returncode, 0) |
| 1264 | |
| 1265 | def test_timeout(self): |
| 1266 | # run() function with timeout argument; we want to test that the child |
| 1267 | # process gets killed when the timeout expires. If the child isn't |
| 1268 | # killed, this call will deadlock since subprocess.run waits for the |
| 1269 | # child. |
| 1270 | with self.assertRaises(subprocess.TimeoutExpired): |
| 1271 | self.run_python("while True: pass", timeout=0.0001) |
| 1272 | |
| 1273 | def test_capture_stdout(self): |
| 1274 | # capture stdout with zero return code |
| 1275 | cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE) |
| 1276 | self.assertIn(b'BDFL', cp.stdout) |
| 1277 | |
| 1278 | def test_capture_stderr(self): |
| 1279 | cp = self.run_python("import sys; sys.stderr.write('BDFL')", |
| 1280 | stderr=subprocess.PIPE) |
| 1281 | self.assertIn(b'BDFL', cp.stderr) |
| 1282 | |
| 1283 | def test_check_output_stdin_arg(self): |
| 1284 | # run() can be called with stdin set to a file |
| 1285 | tf = tempfile.TemporaryFile() |
| 1286 | self.addCleanup(tf.close) |
| 1287 | tf.write(b'pear') |
| 1288 | tf.seek(0) |
| 1289 | cp = self.run_python( |
| 1290 | "import sys; sys.stdout.write(sys.stdin.read().upper())", |
| 1291 | stdin=tf, stdout=subprocess.PIPE) |
| 1292 | self.assertIn(b'PEAR', cp.stdout) |
| 1293 | |
| 1294 | def test_check_output_input_arg(self): |
| 1295 | # check_output() can be called with input set to a string |
| 1296 | cp = self.run_python( |
| 1297 | "import sys; sys.stdout.write(sys.stdin.read().upper())", |
| 1298 | input=b'pear', stdout=subprocess.PIPE) |
| 1299 | self.assertIn(b'PEAR', cp.stdout) |
| 1300 | |
| 1301 | def test_check_output_stdin_with_input_arg(self): |
| 1302 | # run() refuses to accept 'stdin' with 'input' |
| 1303 | tf = tempfile.TemporaryFile() |
| 1304 | self.addCleanup(tf.close) |
| 1305 | tf.write(b'pear') |
| 1306 | tf.seek(0) |
| 1307 | with self.assertRaises(ValueError, |
| 1308 | msg="Expected ValueError when stdin and input args supplied.") as c: |
| 1309 | output = self.run_python("print('will not be run')", |
| 1310 | stdin=tf, input=b'hare') |
| 1311 | self.assertIn('stdin', c.exception.args[0]) |
| 1312 | self.assertIn('input', c.exception.args[0]) |
| 1313 | |
| 1314 | def test_check_output_timeout(self): |
| 1315 | with self.assertRaises(subprocess.TimeoutExpired) as c: |
| 1316 | cp = self.run_python(( |
| 1317 | "import sys, time\n" |
| 1318 | "sys.stdout.write('BDFL')\n" |
| 1319 | "sys.stdout.flush()\n" |
| 1320 | "time.sleep(3600)"), |
| 1321 | # Some heavily loaded buildbots (sparc Debian 3.x) require |
| 1322 | # this much time to start and print. |
| 1323 | timeout=3, stdout=subprocess.PIPE) |
| 1324 | self.assertEqual(c.exception.output, b'BDFL') |
| 1325 | # output is aliased to stdout |
| 1326 | self.assertEqual(c.exception.stdout, b'BDFL') |
| 1327 | |
| 1328 | def test_run_kwargs(self): |
| 1329 | newenv = os.environ.copy() |
| 1330 | newenv["FRUIT"] = "banana" |
| 1331 | cp = self.run_python(('import sys, os;' |
| 1332 | 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'), |
| 1333 | env=newenv) |
| 1334 | self.assertEqual(cp.returncode, 33) |
| 1335 | |
| 1336 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1337 | @unittest.skipIf(mswindows, "POSIX specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1338 | class POSIXProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1339 | |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1340 | def setUp(self): |
| 1341 | super().setUp() |
| 1342 | self._nonexistent_dir = "/_this/pa.th/does/not/exist" |
| 1343 | |
| 1344 | def _get_chdir_exception(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1345 | try: |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1346 | os.chdir(self._nonexistent_dir) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1347 | except OSError as e: |
| 1348 | # This avoids hard coding the errno value or the OS perror() |
| 1349 | # string and instead capture the exception that we want to see |
| 1350 | # below for comparison. |
| 1351 | desired_exception = e |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1352 | desired_exception.strerror += ': ' + repr(self._nonexistent_dir) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1353 | else: |
| 1354 | self.fail("chdir to nonexistant directory %s succeeded." % |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1355 | self._nonexistent_dir) |
| 1356 | return desired_exception |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1357 | |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1358 | def test_exception_cwd(self): |
| 1359 | """Test error in the child raised in the parent for a bad cwd.""" |
| 1360 | desired_exception = self._get_chdir_exception() |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1361 | try: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1362 | p = subprocess.Popen([sys.executable, "-c", ""], |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1363 | cwd=self._nonexistent_dir) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1364 | except OSError as e: |
| 1365 | # Test that the child process chdir failure actually makes |
| 1366 | # it up to the parent process as the correct exception. |
| 1367 | self.assertEqual(desired_exception.errno, e.errno) |
| 1368 | self.assertEqual(desired_exception.strerror, e.strerror) |
| 1369 | else: |
| 1370 | self.fail("Expected OSError: %s" % desired_exception) |
| 1371 | |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1372 | def test_exception_bad_executable(self): |
| 1373 | """Test error in the child raised in the parent for a bad executable.""" |
| 1374 | desired_exception = self._get_chdir_exception() |
| 1375 | try: |
| 1376 | p = subprocess.Popen([sys.executable, "-c", ""], |
| 1377 | executable=self._nonexistent_dir) |
| 1378 | except OSError as e: |
| 1379 | # Test that the child process exec failure actually makes |
| 1380 | # it up to the parent process as the correct exception. |
| 1381 | self.assertEqual(desired_exception.errno, e.errno) |
| 1382 | self.assertEqual(desired_exception.strerror, e.strerror) |
| 1383 | else: |
| 1384 | self.fail("Expected OSError: %s" % desired_exception) |
| 1385 | |
| 1386 | def test_exception_bad_args_0(self): |
| 1387 | """Test error in the child raised in the parent for a bad args[0].""" |
| 1388 | desired_exception = self._get_chdir_exception() |
| 1389 | try: |
| 1390 | p = subprocess.Popen([self._nonexistent_dir, "-c", ""]) |
| 1391 | except OSError as e: |
| 1392 | # Test that the child process exec failure actually makes |
| 1393 | # it up to the parent process as the correct exception. |
| 1394 | self.assertEqual(desired_exception.errno, e.errno) |
| 1395 | self.assertEqual(desired_exception.strerror, e.strerror) |
| 1396 | else: |
| 1397 | self.fail("Expected OSError: %s" % desired_exception) |
| 1398 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1399 | def test_restore_signals(self): |
| 1400 | # Code coverage for both values of restore_signals to make sure it |
| 1401 | # at least does not blow up. |
| 1402 | # A test for behavior would be complex. Contributions welcome. |
| 1403 | subprocess.call([sys.executable, "-c", ""], restore_signals=True) |
| 1404 | subprocess.call([sys.executable, "-c", ""], restore_signals=False) |
| 1405 | |
| 1406 | def test_start_new_session(self): |
| 1407 | # For code coverage of calling setsid(). We don't care if we get an |
| 1408 | # EPERM error from it depending on the test execution environment, that |
| 1409 | # still indicates that it was called. |
| 1410 | try: |
| 1411 | output = subprocess.check_output( |
| 1412 | [sys.executable, "-c", |
| 1413 | "import os; print(os.getpgid(os.getpid()))"], |
| 1414 | start_new_session=True) |
| 1415 | except OSError as e: |
| 1416 | if e.errno != errno.EPERM: |
| 1417 | raise |
| 1418 | else: |
| 1419 | parent_pgid = os.getpgid(os.getpid()) |
| 1420 | child_pgid = int(output) |
| 1421 | self.assertNotEqual(parent_pgid, child_pgid) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1422 | |
| 1423 | def test_run_abort(self): |
| 1424 | # returncode handles signal termination |
Antoine Pitrou | 77e904e | 2013-10-08 23:04:32 +0200 | [diff] [blame] | 1425 | with support.SuppressCrashReport(): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1426 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1427 | 'import os; os.abort()']) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1428 | p.wait() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1429 | self.assertEqual(-p.returncode, signal.SIGABRT) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1430 | |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | d6da760 | 2016-06-03 06:14:06 +0000 | [diff] [blame] | 1431 | def test_CalledProcessError_str_signal(self): |
| 1432 | err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd") |
| 1433 | error_string = str(err) |
| 1434 | # We're relying on the repr() of the signal.Signals intenum to provide |
| 1435 | # the word signal, the signal name and the numeric value. |
| 1436 | self.assertIn("signal", error_string.lower()) |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | b414906 | 2016-06-03 06:19:35 +0000 | [diff] [blame] | 1437 | # We're not being specific about the signal name as some signals have |
| 1438 | # multiple names and which name is revealed can vary. |
| 1439 | self.assertIn("SIG", error_string) |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | d6da760 | 2016-06-03 06:14:06 +0000 | [diff] [blame] | 1440 | self.assertIn(str(signal.SIGABRT), error_string) |
| 1441 | |
| 1442 | def test_CalledProcessError_str_unknown_signal(self): |
| 1443 | err = subprocess.CalledProcessError(-9876543, "fake cmd") |
| 1444 | error_string = str(err) |
| 1445 | self.assertIn("unknown signal 9876543.", error_string) |
| 1446 | |
| 1447 | def test_CalledProcessError_str_non_zero(self): |
| 1448 | err = subprocess.CalledProcessError(2, "fake cmd") |
| 1449 | error_string = str(err) |
| 1450 | self.assertIn("non-zero exit status 2.", error_string) |
| 1451 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1452 | def test_preexec(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1453 | # DISCLAIMER: Setting environment variables is *not* a good use |
| 1454 | # of a preexec_fn. This is merely a test. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1455 | p = subprocess.Popen([sys.executable, "-c", |
| 1456 | 'import sys,os;' |
| 1457 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 1458 | stdout=subprocess.PIPE, |
| 1459 | preexec_fn=lambda: os.putenv("FRUIT", "apple")) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 1460 | with p: |
| 1461 | self.assertEqual(p.stdout.read(), b"apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1462 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1463 | def test_preexec_exception(self): |
| 1464 | def raise_it(): |
| 1465 | raise ValueError("What if two swallows carried a coconut?") |
| 1466 | try: |
| 1467 | p = subprocess.Popen([sys.executable, "-c", ""], |
| 1468 | preexec_fn=raise_it) |
Gregory P. Smith | 8d07c26 | 2012-11-10 23:53:47 -0800 | [diff] [blame] | 1469 | except subprocess.SubprocessError as e: |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1470 | self.assertTrue( |
| 1471 | subprocess._posixsubprocess, |
| 1472 | "Expected a ValueError from the preexec_fn") |
| 1473 | except ValueError as e: |
| 1474 | self.assertIn("coconut", e.args[0]) |
| 1475 | else: |
| 1476 | self.fail("Exception raised by preexec_fn did not make it " |
| 1477 | "to the parent process.") |
| 1478 | |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 1479 | class _TestExecuteChildPopen(subprocess.Popen): |
| 1480 | """Used to test behavior at the end of _execute_child.""" |
| 1481 | def __init__(self, testcase, *args, **kwargs): |
| 1482 | self._testcase = testcase |
| 1483 | subprocess.Popen.__init__(self, *args, **kwargs) |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1484 | |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 1485 | def _execute_child(self, *args, **kwargs): |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1486 | try: |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 1487 | subprocess.Popen._execute_child(self, *args, **kwargs) |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1488 | finally: |
| 1489 | # Open a bunch of file descriptors and verify that |
| 1490 | # none of them are the same as the ones the Popen |
| 1491 | # instance is using for stdin/stdout/stderr. |
| 1492 | devzero_fds = [os.open("/dev/zero", os.O_RDONLY) |
| 1493 | for _ in range(8)] |
| 1494 | try: |
| 1495 | for fd in devzero_fds: |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 1496 | self._testcase.assertNotIn( |
| 1497 | fd, (self.stdin.fileno(), self.stdout.fileno(), |
| 1498 | self.stderr.fileno()), |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1499 | msg="At least one fd was closed early.") |
| 1500 | finally: |
Richard Oudkerk | 0e547b6 | 2013-06-10 16:29:19 +0100 | [diff] [blame] | 1501 | for fd in devzero_fds: |
| 1502 | os.close(fd) |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1503 | |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 1504 | @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.") |
| 1505 | def test_preexec_errpipe_does_not_double_close_pipes(self): |
| 1506 | """Issue16140: Don't double close pipes on preexec error.""" |
| 1507 | |
| 1508 | def raise_it(): |
Gregory P. Smith | 65ee6ec | 2012-11-11 10:12:40 -0800 | [diff] [blame] | 1509 | raise subprocess.SubprocessError( |
| 1510 | "force the _execute_child() errpipe_data path.") |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1511 | |
Gregory P. Smith | c2c4cb6 | 2012-11-11 01:41:49 -0800 | [diff] [blame] | 1512 | with self.assertRaises(subprocess.SubprocessError): |
Gregory P. Smith | e27faac | 2012-11-11 09:59:27 -0800 | [diff] [blame] | 1513 | self._TestExecuteChildPopen( |
| 1514 | self, [sys.executable, "-c", "pass"], |
Gregory P. Smith | 12489d9 | 2012-11-11 01:37:02 -0800 | [diff] [blame] | 1515 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1516 | stderr=subprocess.PIPE, preexec_fn=raise_it) |
| 1517 | |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 1518 | def test_preexec_gc_module_failure(self): |
| 1519 | # This tests the code that disables garbage collection if the child |
| 1520 | # process will execute any Python. |
| 1521 | def raise_runtime_error(): |
| 1522 | raise RuntimeError("this shouldn't escape") |
| 1523 | enabled = gc.isenabled() |
| 1524 | orig_gc_disable = gc.disable |
| 1525 | orig_gc_isenabled = gc.isenabled |
| 1526 | try: |
| 1527 | gc.disable() |
| 1528 | self.assertFalse(gc.isenabled()) |
| 1529 | subprocess.call([sys.executable, '-c', ''], |
| 1530 | preexec_fn=lambda: None) |
| 1531 | self.assertFalse(gc.isenabled(), |
| 1532 | "Popen enabled gc when it shouldn't.") |
| 1533 | |
| 1534 | gc.enable() |
| 1535 | self.assertTrue(gc.isenabled()) |
| 1536 | subprocess.call([sys.executable, '-c', ''], |
| 1537 | preexec_fn=lambda: None) |
| 1538 | self.assertTrue(gc.isenabled(), "Popen left gc disabled.") |
| 1539 | |
| 1540 | gc.disable = raise_runtime_error |
| 1541 | self.assertRaises(RuntimeError, subprocess.Popen, |
| 1542 | [sys.executable, '-c', ''], |
| 1543 | preexec_fn=lambda: None) |
| 1544 | |
| 1545 | del gc.isenabled # force an AttributeError |
| 1546 | self.assertRaises(AttributeError, subprocess.Popen, |
| 1547 | [sys.executable, '-c', ''], |
| 1548 | preexec_fn=lambda: None) |
| 1549 | finally: |
| 1550 | gc.disable = orig_gc_disable |
| 1551 | gc.isenabled = orig_gc_isenabled |
| 1552 | if not enabled: |
| 1553 | gc.disable() |
| 1554 | |
Martin Panter | f7fdbda | 2015-12-05 09:51:52 +0000 | [diff] [blame] | 1555 | @unittest.skipIf( |
| 1556 | sys.platform == 'darwin', 'setrlimit() seems to fail on OS X') |
Martin Panter | afdd513 | 2015-11-30 02:21:41 +0000 | [diff] [blame] | 1557 | def test_preexec_fork_failure(self): |
| 1558 | # The internal code did not preserve the previous exception when |
| 1559 | # re-enabling garbage collection |
| 1560 | try: |
| 1561 | from resource import getrlimit, setrlimit, RLIMIT_NPROC |
| 1562 | except ImportError as err: |
| 1563 | self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD |
| 1564 | limits = getrlimit(RLIMIT_NPROC) |
| 1565 | [_, hard] = limits |
| 1566 | setrlimit(RLIMIT_NPROC, (0, hard)) |
| 1567 | self.addCleanup(setrlimit, RLIMIT_NPROC, limits) |
Martin Panter | 5cf791b | 2015-12-11 05:40:14 +0000 | [diff] [blame] | 1568 | try: |
Martin Panter | afdd513 | 2015-11-30 02:21:41 +0000 | [diff] [blame] | 1569 | subprocess.call([sys.executable, '-c', ''], |
| 1570 | preexec_fn=lambda: None) |
Martin Panter | 5cf791b | 2015-12-11 05:40:14 +0000 | [diff] [blame] | 1571 | except BlockingIOError: |
| 1572 | # Forking should raise EAGAIN, translated to BlockingIOError |
| 1573 | pass |
| 1574 | else: |
| 1575 | self.skipTest('RLIMIT_NPROC had no effect; probably superuser') |
Martin Panter | afdd513 | 2015-11-30 02:21:41 +0000 | [diff] [blame] | 1576 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1577 | def test_args_string(self): |
| 1578 | # args is a string |
Berker Peksag | 16a1f28 | 2015-09-28 13:33:14 +0300 | [diff] [blame] | 1579 | fd, fname = tempfile.mkstemp() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1580 | # reopen in text mode |
Victor Stinner | f6782ac | 2010-10-16 23:46:43 +0000 | [diff] [blame] | 1581 | with open(fd, "w", errors="surrogateescape") as fobj: |
Xavier de Gaye | d141531 | 2016-07-22 12:15:29 +0200 | [diff] [blame^] | 1582 | fobj.write("#!%s\n" % support.unix_shell) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1583 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 1584 | sys.executable) |
| 1585 | os.chmod(fname, 0o700) |
| 1586 | p = subprocess.Popen(fname) |
| 1587 | p.wait() |
| 1588 | os.remove(fname) |
| 1589 | self.assertEqual(p.returncode, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1590 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1591 | def test_invalid_args(self): |
| 1592 | # invalid arguments should raise ValueError |
| 1593 | self.assertRaises(ValueError, subprocess.call, |
| 1594 | [sys.executable, "-c", |
| 1595 | "import sys; sys.exit(47)"], |
| 1596 | startupinfo=47) |
| 1597 | self.assertRaises(ValueError, subprocess.call, |
| 1598 | [sys.executable, "-c", |
| 1599 | "import sys; sys.exit(47)"], |
| 1600 | creationflags=47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1601 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1602 | def test_shell_sequence(self): |
| 1603 | # Run command through the shell (sequence) |
| 1604 | newenv = os.environ.copy() |
| 1605 | newenv["FRUIT"] = "apple" |
| 1606 | p = subprocess.Popen(["echo $FRUIT"], shell=1, |
| 1607 | stdout=subprocess.PIPE, |
| 1608 | env=newenv) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 1609 | with p: |
| 1610 | self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1611 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1612 | def test_shell_string(self): |
| 1613 | # Run command through the shell (string) |
| 1614 | newenv = os.environ.copy() |
| 1615 | newenv["FRUIT"] = "apple" |
| 1616 | p = subprocess.Popen("echo $FRUIT", shell=1, |
| 1617 | stdout=subprocess.PIPE, |
| 1618 | env=newenv) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 1619 | with p: |
| 1620 | self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple") |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1621 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1622 | def test_call_string(self): |
| 1623 | # call() function with string argument on UNIX |
Berker Peksag | 16a1f28 | 2015-09-28 13:33:14 +0300 | [diff] [blame] | 1624 | fd, fname = tempfile.mkstemp() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1625 | # reopen in text mode |
Victor Stinner | f6782ac | 2010-10-16 23:46:43 +0000 | [diff] [blame] | 1626 | with open(fd, "w", errors="surrogateescape") as fobj: |
Xavier de Gaye | d141531 | 2016-07-22 12:15:29 +0200 | [diff] [blame^] | 1627 | fobj.write("#!%s\n" % support.unix_shell) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1628 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 1629 | sys.executable) |
| 1630 | os.chmod(fname, 0o700) |
| 1631 | rc = subprocess.call(fname) |
| 1632 | os.remove(fname) |
| 1633 | self.assertEqual(rc, 47) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1634 | |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 1635 | def test_specific_shell(self): |
| 1636 | # Issue #9265: Incorrect name passed as arg[0]. |
| 1637 | shells = [] |
| 1638 | for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']: |
| 1639 | for name in ['bash', 'ksh']: |
| 1640 | sh = os.path.join(prefix, name) |
| 1641 | if os.path.isfile(sh): |
| 1642 | shells.append(sh) |
| 1643 | if not shells: # Will probably work for any shell but csh. |
| 1644 | self.skipTest("bash or ksh required for this test") |
| 1645 | sh = '/bin/sh' |
| 1646 | if os.path.isfile(sh) and not os.path.islink(sh): |
| 1647 | # Test will fail if /bin/sh is a symlink to csh. |
| 1648 | shells.append(sh) |
| 1649 | for sh in shells: |
| 1650 | p = subprocess.Popen("echo $0", executable=sh, shell=True, |
| 1651 | stdout=subprocess.PIPE) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 1652 | with p: |
| 1653 | self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii')) |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 1654 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1655 | def _kill_process(self, method, *args): |
Florent Xicluna | 1d8ee3a | 2010-03-05 20:26:54 +0000 | [diff] [blame] | 1656 | # Do not inherit file handles from the parent. |
| 1657 | # It should fix failures on some platforms. |
Gregory P. Smith | dee0434 | 2013-08-29 13:35:27 -0700 | [diff] [blame] | 1658 | # Also set the SIGINT handler to the default to make sure it's not |
| 1659 | # being ignored (some tests rely on that.) |
| 1660 | old_handler = signal.signal(signal.SIGINT, signal.default_int_handler) |
| 1661 | try: |
| 1662 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1663 | import sys, time |
| 1664 | sys.stdout.write('x\\n') |
| 1665 | sys.stdout.flush() |
| 1666 | time.sleep(30) |
| 1667 | """], |
| 1668 | close_fds=True, |
| 1669 | stdin=subprocess.PIPE, |
| 1670 | stdout=subprocess.PIPE, |
| 1671 | stderr=subprocess.PIPE) |
| 1672 | finally: |
| 1673 | signal.signal(signal.SIGINT, old_handler) |
Antoine Pitrou | 3d8580f | 2010-09-20 01:33:21 +0000 | [diff] [blame] | 1674 | # Wait for the interpreter to be completely initialized before |
| 1675 | # sending any signal. |
| 1676 | p.stdout.read(1) |
| 1677 | getattr(p, method)(*args) |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1678 | return p |
| 1679 | |
Charles-François Natali | 53221e3 | 2013-01-12 16:52:20 +0100 | [diff] [blame] | 1680 | @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')), |
| 1681 | "Due to known OS bug (issue #16762)") |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1682 | def _kill_dead_process(self, method, *args): |
| 1683 | # Do not inherit file handles from the parent. |
| 1684 | # It should fix failures on some platforms. |
| 1685 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 1686 | import sys, time |
| 1687 | sys.stdout.write('x\\n') |
| 1688 | sys.stdout.flush() |
| 1689 | """], |
| 1690 | close_fds=True, |
| 1691 | stdin=subprocess.PIPE, |
| 1692 | stdout=subprocess.PIPE, |
| 1693 | stderr=subprocess.PIPE) |
| 1694 | # Wait for the interpreter to be completely initialized before |
| 1695 | # sending any signal. |
| 1696 | p.stdout.read(1) |
| 1697 | # The process should end after this |
| 1698 | time.sleep(1) |
| 1699 | # This shouldn't raise even though the child is now dead |
| 1700 | getattr(p, method)(*args) |
| 1701 | p.communicate() |
| 1702 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1703 | def test_send_signal(self): |
| 1704 | p = self._kill_process('send_signal', signal.SIGINT) |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1705 | _, stderr = p.communicate() |
| 1706 | self.assertIn(b'KeyboardInterrupt', stderr) |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1707 | self.assertNotEqual(p.wait(), 0) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1708 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1709 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1710 | p = self._kill_process('kill') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1711 | _, stderr = p.communicate() |
| 1712 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1713 | self.assertEqual(p.wait(), -signal.SIGKILL) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1714 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1715 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1716 | p = self._kill_process('terminate') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1717 | _, stderr = p.communicate() |
| 1718 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1719 | self.assertEqual(p.wait(), -signal.SIGTERM) |
| 1720 | |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1721 | def test_send_signal_dead(self): |
| 1722 | # Sending a signal to a dead process |
| 1723 | self._kill_dead_process('send_signal', signal.SIGINT) |
| 1724 | |
| 1725 | def test_kill_dead(self): |
| 1726 | # Killing a dead process |
| 1727 | self._kill_dead_process('kill') |
| 1728 | |
| 1729 | def test_terminate_dead(self): |
| 1730 | # Terminating a dead process |
| 1731 | self._kill_dead_process('terminate') |
| 1732 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1733 | def _save_fds(self, save_fds): |
| 1734 | fds = [] |
| 1735 | for fd in save_fds: |
| 1736 | inheritable = os.get_inheritable(fd) |
| 1737 | saved = os.dup(fd) |
| 1738 | fds.append((fd, saved, inheritable)) |
| 1739 | return fds |
| 1740 | |
| 1741 | def _restore_fds(self, fds): |
| 1742 | for fd, saved, inheritable in fds: |
| 1743 | os.dup2(saved, fd, inheritable=inheritable) |
| 1744 | os.close(saved) |
| 1745 | |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 1746 | def check_close_std_fds(self, fds): |
| 1747 | # Issue #9905: test that subprocess pipes still work properly with |
| 1748 | # some standard fds closed |
| 1749 | stdin = 0 |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1750 | saved_fds = self._save_fds(fds) |
| 1751 | for fd, saved, inheritable in saved_fds: |
| 1752 | if fd == 0: |
| 1753 | stdin = saved |
| 1754 | break |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 1755 | try: |
| 1756 | for fd in fds: |
| 1757 | os.close(fd) |
| 1758 | out, err = subprocess.Popen([sys.executable, "-c", |
| 1759 | 'import sys;' |
| 1760 | 'sys.stdout.write("apple");' |
| 1761 | 'sys.stdout.flush();' |
| 1762 | 'sys.stderr.write("orange")'], |
| 1763 | stdin=stdin, |
| 1764 | stdout=subprocess.PIPE, |
| 1765 | stderr=subprocess.PIPE).communicate() |
| 1766 | err = support.strip_python_stderr(err) |
| 1767 | self.assertEqual((out, err), (b'apple', b'orange')) |
| 1768 | finally: |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1769 | self._restore_fds(saved_fds) |
Antoine Pitrou | c9c83ba | 2011-01-03 18:23:55 +0000 | [diff] [blame] | 1770 | |
| 1771 | def test_close_fd_0(self): |
| 1772 | self.check_close_std_fds([0]) |
| 1773 | |
| 1774 | def test_close_fd_1(self): |
| 1775 | self.check_close_std_fds([1]) |
| 1776 | |
| 1777 | def test_close_fd_2(self): |
| 1778 | self.check_close_std_fds([2]) |
| 1779 | |
| 1780 | def test_close_fds_0_1(self): |
| 1781 | self.check_close_std_fds([0, 1]) |
| 1782 | |
| 1783 | def test_close_fds_0_2(self): |
| 1784 | self.check_close_std_fds([0, 2]) |
| 1785 | |
| 1786 | def test_close_fds_1_2(self): |
| 1787 | self.check_close_std_fds([1, 2]) |
| 1788 | |
| 1789 | def test_close_fds_0_1_2(self): |
| 1790 | # Issue #10806: test that subprocess pipes still work properly with |
| 1791 | # all standard fds closed. |
| 1792 | self.check_close_std_fds([0, 1, 2]) |
| 1793 | |
Gregory P. Smith | 53dd816 | 2013-12-01 16:03:24 -0800 | [diff] [blame] | 1794 | def test_small_errpipe_write_fd(self): |
| 1795 | """Issue #15798: Popen should work when stdio fds are available.""" |
| 1796 | new_stdin = os.dup(0) |
| 1797 | new_stdout = os.dup(1) |
| 1798 | try: |
| 1799 | os.close(0) |
| 1800 | os.close(1) |
| 1801 | |
| 1802 | # Side test: if errpipe_write fails to have its CLOEXEC |
| 1803 | # flag set this should cause the parent to think the exec |
| 1804 | # failed. Extremely unlikely: everyone supports CLOEXEC. |
| 1805 | subprocess.Popen([ |
| 1806 | sys.executable, "-c", |
| 1807 | "print('AssertionError:0:CLOEXEC failure.')"]).wait() |
| 1808 | finally: |
| 1809 | # Restore original stdin and stdout |
| 1810 | os.dup2(new_stdin, 0) |
| 1811 | os.dup2(new_stdout, 1) |
| 1812 | os.close(new_stdin) |
| 1813 | os.close(new_stdout) |
| 1814 | |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 1815 | def test_remapping_std_fds(self): |
| 1816 | # open up some temporary files |
Berker Peksag | 16a1f28 | 2015-09-28 13:33:14 +0300 | [diff] [blame] | 1817 | temps = [tempfile.mkstemp() for i in range(3)] |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 1818 | try: |
| 1819 | temp_fds = [fd for fd, fname in temps] |
| 1820 | |
| 1821 | # unlink the files -- we won't need to reopen them |
| 1822 | for fd, fname in temps: |
| 1823 | os.unlink(fname) |
| 1824 | |
| 1825 | # write some data to what will become stdin, and rewind |
| 1826 | os.write(temp_fds[1], b"STDIN") |
| 1827 | os.lseek(temp_fds[1], 0, 0) |
| 1828 | |
| 1829 | # move the standard file descriptors out of the way |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1830 | saved_fds = self._save_fds(range(3)) |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 1831 | try: |
| 1832 | # duplicate the file objects over the standard fd's |
| 1833 | for fd, temp_fd in enumerate(temp_fds): |
| 1834 | os.dup2(temp_fd, fd) |
| 1835 | |
| 1836 | # now use those files in the "wrong" order, so that subprocess |
| 1837 | # has to rearrange them in the child |
| 1838 | p = subprocess.Popen([sys.executable, "-c", |
| 1839 | 'import sys; got = sys.stdin.read();' |
| 1840 | 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'], |
| 1841 | stdin=temp_fds[1], |
| 1842 | stdout=temp_fds[2], |
| 1843 | stderr=temp_fds[0]) |
| 1844 | p.wait() |
| 1845 | finally: |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1846 | self._restore_fds(saved_fds) |
Antoine Pitrou | 95aaeee | 2011-01-03 21:15:48 +0000 | [diff] [blame] | 1847 | |
| 1848 | for fd in temp_fds: |
| 1849 | os.lseek(fd, 0, 0) |
| 1850 | |
| 1851 | out = os.read(temp_fds[2], 1024) |
| 1852 | err = support.strip_python_stderr(os.read(temp_fds[0], 1024)) |
| 1853 | self.assertEqual(out, b"got STDIN") |
| 1854 | self.assertEqual(err, b"err") |
| 1855 | |
| 1856 | finally: |
| 1857 | for fd in temp_fds: |
| 1858 | os.close(fd) |
| 1859 | |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 1860 | def check_swap_fds(self, stdin_no, stdout_no, stderr_no): |
| 1861 | # open up some temporary files |
Berker Peksag | 16a1f28 | 2015-09-28 13:33:14 +0300 | [diff] [blame] | 1862 | temps = [tempfile.mkstemp() for i in range(3)] |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 1863 | temp_fds = [fd for fd, fname in temps] |
| 1864 | try: |
| 1865 | # unlink the files -- we won't need to reopen them |
| 1866 | for fd, fname in temps: |
| 1867 | os.unlink(fname) |
| 1868 | |
| 1869 | # save a copy of the standard file descriptors |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1870 | saved_fds = self._save_fds(range(3)) |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 1871 | try: |
| 1872 | # duplicate the temp files over the standard fd's 0, 1, 2 |
| 1873 | for fd, temp_fd in enumerate(temp_fds): |
| 1874 | os.dup2(temp_fd, fd) |
| 1875 | |
| 1876 | # write some data to what will become stdin, and rewind |
| 1877 | os.write(stdin_no, b"STDIN") |
| 1878 | os.lseek(stdin_no, 0, 0) |
| 1879 | |
| 1880 | # now use those files in the given order, so that subprocess |
| 1881 | # has to rearrange them in the child |
| 1882 | p = subprocess.Popen([sys.executable, "-c", |
| 1883 | 'import sys; got = sys.stdin.read();' |
| 1884 | 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'], |
| 1885 | stdin=stdin_no, |
| 1886 | stdout=stdout_no, |
| 1887 | stderr=stderr_no) |
| 1888 | p.wait() |
| 1889 | |
| 1890 | for fd in temp_fds: |
| 1891 | os.lseek(fd, 0, 0) |
| 1892 | |
| 1893 | out = os.read(stdout_no, 1024) |
| 1894 | err = support.strip_python_stderr(os.read(stderr_no, 1024)) |
| 1895 | finally: |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1896 | self._restore_fds(saved_fds) |
Ross Lagerwall | d98646e | 2011-07-27 07:16:31 +0200 | [diff] [blame] | 1897 | |
| 1898 | self.assertEqual(out, b"got STDIN") |
| 1899 | self.assertEqual(err, b"err") |
| 1900 | |
| 1901 | finally: |
| 1902 | for fd in temp_fds: |
| 1903 | os.close(fd) |
| 1904 | |
| 1905 | # When duping fds, if there arises a situation where one of the fds is |
| 1906 | # either 0, 1 or 2, it is possible that it is overwritten (#12607). |
| 1907 | # This tests all combinations of this. |
| 1908 | def test_swap_fds(self): |
| 1909 | self.check_swap_fds(0, 1, 2) |
| 1910 | self.check_swap_fds(0, 2, 1) |
| 1911 | self.check_swap_fds(1, 0, 2) |
| 1912 | self.check_swap_fds(1, 2, 0) |
| 1913 | self.check_swap_fds(2, 0, 1) |
| 1914 | self.check_swap_fds(2, 1, 0) |
| 1915 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1916 | def test_surrogates_error_message(self): |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 1917 | def prepare(): |
| 1918 | raise ValueError("surrogate:\uDCff") |
| 1919 | |
| 1920 | try: |
| 1921 | subprocess.call( |
| 1922 | [sys.executable, "-c", "pass"], |
| 1923 | preexec_fn=prepare) |
| 1924 | except ValueError as err: |
| 1925 | # Pure Python implementations keeps the message |
| 1926 | self.assertIsNone(subprocess._posixsubprocess) |
| 1927 | self.assertEqual(str(err), "surrogate:\uDCff") |
Gregory P. Smith | 8d07c26 | 2012-11-10 23:53:47 -0800 | [diff] [blame] | 1928 | except subprocess.SubprocessError as err: |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 1929 | # _posixsubprocess uses a default message |
| 1930 | self.assertIsNotNone(subprocess._posixsubprocess) |
| 1931 | self.assertEqual(str(err), "Exception occurred in preexec_fn.") |
| 1932 | else: |
Gregory P. Smith | 8d07c26 | 2012-11-10 23:53:47 -0800 | [diff] [blame] | 1933 | self.fail("Expected ValueError or subprocess.SubprocessError") |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 1934 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1935 | def test_undecodable_env(self): |
| 1936 | for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')): |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 1937 | encoded_value = value.encode("ascii", "surrogateescape") |
| 1938 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1939 | # test str with surrogates |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 1940 | script = "import os; print(ascii(os.getenv(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1941 | env = os.environ.copy() |
| 1942 | env[key] = value |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 1943 | # Use C locale to get ASCII for the locale encoding to force |
Victor Stinner | 89f3ad1 | 2010-10-14 10:43:31 +0000 | [diff] [blame] | 1944 | # surrogate-escaping of \xFF in the child process; otherwise it can |
| 1945 | # be decoded as-is if the default locale is latin-1. |
Victor Stinner | ebc78d2 | 2010-10-14 10:38:17 +0000 | [diff] [blame] | 1946 | env['LC_ALL'] = 'C' |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 1947 | if sys.platform.startswith("aix"): |
| 1948 | # On AIX, the C locale uses the Latin1 encoding |
| 1949 | decoded_value = encoded_value.decode("latin1", "surrogateescape") |
| 1950 | else: |
| 1951 | # On other UNIXes, the C locale uses the ASCII encoding |
| 1952 | decoded_value = value |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1953 | stdout = subprocess.check_output( |
| 1954 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1955 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1956 | stdout = stdout.rstrip(b'\n\r') |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 1957 | self.assertEqual(stdout.decode('ascii'), ascii(decoded_value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1958 | |
| 1959 | # test bytes |
| 1960 | key = key.encode("ascii", "surrogateescape") |
Antoine Pitrou | fb8db8f | 2010-09-19 22:46:05 +0000 | [diff] [blame] | 1961 | script = "import os; print(ascii(os.getenvb(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1962 | env = os.environ.copy() |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 1963 | env[key] = encoded_value |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1964 | stdout = subprocess.check_output( |
| 1965 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 1966 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1967 | stdout = stdout.rstrip(b'\n\r') |
Victor Stinner | 5323fb0 | 2013-11-19 23:46:06 +0100 | [diff] [blame] | 1968 | self.assertEqual(stdout.decode('ascii'), ascii(encoded_value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 1969 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1970 | def test_bytes_program(self): |
| 1971 | abs_program = os.fsencode(sys.executable) |
| 1972 | path, program = os.path.split(sys.executable) |
| 1973 | program = os.fsencode(program) |
| 1974 | |
| 1975 | # absolute bytes path |
| 1976 | exitcode = subprocess.call([abs_program, "-c", "pass"]) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1977 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1978 | |
Victor Stinner | 7b3b20a | 2011-03-03 12:54:05 +0000 | [diff] [blame] | 1979 | # absolute bytes path as a string |
| 1980 | cmd = b"'" + abs_program + b"' -c pass" |
| 1981 | exitcode = subprocess.call(cmd, shell=True) |
| 1982 | self.assertEqual(exitcode, 0) |
| 1983 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1984 | # bytes program, unicode PATH |
| 1985 | env = os.environ.copy() |
| 1986 | env["PATH"] = path |
| 1987 | exitcode = subprocess.call([program, "-c", "pass"], env=env) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1988 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1989 | |
| 1990 | # bytes program, bytes PATH |
| 1991 | envb = os.environb.copy() |
| 1992 | envb[b"PATH"] = os.fsencode(path) |
| 1993 | exitcode = subprocess.call([program, "-c", "pass"], env=envb) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1994 | self.assertEqual(exitcode, 0) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1995 | |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 1996 | def test_pipe_cloexec(self): |
| 1997 | sleeper = support.findfile("input_reader.py", subdir="subprocessdata") |
| 1998 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 1999 | |
| 2000 | p1 = subprocess.Popen([sys.executable, sleeper], |
| 2001 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 2002 | stderr=subprocess.PIPE, close_fds=False) |
| 2003 | |
| 2004 | self.addCleanup(p1.communicate, b'') |
| 2005 | |
| 2006 | p2 = subprocess.Popen([sys.executable, fd_status], |
| 2007 | stdout=subprocess.PIPE, close_fds=False) |
| 2008 | |
| 2009 | output, error = p2.communicate() |
| 2010 | result_fds = set(map(int, output.split(b','))) |
| 2011 | unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(), |
| 2012 | p1.stderr.fileno()]) |
| 2013 | |
| 2014 | self.assertFalse(result_fds & unwanted_fds, |
| 2015 | "Expected no fds from %r to be open in child, " |
| 2016 | "found %r" % |
| 2017 | (unwanted_fds, result_fds & unwanted_fds)) |
| 2018 | |
| 2019 | def test_pipe_cloexec_real_tools(self): |
| 2020 | qcat = support.findfile("qcat.py", subdir="subprocessdata") |
| 2021 | qgrep = support.findfile("qgrep.py", subdir="subprocessdata") |
| 2022 | |
| 2023 | subdata = b'zxcvbn' |
| 2024 | data = subdata * 4 + b'\n' |
| 2025 | |
| 2026 | p1 = subprocess.Popen([sys.executable, qcat], |
| 2027 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 2028 | close_fds=False) |
| 2029 | |
| 2030 | p2 = subprocess.Popen([sys.executable, qgrep, subdata], |
| 2031 | stdin=p1.stdout, stdout=subprocess.PIPE, |
| 2032 | close_fds=False) |
| 2033 | |
| 2034 | self.addCleanup(p1.wait) |
| 2035 | self.addCleanup(p2.wait) |
Gregory P. Smith | 886455c | 2012-01-21 22:05:10 -0800 | [diff] [blame] | 2036 | def kill_p1(): |
| 2037 | try: |
| 2038 | p1.terminate() |
| 2039 | except ProcessLookupError: |
| 2040 | pass |
| 2041 | def kill_p2(): |
| 2042 | try: |
| 2043 | p2.terminate() |
| 2044 | except ProcessLookupError: |
| 2045 | pass |
| 2046 | self.addCleanup(kill_p1) |
| 2047 | self.addCleanup(kill_p2) |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 2048 | |
| 2049 | p1.stdin.write(data) |
| 2050 | p1.stdin.close() |
| 2051 | |
| 2052 | readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10) |
| 2053 | |
| 2054 | self.assertTrue(readfiles, "The child hung") |
| 2055 | self.assertEqual(p2.stdout.read(), data) |
| 2056 | |
Victor Stinner | faa8c13 | 2011-01-03 16:36:00 +0000 | [diff] [blame] | 2057 | p1.stdout.close() |
| 2058 | p2.stdout.close() |
| 2059 | |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 2060 | def test_close_fds(self): |
| 2061 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 2062 | |
| 2063 | fds = os.pipe() |
| 2064 | self.addCleanup(os.close, fds[0]) |
| 2065 | self.addCleanup(os.close, fds[1]) |
| 2066 | |
| 2067 | open_fds = set(fds) |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 2068 | # add a bunch more fds |
| 2069 | for _ in range(9): |
Serhiy Storchaka | 85c3033 | 2015-02-15 13:58:23 +0200 | [diff] [blame] | 2070 | fd = os.open(os.devnull, os.O_RDONLY) |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 2071 | self.addCleanup(os.close, fd) |
| 2072 | open_fds.add(fd) |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 2073 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2074 | for fd in open_fds: |
| 2075 | os.set_inheritable(fd, True) |
| 2076 | |
Gregory P. Smith | 51ee270 | 2010-12-13 07:59:39 +0000 | [diff] [blame] | 2077 | p = subprocess.Popen([sys.executable, fd_status], |
| 2078 | stdout=subprocess.PIPE, close_fds=False) |
| 2079 | output, ignored = p.communicate() |
| 2080 | remaining_fds = set(map(int, output.split(b','))) |
| 2081 | |
| 2082 | self.assertEqual(remaining_fds & open_fds, open_fds, |
| 2083 | "Some fds were closed") |
| 2084 | |
| 2085 | p = subprocess.Popen([sys.executable, fd_status], |
| 2086 | stdout=subprocess.PIPE, close_fds=True) |
| 2087 | output, ignored = p.communicate() |
| 2088 | remaining_fds = set(map(int, output.split(b','))) |
| 2089 | |
| 2090 | self.assertFalse(remaining_fds & open_fds, |
| 2091 | "Some fds were left open") |
| 2092 | self.assertIn(1, remaining_fds, "Subprocess failed") |
| 2093 | |
Gregory P. Smith | 8facece | 2012-01-21 14:01:08 -0800 | [diff] [blame] | 2094 | # Keep some of the fd's we opened open in the subprocess. |
| 2095 | # This tests _posixsubprocess.c's proper handling of fds_to_keep. |
| 2096 | fds_to_keep = set(open_fds.pop() for _ in range(8)) |
| 2097 | p = subprocess.Popen([sys.executable, fd_status], |
| 2098 | stdout=subprocess.PIPE, close_fds=True, |
| 2099 | pass_fds=()) |
| 2100 | output, ignored = p.communicate() |
| 2101 | remaining_fds = set(map(int, output.split(b','))) |
| 2102 | |
| 2103 | self.assertFalse(remaining_fds & fds_to_keep & open_fds, |
| 2104 | "Some fds not in pass_fds were left open") |
| 2105 | self.assertIn(1, remaining_fds, "Subprocess failed") |
| 2106 | |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2107 | |
Gregory P. Smith | d04f699 | 2014-06-01 15:27:28 -0700 | [diff] [blame] | 2108 | @unittest.skipIf(sys.platform.startswith("freebsd") and |
| 2109 | os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev, |
| 2110 | "Requires fdescfs mounted on /dev/fd on FreeBSD.") |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2111 | def test_close_fds_when_max_fd_is_lowered(self): |
| 2112 | """Confirm that issue21618 is fixed (may fail under valgrind).""" |
| 2113 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 2114 | |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2115 | # This launches the meat of the test in a child process to |
| 2116 | # avoid messing with the larger unittest processes maximum |
| 2117 | # number of file descriptors. |
| 2118 | # This process launches: |
| 2119 | # +--> Process that lowers its RLIMIT_NOFILE aftr setting up |
| 2120 | # a bunch of high open fds above the new lower rlimit. |
| 2121 | # Those are reported via stdout before launching a new |
| 2122 | # process with close_fds=False to run the actual test: |
| 2123 | # +--> The TEST: This one launches a fd_status.py |
| 2124 | # subprocess with close_fds=True so we can find out if |
| 2125 | # any of the fds above the lowered rlimit are still open. |
| 2126 | p = subprocess.Popen([sys.executable, '-c', textwrap.dedent( |
| 2127 | ''' |
| 2128 | import os, resource, subprocess, sys, textwrap |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2129 | open_fds = set() |
| 2130 | # Add a bunch more fds to pass down. |
Gregory P. Smith | 8fed4de | 2014-06-01 15:15:44 -0700 | [diff] [blame] | 2131 | for _ in range(40): |
Serhiy Storchaka | 85c3033 | 2015-02-15 13:58:23 +0200 | [diff] [blame] | 2132 | fd = os.open(os.devnull, os.O_RDONLY) |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2133 | open_fds.add(fd) |
| 2134 | |
| 2135 | # Leave a two pairs of low ones available for use by the |
| 2136 | # internal child error pipe and the stdout pipe. |
Gregory P. Smith | 8fed4de | 2014-06-01 15:15:44 -0700 | [diff] [blame] | 2137 | # We also leave 10 more open as some Python buildbots run into |
| 2138 | # "too many open files" errors during the test if we do not. |
| 2139 | for fd in sorted(open_fds)[:14]: |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2140 | os.close(fd) |
| 2141 | open_fds.remove(fd) |
| 2142 | |
| 2143 | for fd in open_fds: |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2144 | #self.addCleanup(os.close, fd) |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2145 | os.set_inheritable(fd, True) |
| 2146 | |
| 2147 | max_fd_open = max(open_fds) |
| 2148 | |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2149 | # Communicate the open_fds to the parent unittest.TestCase process. |
| 2150 | print(','.join(map(str, sorted(open_fds)))) |
| 2151 | sys.stdout.flush() |
| 2152 | |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2153 | rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE) |
| 2154 | try: |
Gregory P. Smith | 8fed4de | 2014-06-01 15:15:44 -0700 | [diff] [blame] | 2155 | # 29 is lower than the highest fds we are leaving open. |
| 2156 | resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max)) |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2157 | # Launch a new Python interpreter with our low fd rlim_cur that |
| 2158 | # inherits open fds above that limit. It then uses subprocess |
| 2159 | # with close_fds=True to get a report of open fds in the child. |
| 2160 | # An explicit list of fds to check is passed to fd_status.py as |
| 2161 | # letting fd_status rely on its default logic would miss the |
| 2162 | # fds above rlim_cur as it normally only checks up to that limit. |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2163 | subprocess.Popen( |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2164 | [sys.executable, '-c', |
| 2165 | textwrap.dedent(""" |
| 2166 | import subprocess, sys |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2167 | subprocess.Popen([sys.executable, %r] + |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2168 | [str(x) for x in range({max_fd})], |
Gregory P. Smith | ffd529c | 2014-06-01 13:46:54 -0700 | [diff] [blame] | 2169 | close_fds=True).wait() |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2170 | """.format(max_fd=max_fd_open+1))], |
| 2171 | close_fds=False).wait() |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2172 | finally: |
| 2173 | resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max)) |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2174 | ''' % fd_status)], stdout=subprocess.PIPE) |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2175 | |
| 2176 | output, unused_stderr = p.communicate() |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2177 | output_lines = output.splitlines() |
| 2178 | self.assertEqual(len(output_lines), 2, |
Gregory P. Smith | 9204e09 | 2014-06-15 20:16:01 -0700 | [diff] [blame] | 2179 | msg="expected exactly two lines of output:\n%r" % output) |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2180 | opened_fds = set(map(int, output_lines[0].strip().split(b','))) |
| 2181 | remaining_fds = set(map(int, output_lines[1].strip().split(b','))) |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2182 | |
Gregory P. Smith | 634aa68 | 2014-06-15 17:51:04 -0700 | [diff] [blame] | 2183 | self.assertFalse(remaining_fds & opened_fds, |
Gregory P. Smith | d4dcb70 | 2014-06-01 13:18:28 -0700 | [diff] [blame] | 2184 | msg="Some fds were left open.") |
| 2185 | |
| 2186 | |
Victor Stinner | 88701e2 | 2011-06-01 13:13:04 +0200 | [diff] [blame] | 2187 | # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file |
| 2188 | # descriptor of a pipe closed in the parent process is valid in the |
| 2189 | # child process according to fstat(), but the mode of the file |
| 2190 | # descriptor is invalid, and read or write raise an error. |
| 2191 | @support.requires_mac_ver(10, 5) |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 2192 | def test_pass_fds(self): |
| 2193 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 2194 | |
| 2195 | open_fds = set() |
| 2196 | |
| 2197 | for x in range(5): |
| 2198 | fds = os.pipe() |
| 2199 | self.addCleanup(os.close, fds[0]) |
| 2200 | self.addCleanup(os.close, fds[1]) |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2201 | os.set_inheritable(fds[0], True) |
| 2202 | os.set_inheritable(fds[1], True) |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 2203 | open_fds.update(fds) |
| 2204 | |
| 2205 | for fd in open_fds: |
| 2206 | p = subprocess.Popen([sys.executable, fd_status], |
| 2207 | stdout=subprocess.PIPE, close_fds=True, |
| 2208 | pass_fds=(fd, )) |
| 2209 | output, ignored = p.communicate() |
| 2210 | |
| 2211 | remaining_fds = set(map(int, output.split(b','))) |
| 2212 | to_be_closed = open_fds - {fd} |
| 2213 | |
| 2214 | self.assertIn(fd, remaining_fds, "fd to be passed not passed") |
| 2215 | self.assertFalse(remaining_fds & to_be_closed, |
| 2216 | "fd to be closed passed") |
| 2217 | |
| 2218 | # pass_fds overrides close_fds with a warning. |
| 2219 | with self.assertWarns(RuntimeWarning) as context: |
| 2220 | self.assertFalse(subprocess.call( |
| 2221 | [sys.executable, "-c", "import sys; sys.exit(0)"], |
| 2222 | close_fds=False, pass_fds=(fd, ))) |
| 2223 | self.assertIn('overriding close_fds', str(context.warning)) |
| 2224 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2225 | def test_pass_fds_inheritable(self): |
Victor Stinner | f6fa22e | 2013-09-01 10:22:41 +0200 | [diff] [blame] | 2226 | script = support.findfile("fd_status.py", subdir="subprocessdata") |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2227 | |
| 2228 | inheritable, non_inheritable = os.pipe() |
| 2229 | self.addCleanup(os.close, inheritable) |
| 2230 | self.addCleanup(os.close, non_inheritable) |
| 2231 | os.set_inheritable(inheritable, True) |
| 2232 | os.set_inheritable(non_inheritable, False) |
| 2233 | pass_fds = (inheritable, non_inheritable) |
| 2234 | args = [sys.executable, script] |
| 2235 | args += list(map(str, pass_fds)) |
| 2236 | |
| 2237 | p = subprocess.Popen(args, |
| 2238 | stdout=subprocess.PIPE, close_fds=True, |
| 2239 | pass_fds=pass_fds) |
| 2240 | output, ignored = p.communicate() |
| 2241 | fds = set(map(int, output.split(b','))) |
| 2242 | |
| 2243 | # the inheritable file descriptor must be inherited, so its inheritable |
| 2244 | # flag must be set in the child process after fork() and before exec() |
Victor Stinner | f6fa22e | 2013-09-01 10:22:41 +0200 | [diff] [blame] | 2245 | self.assertEqual(fds, set(pass_fds), "output=%a" % output) |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 2246 | |
| 2247 | # inheritable flag must not be changed in the parent process |
| 2248 | self.assertEqual(os.get_inheritable(inheritable), True) |
| 2249 | self.assertEqual(os.get_inheritable(non_inheritable), False) |
| 2250 | |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 2251 | def test_stdout_stdin_are_single_inout_fd(self): |
| 2252 | with io.open(os.devnull, "r+") as inout: |
| 2253 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 2254 | stdout=inout, stdin=inout) |
| 2255 | p.wait() |
| 2256 | |
| 2257 | def test_stdout_stderr_are_single_inout_fd(self): |
| 2258 | with io.open(os.devnull, "r+") as inout: |
| 2259 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 2260 | stdout=inout, stderr=inout) |
| 2261 | p.wait() |
| 2262 | |
| 2263 | def test_stderr_stdin_are_single_inout_fd(self): |
| 2264 | with io.open(os.devnull, "r+") as inout: |
| 2265 | p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], |
| 2266 | stderr=inout, stdin=inout) |
| 2267 | p.wait() |
| 2268 | |
Gregory P. Smith | e85db2b | 2010-12-14 14:38:00 +0000 | [diff] [blame] | 2269 | def test_wait_when_sigchild_ignored(self): |
| 2270 | # NOTE: sigchild_ignore.py may not be an effective test on all OSes. |
| 2271 | sigchild_ignore = support.findfile("sigchild_ignore.py", |
| 2272 | subdir="subprocessdata") |
| 2273 | p = subprocess.Popen([sys.executable, sigchild_ignore], |
| 2274 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 2275 | stdout, stderr = p.communicate() |
| 2276 | self.assertEqual(0, p.returncode, "sigchild_ignore.py exited" |
Gregory P. Smith | a80f4fb | 2010-12-14 15:23:02 +0000 | [diff] [blame] | 2277 | " non-zero with this error:\n%s" % |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 2278 | stderr.decode('utf-8')) |
Gregory P. Smith | e85db2b | 2010-12-14 14:38:00 +0000 | [diff] [blame] | 2279 | |
Antoine Pitrou | 7b98d02 | 2011-03-19 17:04:13 +0100 | [diff] [blame] | 2280 | def test_select_unbuffered(self): |
| 2281 | # Issue #11459: bufsize=0 should really set the pipes as |
| 2282 | # unbuffered (and therefore let select() work properly). |
| 2283 | select = support.import_module("select") |
| 2284 | p = subprocess.Popen([sys.executable, "-c", |
| 2285 | 'import sys;' |
| 2286 | 'sys.stdout.write("apple")'], |
| 2287 | stdout=subprocess.PIPE, |
| 2288 | bufsize=0) |
| 2289 | f = p.stdout |
Ross Lagerwall | 17ace7a | 2011-03-26 21:21:46 +0200 | [diff] [blame] | 2290 | self.addCleanup(f.close) |
Antoine Pitrou | 7b98d02 | 2011-03-19 17:04:13 +0100 | [diff] [blame] | 2291 | try: |
| 2292 | self.assertEqual(f.read(4), b"appl") |
| 2293 | self.assertIn(f, select.select([f], [], [], 0.0)[0]) |
| 2294 | finally: |
| 2295 | p.wait() |
| 2296 | |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2297 | def test_zombie_fast_process_del(self): |
| 2298 | # Issue #12650: on Unix, if Popen.__del__() was called before the |
| 2299 | # process exited, it wouldn't be added to subprocess._active, and would |
| 2300 | # remain a zombie. |
| 2301 | # spawn a Popen, and delete its reference before it exits |
| 2302 | p = subprocess.Popen([sys.executable, "-c", |
| 2303 | 'import sys, time;' |
| 2304 | 'time.sleep(0.2)'], |
| 2305 | stdout=subprocess.PIPE, |
| 2306 | stderr=subprocess.PIPE) |
Nadeem Vawda | 0d7cda3 | 2011-08-19 05:12:01 +0200 | [diff] [blame] | 2307 | self.addCleanup(p.stdout.close) |
| 2308 | self.addCleanup(p.stderr.close) |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2309 | ident = id(p) |
| 2310 | pid = p.pid |
Victor Stinner | 5a48e21 | 2016-05-20 12:11:15 +0200 | [diff] [blame] | 2311 | with support.check_warnings(('', ResourceWarning)): |
| 2312 | p = None |
| 2313 | |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2314 | # check that p is in the active processes list |
| 2315 | self.assertIn(ident, [id(o) for o in subprocess._active]) |
| 2316 | |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2317 | def test_leak_fast_process_del_killed(self): |
| 2318 | # Issue #12650: on Unix, if Popen.__del__() was called before the |
| 2319 | # process exited, and the process got killed by a signal, it would never |
| 2320 | # be removed from subprocess._active, which triggered a FD and memory |
| 2321 | # leak. |
| 2322 | # spawn a Popen, delete its reference and kill it |
| 2323 | p = subprocess.Popen([sys.executable, "-c", |
| 2324 | 'import time;' |
| 2325 | 'time.sleep(3)'], |
| 2326 | stdout=subprocess.PIPE, |
| 2327 | stderr=subprocess.PIPE) |
Nadeem Vawda | 0d7cda3 | 2011-08-19 05:12:01 +0200 | [diff] [blame] | 2328 | self.addCleanup(p.stdout.close) |
| 2329 | self.addCleanup(p.stderr.close) |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2330 | ident = id(p) |
| 2331 | pid = p.pid |
Victor Stinner | 5a48e21 | 2016-05-20 12:11:15 +0200 | [diff] [blame] | 2332 | with support.check_warnings(('', ResourceWarning)): |
| 2333 | p = None |
| 2334 | |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2335 | os.kill(pid, signal.SIGKILL) |
| 2336 | # check that p is in the active processes list |
| 2337 | self.assertIn(ident, [id(o) for o in subprocess._active]) |
| 2338 | |
| 2339 | # let some time for the process to exit, and create a new Popen: this |
| 2340 | # should trigger the wait() of p |
| 2341 | time.sleep(0.2) |
Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 2342 | with self.assertRaises(OSError) as c: |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 2343 | with subprocess.Popen(['nonexisting_i_hope'], |
| 2344 | stdout=subprocess.PIPE, |
| 2345 | stderr=subprocess.PIPE) as proc: |
| 2346 | pass |
| 2347 | # p should have been wait()ed on, and removed from the _active list |
| 2348 | self.assertRaises(OSError, os.waitpid, pid, 0) |
| 2349 | self.assertNotIn(ident, [id(o) for o in subprocess._active]) |
| 2350 | |
Charles-François Natali | 249cdc3 | 2013-08-25 18:24:45 +0200 | [diff] [blame] | 2351 | def test_close_fds_after_preexec(self): |
| 2352 | fd_status = support.findfile("fd_status.py", subdir="subprocessdata") |
| 2353 | |
| 2354 | # this FD is used as dup2() target by preexec_fn, and should be closed |
| 2355 | # in the child process |
| 2356 | fd = os.dup(1) |
| 2357 | self.addCleanup(os.close, fd) |
| 2358 | |
| 2359 | p = subprocess.Popen([sys.executable, fd_status], |
| 2360 | stdout=subprocess.PIPE, close_fds=True, |
| 2361 | preexec_fn=lambda: os.dup2(1, fd)) |
| 2362 | output, ignored = p.communicate() |
| 2363 | |
| 2364 | remaining_fds = set(map(int, output.split(b','))) |
| 2365 | |
| 2366 | self.assertNotIn(fd, remaining_fds) |
| 2367 | |
Victor Stinner | 8f437aa | 2014-10-05 17:25:19 +0200 | [diff] [blame] | 2368 | @support.cpython_only |
| 2369 | def test_fork_exec(self): |
| 2370 | # Issue #22290: fork_exec() must not crash on memory allocation failure |
| 2371 | # or other errors |
| 2372 | import _posixsubprocess |
| 2373 | gc_enabled = gc.isenabled() |
| 2374 | try: |
| 2375 | # Use a preexec function and enable the garbage collector |
| 2376 | # to force fork_exec() to re-enable the garbage collector |
| 2377 | # on error. |
| 2378 | func = lambda: None |
| 2379 | gc.enable() |
| 2380 | |
Victor Stinner | 8f437aa | 2014-10-05 17:25:19 +0200 | [diff] [blame] | 2381 | for args, exe_list, cwd, env_list in ( |
| 2382 | (123, [b"exe"], None, [b"env"]), |
| 2383 | ([b"arg"], 123, None, [b"env"]), |
| 2384 | ([b"arg"], [b"exe"], 123, [b"env"]), |
| 2385 | ([b"arg"], [b"exe"], None, 123), |
| 2386 | ): |
| 2387 | with self.assertRaises(TypeError): |
| 2388 | _posixsubprocess.fork_exec( |
| 2389 | args, exe_list, |
| 2390 | True, [], cwd, env_list, |
| 2391 | -1, -1, -1, -1, |
| 2392 | 1, 2, 3, 4, |
| 2393 | True, True, func) |
| 2394 | finally: |
| 2395 | if not gc_enabled: |
| 2396 | gc.disable() |
| 2397 | |
Gregory P. Smith | d0a5b1c | 2015-11-15 21:15:26 -0800 | [diff] [blame] | 2398 | @support.cpython_only |
| 2399 | def test_fork_exec_sorted_fd_sanity_check(self): |
| 2400 | # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check. |
| 2401 | import _posixsubprocess |
| 2402 | gc_enabled = gc.isenabled() |
| 2403 | try: |
| 2404 | gc.enable() |
| 2405 | |
| 2406 | for fds_to_keep in ( |
| 2407 | (-1, 2, 3, 4, 5), # Negative number. |
| 2408 | ('str', 4), # Not an int. |
| 2409 | (18, 23, 42, 2**63), # Out of range. |
| 2410 | (5, 4), # Not sorted. |
| 2411 | (6, 7, 7, 8), # Duplicate. |
| 2412 | ): |
| 2413 | with self.assertRaises( |
| 2414 | ValueError, |
| 2415 | msg='fds_to_keep={}'.format(fds_to_keep)) as c: |
| 2416 | _posixsubprocess.fork_exec( |
| 2417 | [b"false"], [b"false"], |
| 2418 | True, fds_to_keep, None, [b"env"], |
| 2419 | -1, -1, -1, -1, |
| 2420 | 1, 2, 3, 4, |
| 2421 | True, True, None) |
| 2422 | self.assertIn('fds_to_keep', str(c.exception)) |
| 2423 | finally: |
| 2424 | if not gc_enabled: |
| 2425 | gc.disable() |
Victor Stinner | 8f437aa | 2014-10-05 17:25:19 +0200 | [diff] [blame] | 2426 | |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 2daf8e7 | 2016-06-05 02:57:47 +0000 | [diff] [blame] | 2427 | def test_communicate_BrokenPipeError_stdin_close(self): |
| 2428 | # By not setting stdout or stderr or a timeout we force the fast path |
| 2429 | # that just calls _stdin_write() internally due to our mock. |
| 2430 | proc = subprocess.Popen([sys.executable, '-c', 'pass']) |
| 2431 | with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin: |
| 2432 | mock_proc_stdin.close.side_effect = BrokenPipeError |
| 2433 | proc.communicate() # Should swallow BrokenPipeError from close. |
| 2434 | mock_proc_stdin.close.assert_called_with() |
| 2435 | |
| 2436 | def test_communicate_BrokenPipeError_stdin_write(self): |
| 2437 | # By not setting stdout or stderr or a timeout we force the fast path |
| 2438 | # that just calls _stdin_write() internally due to our mock. |
| 2439 | proc = subprocess.Popen([sys.executable, '-c', 'pass']) |
| 2440 | with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin: |
| 2441 | mock_proc_stdin.write.side_effect = BrokenPipeError |
| 2442 | proc.communicate(b'stuff') # Should swallow the BrokenPipeError. |
| 2443 | mock_proc_stdin.write.assert_called_once_with(b'stuff') |
| 2444 | mock_proc_stdin.close.assert_called_once_with() |
| 2445 | |
| 2446 | def test_communicate_BrokenPipeError_stdin_flush(self): |
| 2447 | # Setting stdin and stdout forces the ._communicate() code path. |
| 2448 | # python -h exits faster than python -c pass (but spams stdout). |
| 2449 | proc = subprocess.Popen([sys.executable, '-h'], |
| 2450 | stdin=subprocess.PIPE, |
| 2451 | stdout=subprocess.PIPE) |
| 2452 | with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \ |
| 2453 | open(os.devnull, 'wb') as dev_null: |
| 2454 | mock_proc_stdin.flush.side_effect = BrokenPipeError |
| 2455 | # because _communicate registers a selector using proc.stdin... |
| 2456 | mock_proc_stdin.fileno.return_value = dev_null.fileno() |
| 2457 | # _communicate() should swallow BrokenPipeError from flush. |
| 2458 | proc.communicate(b'stuff') |
| 2459 | mock_proc_stdin.flush.assert_called_once_with() |
| 2460 | |
| 2461 | def test_communicate_BrokenPipeError_stdin_close_with_timeout(self): |
| 2462 | # Setting stdin and stdout forces the ._communicate() code path. |
| 2463 | # python -h exits faster than python -c pass (but spams stdout). |
| 2464 | proc = subprocess.Popen([sys.executable, '-h'], |
| 2465 | stdin=subprocess.PIPE, |
| 2466 | stdout=subprocess.PIPE) |
| 2467 | with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin: |
| 2468 | mock_proc_stdin.close.side_effect = BrokenPipeError |
| 2469 | # _communicate() should swallow BrokenPipeError from close. |
| 2470 | proc.communicate(timeout=999) |
| 2471 | mock_proc_stdin.close.assert_called_once_with() |
| 2472 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2473 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 2474 | @unittest.skipUnless(mswindows, "Windows specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 2475 | class Win32ProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 2476 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2477 | def test_startupinfo(self): |
| 2478 | # startupinfo argument |
| 2479 | # We uses hardcoded constants, because we do not want to |
| 2480 | # depend on win32all. |
| 2481 | STARTF_USESHOWWINDOW = 1 |
| 2482 | SW_MAXIMIZE = 3 |
| 2483 | startupinfo = subprocess.STARTUPINFO() |
| 2484 | startupinfo.dwFlags = STARTF_USESHOWWINDOW |
| 2485 | startupinfo.wShowWindow = SW_MAXIMIZE |
| 2486 | # Since Python is a console process, it won't be affected |
| 2487 | # by wShowWindow, but the argument should be silently |
| 2488 | # ignored |
| 2489 | subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2490 | startupinfo=startupinfo) |
| 2491 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2492 | def test_creationflags(self): |
| 2493 | # creationflags argument |
| 2494 | CREATE_NEW_CONSOLE = 16 |
| 2495 | sys.stderr.write(" a DOS box should flash briefly ...\n") |
| 2496 | subprocess.call(sys.executable + |
| 2497 | ' -c "import time; time.sleep(0.25)"', |
| 2498 | creationflags=CREATE_NEW_CONSOLE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2499 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2500 | def test_invalid_args(self): |
| 2501 | # invalid arguments should raise ValueError |
| 2502 | self.assertRaises(ValueError, subprocess.call, |
| 2503 | [sys.executable, "-c", |
| 2504 | "import sys; sys.exit(47)"], |
| 2505 | preexec_fn=lambda: 1) |
| 2506 | self.assertRaises(ValueError, subprocess.call, |
| 2507 | [sys.executable, "-c", |
| 2508 | "import sys; sys.exit(47)"], |
| 2509 | stdout=subprocess.PIPE, |
| 2510 | close_fds=True) |
| 2511 | |
| 2512 | def test_close_fds(self): |
| 2513 | # close file descriptors |
| 2514 | rc = subprocess.call([sys.executable, "-c", |
| 2515 | "import sys; sys.exit(47)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2516 | close_fds=True) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2517 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2518 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2519 | def test_shell_sequence(self): |
| 2520 | # Run command through the shell (sequence) |
| 2521 | newenv = os.environ.copy() |
| 2522 | newenv["FRUIT"] = "physalis" |
| 2523 | p = subprocess.Popen(["set"], shell=1, |
| 2524 | stdout=subprocess.PIPE, |
| 2525 | env=newenv) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 2526 | with p: |
| 2527 | self.assertIn(b"physalis", p.stdout.read()) |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 2528 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2529 | def test_shell_string(self): |
| 2530 | # Run command through the shell (string) |
| 2531 | newenv = os.environ.copy() |
| 2532 | newenv["FRUIT"] = "physalis" |
| 2533 | p = subprocess.Popen("set", shell=1, |
| 2534 | stdout=subprocess.PIPE, |
| 2535 | env=newenv) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 2536 | with p: |
| 2537 | self.assertIn(b"physalis", p.stdout.read()) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2538 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2539 | def test_call_string(self): |
| 2540 | # call() function with string argument on Windows |
| 2541 | rc = subprocess.call(sys.executable + |
| 2542 | ' -c "import sys; sys.exit(47)"') |
| 2543 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2544 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2545 | def _kill_process(self, method, *args): |
| 2546 | # Some win32 buildbot raises EOFError if stdin is inherited |
Antoine Pitrou | a4024e2 | 2010-09-24 18:57:01 +0000 | [diff] [blame] | 2547 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 2548 | import sys, time |
| 2549 | sys.stdout.write('x\\n') |
| 2550 | sys.stdout.flush() |
| 2551 | time.sleep(30) |
| 2552 | """], |
| 2553 | stdin=subprocess.PIPE, |
| 2554 | stdout=subprocess.PIPE, |
| 2555 | stderr=subprocess.PIPE) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 2556 | with p: |
| 2557 | # Wait for the interpreter to be completely initialized before |
| 2558 | # sending any signal. |
| 2559 | p.stdout.read(1) |
| 2560 | getattr(p, method)(*args) |
| 2561 | _, stderr = p.communicate() |
| 2562 | self.assertStderrEqual(stderr, b'') |
| 2563 | returncode = p.wait() |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2564 | self.assertNotEqual(returncode, 0) |
| 2565 | |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 2566 | def _kill_dead_process(self, method, *args): |
| 2567 | p = subprocess.Popen([sys.executable, "-c", """if 1: |
| 2568 | import sys, time |
| 2569 | sys.stdout.write('x\\n') |
| 2570 | sys.stdout.flush() |
| 2571 | sys.exit(42) |
| 2572 | """], |
| 2573 | stdin=subprocess.PIPE, |
| 2574 | stdout=subprocess.PIPE, |
| 2575 | stderr=subprocess.PIPE) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 2576 | with p: |
| 2577 | # Wait for the interpreter to be completely initialized before |
| 2578 | # sending any signal. |
| 2579 | p.stdout.read(1) |
| 2580 | # The process should end after this |
| 2581 | time.sleep(1) |
| 2582 | # This shouldn't raise even though the child is now dead |
| 2583 | getattr(p, method)(*args) |
| 2584 | _, stderr = p.communicate() |
| 2585 | self.assertStderrEqual(stderr, b'') |
| 2586 | rc = p.wait() |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 2587 | self.assertEqual(rc, 42) |
| 2588 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2589 | def test_send_signal(self): |
| 2590 | self._kill_process('send_signal', signal.SIGTERM) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 2591 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2592 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2593 | self._kill_process('kill') |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 2594 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2595 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 2596 | self._kill_process('terminate') |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 2597 | |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 2598 | def test_send_signal_dead(self): |
| 2599 | self._kill_dead_process('send_signal', signal.SIGTERM) |
| 2600 | |
| 2601 | def test_kill_dead(self): |
| 2602 | self._kill_dead_process('kill') |
| 2603 | |
| 2604 | def test_terminate_dead(self): |
| 2605 | self._kill_dead_process('terminate') |
| 2606 | |
Martin Panter | 23172bd | 2016-04-16 11:28:10 +0000 | [diff] [blame] | 2607 | class MiscTests(unittest.TestCase): |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2608 | def test_getoutput(self): |
| 2609 | self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy') |
| 2610 | self.assertEqual(subprocess.getstatusoutput('echo xyzzy'), |
| 2611 | (0, 'xyzzy')) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 2612 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2613 | # we use mkdtemp in the next line to create an empty directory |
| 2614 | # under our exclusive control; from that, we can invent a pathname |
| 2615 | # that we _know_ won't exist. This is guaranteed to fail. |
| 2616 | dir = None |
| 2617 | try: |
| 2618 | dir = tempfile.mkdtemp() |
| 2619 | name = os.path.join(dir, "foo") |
Tim Golden | e004175 | 2013-11-03 12:53:17 +0000 | [diff] [blame] | 2620 | status, output = subprocess.getstatusoutput( |
| 2621 | ("type " if mswindows else "cat ") + name) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 2622 | self.assertNotEqual(status, 0) |
| 2623 | finally: |
| 2624 | if dir is not None: |
| 2625 | os.rmdir(dir) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 2626 | |
Gregory P. Smith | ace5586 | 2015-04-07 15:57:54 -0700 | [diff] [blame] | 2627 | def test__all__(self): |
| 2628 | """Ensure that __all__ is populated properly.""" |
Martin Panter | 528619b | 2016-04-16 23:42:37 +0000 | [diff] [blame] | 2629 | intentionally_excluded = {"list2cmdline", "Handle"} |
Gregory P. Smith | ace5586 | 2015-04-07 15:57:54 -0700 | [diff] [blame] | 2630 | exported = set(subprocess.__all__) |
| 2631 | possible_exports = set() |
| 2632 | import types |
| 2633 | for name, value in subprocess.__dict__.items(): |
| 2634 | if name.startswith('_'): |
| 2635 | continue |
| 2636 | if isinstance(value, (types.ModuleType,)): |
| 2637 | continue |
| 2638 | possible_exports.add(name) |
| 2639 | self.assertEqual(exported, possible_exports - intentionally_excluded) |
| 2640 | |
| 2641 | |
Martin Panter | 23172bd | 2016-04-16 11:28:10 +0000 | [diff] [blame] | 2642 | @unittest.skipUnless(hasattr(selectors, 'PollSelector'), |
| 2643 | "Test needs selectors.PollSelector") |
| 2644 | class ProcessTestCaseNoPoll(ProcessTestCase): |
| 2645 | def setUp(self): |
| 2646 | self.orig_selector = subprocess._PopenSelector |
| 2647 | subprocess._PopenSelector = selectors.SelectSelector |
| 2648 | ProcessTestCase.setUp(self) |
| 2649 | |
| 2650 | def tearDown(self): |
| 2651 | subprocess._PopenSelector = self.orig_selector |
| 2652 | ProcessTestCase.tearDown(self) |
| 2653 | |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 2654 | |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 2655 | @unittest.skipUnless(mswindows, "Windows-specific tests") |
| 2656 | class CommandsWithSpaces (BaseTestCase): |
| 2657 | |
| 2658 | def setUp(self): |
| 2659 | super().setUp() |
Berker Peksag | 16a1f28 | 2015-09-28 13:33:14 +0300 | [diff] [blame] | 2660 | f, fname = tempfile.mkstemp(".py", "te st") |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 2661 | self.fname = fname.lower () |
| 2662 | os.write(f, b"import sys;" |
| 2663 | b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))" |
| 2664 | ) |
| 2665 | os.close(f) |
| 2666 | |
| 2667 | def tearDown(self): |
| 2668 | os.remove(self.fname) |
| 2669 | super().tearDown() |
| 2670 | |
| 2671 | def with_spaces(self, *args, **kwargs): |
| 2672 | kwargs['stdout'] = subprocess.PIPE |
| 2673 | p = subprocess.Popen(*args, **kwargs) |
Victor Stinner | 7438c61 | 2016-05-20 12:43:15 +0200 | [diff] [blame] | 2674 | with p: |
| 2675 | self.assertEqual( |
| 2676 | p.stdout.read ().decode("mbcs"), |
| 2677 | "2 [%r, 'ab cd']" % self.fname |
| 2678 | ) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 2679 | |
| 2680 | def test_shell_string_with_spaces(self): |
| 2681 | # call() function with string argument with spaces on Windows |
Brian Curtin | d835cf1 | 2010-08-13 20:42:57 +0000 | [diff] [blame] | 2682 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 2683 | "ab cd"), shell=1) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 2684 | |
| 2685 | def test_shell_sequence_with_spaces(self): |
| 2686 | # call() function with sequence argument with spaces on Windows |
Brian Curtin | d835cf1 | 2010-08-13 20:42:57 +0000 | [diff] [blame] | 2687 | self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1) |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 2688 | |
| 2689 | def test_noshell_string_with_spaces(self): |
| 2690 | # call() function with string argument with spaces on Windows |
| 2691 | self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, |
| 2692 | "ab cd")) |
| 2693 | |
| 2694 | def test_noshell_sequence_with_spaces(self): |
| 2695 | # call() function with sequence argument with spaces on Windows |
| 2696 | self.with_spaces([sys.executable, self.fname, "ab cd"]) |
| 2697 | |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2698 | |
Georg Brandl | a86b262 | 2012-02-20 21:34:57 +0100 | [diff] [blame] | 2699 | class ContextManagerTests(BaseTestCase): |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2700 | |
| 2701 | def test_pipe(self): |
| 2702 | with subprocess.Popen([sys.executable, "-c", |
| 2703 | "import sys;" |
| 2704 | "sys.stdout.write('stdout');" |
| 2705 | "sys.stderr.write('stderr');"], |
| 2706 | stdout=subprocess.PIPE, |
| 2707 | stderr=subprocess.PIPE) as proc: |
| 2708 | self.assertEqual(proc.stdout.read(), b"stdout") |
| 2709 | self.assertStderrEqual(proc.stderr.read(), b"stderr") |
| 2710 | |
| 2711 | self.assertTrue(proc.stdout.closed) |
| 2712 | self.assertTrue(proc.stderr.closed) |
| 2713 | |
| 2714 | def test_returncode(self): |
| 2715 | with subprocess.Popen([sys.executable, "-c", |
| 2716 | "import sys; sys.exit(100)"]) as proc: |
Gregory P. Smith | 6b65745 | 2011-05-11 21:42:08 -0700 | [diff] [blame] | 2717 | pass |
| 2718 | # __exit__ calls wait(), so the returncode should be set |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2719 | self.assertEqual(proc.returncode, 100) |
| 2720 | |
| 2721 | def test_communicate_stdin(self): |
| 2722 | with subprocess.Popen([sys.executable, "-c", |
| 2723 | "import sys;" |
| 2724 | "sys.exit(sys.stdin.read() == 'context')"], |
| 2725 | stdin=subprocess.PIPE) as proc: |
| 2726 | proc.communicate(b"context") |
| 2727 | self.assertEqual(proc.returncode, 1) |
| 2728 | |
| 2729 | def test_invalid_args(self): |
Andrew Svetlov | b172697 | 2012-12-26 23:34:54 +0200 | [diff] [blame] | 2730 | with self.assertRaises(FileNotFoundError) as c: |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2731 | with subprocess.Popen(['nonexisting_i_hope'], |
| 2732 | stdout=subprocess.PIPE, |
| 2733 | stderr=subprocess.PIPE) as proc: |
| 2734 | pass |
| 2735 | |
Serhiy Storchaka | ab900c2 | 2015-02-28 12:43:08 +0200 | [diff] [blame] | 2736 | def test_broken_pipe_cleanup(self): |
| 2737 | """Broken pipe error should not prevent wait() (Issue 21619)""" |
Serhiy Storchaka | f87afb0 | 2015-03-08 09:16:40 +0200 | [diff] [blame] | 2738 | proc = subprocess.Popen([sys.executable, '-c', 'pass'], |
Victor Stinner | 20f4bd4 | 2015-03-05 02:38:41 +0100 | [diff] [blame] | 2739 | stdin=subprocess.PIPE, |
Victor Stinner | 20f4bd4 | 2015-03-05 02:38:41 +0100 | [diff] [blame] | 2740 | bufsize=support.PIPE_MAX_SIZE*2) |
Serhiy Storchaka | f87afb0 | 2015-03-08 09:16:40 +0200 | [diff] [blame] | 2741 | proc = proc.__enter__() |
| 2742 | # Prepare to send enough data to overflow any OS pipe buffering and |
| 2743 | # guarantee a broken pipe error. Data is held in BufferedWriter |
| 2744 | # buffer until closed. |
| 2745 | proc.stdin.write(b'x' * support.PIPE_MAX_SIZE) |
Serhiy Storchaka | ab900c2 | 2015-02-28 12:43:08 +0200 | [diff] [blame] | 2746 | self.assertIsNone(proc.returncode) |
Serhiy Storchaka | f87afb0 | 2015-03-08 09:16:40 +0200 | [diff] [blame] | 2747 | # EPIPE expected under POSIX; EINVAL under Windows |
Serhiy Storchaka | cf265fd | 2015-02-28 13:27:54 +0200 | [diff] [blame] | 2748 | self.assertRaises(OSError, proc.__exit__, None, None, None) |
Serhiy Storchaka | f87afb0 | 2015-03-08 09:16:40 +0200 | [diff] [blame] | 2749 | self.assertEqual(proc.returncode, 0) |
Serhiy Storchaka | ab900c2 | 2015-02-28 12:43:08 +0200 | [diff] [blame] | 2750 | self.assertTrue(proc.stdin.closed) |
Serhiy Storchaka | ab900c2 | 2015-02-28 12:43:08 +0200 | [diff] [blame] | 2751 | |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 2752 | |
Gregory P. Smith | 3b4652e | 2011-03-15 15:43:39 -0400 | [diff] [blame] | 2753 | def test_main(): |
| 2754 | unit_tests = (ProcessTestCase, |
| 2755 | POSIXProcessTestCase, |
| 2756 | Win32ProcessTestCase, |
Martin Panter | 23172bd | 2016-04-16 11:28:10 +0000 | [diff] [blame] | 2757 | MiscTests, |
Gregory P. Smith | 3b4652e | 2011-03-15 15:43:39 -0400 | [diff] [blame] | 2758 | ProcessTestCaseNoPoll, |
Gregory P. Smith | 3b4652e | 2011-03-15 15:43:39 -0400 | [diff] [blame] | 2759 | CommandsWithSpaces, |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 2760 | ContextManagerTests, |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 2761 | RunFuncTestCase, |
Antoine Pitrou | ab85ff3 | 2011-07-23 22:03:45 +0200 | [diff] [blame] | 2762 | ) |
Gregory P. Smith | 3b4652e | 2011-03-15 15:43:39 -0400 | [diff] [blame] | 2763 | |
| 2764 | support.run_unittest(*unit_tests) |
| 2765 | support.reap_children() |
| 2766 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 2767 | if __name__ == "__main__": |
Gregory P. Smith | 112bb3a | 2011-03-15 14:55:17 -0400 | [diff] [blame] | 2768 | unittest.main() |