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