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