blob: eacd7a6ae436969853bd4d2a694889f374dd9938 [file] [log] [blame]
Christian Heimes9cd17752007-11-18 19:35:23 +00001# Tests invocation of the interpreter with various command line arguments
2# All tests are executed with environment variables ignored
3# See test_cmd_line_script.py for testing of script execution
Neal Norwitz11bd1192005-10-03 00:54:56 +00004
Philip Jenveyab7481a2009-05-22 05:46:35 +00005import os
Benjamin Petersonee8712c2008-05-20 21:35:26 +00006import test.support, unittest
Neal Norwitz11bd1192005-10-03 00:54:56 +00007import sys
Walter Dörwald9356fb92005-11-25 15:22:10 +00008import subprocess
Neal Norwitz11bd1192005-10-03 00:54:56 +00009
Thomas Woutersed03b412007-08-28 21:37:11 +000010def _spawn_python(*args):
Antoine Pitrou87695762008-08-14 22:44:29 +000011 cmd_line = [sys.executable]
12 # When testing -S, we need PYTHONPATH to work (see test_site_flag())
13 if '-S' not in args:
14 cmd_line.append('-E')
Thomas Woutersed03b412007-08-28 21:37:11 +000015 cmd_line.extend(args)
16 return subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
17 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
18
19def _kill_python(p):
Trent Nelson39e307e2008-03-19 06:45:48 +000020 return _kill_python_and_exit_code(p)[0]
21
22def _kill_python_and_exit_code(p):
Thomas Woutersed03b412007-08-28 21:37:11 +000023 p.stdin.close()
24 data = p.stdout.read()
25 p.stdout.close()
26 # try to cleanup the child so we don't appear to leak when running
27 # with regrtest -R. This should be a no-op on Windows.
28 subprocess._cleanup()
Trent Nelson39e307e2008-03-19 06:45:48 +000029 returncode = p.wait()
30 return data, returncode
Thomas Woutersed03b412007-08-28 21:37:11 +000031
Neal Norwitz11bd1192005-10-03 00:54:56 +000032class CmdLineTest(unittest.TestCase):
Thomas Woutersed03b412007-08-28 21:37:11 +000033 def start_python(self, *args):
Trent Nelson39e307e2008-03-19 06:45:48 +000034 return self.start_python_and_exit_code(*args)[0]
35
36 def start_python_and_exit_code(self, *args):
Thomas Woutersed03b412007-08-28 21:37:11 +000037 p = _spawn_python(*args)
Trent Nelson39e307e2008-03-19 06:45:48 +000038 return _kill_python_and_exit_code(p)
Neal Norwitz11bd1192005-10-03 00:54:56 +000039
Thomas Wouters477c8d52006-05-27 19:21:47 +000040 def exit_code(self, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +000041 cmd_line = [sys.executable, '-E']
Thomas Wouters477c8d52006-05-27 19:21:47 +000042 cmd_line.extend(args)
Philip Jenveyab7481a2009-05-22 05:46:35 +000043 with open(os.devnull, 'w') as devnull:
44 return subprocess.call(cmd_line, stdout=devnull,
45 stderr=subprocess.STDOUT)
Walter Dörwald9356fb92005-11-25 15:22:10 +000046
Neal Norwitz11bd1192005-10-03 00:54:56 +000047 def test_directories(self):
Neal Norwitz72c2c062006-03-09 05:58:11 +000048 self.assertNotEqual(self.exit_code('.'), 0)
49 self.assertNotEqual(self.exit_code('< .'), 0)
Neal Norwitz11bd1192005-10-03 00:54:56 +000050
51 def verify_valid_flag(self, cmd_line):
52 data = self.start_python(cmd_line)
Guido van Rossuma1c42a92007-08-29 03:47:36 +000053 self.assertTrue(data == b'' or data.endswith(b'\n'))
Guido van Rossumf074b642007-07-11 06:56:16 +000054 self.assertTrue(b'Traceback' not in data)
Neal Norwitz11bd1192005-10-03 00:54:56 +000055
Neal Norwitz11bd1192005-10-03 00:54:56 +000056 def test_optimize(self):
57 self.verify_valid_flag('-O')
58 self.verify_valid_flag('-OO')
59
60 def test_q(self):
61 self.verify_valid_flag('-Qold')
62 self.verify_valid_flag('-Qnew')
63 self.verify_valid_flag('-Qwarn')
64 self.verify_valid_flag('-Qwarnall')
65
66 def test_site_flag(self):
Antoine Pitrou87695762008-08-14 22:44:29 +000067 if os.name == 'posix':
68 # Workaround bug #586680 by adding the extension dir to PYTHONPATH
69 from distutils.util import get_platform
70 s = "./build/lib.%s-%.3s" % (get_platform(), sys.version)
71 if hasattr(sys, 'gettotalrefcount'):
72 s += '-pydebug'
73 p = os.environ.get('PYTHONPATH', '')
74 if p:
75 p += ':'
76 os.environ['PYTHONPATH'] = p + s
Neal Norwitz11bd1192005-10-03 00:54:56 +000077 self.verify_valid_flag('-S')
78
79 def test_usage(self):
Guido van Rossumf074b642007-07-11 06:56:16 +000080 self.assertTrue(b'usage' in self.start_python('-h'))
Neal Norwitz11bd1192005-10-03 00:54:56 +000081
82 def test_version(self):
Guido van Rossuma1c42a92007-08-29 03:47:36 +000083 version = ('Python %d.%d' % sys.version_info[:2]).encode("ascii")
Neal Norwitz11bd1192005-10-03 00:54:56 +000084 self.assertTrue(self.start_python('-V').startswith(version))
85
Trent Nelson39e307e2008-03-19 06:45:48 +000086 def test_verbose(self):
87 # -v causes imports to write to stderr. If the write to
88 # stderr itself causes an import to happen (for the output
89 # codec), a recursion loop can occur.
90 data, rc = self.start_python_and_exit_code('-v')
91 self.assertEqual(rc, 0)
92 self.assertTrue(b'stack overflow' not in data)
93 data, rc = self.start_python_and_exit_code('-vv')
94 self.assertEqual(rc, 0)
95 self.assertTrue(b'stack overflow' not in data)
96
Thomas Wouters477c8d52006-05-27 19:21:47 +000097 def test_run_module(self):
98 # Test expected operation of the '-m' switch
99 # Switch needs an argument
100 self.assertNotEqual(self.exit_code('-m'), 0)
101 # Check we get an error for a nonexistent module
102 self.assertNotEqual(
103 self.exit_code('-m', 'fnord43520xyz'),
104 0)
105 # Check the runpy module also gives an error for
106 # a nonexistent module
107 self.assertNotEqual(
108 self.exit_code('-m', 'runpy', 'fnord43520xyz'),
109 0)
110 # All good if module is located and run successfully
111 self.assertEqual(
112 self.exit_code('-m', 'timeit', '-n', '1'),
113 0)
114
Thomas Woutersed03b412007-08-28 21:37:11 +0000115 def test_run_module_bug1764407(self):
116 # -m and -i need to play well together
117 # Runs the timeit module and checks the __main__
118 # namespace has been populated appropriately
119 p = _spawn_python('-i', '-m', 'timeit', '-n', '1')
Guido van Rossuma1c42a92007-08-29 03:47:36 +0000120 p.stdin.write(b'Timer\n')
121 p.stdin.write(b'exit()\n')
Thomas Woutersed03b412007-08-28 21:37:11 +0000122 data = _kill_python(p)
123 self.assertTrue(data.find(b'1 loop') != -1)
124 self.assertTrue(data.find(b'__main__.Timer') != -1)
125
Thomas Wouters477c8d52006-05-27 19:21:47 +0000126 def test_run_code(self):
127 # Test expected operation of the '-c' switch
128 # Switch needs an argument
129 self.assertNotEqual(self.exit_code('-c'), 0)
130 # Check we get an error for an uncaught exception
131 self.assertNotEqual(
132 self.exit_code('-c', 'raise Exception'),
133 0)
134 # All good if execution is successful
135 self.assertEqual(
136 self.exit_code('-c', 'pass'),
137 0)
138
Amaury Forgeot d'Arc9a5499b2008-11-11 23:04:59 +0000139 # Test handling of non-ascii data
Amaury Forgeot d'Arce2557642008-11-12 00:59:11 +0000140 if sys.getfilesystemencoding() != 'ascii':
141 command = "assert(ord('\xe9') == 0xe9)"
142 self.assertEqual(
143 self.exit_code('-c', command),
144 0)
Amaury Forgeot d'Arc9a5499b2008-11-11 23:04:59 +0000145
Antoine Pitrou05608432009-01-09 18:53:14 +0000146 def test_unbuffered_output(self):
147 # Test expected operation of the '-u' switch
148 for stream in ('stdout', 'stderr'):
149 # Binary is unbuffered
150 code = ("import os, sys; sys.%s.buffer.write(b'x'); os._exit(0)"
151 % stream)
152 data, rc = self.start_python_and_exit_code('-u', '-c', code)
153 self.assertEqual(rc, 0)
154 self.assertEqual(data, b'x', "binary %s not unbuffered" % stream)
155 # Text is line-buffered
156 code = ("import os, sys; sys.%s.write('x\\n'); os._exit(0)"
157 % stream)
158 data, rc = self.start_python_and_exit_code('-u', '-c', code)
159 self.assertEqual(rc, 0)
160 self.assertEqual(data.strip(), b'x',
161 "text %s not line-buffered" % stream)
162
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000163 def test_unbuffered_input(self):
164 # sys.stdin still works with '-u'
165 code = ("import sys; sys.stdout.write(sys.stdin.read(1))")
166 p = _spawn_python('-u', '-c', code)
167 p.stdin.write(b'x')
168 p.stdin.flush()
169 data, rc = _kill_python_and_exit_code(p)
170 self.assertEqual(rc, 0)
Georg Brandlab91fde2009-08-13 08:51:18 +0000171 self.assertTrue(data.startswith(b'x'), data)
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000172
Amaury Forgeot d'Arc66f8c432009-06-09 21:30:01 +0000173 def test_large_PYTHONPATH(self):
174 with test.support.EnvironmentVarGuard() as env:
175 path1 = "ABCDE" * 100
176 path2 = "FGHIJ" * 100
177 env['PYTHONPATH'] = path1 + os.pathsep + path2
Victor Stinner30ba25b2010-04-16 15:44:04 +0000178
179 code = """
180import sys
181path = ":".join(sys.path)
182path = path.encode("ascii", "backslashreplace")
183sys.stdout.buffer.write(path)"""
184 code = code.strip().splitlines()
185 code = '; '.join(code)
186 p = _spawn_python('-S', '-c', code)
Amaury Forgeot d'Arc66f8c432009-06-09 21:30:01 +0000187 stdout, _ = p.communicate()
Brian Curtin8581c7e2010-11-01 14:08:58 +0000188 p.stdout.close()
Georg Brandlab91fde2009-08-13 08:51:18 +0000189 self.assertTrue(path1.encode('ascii') in stdout)
190 self.assertTrue(path2.encode('ascii') in stdout)
Amaury Forgeot d'Arc66f8c432009-06-09 21:30:01 +0000191
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100192 def test_hash_randomization(self):
193 # Verify that -R enables hash randomization:
194 self.verify_valid_flag('-R')
195 hashes = []
196 for i in range(2):
197 code = 'print(hash("spam"))'
198 data, rc = self.start_python_and_exit_code('-R', '-c', code)
199 self.assertEqual(rc, 0)
200 hashes.append(data)
201 self.assertNotEqual(hashes[0], hashes[1])
202
203 # Verify that sys.flags contains hash_randomization
204 code = 'import sys; print("random is", sys.flags.hash_randomization)'
205 data, rc = self.start_python_and_exit_code('-R', '-c', code)
206 self.assertEqual(rc, 0)
207 self.assertIn(b'random is 1', data)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000208
Neal Norwitz11bd1192005-10-03 00:54:56 +0000209def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000210 test.support.run_unittest(CmdLineTest)
211 test.support.reap_children()
Neal Norwitz11bd1192005-10-03 00:54:56 +0000212
213if __name__ == "__main__":
214 test_main()