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