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