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