Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1 | import unittest |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 2 | from test import support |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 3 | import subprocess |
| 4 | import sys |
| 5 | import signal |
| 6 | import os |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 7 | import errno |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 8 | import tempfile |
| 9 | import time |
Tim Peters | 3761e8d | 2004-10-13 04:07:12 +0000 | [diff] [blame] | 10 | import re |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 11 | import sysconfig |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 12 | try: |
| 13 | import gc |
| 14 | except ImportError: |
| 15 | gc = None |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 16 | |
| 17 | mswindows = (sys.platform == "win32") |
| 18 | |
| 19 | # |
| 20 | # Depends on the following external programs: Python |
| 21 | # |
| 22 | |
| 23 | if mswindows: |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 24 | SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), ' |
| 25 | 'os.O_BINARY);') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 26 | else: |
| 27 | SETBINARY = '' |
| 28 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 29 | |
| 30 | try: |
| 31 | mkstemp = tempfile.mkstemp |
| 32 | except AttributeError: |
| 33 | # tempfile.mkstemp is not available |
| 34 | def mkstemp(): |
| 35 | """Replacement for mkstemp, calling mktemp.""" |
| 36 | fname = tempfile.mktemp() |
| 37 | return os.open(fname, os.O_RDWR|os.O_CREAT), fname |
| 38 | |
Tim Peters | 3761e8d | 2004-10-13 04:07:12 +0000 | [diff] [blame] | 39 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 40 | class BaseTestCase(unittest.TestCase): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 41 | def setUp(self): |
| 42 | # Try to minimize the number of children we have so this test |
| 43 | # doesn't crash on some buildbots (Alphas in particular). |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 44 | support.reap_children() |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 45 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 46 | def tearDown(self): |
| 47 | for inst in subprocess._active: |
| 48 | inst.wait() |
| 49 | subprocess._cleanup() |
| 50 | self.assertFalse(subprocess._active, "subprocess._active not empty") |
| 51 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 52 | def assertStderrEqual(self, stderr, expected, msg=None): |
| 53 | # In a debug build, stuff like "[6580 refs]" is printed to stderr at |
| 54 | # shutdown time. That frustrates tests trying to check stderr produced |
| 55 | # from a spawned Python process. |
Antoine Pitrou | 62f68ed | 2010-08-04 11:48:56 +0000 | [diff] [blame] | 56 | actual = support.strip_python_stderr(stderr) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 57 | self.assertEqual(actual, expected, msg) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 58 | |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 59 | |
| 60 | class ProcessTestCase(BaseTestCase): |
| 61 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 62 | def test_call_seq(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 63 | # call() function with sequence argument |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 64 | rc = subprocess.call([sys.executable, "-c", |
| 65 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 66 | self.assertEqual(rc, 47) |
| 67 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 68 | def test_check_call_zero(self): |
| 69 | # check_call() function with zero return code |
| 70 | rc = subprocess.check_call([sys.executable, "-c", |
| 71 | "import sys; sys.exit(0)"]) |
| 72 | self.assertEqual(rc, 0) |
| 73 | |
| 74 | def test_check_call_nonzero(self): |
| 75 | # check_call() function with non-zero return code |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 76 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 77 | subprocess.check_call([sys.executable, "-c", |
| 78 | "import sys; sys.exit(47)"]) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 79 | self.assertEqual(c.exception.returncode, 47) |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 80 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 81 | def test_check_output(self): |
| 82 | # check_output() function with zero return code |
| 83 | output = subprocess.check_output( |
| 84 | [sys.executable, "-c", "print('BDFL')"]) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 85 | self.assertIn(b'BDFL', output) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 86 | |
| 87 | def test_check_output_nonzero(self): |
| 88 | # check_call() function with non-zero return code |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 89 | with self.assertRaises(subprocess.CalledProcessError) as c: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 90 | subprocess.check_output( |
| 91 | [sys.executable, "-c", "import sys; sys.exit(5)"]) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 92 | self.assertEqual(c.exception.returncode, 5) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 93 | |
| 94 | def test_check_output_stderr(self): |
| 95 | # check_output() function stderr redirected to stdout |
| 96 | output = subprocess.check_output( |
| 97 | [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"], |
| 98 | stderr=subprocess.STDOUT) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 99 | self.assertIn(b'BDFL', output) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 100 | |
| 101 | def test_check_output_stdout_arg(self): |
| 102 | # check_output() function stderr redirected to stdout |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 103 | with self.assertRaises(ValueError) as c: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 104 | output = subprocess.check_output( |
| 105 | [sys.executable, "-c", "print('will not be run')"], |
| 106 | stdout=sys.stdout) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 107 | self.fail("Expected ValueError when stdout arg supplied.") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 108 | self.assertIn('stdout', c.exception.args[0]) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 109 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 110 | def test_call_kwargs(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 111 | # call() function with keyword args |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 112 | newenv = os.environ.copy() |
| 113 | newenv["FRUIT"] = "banana" |
| 114 | rc = subprocess.call([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 115 | 'import sys, os;' |
| 116 | 'sys.exit(os.getenv("FRUIT")=="banana")'], |
| 117 | env=newenv) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 118 | self.assertEqual(rc, 1) |
| 119 | |
| 120 | def test_stdin_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 121 | # .stdin is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 122 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 123 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 124 | p.wait() |
| 125 | self.assertEqual(p.stdin, None) |
| 126 | |
| 127 | def test_stdout_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 128 | # .stdout is None when not redirected |
Tim Peters | 29b6b4f | 2004-10-13 03:43:40 +0000 | [diff] [blame] | 129 | p = subprocess.Popen([sys.executable, "-c", |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 130 | 'print(" this bit of output is from a ' |
Tim Peters | 4052fe5 | 2004-10-13 03:29:54 +0000 | [diff] [blame] | 131 | 'test of stdout in a different ' |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 132 | 'process ...")'], |
Tim Peters | 4052fe5 | 2004-10-13 03:29:54 +0000 | [diff] [blame] | 133 | stdin=subprocess.PIPE, stderr=subprocess.PIPE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 134 | p.wait() |
| 135 | self.assertEqual(p.stdout, None) |
| 136 | |
| 137 | def test_stderr_none(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 138 | # .stderr is None when not redirected |
Georg Brandl | 88fc664 | 2007-02-09 21:28:07 +0000 | [diff] [blame] | 139 | p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 140 | stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
| 141 | p.wait() |
| 142 | self.assertEqual(p.stderr, None) |
| 143 | |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 144 | def test_executable_with_cwd(self): |
Florent Xicluna | 1d1ab97 | 2010-03-11 01:53:10 +0000 | [diff] [blame] | 145 | python_dir = os.path.dirname(os.path.realpath(sys.executable)) |
Ezio Melotti | 184bdfb | 2010-02-18 09:37:05 +0000 | [diff] [blame] | 146 | p = subprocess.Popen(["somethingyoudonthave", "-c", |
| 147 | "import sys; sys.exit(47)"], |
| 148 | executable=sys.executable, cwd=python_dir) |
| 149 | p.wait() |
| 150 | self.assertEqual(p.returncode, 47) |
| 151 | |
| 152 | @unittest.skipIf(sysconfig.is_python_build(), |
| 153 | "need an installed Python. See #7774") |
| 154 | def test_executable_without_cwd(self): |
| 155 | # For a normal installation, it should work without 'cwd' |
| 156 | # argument. For test runs in the build directory, see #7774. |
| 157 | p = subprocess.Popen(["somethingyoudonthave", "-c", |
| 158 | "import sys; sys.exit(47)"], |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 159 | executable=sys.executable) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 160 | p.wait() |
| 161 | self.assertEqual(p.returncode, 47) |
| 162 | |
| 163 | def test_stdin_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 164 | # stdin redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 165 | p = subprocess.Popen([sys.executable, "-c", |
| 166 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 167 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 168 | p.stdin.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 169 | p.stdin.close() |
| 170 | p.wait() |
| 171 | self.assertEqual(p.returncode, 1) |
| 172 | |
| 173 | def test_stdin_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 174 | # stdin is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 175 | tf = tempfile.TemporaryFile() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 176 | d = tf.fileno() |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 177 | os.write(d, b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 178 | os.lseek(d, 0, 0) |
| 179 | p = subprocess.Popen([sys.executable, "-c", |
| 180 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 181 | stdin=d) |
| 182 | p.wait() |
| 183 | self.assertEqual(p.returncode, 1) |
| 184 | |
| 185 | def test_stdin_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 186 | # stdin is set to open file object |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 187 | tf = tempfile.TemporaryFile() |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 188 | tf.write(b"pear") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 189 | tf.seek(0) |
| 190 | p = subprocess.Popen([sys.executable, "-c", |
| 191 | 'import sys; sys.exit(sys.stdin.read() == "pear")'], |
| 192 | stdin=tf) |
| 193 | p.wait() |
| 194 | self.assertEqual(p.returncode, 1) |
| 195 | |
| 196 | def test_stdout_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 197 | # stdout redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 198 | p = subprocess.Popen([sys.executable, "-c", |
| 199 | 'import sys; sys.stdout.write("orange")'], |
| 200 | stdout=subprocess.PIPE) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 201 | self.assertEqual(p.stdout.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 202 | |
| 203 | def test_stdout_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 204 | # stdout is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 205 | tf = tempfile.TemporaryFile() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 206 | d = tf.fileno() |
| 207 | p = subprocess.Popen([sys.executable, "-c", |
| 208 | 'import sys; sys.stdout.write("orange")'], |
| 209 | stdout=d) |
| 210 | p.wait() |
| 211 | os.lseek(d, 0, 0) |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 212 | self.assertEqual(os.read(d, 1024), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 213 | |
| 214 | def test_stdout_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 215 | # stdout is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 216 | tf = tempfile.TemporaryFile() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 217 | p = subprocess.Popen([sys.executable, "-c", |
| 218 | 'import sys; sys.stdout.write("orange")'], |
| 219 | stdout=tf) |
| 220 | p.wait() |
| 221 | tf.seek(0) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 222 | self.assertEqual(tf.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 223 | |
| 224 | def test_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 225 | # stderr redirection |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 226 | p = subprocess.Popen([sys.executable, "-c", |
| 227 | 'import sys; sys.stderr.write("strawberry")'], |
| 228 | stderr=subprocess.PIPE) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 229 | self.assertStderrEqual(p.stderr.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 230 | |
| 231 | def test_stderr_filedes(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 232 | # stderr is set to open file descriptor |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 233 | tf = tempfile.TemporaryFile() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 234 | d = tf.fileno() |
| 235 | p = subprocess.Popen([sys.executable, "-c", |
| 236 | 'import sys; sys.stderr.write("strawberry")'], |
| 237 | stderr=d) |
| 238 | p.wait() |
| 239 | os.lseek(d, 0, 0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 240 | self.assertStderrEqual(os.read(d, 1024), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 241 | |
| 242 | def test_stderr_fileobj(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 243 | # stderr is set to open file object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 244 | tf = tempfile.TemporaryFile() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 245 | p = subprocess.Popen([sys.executable, "-c", |
| 246 | 'import sys; sys.stderr.write("strawberry")'], |
| 247 | stderr=tf) |
| 248 | p.wait() |
| 249 | tf.seek(0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 250 | self.assertStderrEqual(tf.read(), b"strawberry") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 251 | |
| 252 | def test_stdout_stderr_pipe(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 253 | # capture stdout and stderr to the same pipe |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 254 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 255 | 'import sys;' |
| 256 | 'sys.stdout.write("apple");' |
| 257 | 'sys.stdout.flush();' |
| 258 | 'sys.stderr.write("orange")'], |
| 259 | stdout=subprocess.PIPE, |
| 260 | stderr=subprocess.STDOUT) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 261 | self.assertStderrEqual(p.stdout.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 262 | |
| 263 | def test_stdout_stderr_file(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 264 | # capture stdout and stderr to the same open file |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 265 | tf = tempfile.TemporaryFile() |
| 266 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 267 | 'import sys;' |
| 268 | 'sys.stdout.write("apple");' |
| 269 | 'sys.stdout.flush();' |
| 270 | 'sys.stderr.write("orange")'], |
| 271 | stdout=tf, |
| 272 | stderr=tf) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 273 | p.wait() |
| 274 | tf.seek(0) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 275 | self.assertStderrEqual(tf.read(), b"appleorange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 276 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 277 | def test_stdout_filedes_of_stdout(self): |
| 278 | # stdout is set to 1 (#1531862). |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 279 | 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] | 280 | rc = subprocess.call([sys.executable, "-c", cmd], stdout=1) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 281 | self.assertEqual(rc, 2) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 282 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 283 | def test_cwd(self): |
Christian Heimes | 5fb7c2a | 2007-12-24 08:52:31 +0000 | [diff] [blame] | 284 | tmpdir = tempfile.gettempdir() |
Peter Astrand | 195404f | 2004-11-12 15:51:48 +0000 | [diff] [blame] | 285 | # We cannot use os.path.realpath to canonicalize the path, |
| 286 | # since it doesn't expand Tru64 {memb} strings. See bug 1063571. |
| 287 | cwd = os.getcwd() |
| 288 | os.chdir(tmpdir) |
| 289 | tmpdir = os.getcwd() |
| 290 | os.chdir(cwd) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 291 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 292 | 'import sys,os;' |
| 293 | 'sys.stdout.write(os.getcwd())'], |
| 294 | stdout=subprocess.PIPE, |
| 295 | cwd=tmpdir) |
Fredrik Lundh | 59c0559 | 2004-10-13 06:55:40 +0000 | [diff] [blame] | 296 | normcase = os.path.normcase |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 297 | self.assertEqual(normcase(p.stdout.read().decode("utf-8")), |
| 298 | normcase(tmpdir)) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 299 | |
| 300 | def test_env(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 301 | newenv = os.environ.copy() |
| 302 | newenv["FRUIT"] = "orange" |
| 303 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 304 | 'import sys,os;' |
| 305 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 306 | stdout=subprocess.PIPE, |
| 307 | env=newenv) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 308 | self.assertEqual(p.stdout.read(), b"orange") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 309 | |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 310 | def test_communicate_stdin(self): |
| 311 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 312 | 'import sys;' |
| 313 | 'sys.exit(sys.stdin.read() == "pear")'], |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 314 | stdin=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 315 | p.communicate(b"pear") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 316 | self.assertEqual(p.returncode, 1) |
| 317 | |
| 318 | def test_communicate_stdout(self): |
| 319 | p = subprocess.Popen([sys.executable, "-c", |
| 320 | 'import sys; sys.stdout.write("pineapple")'], |
| 321 | stdout=subprocess.PIPE) |
| 322 | (stdout, stderr) = p.communicate() |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 323 | self.assertEqual(stdout, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 324 | self.assertEqual(stderr, None) |
| 325 | |
| 326 | def test_communicate_stderr(self): |
| 327 | p = subprocess.Popen([sys.executable, "-c", |
| 328 | 'import sys; sys.stderr.write("pineapple")'], |
| 329 | stderr=subprocess.PIPE) |
| 330 | (stdout, stderr) = p.communicate() |
| 331 | self.assertEqual(stdout, None) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 332 | self.assertStderrEqual(stderr, b"pineapple") |
Peter Astrand | cbac93c | 2005-03-03 20:24:28 +0000 | [diff] [blame] | 333 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 334 | def test_communicate(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 335 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 336 | 'import sys,os;' |
| 337 | 'sys.stderr.write("pineapple");' |
| 338 | 'sys.stdout.write(sys.stdin.read())'], |
| 339 | stdin=subprocess.PIPE, |
| 340 | stdout=subprocess.PIPE, |
| 341 | stderr=subprocess.PIPE) |
Georg Brandl | 1abcbf8 | 2008-07-01 19:28:43 +0000 | [diff] [blame] | 342 | (stdout, stderr) = p.communicate(b"banana") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 343 | self.assertEqual(stdout, b"banana") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 344 | self.assertStderrEqual(stderr, b"pineapple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 345 | |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 346 | # This test is Linux specific for simplicity to at least have |
| 347 | # some coverage. It is not a platform specific bug. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 348 | @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()), |
| 349 | "Linux specific") |
| 350 | # Test for the fd leak reported in http://bugs.python.org/issue2791. |
| 351 | def test_communicate_pipe_fd_leak(self): |
| 352 | fd_directory = '/proc/%d/fd' % os.getpid() |
| 353 | num_fds_before_popen = len(os.listdir(fd_directory)) |
| 354 | p = subprocess.Popen([sys.executable, "-c", "print()"], |
| 355 | stdout=subprocess.PIPE) |
| 356 | p.communicate() |
| 357 | num_fds_after_communicate = len(os.listdir(fd_directory)) |
| 358 | del p |
| 359 | num_fds_after_destruction = len(os.listdir(fd_directory)) |
| 360 | self.assertEqual(num_fds_before_popen, num_fds_after_destruction) |
| 361 | self.assertEqual(num_fds_before_popen, num_fds_after_communicate) |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 362 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 363 | def test_communicate_returns(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 364 | # communicate() should return None if no redirection is active |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 365 | p = subprocess.Popen([sys.executable, "-c", |
| 366 | "import sys; sys.exit(47)"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 367 | (stdout, stderr) = p.communicate() |
| 368 | self.assertEqual(stdout, None) |
| 369 | self.assertEqual(stderr, None) |
| 370 | |
| 371 | def test_communicate_pipe_buf(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 372 | # communicate() with writes larger than pipe_buf |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 373 | # This test will probably deadlock rather than fail, if |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 374 | # communicate() does not work properly. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 375 | x, y = os.pipe() |
| 376 | if mswindows: |
| 377 | pipe_buf = 512 |
| 378 | else: |
| 379 | pipe_buf = os.fpathconf(x, "PC_PIPE_BUF") |
| 380 | os.close(x) |
| 381 | os.close(y) |
| 382 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 383 | 'import sys,os;' |
| 384 | 'sys.stdout.write(sys.stdin.read(47));' |
| 385 | 'sys.stderr.write("xyz"*%d);' |
| 386 | 'sys.stdout.write(sys.stdin.read())' % pipe_buf], |
| 387 | stdin=subprocess.PIPE, |
| 388 | stdout=subprocess.PIPE, |
| 389 | stderr=subprocess.PIPE) |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 390 | string_to_write = b"abc"*pipe_buf |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 391 | (stdout, stderr) = p.communicate(string_to_write) |
| 392 | self.assertEqual(stdout, string_to_write) |
| 393 | |
| 394 | def test_writes_before_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 395 | # stdin.write before communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 396 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 397 | 'import sys,os;' |
| 398 | 'sys.stdout.write(sys.stdin.read())'], |
| 399 | stdin=subprocess.PIPE, |
| 400 | stdout=subprocess.PIPE, |
| 401 | stderr=subprocess.PIPE) |
Guido van Rossum | bb839ef | 2007-08-27 23:58:21 +0000 | [diff] [blame] | 402 | p.stdin.write(b"banana") |
| 403 | (stdout, stderr) = p.communicate(b"split") |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 404 | self.assertEqual(stdout, b"bananasplit") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 405 | self.assertStderrEqual(stderr, b"") |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 406 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 407 | def test_universal_newlines(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 408 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 409 | 'import sys,os;' + SETBINARY + |
| 410 | 'sys.stdout.write("line1\\n");' |
| 411 | 'sys.stdout.flush();' |
| 412 | 'sys.stdout.write("line2\\n");' |
| 413 | 'sys.stdout.flush();' |
| 414 | 'sys.stdout.write("line3\\r\\n");' |
| 415 | 'sys.stdout.flush();' |
| 416 | 'sys.stdout.write("line4\\r");' |
| 417 | 'sys.stdout.flush();' |
| 418 | 'sys.stdout.write("\\nline5");' |
| 419 | 'sys.stdout.flush();' |
| 420 | 'sys.stdout.write("\\nline6");'], |
| 421 | stdout=subprocess.PIPE, |
| 422 | universal_newlines=1) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 423 | stdout = p.stdout.read() |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 424 | self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 425 | |
| 426 | def test_universal_newlines_communicate(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 427 | # universal newlines through communicate() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 428 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 429 | 'import sys,os;' + SETBINARY + |
| 430 | 'sys.stdout.write("line1\\n");' |
| 431 | 'sys.stdout.flush();' |
| 432 | 'sys.stdout.write("line2\\n");' |
| 433 | 'sys.stdout.flush();' |
| 434 | 'sys.stdout.write("line3\\r\\n");' |
| 435 | 'sys.stdout.flush();' |
| 436 | 'sys.stdout.write("line4\\r");' |
| 437 | 'sys.stdout.flush();' |
| 438 | 'sys.stdout.write("\\nline5");' |
| 439 | 'sys.stdout.flush();' |
| 440 | 'sys.stdout.write("\\nline6");'], |
| 441 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 442 | universal_newlines=1) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 443 | (stdout, stderr) = p.communicate() |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 444 | self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 445 | |
| 446 | def test_no_leaking(self): |
Tim Peters | 7b759da | 2004-10-12 22:29:54 +0000 | [diff] [blame] | 447 | # Make sure we leak no resources |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 448 | if (not hasattr(support, "is_resource_enabled") or |
| 449 | support.is_resource_enabled("subprocess") and not mswindows): |
Peter Astrand | f7f1bb7 | 2005-03-03 20:47:37 +0000 | [diff] [blame] | 450 | max_handles = 1026 # too much for most UNIX systems |
| 451 | else: |
Tim Peters | eba28be | 2005-03-28 01:08:02 +0000 | [diff] [blame] | 452 | max_handles = 65 |
Fredrik Lundh | 9e29fc5 | 2004-10-13 07:54:54 +0000 | [diff] [blame] | 453 | for i in range(max_handles): |
Tim Peters | 3b01a70 | 2004-10-12 22:19:32 +0000 | [diff] [blame] | 454 | p = subprocess.Popen([sys.executable, "-c", |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 455 | "import sys;" |
| 456 | "sys.stdout.write(sys.stdin.read())"], |
| 457 | stdin=subprocess.PIPE, |
| 458 | stdout=subprocess.PIPE, |
| 459 | stderr=subprocess.PIPE) |
Georg Brandl | 1abcbf8 | 2008-07-01 19:28:43 +0000 | [diff] [blame] | 460 | data = p.communicate(b"lime")[0] |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 461 | self.assertEqual(data, b"lime") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 462 | |
| 463 | |
| 464 | def test_list2cmdline(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 465 | self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']), |
| 466 | '"a b c" d e') |
| 467 | self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']), |
| 468 | 'ab\\"c \\ d') |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 469 | self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']), |
| 470 | 'ab\\"c " \\\\" d') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 471 | self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']), |
| 472 | 'a\\\\\\b "de fg" h') |
| 473 | self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']), |
| 474 | 'a\\\\\\"b c d') |
| 475 | self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']), |
| 476 | '"a\\\\b c" d e') |
| 477 | self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']), |
| 478 | '"a\\\\b\\ c" d e') |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 479 | self.assertEqual(subprocess.list2cmdline(['ab', '']), |
| 480 | 'ab ""') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 481 | |
| 482 | |
| 483 | def test_poll(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 484 | p = subprocess.Popen([sys.executable, |
Tim Peters | 29b6b4f | 2004-10-13 03:43:40 +0000 | [diff] [blame] | 485 | "-c", "import time; time.sleep(1)"]) |
| 486 | count = 0 |
| 487 | while p.poll() is None: |
| 488 | time.sleep(0.1) |
| 489 | count += 1 |
| 490 | # We expect that the poll loop probably went around about 10 times, |
| 491 | # but, based on system scheduling we can't control, it's possible |
| 492 | # poll() never returned None. It "should be" very rare that it |
| 493 | # didn't go around at least twice. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 494 | self.assertGreaterEqual(count, 2) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 495 | # Subsequent invocations should just return the returncode |
| 496 | self.assertEqual(p.poll(), 0) |
| 497 | |
| 498 | |
| 499 | def test_wait(self): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 500 | p = subprocess.Popen([sys.executable, |
| 501 | "-c", "import time; time.sleep(2)"]) |
| 502 | self.assertEqual(p.wait(), 0) |
| 503 | # Subsequent invocations should just return the returncode |
| 504 | self.assertEqual(p.wait(), 0) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 505 | |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 506 | |
| 507 | def test_invalid_bufsize(self): |
| 508 | # an invalid type of the bufsize argument should raise |
| 509 | # TypeError. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 510 | with self.assertRaises(TypeError): |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 511 | subprocess.Popen([sys.executable, "-c", "pass"], "orange") |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 512 | |
Guido van Rossum | 46a05a7 | 2007-06-07 21:56:45 +0000 | [diff] [blame] | 513 | def test_bufsize_is_none(self): |
| 514 | # bufsize=None should be the same as bufsize=0. |
| 515 | p = subprocess.Popen([sys.executable, "-c", "pass"], None) |
| 516 | self.assertEqual(p.wait(), 0) |
| 517 | # Again with keyword arg |
| 518 | p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None) |
| 519 | self.assertEqual(p.wait(), 0) |
| 520 | |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 521 | def test_leaking_fds_on_error(self): |
| 522 | # see bug #5179: Popen leaks file descriptors to PIPEs if |
| 523 | # the child fails to execute; this will eventually exhaust |
| 524 | # the maximum number of open fds. 1024 seems a very common |
| 525 | # value for that limit, but Windows has 2048, so we loop |
| 526 | # 1024 times (each call leaked two fds). |
| 527 | for i in range(1024): |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 528 | # Windows raises IOError. Others raise OSError. |
| 529 | with self.assertRaises(EnvironmentError) as c: |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 530 | subprocess.Popen(['nonexisting_i_hope'], |
| 531 | stdout=subprocess.PIPE, |
| 532 | stderr=subprocess.PIPE) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 533 | if c.exception.errno != 2: # ignore "no such file" |
| 534 | raise c.exception |
Benjamin Peterson | d75fcb4 | 2009-02-19 04:22:03 +0000 | [diff] [blame] | 535 | |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 536 | def test_issue8780(self): |
| 537 | # Ensure that stdout is inherited from the parent |
| 538 | # if stdout=PIPE is not used |
| 539 | code = ';'.join(( |
| 540 | 'import subprocess, sys', |
| 541 | 'retcode = subprocess.call(' |
| 542 | "[sys.executable, '-c', 'print(\"Hello World!\")'])", |
| 543 | 'assert retcode == 0')) |
| 544 | output = subprocess.check_output([sys.executable, '-c', code]) |
| 545 | self.assert_(output.startswith(b'Hello World!'), ascii(output)) |
| 546 | |
Tim Golden | af5ac39 | 2010-08-06 13:03:56 +0000 | [diff] [blame] | 547 | def test_handles_closed_on_exception(self): |
| 548 | # If CreateProcess exits with an error, ensure the |
| 549 | # duplicate output handles are released |
| 550 | ifhandle, ifname = mkstemp() |
| 551 | ofhandle, ofname = mkstemp() |
| 552 | efhandle, efname = mkstemp() |
| 553 | try: |
| 554 | subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle, |
| 555 | stderr=efhandle) |
| 556 | except OSError: |
| 557 | os.close(ifhandle) |
| 558 | os.remove(ifname) |
| 559 | os.close(ofhandle) |
| 560 | os.remove(ofname) |
| 561 | os.close(efhandle) |
| 562 | os.remove(efname) |
| 563 | self.assertFalse(os.path.exists(ifname)) |
| 564 | self.assertFalse(os.path.exists(ofname)) |
| 565 | self.assertFalse(os.path.exists(efname)) |
| 566 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 567 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 568 | # context manager |
| 569 | class _SuppressCoreFiles(object): |
| 570 | """Try to prevent core files from being created.""" |
| 571 | old_limit = None |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 572 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 573 | def __enter__(self): |
| 574 | """Try to save previous ulimit, then set it to (0, 0).""" |
| 575 | try: |
| 576 | import resource |
| 577 | self.old_limit = resource.getrlimit(resource.RLIMIT_CORE) |
| 578 | resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) |
| 579 | except (ImportError, ValueError, resource.error): |
| 580 | pass |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 581 | |
Ronald Oussoren | 102d11a | 2010-07-23 09:50:05 +0000 | [diff] [blame] | 582 | if sys.platform == 'darwin': |
| 583 | # Check if the 'Crash Reporter' on OSX was configured |
| 584 | # in 'Developer' mode and warn that it will get triggered |
| 585 | # when it is. |
| 586 | # |
| 587 | # This assumes that this context manager is used in tests |
| 588 | # that might trigger the next manager. |
| 589 | value = subprocess.Popen(['/usr/bin/defaults', 'read', |
| 590 | 'com.apple.CrashReporter', 'DialogType'], |
| 591 | stdout=subprocess.PIPE).communicate()[0] |
| 592 | if value.strip() == b'developer': |
| 593 | print("this tests triggers the Crash Reporter, " |
| 594 | "that is intentional", end='') |
| 595 | sys.stdout.flush() |
| 596 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 597 | def __exit__(self, *args): |
| 598 | """Return core file behavior to default.""" |
| 599 | if self.old_limit is None: |
| 600 | return |
| 601 | try: |
| 602 | import resource |
| 603 | resource.setrlimit(resource.RLIMIT_CORE, self.old_limit) |
| 604 | except (ImportError, ValueError, resource.error): |
| 605 | pass |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 606 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 607 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 608 | @unittest.skipIf(mswindows, "POSIX specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 609 | class POSIXProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 610 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 611 | def test_exceptions(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 612 | nonexistent_dir = "/_this/pa.th/does/not/exist" |
| 613 | try: |
| 614 | os.chdir(nonexistent_dir) |
| 615 | except OSError as e: |
| 616 | # This avoids hard coding the errno value or the OS perror() |
| 617 | # string and instead capture the exception that we want to see |
| 618 | # below for comparison. |
| 619 | desired_exception = e |
| 620 | else: |
| 621 | self.fail("chdir to nonexistant directory %s succeeded." % |
| 622 | nonexistent_dir) |
| 623 | |
| 624 | # Error in the child re-raised in the parent. |
| 625 | try: |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 626 | p = subprocess.Popen([sys.executable, "-c", ""], |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 627 | cwd=nonexistent_dir) |
| 628 | except OSError as e: |
| 629 | # Test that the child process chdir failure actually makes |
| 630 | # it up to the parent process as the correct exception. |
| 631 | self.assertEqual(desired_exception.errno, e.errno) |
| 632 | self.assertEqual(desired_exception.strerror, e.strerror) |
| 633 | else: |
| 634 | self.fail("Expected OSError: %s" % desired_exception) |
| 635 | |
| 636 | def test_restore_signals(self): |
| 637 | # Code coverage for both values of restore_signals to make sure it |
| 638 | # at least does not blow up. |
| 639 | # A test for behavior would be complex. Contributions welcome. |
| 640 | subprocess.call([sys.executable, "-c", ""], restore_signals=True) |
| 641 | subprocess.call([sys.executable, "-c", ""], restore_signals=False) |
| 642 | |
| 643 | def test_start_new_session(self): |
| 644 | # For code coverage of calling setsid(). We don't care if we get an |
| 645 | # EPERM error from it depending on the test execution environment, that |
| 646 | # still indicates that it was called. |
| 647 | try: |
| 648 | output = subprocess.check_output( |
| 649 | [sys.executable, "-c", |
| 650 | "import os; print(os.getpgid(os.getpid()))"], |
| 651 | start_new_session=True) |
| 652 | except OSError as e: |
| 653 | if e.errno != errno.EPERM: |
| 654 | raise |
| 655 | else: |
| 656 | parent_pgid = os.getpgid(os.getpid()) |
| 657 | child_pgid = int(output) |
| 658 | self.assertNotEqual(parent_pgid, child_pgid) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 659 | |
| 660 | def test_run_abort(self): |
| 661 | # returncode handles signal termination |
| 662 | with _SuppressCoreFiles(): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 663 | p = subprocess.Popen([sys.executable, "-c", |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 664 | 'import os; os.abort()']) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 665 | p.wait() |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 666 | self.assertEqual(-p.returncode, signal.SIGABRT) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 667 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 668 | def test_preexec(self): |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 669 | # DISCLAIMER: Setting environment variables is *not* a good use |
| 670 | # of a preexec_fn. This is merely a test. |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 671 | p = subprocess.Popen([sys.executable, "-c", |
| 672 | 'import sys,os;' |
| 673 | 'sys.stdout.write(os.getenv("FRUIT"))'], |
| 674 | stdout=subprocess.PIPE, |
| 675 | preexec_fn=lambda: os.putenv("FRUIT", "apple")) |
| 676 | self.assertEqual(p.stdout.read(), b"apple") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 677 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 678 | def test_preexec_exception(self): |
| 679 | def raise_it(): |
| 680 | raise ValueError("What if two swallows carried a coconut?") |
| 681 | try: |
| 682 | p = subprocess.Popen([sys.executable, "-c", ""], |
| 683 | preexec_fn=raise_it) |
| 684 | except RuntimeError as e: |
| 685 | self.assertTrue( |
| 686 | subprocess._posixsubprocess, |
| 687 | "Expected a ValueError from the preexec_fn") |
| 688 | except ValueError as e: |
| 689 | self.assertIn("coconut", e.args[0]) |
| 690 | else: |
| 691 | self.fail("Exception raised by preexec_fn did not make it " |
| 692 | "to the parent process.") |
| 693 | |
Gregory P. Smith | 32ec9da | 2010-03-19 16:53:08 +0000 | [diff] [blame] | 694 | @unittest.skipUnless(gc, "Requires a gc module.") |
| 695 | def test_preexec_gc_module_failure(self): |
| 696 | # This tests the code that disables garbage collection if the child |
| 697 | # process will execute any Python. |
| 698 | def raise_runtime_error(): |
| 699 | raise RuntimeError("this shouldn't escape") |
| 700 | enabled = gc.isenabled() |
| 701 | orig_gc_disable = gc.disable |
| 702 | orig_gc_isenabled = gc.isenabled |
| 703 | try: |
| 704 | gc.disable() |
| 705 | self.assertFalse(gc.isenabled()) |
| 706 | subprocess.call([sys.executable, '-c', ''], |
| 707 | preexec_fn=lambda: None) |
| 708 | self.assertFalse(gc.isenabled(), |
| 709 | "Popen enabled gc when it shouldn't.") |
| 710 | |
| 711 | gc.enable() |
| 712 | self.assertTrue(gc.isenabled()) |
| 713 | subprocess.call([sys.executable, '-c', ''], |
| 714 | preexec_fn=lambda: None) |
| 715 | self.assertTrue(gc.isenabled(), "Popen left gc disabled.") |
| 716 | |
| 717 | gc.disable = raise_runtime_error |
| 718 | self.assertRaises(RuntimeError, subprocess.Popen, |
| 719 | [sys.executable, '-c', ''], |
| 720 | preexec_fn=lambda: None) |
| 721 | |
| 722 | del gc.isenabled # force an AttributeError |
| 723 | self.assertRaises(AttributeError, subprocess.Popen, |
| 724 | [sys.executable, '-c', ''], |
| 725 | preexec_fn=lambda: None) |
| 726 | finally: |
| 727 | gc.disable = orig_gc_disable |
| 728 | gc.isenabled = orig_gc_isenabled |
| 729 | if not enabled: |
| 730 | gc.disable() |
| 731 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 732 | def test_args_string(self): |
| 733 | # args is a string |
| 734 | fd, fname = mkstemp() |
| 735 | # reopen in text mode |
| 736 | with open(fd, "w") as fobj: |
| 737 | fobj.write("#!/bin/sh\n") |
| 738 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 739 | sys.executable) |
| 740 | os.chmod(fname, 0o700) |
| 741 | p = subprocess.Popen(fname) |
| 742 | p.wait() |
| 743 | os.remove(fname) |
| 744 | self.assertEqual(p.returncode, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 745 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 746 | def test_invalid_args(self): |
| 747 | # invalid arguments should raise ValueError |
| 748 | self.assertRaises(ValueError, subprocess.call, |
| 749 | [sys.executable, "-c", |
| 750 | "import sys; sys.exit(47)"], |
| 751 | startupinfo=47) |
| 752 | self.assertRaises(ValueError, subprocess.call, |
| 753 | [sys.executable, "-c", |
| 754 | "import sys; sys.exit(47)"], |
| 755 | creationflags=47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 756 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 757 | def test_shell_sequence(self): |
| 758 | # Run command through the shell (sequence) |
| 759 | newenv = os.environ.copy() |
| 760 | newenv["FRUIT"] = "apple" |
| 761 | p = subprocess.Popen(["echo $FRUIT"], shell=1, |
| 762 | stdout=subprocess.PIPE, |
| 763 | env=newenv) |
| 764 | 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] | 765 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 766 | def test_shell_string(self): |
| 767 | # Run command through the shell (string) |
| 768 | newenv = os.environ.copy() |
| 769 | newenv["FRUIT"] = "apple" |
| 770 | p = subprocess.Popen("echo $FRUIT", shell=1, |
| 771 | stdout=subprocess.PIPE, |
| 772 | env=newenv) |
| 773 | 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] | 774 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 775 | def test_call_string(self): |
| 776 | # call() function with string argument on UNIX |
| 777 | fd, fname = mkstemp() |
| 778 | # reopen in text mode |
| 779 | with open(fd, "w") as fobj: |
| 780 | fobj.write("#!/bin/sh\n") |
| 781 | fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" % |
| 782 | sys.executable) |
| 783 | os.chmod(fname, 0o700) |
| 784 | rc = subprocess.call(fname) |
| 785 | os.remove(fname) |
| 786 | self.assertEqual(rc, 47) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 787 | |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 788 | def test_specific_shell(self): |
| 789 | # Issue #9265: Incorrect name passed as arg[0]. |
| 790 | shells = [] |
| 791 | for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']: |
| 792 | for name in ['bash', 'ksh']: |
| 793 | sh = os.path.join(prefix, name) |
| 794 | if os.path.isfile(sh): |
| 795 | shells.append(sh) |
| 796 | if not shells: # Will probably work for any shell but csh. |
| 797 | self.skipTest("bash or ksh required for this test") |
| 798 | sh = '/bin/sh' |
| 799 | if os.path.isfile(sh) and not os.path.islink(sh): |
| 800 | # Test will fail if /bin/sh is a symlink to csh. |
| 801 | shells.append(sh) |
| 802 | for sh in shells: |
| 803 | p = subprocess.Popen("echo $0", executable=sh, shell=True, |
| 804 | stdout=subprocess.PIPE) |
| 805 | self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii')) |
| 806 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 807 | def _kill_process(self, method, *args): |
Florent Xicluna | 1d8ee3a | 2010-03-05 20:26:54 +0000 | [diff] [blame] | 808 | # Do not inherit file handles from the parent. |
| 809 | # It should fix failures on some platforms. |
| 810 | p = subprocess.Popen([sys.executable, "-c", "input()"], close_fds=True, |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 811 | stdin=subprocess.PIPE, stderr=subprocess.PIPE) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 812 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 813 | # Let the process initialize (Issue #3137) |
Florent Xicluna | 129226d | 2010-03-05 00:52:00 +0000 | [diff] [blame] | 814 | time.sleep(0.1) |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 815 | # The process should not terminate prematurely |
Florent Xicluna | b8f22b1 | 2010-03-05 01:18:04 +0000 | [diff] [blame] | 816 | self.assertIsNone(p.poll()) |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 817 | # Retry if the process do not receive the signal. |
Florent Xicluna | 129226d | 2010-03-05 00:52:00 +0000 | [diff] [blame] | 818 | count, maxcount = 0, 3 |
Florent Xicluna | 129226d | 2010-03-05 00:52:00 +0000 | [diff] [blame] | 819 | while count < maxcount and p.poll() is None: |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 820 | getattr(p, method)(*args) |
Florent Xicluna | 129226d | 2010-03-05 00:52:00 +0000 | [diff] [blame] | 821 | time.sleep(0.1) |
| 822 | count += 1 |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 823 | |
| 824 | self.assertIsNotNone(p.poll(), "the subprocess did not terminate") |
Florent Xicluna | b8f22b1 | 2010-03-05 01:18:04 +0000 | [diff] [blame] | 825 | if count > 1: |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 826 | print("p.{}{} succeeded after " |
| 827 | "{} attempts".format(method, args, count), file=sys.stderr) |
| 828 | return p |
| 829 | |
| 830 | def test_send_signal(self): |
| 831 | p = self._kill_process('send_signal', signal.SIGINT) |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 832 | _, stderr = p.communicate() |
| 833 | self.assertIn(b'KeyboardInterrupt', stderr) |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 834 | self.assertNotEqual(p.wait(), 0) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 835 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 836 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 837 | p = self._kill_process('kill') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 838 | _, stderr = p.communicate() |
| 839 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 840 | self.assertEqual(p.wait(), -signal.SIGKILL) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 841 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 842 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 843 | p = self._kill_process('terminate') |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 844 | _, stderr = p.communicate() |
| 845 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 846 | self.assertEqual(p.wait(), -signal.SIGTERM) |
| 847 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 848 | def test_surrogates_error_message(self): |
Victor Stinner | 4d07804 | 2010-04-23 19:28:32 +0000 | [diff] [blame] | 849 | def prepare(): |
| 850 | raise ValueError("surrogate:\uDCff") |
| 851 | |
| 852 | try: |
| 853 | subprocess.call( |
| 854 | [sys.executable, "-c", "pass"], |
| 855 | preexec_fn=prepare) |
| 856 | except ValueError as err: |
| 857 | # Pure Python implementations keeps the message |
| 858 | self.assertIsNone(subprocess._posixsubprocess) |
| 859 | self.assertEqual(str(err), "surrogate:\uDCff") |
| 860 | except RuntimeError as err: |
| 861 | # _posixsubprocess uses a default message |
| 862 | self.assertIsNotNone(subprocess._posixsubprocess) |
| 863 | self.assertEqual(str(err), "Exception occurred in preexec_fn.") |
| 864 | else: |
| 865 | self.fail("Expected ValueError or RuntimeError") |
| 866 | |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 867 | def test_undecodable_env(self): |
| 868 | for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')): |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 869 | # test str with surrogates |
| 870 | script = "import os; print(repr(os.getenv(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 871 | env = os.environ.copy() |
| 872 | env[key] = value |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 873 | stdout = subprocess.check_output( |
| 874 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 875 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 876 | stdout = stdout.rstrip(b'\n\r') |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 877 | self.assertEquals(stdout.decode('ascii'), repr(value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 878 | |
| 879 | # test bytes |
| 880 | key = key.encode("ascii", "surrogateescape") |
| 881 | value = value.encode("ascii", "surrogateescape") |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 882 | script = "import os; print(repr(os.getenvb(%s)))" % repr(key) |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 883 | env = os.environ.copy() |
| 884 | env[key] = value |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 885 | stdout = subprocess.check_output( |
| 886 | [sys.executable, "-c", script], |
Victor Stinner | ce2d24d | 2010-04-23 22:55:39 +0000 | [diff] [blame] | 887 | env=env) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 888 | stdout = stdout.rstrip(b'\n\r') |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 889 | self.assertEquals(stdout.decode('ascii'), repr(value)) |
Victor Stinner | 13bb71c | 2010-04-23 21:41:56 +0000 | [diff] [blame] | 890 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 891 | def test_bytes_program(self): |
| 892 | abs_program = os.fsencode(sys.executable) |
| 893 | path, program = os.path.split(sys.executable) |
| 894 | program = os.fsencode(program) |
| 895 | |
| 896 | # absolute bytes path |
| 897 | exitcode = subprocess.call([abs_program, "-c", "pass"]) |
| 898 | self.assertEquals(exitcode, 0) |
| 899 | |
| 900 | # bytes program, unicode PATH |
| 901 | env = os.environ.copy() |
| 902 | env["PATH"] = path |
| 903 | exitcode = subprocess.call([program, "-c", "pass"], env=env) |
| 904 | self.assertEquals(exitcode, 0) |
| 905 | |
| 906 | # bytes program, bytes PATH |
| 907 | envb = os.environb.copy() |
| 908 | envb[b"PATH"] = os.fsencode(path) |
| 909 | exitcode = subprocess.call([program, "-c", "pass"], env=envb) |
| 910 | self.assertEquals(exitcode, 0) |
| 911 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 912 | |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 913 | @unittest.skipUnless(mswindows, "Windows specific tests") |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 914 | class Win32ProcessTestCase(BaseTestCase): |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 915 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 916 | def test_startupinfo(self): |
| 917 | # startupinfo argument |
| 918 | # We uses hardcoded constants, because we do not want to |
| 919 | # depend on win32all. |
| 920 | STARTF_USESHOWWINDOW = 1 |
| 921 | SW_MAXIMIZE = 3 |
| 922 | startupinfo = subprocess.STARTUPINFO() |
| 923 | startupinfo.dwFlags = STARTF_USESHOWWINDOW |
| 924 | startupinfo.wShowWindow = SW_MAXIMIZE |
| 925 | # Since Python is a console process, it won't be affected |
| 926 | # by wShowWindow, but the argument should be silently |
| 927 | # ignored |
| 928 | subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 929 | startupinfo=startupinfo) |
| 930 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 931 | def test_creationflags(self): |
| 932 | # creationflags argument |
| 933 | CREATE_NEW_CONSOLE = 16 |
| 934 | sys.stderr.write(" a DOS box should flash briefly ...\n") |
| 935 | subprocess.call(sys.executable + |
| 936 | ' -c "import time; time.sleep(0.25)"', |
| 937 | creationflags=CREATE_NEW_CONSOLE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 938 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 939 | def test_invalid_args(self): |
| 940 | # invalid arguments should raise ValueError |
| 941 | self.assertRaises(ValueError, subprocess.call, |
| 942 | [sys.executable, "-c", |
| 943 | "import sys; sys.exit(47)"], |
| 944 | preexec_fn=lambda: 1) |
| 945 | self.assertRaises(ValueError, subprocess.call, |
| 946 | [sys.executable, "-c", |
| 947 | "import sys; sys.exit(47)"], |
| 948 | stdout=subprocess.PIPE, |
| 949 | close_fds=True) |
| 950 | |
| 951 | def test_close_fds(self): |
| 952 | # close file descriptors |
| 953 | rc = subprocess.call([sys.executable, "-c", |
| 954 | "import sys; sys.exit(47)"], |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 955 | close_fds=True) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 956 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 957 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 958 | def test_shell_sequence(self): |
| 959 | # Run command through the shell (sequence) |
| 960 | newenv = os.environ.copy() |
| 961 | newenv["FRUIT"] = "physalis" |
| 962 | p = subprocess.Popen(["set"], shell=1, |
| 963 | stdout=subprocess.PIPE, |
| 964 | env=newenv) |
| 965 | self.assertIn(b"physalis", p.stdout.read()) |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 966 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 967 | def test_shell_string(self): |
| 968 | # Run command through the shell (string) |
| 969 | newenv = os.environ.copy() |
| 970 | newenv["FRUIT"] = "physalis" |
| 971 | p = subprocess.Popen("set", shell=1, |
| 972 | stdout=subprocess.PIPE, |
| 973 | env=newenv) |
| 974 | self.assertIn(b"physalis", p.stdout.read()) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 975 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 976 | def test_call_string(self): |
| 977 | # call() function with string argument on Windows |
| 978 | rc = subprocess.call(sys.executable + |
| 979 | ' -c "import sys; sys.exit(47)"') |
| 980 | self.assertEqual(rc, 47) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 981 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 982 | def _kill_process(self, method, *args): |
| 983 | # Some win32 buildbot raises EOFError if stdin is inherited |
| 984 | p = subprocess.Popen([sys.executable, "-c", "input()"], |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 985 | stdin=subprocess.PIPE, stderr=subprocess.PIPE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 986 | |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 987 | # Let the process initialize (Issue #3137) |
| 988 | time.sleep(0.1) |
| 989 | # The process should not terminate prematurely |
| 990 | self.assertIsNone(p.poll()) |
| 991 | # Retry if the process do not receive the signal. |
| 992 | count, maxcount = 0, 3 |
| 993 | while count < maxcount and p.poll() is None: |
| 994 | getattr(p, method)(*args) |
| 995 | time.sleep(0.1) |
| 996 | count += 1 |
| 997 | |
| 998 | returncode = p.poll() |
| 999 | self.assertIsNotNone(returncode, "the subprocess did not terminate") |
| 1000 | if count > 1: |
| 1001 | print("p.{}{} succeeded after " |
| 1002 | "{} attempts".format(method, args, count), file=sys.stderr) |
Florent Xicluna | c049d87 | 2010-03-27 22:47:23 +0000 | [diff] [blame] | 1003 | _, stderr = p.communicate() |
| 1004 | self.assertStderrEqual(stderr, b'') |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1005 | self.assertEqual(p.wait(), returncode) |
| 1006 | self.assertNotEqual(returncode, 0) |
| 1007 | |
| 1008 | def test_send_signal(self): |
| 1009 | self._kill_process('send_signal', signal.SIGTERM) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1010 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1011 | def test_kill(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1012 | self._kill_process('kill') |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1013 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1014 | def test_terminate(self): |
Florent Xicluna | 4886d24 | 2010-03-08 13:27:26 +0000 | [diff] [blame] | 1015 | self._kill_process('terminate') |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1016 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1017 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1018 | # The module says: |
| 1019 | # "NB This only works (and is only relevant) for UNIX." |
| 1020 | # |
| 1021 | # Actually, getoutput should work on any platform with an os.popen, but |
| 1022 | # I'll take the comment as given, and skip this suite. |
Florent Xicluna | f0cbd82 | 2010-03-04 21:50:56 +0000 | [diff] [blame] | 1023 | @unittest.skipUnless(os.name == 'posix', "only relevant for UNIX") |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1024 | class CommandTests(unittest.TestCase): |
| 1025 | def test_getoutput(self): |
| 1026 | self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy') |
| 1027 | self.assertEqual(subprocess.getstatusoutput('echo xyzzy'), |
| 1028 | (0, 'xyzzy')) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1029 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1030 | # we use mkdtemp in the next line to create an empty directory |
| 1031 | # under our exclusive control; from that, we can invent a pathname |
| 1032 | # that we _know_ won't exist. This is guaranteed to fail. |
| 1033 | dir = None |
| 1034 | try: |
| 1035 | dir = tempfile.mkdtemp() |
| 1036 | name = os.path.join(dir, "foo") |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1037 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1038 | status, output = subprocess.getstatusoutput('cat ' + name) |
| 1039 | self.assertNotEqual(status, 0) |
| 1040 | finally: |
| 1041 | if dir is not None: |
| 1042 | os.rmdir(dir) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1043 | |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1044 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1045 | @unittest.skipUnless(getattr(subprocess, '_has_poll', False), |
| 1046 | "poll system call not supported") |
| 1047 | class ProcessTestCaseNoPoll(ProcessTestCase): |
| 1048 | def setUp(self): |
| 1049 | subprocess._has_poll = False |
| 1050 | ProcessTestCase.setUp(self) |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1051 | |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1052 | def tearDown(self): |
| 1053 | subprocess._has_poll = True |
| 1054 | ProcessTestCase.tearDown(self) |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1055 | |
| 1056 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1057 | @unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False), |
| 1058 | "_posixsubprocess extension module not found.") |
| 1059 | class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase): |
| 1060 | def setUp(self): |
| 1061 | subprocess._posixsubprocess = None |
| 1062 | ProcessTestCase.setUp(self) |
| 1063 | POSIXProcessTestCase.setUp(self) |
| 1064 | |
| 1065 | def tearDown(self): |
| 1066 | subprocess._posixsubprocess = sys.modules['_posixsubprocess'] |
| 1067 | POSIXProcessTestCase.tearDown(self) |
| 1068 | ProcessTestCase.tearDown(self) |
| 1069 | |
| 1070 | |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 1071 | class HelperFunctionTests(unittest.TestCase): |
Gregory P. Smith | af6d3b8 | 2010-03-01 02:56:44 +0000 | [diff] [blame] | 1072 | @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows") |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 1073 | def test_eintr_retry_call(self): |
| 1074 | record_calls = [] |
| 1075 | def fake_os_func(*args): |
| 1076 | record_calls.append(args) |
| 1077 | if len(record_calls) == 2: |
| 1078 | raise OSError(errno.EINTR, "fake interrupted system call") |
| 1079 | return tuple(reversed(args)) |
| 1080 | |
| 1081 | self.assertEqual((999, 256), |
| 1082 | subprocess._eintr_retry_call(fake_os_func, 256, 999)) |
| 1083 | self.assertEqual([(256, 999)], record_calls) |
| 1084 | # This time there will be an EINTR so it will loop once. |
| 1085 | self.assertEqual((666,), |
| 1086 | subprocess._eintr_retry_call(fake_os_func, 666)) |
| 1087 | self.assertEqual([(256, 999), (666,), (666,)], record_calls) |
| 1088 | |
| 1089 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1090 | def test_main(): |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1091 | unit_tests = (ProcessTestCase, |
| 1092 | POSIXProcessTestCase, |
| 1093 | Win32ProcessTestCase, |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1094 | ProcessTestCasePOSIXPurePython, |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1095 | CommandTests, |
Gregory P. Smith | a59c59f | 2010-03-01 00:17:40 +0000 | [diff] [blame] | 1096 | ProcessTestCaseNoPoll, |
| 1097 | HelperFunctionTests) |
Florent Xicluna | b1e94e8 | 2010-02-27 22:12:37 +0000 | [diff] [blame] | 1098 | |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1099 | support.run_unittest(*unit_tests) |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1100 | support.reap_children() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1101 | |
| 1102 | if __name__ == "__main__": |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 1103 | test_main() |