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