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