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