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