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