blob: b21b61e6590e1db378aad4c5f978e49d8a562796 [file] [log] [blame]
Christian Heimes9cd17752007-11-18 19:35:23 +00001# Tests invocation of the interpreter with various command line arguments
Nick Coghland26c18a2010-08-17 13:06:11 +00002# Most tests are executed with environment variables ignored
Christian Heimes9cd17752007-11-18 19:35:23 +00003# See test_cmd_line_script.py for testing of script execution
Neal Norwitz11bd1192005-10-03 00:54:56 +00004
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005import test.support, unittest
Antoine Pitrou87695762008-08-14 22:44:29 +00006import os
Neal Norwitz11bd1192005-10-03 00:54:56 +00007import sys
Nick Coghlan260bd3e2009-11-16 06:49:25 +00008import subprocess
Antoine Pitrou9bc35682010-11-09 21:33:55 +00009from test.script_helper import spawn_python, kill_python, assert_python_ok, assert_python_failure
Thomas Woutersed03b412007-08-28 21:37:11 +000010
Trent Nelson39e307e2008-03-19 06:45:48 +000011
Nick Coghlan260bd3e2009-11-16 06:49:25 +000012# XXX (ncoghlan): Move to script_helper and make consistent with run_python
Trent Nelson39e307e2008-03-19 06:45:48 +000013def _kill_python_and_exit_code(p):
Nick Coghlan260bd3e2009-11-16 06:49:25 +000014 data = kill_python(p)
Trent Nelson39e307e2008-03-19 06:45:48 +000015 returncode = p.wait()
16 return data, returncode
Thomas Woutersed03b412007-08-28 21:37:11 +000017
Neal Norwitz11bd1192005-10-03 00:54:56 +000018class CmdLineTest(unittest.TestCase):
Neal Norwitz11bd1192005-10-03 00:54:56 +000019 def test_directories(self):
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000020 assert_python_failure('.')
21 assert_python_failure('< .')
Neal Norwitz11bd1192005-10-03 00:54:56 +000022
23 def verify_valid_flag(self, cmd_line):
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000024 rc, out, err = assert_python_ok(*cmd_line)
25 self.assertTrue(out == b'' or out.endswith(b'\n'))
26 self.assertNotIn(b'Traceback', out)
27 self.assertNotIn(b'Traceback', err)
Neal Norwitz11bd1192005-10-03 00:54:56 +000028
Neal Norwitz11bd1192005-10-03 00:54:56 +000029 def test_optimize(self):
30 self.verify_valid_flag('-O')
31 self.verify_valid_flag('-OO')
32
33 def test_q(self):
34 self.verify_valid_flag('-Qold')
35 self.verify_valid_flag('-Qnew')
36 self.verify_valid_flag('-Qwarn')
37 self.verify_valid_flag('-Qwarnall')
38
39 def test_site_flag(self):
40 self.verify_valid_flag('-S')
41
42 def test_usage(self):
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000043 rc, out, err = assert_python_ok('-h')
44 self.assertIn(b'usage', out)
Neal Norwitz11bd1192005-10-03 00:54:56 +000045
46 def test_version(self):
Guido van Rossuma1c42a92007-08-29 03:47:36 +000047 version = ('Python %d.%d' % sys.version_info[:2]).encode("ascii")
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000048 rc, out, err = assert_python_ok('-V')
49 self.assertTrue(err.startswith(version))
Neal Norwitz11bd1192005-10-03 00:54:56 +000050
Trent Nelson39e307e2008-03-19 06:45:48 +000051 def test_verbose(self):
52 # -v causes imports to write to stderr. If the write to
53 # stderr itself causes an import to happen (for the output
54 # codec), a recursion loop can occur.
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000055 rc, out, err = assert_python_ok('-v')
56 self.assertNotIn(b'stack overflow', err)
57 rc, out, err = assert_python_ok('-vv')
58 self.assertNotIn(b'stack overflow', err)
Trent Nelson39e307e2008-03-19 06:45:48 +000059
Antoine Pitrou9583cac2010-10-21 13:42:28 +000060 def test_xoptions(self):
61 rc, out, err = assert_python_ok('-c', 'import sys; print(sys._xoptions)')
62 opts = eval(out.splitlines()[0])
63 self.assertEqual(opts, {})
64 rc, out, err = assert_python_ok(
65 '-Xa', '-Xb=c,d=e', '-c', 'import sys; print(sys._xoptions)')
66 opts = eval(out.splitlines()[0])
67 self.assertEqual(opts, {'a': True, 'b': 'c,d=e'})
68
Thomas Wouters477c8d52006-05-27 19:21:47 +000069 def test_run_module(self):
70 # Test expected operation of the '-m' switch
71 # Switch needs an argument
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000072 assert_python_failure('-m')
Thomas Wouters477c8d52006-05-27 19:21:47 +000073 # Check we get an error for a nonexistent module
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000074 assert_python_failure('-m', 'fnord43520xyz')
Thomas Wouters477c8d52006-05-27 19:21:47 +000075 # Check the runpy module also gives an error for
76 # a nonexistent module
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000077 assert_python_failure('-m', 'runpy', 'fnord43520xyz'),
Thomas Wouters477c8d52006-05-27 19:21:47 +000078 # All good if module is located and run successfully
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000079 assert_python_ok('-m', 'timeit', '-n', '1'),
Thomas Wouters477c8d52006-05-27 19:21:47 +000080
Thomas Woutersed03b412007-08-28 21:37:11 +000081 def test_run_module_bug1764407(self):
82 # -m and -i need to play well together
83 # Runs the timeit module and checks the __main__
84 # namespace has been populated appropriately
Nick Coghlan260bd3e2009-11-16 06:49:25 +000085 p = spawn_python('-i', '-m', 'timeit', '-n', '1')
Guido van Rossuma1c42a92007-08-29 03:47:36 +000086 p.stdin.write(b'Timer\n')
87 p.stdin.write(b'exit()\n')
Nick Coghlan260bd3e2009-11-16 06:49:25 +000088 data = kill_python(p)
Thomas Woutersed03b412007-08-28 21:37:11 +000089 self.assertTrue(data.find(b'1 loop') != -1)
90 self.assertTrue(data.find(b'__main__.Timer') != -1)
91
Thomas Wouters477c8d52006-05-27 19:21:47 +000092 def test_run_code(self):
93 # Test expected operation of the '-c' switch
94 # Switch needs an argument
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000095 assert_python_failure('-c')
Thomas Wouters477c8d52006-05-27 19:21:47 +000096 # Check we get an error for an uncaught exception
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000097 assert_python_failure('-c', 'raise Exception')
Thomas Wouters477c8d52006-05-27 19:21:47 +000098 # All good if execution is successful
Antoine Pitrouf51d8d32010-10-08 18:05:42 +000099 assert_python_ok('-c', 'pass')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000100
Victor Stinner073f7592010-10-20 21:56:55 +0000101 @unittest.skipIf(sys.getfilesystemencoding() == 'ascii',
102 'need a filesystem encoding different than ASCII')
103 def test_non_ascii(self):
Amaury Forgeot d'Arc9a5499b2008-11-11 23:04:59 +0000104 # Test handling of non-ascii data
Victor Stinner073f7592010-10-20 21:56:55 +0000105 if test.support.verbose:
106 import locale
107 print('locale encoding = %s, filesystem encoding = %s'
108 % (locale.getpreferredencoding(), sys.getfilesystemencoding()))
109 command = "assert(ord('\xe9') == 0xe9)"
110 assert_python_ok('-c', command)
Amaury Forgeot d'Arc9a5499b2008-11-11 23:04:59 +0000111
Victor Stinnerf6211ed2010-10-20 21:52:33 +0000112 # On Windows, pass bytes to subprocess doesn't test how Python decodes the
113 # command line, but how subprocess does decode bytes to unicode. Python
114 # doesn't decode the command line because Windows provides directly the
115 # arguments as unicode (using wmain() instead of main()).
116 @unittest.skipIf(sys.platform == 'win32',
117 'Windows has a native unicode API')
118 def test_undecodable_code(self):
119 undecodable = b"\xff"
120 env = os.environ.copy()
121 # Use C locale to get ascii for the locale encoding
122 env['LC_ALL'] = 'C'
123 code = (
124 b'import locale; '
125 b'print(ascii("' + undecodable + b'"), '
126 b'locale.getpreferredencoding())')
127 p = subprocess.Popen(
128 [sys.executable, "-c", code],
129 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
130 env=env)
131 stdout, stderr = p.communicate()
132 if p.returncode == 1:
133 # _Py_char2wchar() decoded b'\xff' as '\udcff' (b'\xff' is not
134 # decodable from ASCII) and run_command() failed on
135 # PyUnicode_AsUTF8String(). This is the expected behaviour on
136 # Linux.
137 pattern = b"Unable to decode the command from the command line:"
138 elif p.returncode == 0:
139 # _Py_char2wchar() decoded b'\xff' as '\xff' even if the locale is
140 # C and the locale encoding is ASCII. It occurs on FreeBSD, Solaris
141 # and Mac OS X.
142 pattern = b"'\\xff' "
143 # The output is followed by the encoding name, an alias to ASCII.
144 # Examples: "US-ASCII" or "646" (ISO 646, on Solaris).
145 else:
146 raise AssertionError("Unknown exit code: %s, output=%a" % (p.returncode, stdout))
147 if not stdout.startswith(pattern):
148 raise AssertionError("%a doesn't start with %a" % (stdout, pattern))
149
Victor Stinnerf933e1a2010-10-20 22:58:25 +0000150 @unittest.skipUnless(sys.platform == 'darwin', 'test specific to Mac OS X')
151 def test_osx_utf8(self):
152 def check_output(text):
153 decoded = text.decode('utf8', 'surrogateescape')
154 expected = ascii(decoded).encode('ascii') + b'\n'
155
156 env = os.environ.copy()
157 # C locale gives ASCII locale encoding, but Python uses UTF-8
158 # to parse the command line arguments on Mac OS X
159 env['LC_ALL'] = 'C'
160
161 p = subprocess.Popen(
162 (sys.executable, "-c", "import sys; print(ascii(sys.argv[1]))", text),
163 stdout=subprocess.PIPE,
164 env=env)
165 stdout, stderr = p.communicate()
166 self.assertEqual(stdout, expected)
167 self.assertEqual(p.returncode, 0)
168
169 # test valid utf-8
170 text = 'e:\xe9, euro:\u20ac, non-bmp:\U0010ffff'.encode('utf-8')
171 check_output(text)
172
173 # test invalid utf-8
174 text = (
175 b'\xff' # invalid byte
176 b'\xc3\xa9' # valid utf-8 character
177 b'\xc3\xff' # invalid byte sequence
178 b'\xed\xa0\x80' # lone surrogate character (invalid)
179 )
180 check_output(text)
181
Antoine Pitrou05608432009-01-09 18:53:14 +0000182 def test_unbuffered_output(self):
183 # Test expected operation of the '-u' switch
184 for stream in ('stdout', 'stderr'):
185 # Binary is unbuffered
186 code = ("import os, sys; sys.%s.buffer.write(b'x'); os._exit(0)"
187 % stream)
Antoine Pitrouf51d8d32010-10-08 18:05:42 +0000188 rc, out, err = assert_python_ok('-u', '-c', code)
189 data = err if stream == 'stderr' else out
Antoine Pitrou05608432009-01-09 18:53:14 +0000190 self.assertEqual(data, b'x', "binary %s not unbuffered" % stream)
191 # Text is line-buffered
192 code = ("import os, sys; sys.%s.write('x\\n'); os._exit(0)"
193 % stream)
Antoine Pitrouf51d8d32010-10-08 18:05:42 +0000194 rc, out, err = assert_python_ok('-u', '-c', code)
195 data = err if stream == 'stderr' else out
Antoine Pitrou05608432009-01-09 18:53:14 +0000196 self.assertEqual(data.strip(), b'x',
197 "text %s not line-buffered" % stream)
198
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000199 def test_unbuffered_input(self):
200 # sys.stdin still works with '-u'
201 code = ("import sys; sys.stdout.write(sys.stdin.read(1))")
Nick Coghlan260bd3e2009-11-16 06:49:25 +0000202 p = spawn_python('-u', '-c', code)
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000203 p.stdin.write(b'x')
204 p.stdin.flush()
205 data, rc = _kill_python_and_exit_code(p)
206 self.assertEqual(rc, 0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000207 self.assertTrue(data.startswith(b'x'), data)
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000208
Amaury Forgeot d'Arc66f8c432009-06-09 21:30:01 +0000209 def test_large_PYTHONPATH(self):
Antoine Pitrou9bc35682010-11-09 21:33:55 +0000210 path1 = "ABCDE" * 100
211 path2 = "FGHIJ" * 100
212 path = path1 + os.pathsep + path2
Victor Stinner76cf6872010-04-16 15:10:27 +0000213
Antoine Pitrou9bc35682010-11-09 21:33:55 +0000214 code = """if 1:
215 import sys
216 path = ":".join(sys.path)
217 path = path.encode("ascii", "backslashreplace")
218 sys.stdout.buffer.write(path)"""
219 rc, out, err = assert_python_ok('-S', '-c', code,
220 PYTHONPATH=path)
221 self.assertIn(path1.encode('ascii'), out)
222 self.assertIn(path2.encode('ascii'), out)
Amaury Forgeot d'Arc66f8c432009-06-09 21:30:01 +0000223
Victor Stinner13d49ee2010-12-04 17:24:33 +0000224 def test_displayhook_unencodable(self):
225 for encoding in ('ascii', 'latin1', 'utf8'):
226 env = os.environ.copy()
227 env['PYTHONIOENCODING'] = encoding
228 p = subprocess.Popen(
229 [sys.executable, '-i'],
230 stdin=subprocess.PIPE,
231 stdout=subprocess.PIPE,
232 stderr=subprocess.STDOUT,
233 env=env)
234 # non-ascii, surrogate, non-BMP printable, non-BMP unprintable
235 text = "a=\xe9 b=\uDC80 c=\U00010000 d=\U0010FFFF"
236 p.stdin.write(ascii(text).encode('ascii') + b"\n")
237 p.stdin.write(b'exit()\n')
238 data = kill_python(p)
239 escaped = repr(text).encode(encoding, 'backslashreplace')
240 self.assertIn(escaped, data)
241
Thomas Wouters477c8d52006-05-27 19:21:47 +0000242
Neal Norwitz11bd1192005-10-03 00:54:56 +0000243def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000244 test.support.run_unittest(CmdLineTest)
245 test.support.reap_children()
Neal Norwitz11bd1192005-10-03 00:54:56 +0000246
247if __name__ == "__main__":
248 test_main()