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