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