Debian Codegraph @

pypy/interpreter/test/test_app_main.py

raw symbols SCIP
1 """
2 Tests for the entry point of pypy3-c, app_main.py.
3 """
4 from __future__ import with_statement, print_function
5 import py
6 import sys, os, re, runpy, subprocess
7 import shutil
8 from rpython.tool.udir import udir
9 from contextlib import contextmanager
10 import textwrap
11 from pypy import pypydir
12 from pypy.conftest import PYTHON3, LOOK_FOR_PYTHON3
13 from pypy.interpreter.test.conftest import banner
14 from lib_pypy._pypy_interact import irc_header
15
16 app_main = os.path.join(os.path.realpath(os.path.dirname(__file__)), os.pardir, 'app_main.py')
17 app_main = os.path.abspath(app_main)
18
19 def get_python3():
20 if PYTHON3:
21 return PYTHON3
22 py.test.skip("Test requires %r (not found in PATH) or a PYTHON3 "
23 "environment variable set" % (LOOK_FOR_PYTHON3,))
24
25 _counter = 0
26 def _get_next_path(ext='.py'):
27 global _counter
28 p = udir.join('demo_test_app_main_%d%s' % (_counter, ext))
29 _counter += 1
30 return p
31
32 def getscript(source):
33 p = _get_next_path()
34 p.write(str(py.code.Source(source)))
35 return str(p)
36
37 def getscript_pyc(space, source):
38 p = _get_next_path()
39 p.write(str(py.code.Source(source)))
40 subprocess.check_call([get_python3(), "-c", "import " + p.purebasename],
41 env={'PYTHONPATH': str(p.dirpath())})
42 # the .pyc file should have been created above
43 pycache = p.dirpath('__pycache__')
44 pycs = pycache.listdir(p.purebasename + '*.pyc')
45 assert len(pycs) == 1
46 return str(pycs[0])
47
48 def getscript_in_dir(source):
49 pdir = _get_next_path(ext='')
50 p = pdir.ensure(dir=1).join('__main__.py')
51 p.write(str(py.code.Source(source)))
52 # return relative path for testing purposes
53 return py.path.local().bestrelpath(pdir)
54
55 @py.test.fixture
56 def demo_script():
57 return getscript("""
58 print('hello')
59 print('Name:', __name__)
60 print('File:', __file__)
61 print('Cached:', __cached__)
62 import sys
63 print('Exec:', sys.executable)
64 print('Argv:', sys.argv)
65 print('goodbye')
66 myvalue = 6*7
67 """)
68
69 @py.test.fixture
70 def crashing_demo_script():
71 return getscript("""
72 print('Hello2')
73 myvalue2 = 11
74 ooups
75 myvalue2 = 22
76 print('Goodbye2') # should not be reached
77 """)
78
79 script_with_future = getscript("""
80 from __future__ import division
81 from __future__ import print_function
82 """)
83
84
85 @contextmanager
86 def setpythonpath():
87 old_pythonpath = os.getenv('PYTHONPATH')
88 rootdir = os.path.dirname(pypydir)
89 os.putenv('PYTHONPATH', rootdir)
90 try:
91 yield
92 finally:
93 if old_pythonpath is None:
94 os.unsetenv('PYTHONPATH')
95 else:
96 os.putenv('PYTHONPATH', old_pythonpath)
97
98
99 class TestParseCommandLine:
100 def check_options(self, options, **expected):
101 for key, value in expected.items():
102 assert options[key] == value
103 for key, value in options.items():
104 if key not in expected:
105 if key == "check_hash_based_pycs":
106 assert value == "default"
107 elif key == "utf8_mode":
108 # this doesn't work untranslated in the docker images for
109 # linux, somehow the "value" is 1 since the call to
110 # _locale.setlocale(_locale.LC_CTYPE, None) in the PYTHON3
111 # returns "C" even when the locale is set to "en_US.UTF-8"
112 import _locale
113 lc = _locale.setlocale(_locale.LC_CTYPE, None)
114 #assert value == (lc == "C" or lc == "POSIX")
115 elif key == "int_max_str_digits":
116 assert value == -1
117 else:
118 assert not value, (
119 "option %r has unexpectedly the value %r" % (key, value))
120
121 def check(self, argv, env, **expected):
122 # print("testing", argv)
123 args_for_popen = [get_python3(), app_main,
124 '--argparse-only'] + list(argv)
125 # print("calling popen with", ' '.join(args_for_popen))
126 p = subprocess.Popen(args_for_popen,
127 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
128 env=env)
129 res = p.wait()
130 outcome = p.stdout.readline()
131 if outcome == 'SystemExit\n' or outcome == "Error\n":
132 output = p.stdout.read()
133 assert expected['output_contains'] in output
134 else:
135 app_options = eval(p.stdout.readline())
136 sys_argv = eval(p.stdout.readline())
137 app_options['sys_argv'] = sys_argv
138 self.check_options(app_options, **expected)
139
140 @py.test.mark.skipif(sys.platform=='win32', reason="hangs in Popen")
141 def test_all_combinations_I_can_think_of(self):
142 env = os.environ.copy()
143 self.check([], env, sys_argv=[''], run_stdin=True)
144 self.check(['-'], env, sys_argv=['-'], run_stdin=True)
145 self.check(['-S'], env, sys_argv=[''], run_stdin=True, no_site=1)
146 self.check(['-OO'], env, sys_argv=[''], run_stdin=True, optimize=2)
147 self.check(['-O', '-O'], env, sys_argv=[''], run_stdin=True, optimize=2)
148 self.check(['-SO'], env, sys_argv=[''], run_stdin=True,
149 no_site=1, optimize=1)
150 self.check(['-i'], env, sys_argv=[''], run_stdin=True,
151 interactive=1, inspect=1)
152 self.check(['-?'], env, output_contains='usage:')
153 self.check(['-h'], env, output_contains='usage:')
154 self.check(['-S', '-O', '-h'], env, output_contains='usage:')
155 self.check(['-S', '-hO'], env, output_contains='usage:')
156 self.check(['-S', '-O', '--help'], env, output_contains='usage:')
157 self.check(['-S', '-O', '--info'], env, output_contains='translation')
158 self.check(['-S', '-O', '--version'], env, output_contains='Python')
159 self.check(['-S', '-OV'], env, output_contains='Python')
160 self.check(['--jit', 'off', '-S'], {}, sys_argv=[''],
161 run_stdin=True, no_site=1, _jitoptions='off')
162 self.check(['-X', 'jit-off', '-S'], {}, sys_argv=[''],
163 run_stdin=True, no_site=1, _jitoptions='off', _xoptions=['jit-off'])
164 self.check(['-c', 'pass'], env, sys_argv=['-c'], run_command='pass')
165 self.check(['-cpass'], env, sys_argv=['-c'], run_command='pass')
166 self.check(['-cpass','x'], env, sys_argv=['-c','x'], run_command='pass')
167 self.check(['-Sc', 'pass'], env, sys_argv=['-c'], run_command='pass',
168 no_site=1)
169 self.check(['-Scpass'], env, sys_argv=['-c'], run_command='pass', no_site=1)
170 self.check(['-c', '', ''], env, sys_argv=['-c', ''], run_command='')
171 self.check(['-mfoo', 'bar', 'baz'], env, sys_argv=['-m', 'bar', 'baz'],
172 run_module='foo')
173 self.check(['-m', 'foo', 'bar', 'baz'], env, sys_argv=['-m', 'bar', 'baz'],
174 run_module='foo')
175 self.check(['-Smfoo', 'bar', 'baz'], env, sys_argv=['-m', 'bar', 'baz'],
176 run_module='foo', no_site=1)
177 self.check(['-Sm', 'foo', 'bar', 'baz'], env, sys_argv=['-m', 'bar', 'baz'],
178 run_module='foo', no_site=1)
179 self.check(['-', 'foo', 'bar'], env, sys_argv=['-', 'foo', 'bar'],
180 run_stdin=True)
181 self.check(['foo', 'bar'], env, sys_argv=['foo', 'bar'])
182 self.check(['foo', '-i'], env, sys_argv=['foo', '-i'])
183 self.check(['-i', 'foo'], env, sys_argv=['foo'], interactive=1, inspect=1)
184 self.check(['--', 'foo'], env, sys_argv=['foo'])
185 self.check(['--', '-i', 'foo'], env, sys_argv=['-i', 'foo'])
186 self.check(['--', '-', 'foo'], env, sys_argv=['-', 'foo'], run_stdin=True)
187 self.check(['-Wbog'], env, sys_argv=[''], warnoptions=['bog'], run_stdin=True)
188 self.check(['-W', 'ab', '-SWc'], env, sys_argv=[''], warnoptions=['ab', 'c'],
189 run_stdin=True, no_site=1)
190 self.check(['-X', 'foo'], env, sys_argv=[''], _xoptions=['foo'],
191 run_stdin=True)
192 self.check(['-X', 'foo=bar', '-Xbaz'], env, sys_argv=[''],
193 _xoptions=['foo=bar', 'baz'], run_stdin=True)
194
195 self.check([], dict(env, PYTHONDEBUG='1'), sys_argv=[''], run_stdin=True, debug=1)
196 self.check([], dict(env, PYTHONDONTWRITEBYTECODE='4'), sys_argv=[''], run_stdin=True, dont_write_bytecode=1)
197 self.check([], dict(env, PYTHONNOUSERSITE='1'), sys_argv=[''], run_stdin=True, no_user_site=1)
198 self.check([], dict(env, PYTHONUNBUFFERED='1'), sys_argv=[''], run_stdin=True, unbuffered=1)
199 self.check([], dict(env, PYTHONVERBOSE='1'), sys_argv=[''], run_stdin=True, verbose=1)
200 self.check([], dict(env, PYTHONOPTIMIZE='1'), sys_argv=[''], run_stdin=True, optimize=1)
201 self.check([], dict(env, PYTHONOPTIMIZE='0'), sys_argv=[''], run_stdin=True, optimize=1)
202 self.check([], dict(env, PYTHONOPTIMIZE='10'), sys_argv=[''], run_stdin=True, optimize=10)
203 self.check(['-O'], dict(env, PYTHONOPTIMIZE='10'), sys_argv=[''], run_stdin=True, optimize=10)
204 self.check(['-OOO'], dict(env, PYTHONOPTIMIZE='abc'), sys_argv=[''], run_stdin=True, optimize=3)
205 self.check([], {'PYPY_DISABLE_JIT': '1'}, sys_argv=[''], run_stdin=True, _jitoptions='off')
206 self.check([], {'PYTHON_DISABLE_REMOTE_DEBUG': '1'}, sys_argv=[''], run_stdin=True, _remote_debug='off')
207 self.check(['-X', 'disable-remote-debug'], {}, sys_argv=[''], run_stdin=True, _xoptions=['disable-remote-debug'], _remote_debug='off')
208
209 def test_error(self):
210 env = os.environ.copy()
211 self.check(['-a'], env, output_contains="Unknown option: -a")
212 self.check(['--abc'], env, output_contains="unknown option --abc")
213
214
215 def test_sysflags(self):
216 env = os.environ.copy()
217 flags = (
218 ("debug", "-d", "1"),
219 (["inspect", "interactive"], "-i", "1"),
220 ("optimize", "-O", "1"),
221 ("optimize", "-OO", "2"),
222 ("dont_write_bytecode", "-B", "1"),
223 ("no_user_site", "-s", "1"),
224 ("no_site", "-S", "1"),
225 ("ignore_environment", "-E", "1"),
226 ("verbose", "-v", "1"),
227 ("bytes_warning", "-b", "1"),
228 (["isolated", "no_user_site", "ignore_environment", "safe_path"], "-I", "1"),
229 )
230 for flag, opt, value in flags:
231 if isinstance(flag, list): # this is for inspect&interactive
232 expected = {}
233 for flag1 in flag:
234 expected[flag1] = int(value)
235 else:
236 expected = {flag: int(value)}
237 self.check([opt, '-c', 'pass'], env, sys_argv=['-c'],
238 run_command='pass', **expected)
239 self.check(['-X', 'dev', '-c', 'pass'], env, sys_argv=['-c'],
240 run_command='pass', _xoptions=['dev'], dev_mode=True)
241
242 def test_sysflags_utf8mode(self):
243 env = os.environ.copy()
244 self.check(['-X', 'utf8', '-c', 'pass'], env, sys_argv=['-c'],
245 run_command='pass', _xoptions=['utf8'], utf8_mode=True)
246 self.check(['-X', 'utf8=1', '-c', 'pass'], env, sys_argv=['-c'],
247 run_command='pass', _xoptions=['utf8=1'], utf8_mode=True)
248 self.check(['-X', 'utf8=0', '-c', 'pass'], env, sys_argv=['-c'],
249 run_command='pass', _xoptions=['utf8=0'], utf8_mode=False)
250
251 def test_sysflags_envvar(self):
252 env = os.environ.copy()
253 expected = {"no_user_site": True}
254 self.check(['-c', 'pass'], dict(env, PYTHONNOUSERSITE='1'), sys_argv=['-c'],
255 run_command='pass', **expected)
256 self.check(['-c', 'pass'], dict(env, PYTHONDEVMODE='1'), sys_argv=['-c'],
257 run_command='pass', dev_mode=True)
258
259 def test_sysflags_utf8mode_envvar(self):
260 env = os.environ.copy()
261 self.check(['-c', 'pass'], dict(env, PYTHONUTF8='1'), sys_argv=['-c'],
262 run_command='pass', utf8_mode=True)
263 self.check(['-c', 'pass'], dict(env, PYTHONUTF8='0'), sys_argv=['-c'],
264 run_command='pass', utf8_mode=False)
265 # -X takes precedence
266 self.check(['-X', 'utf8', '-c', 'pass'], dict(env, PYTHONUTF8='0'), sys_argv=['-c'],
267 run_command='pass', _xoptions=['utf8'], utf8_mode=True)
268 self.check(['-X', 'utf8=0', '-c', 'pass'], dict(env, PYTHONUTF8='1'), sys_argv=['-c'],
269 run_command='pass', _xoptions=['utf8=0'], utf8_mode=False)
270 # -E ignores PYTHONUTF8
271 import _locale
272 if _locale.setlocale(_locale.LC_CTYPE, None) not in ('C', 'POSIX'):
273 self.check(['-E', '-c', 'pass'], dict(env, PYTHONUTF8='1'), sys_argv=['-c'],
274 run_command='pass', ignore_environment=1, utf8_mode=False)
275
276 def test_check_hash_based_pycs(self):
277 env = os.environ.copy()
278 for val in ['default', 'always', 'never']:
279 self.check(
280 ['--check-hash-based-pycs', val],
281 env,
282 sys_argv=[''], run_stdin=True,
283 check_hash_based_pycs=val)
284
285
286
287 class TestInteraction:
288 """
289 These tests require pexpect (UNIX-only).
290 http://pexpect.sourceforge.net/
291 """
292 def _spawn(self, *args, **kwds):
293 try:
294 import pexpect
295 except ImportError as e:
296 py.test.skip(str(e))
297 else:
298 # Version is of the style "0.999" or "2.1". Older versions of
299 # pexpect try to get the fileno of stdin, which generally won't
300 # work with py.test (due to sys.stdin being a DontReadFromInput
301 # instance).
302 version = map(int, pexpect.__version__.split('.'))
303
304 # I only tested 0.999 and 2.1. The former does not work, the
305 # latter does. Feel free to refine this measurement.
306 # -exarkun, 17/12/2007
307 if version < [2, 1]:
308 py.test.skip(
309 "pexpect version too old, requires 2.1 or newer: %r" % (
310 pexpect.__version__,))
311
312 kwds.setdefault('timeout', 10)
313 print('SPAWN:', ' '.join([args[0]] + args[1]), kwds)
314 child = pexpect.spawn(*args, **kwds)
315 child.logfile = sys.stdout
316 return child
317
318 def spawn(self, argv, env=None):
319 # make sure that when we do 'import pypy' we get the correct package
320 with setpythonpath():
321 return self._spawn(get_python3(), [app_main] + argv, env=env)
322
323 def test_interactive(self):
324 child = self.spawn([])
325 child.expect('Python ') # banner
326 child.expect('>>> ') # prompt
327 child.sendline('[6*7]')
328 child.expect(re.escape('[42]'))
329 child.sendline('def f(x):')
330 child.expect(re.escape('... '))
331 child.sendline(' return x + 100')
332 child.expect(re.escape('... '))
333 child.sendline('')
334 child.expect('>>> ')
335 child.sendline('f(98)')
336 child.expect('198')
337 child.expect('>>> ')
338 child.sendline('__name__')
339 child.expect("'__main__'")
340 child.expect('>>> ')
341 child.sendline('import sys')
342 child.expect('>>> ')
343 child.sendline("'' in sys.path")
344 child.expect("True")
345
346 def test_yes_irc_topic(self, monkeypatch):
347 monkeypatch.setenv('PYPY_IRC_TOPIC', '1')
348 child = self.spawn([])
349 child.expect(irc_header) # banner
350
351 def test_maybe_irc_topic(self):
352 import sys
353 pypy_version_info = getattr(sys, 'pypy_version_info', sys.version_info)
354 irc_topic = pypy_version_info[3] != 'final'
355 child = self.spawn([])
356 child.expect('>>>') # banner
357 if irc_topic:
358 assert irc_header in child.before
359 else:
360 assert irc_header not in child.before
361
362 def test_help(self):
363 # test that -h prints the usage, including the name of the executable
364 # which should be /full/path/to/app_main.py in this case
365 child = self.spawn(['-h'])
366 child.expect(r'usage: .*app_main.py \[option\]')
367 child.expect('PyPy options and arguments:')
368
369 def test_run_script(self, demo_script):
370 child = self.spawn([demo_script])
371 idx = child.expect(['hello', 'Python ', '>>> '])
372 assert idx == 0 # no banner or prompt
373 child.expect(re.escape("Name: __main__"))
374 child.expect(re.escape('File: ' + demo_script))
375 child.expect(re.escape('Exec: ' + app_main))
376 child.expect(re.escape('Argv: ' + repr([demo_script])))
377 child.expect('goodbye')
378
379 def test_run_script_file_path(self, demo_script):
380 demo_script = str(py.path.local().bestrelpath(py.path.local(demo_script)))
381 child = self.spawn([demo_script])
382 idx = child.expect(['hello', 'Python ', '>>> '])
383 assert idx == 0 # no banner or prompt
384 child.expect(re.escape("Name: __main__"))
385 child.expect(re.escape('File: ' + os.path.join(os.getcwd(), demo_script)))
386 child.expect(re.escape('Exec: ' + app_main))
387 child.expect(re.escape('Argv: ' + repr([demo_script])))
388 child.expect('goodbye')
389
390 def test_run_script_with_args(self, demo_script):
391 argv = [demo_script, 'hello', 'world']
392 child = self.spawn(argv)
393 child.expect(re.escape('Argv: ' + repr(argv)))
394 child.expect('goodbye')
395
396 def test_no_such_script(self):
397 import errno
398 msg = os.strerror(errno.ENOENT) # 'No such file or directory'
399 child = self.spawn(['xxx-no-such-file-xxx'])
400 child.expect(re.escape(msg))
401
402 def test_option_i(self, demo_script):
403 argv = [demo_script, 'foo', 'bar']
404 child = self.spawn(['-i'] + argv)
405 idx = child.expect(['hello', re.escape(banner)])
406 assert idx == 0 # no banner
407 child.expect(re.escape('File: ' + demo_script))
408 child.expect(re.escape('Argv: ' + repr(argv)))
409 child.expect('goodbye')
410 idx = child.expect(['>>> ', re.escape(banner)])
411 assert idx == 0 # prompt, but still no banner
412 child.sendline('myvalue * 102')
413 child.expect('4284')
414 child.sendline('__name__')
415 child.expect('__main__')
416
417 def test_option_i_crashing(self, crashing_demo_script):
418 argv = [crashing_demo_script, 'foo', 'bar']
419 child = self.spawn(['-i'] + argv)
420 idx = child.expect(['Hello2', re.escape(banner)])
421 assert idx == 0 # no banner
422 child.expect('NameError')
423 child.sendline('myvalue2 * 1001')
424 child.expect('11011')
425 child.sendline('import sys; sys.argv')
426 child.expect(re.escape(repr(argv)))
427 child.sendline('sys.last_type.__name__')
428 child.expect(re.escape(repr('NameError')))
429
430 def test_options_i_c(self):
431 child = self.spawn(['-i', '-c', 'x=555'])
432 idx = child.expect(['>>> ', re.escape(banner)])
433 assert idx == 0 # prompt, but no banner
434 child.sendline('x')
435 child.expect('555')
436 child.sendline('__name__')
437 child.expect('__main__')
438 child.sendline('import sys; sys.argv')
439 child.expect(re.escape("['-c']"))
440
441 def test_options_i_c_crashing(self, monkeypatch):
442 monkeypatch.setenv('PYTHONPATH', None)
443 child = self.spawn(['-i', '-c', 'x=666;foobar'])
444 child.expect('NameError')
445 idx = child.expect(['>>> ', re.escape(banner)])
446 assert idx == 0 # prompt, but no banner
447 child.sendline('x')
448 child.expect('666')
449 child.sendline('__name__')
450 child.expect('__main__')
451 child.sendline('import sys; sys.argv')
452 child.expect(re.escape("['-c']"))
453 child.sendline('sys.last_type.__name__')
454 child.expect(re.escape(repr('NameError')))
455
456 def test_options_i_c_sysexit(self):
457 child = self.spawn(['-i', '-c', 'import sys; sys.exit(1)'])
458 child.expect('SystemExit: 1')
459 child.expect('>>>')
460
461 def test_atexit(self):
462 py.test.skip("Python3 atexit is a builtin module")
463 child = self.spawn([])
464 child.expect('>>> ')
465 child.sendline('def f(): print("foobye")')
466 child.sendline('')
467 child.sendline('import atexit; atexit.register(f)')
468 child.sendline('6*7')
469 child.expect('42')
470 # pexpect's sendeof() is confused by py.test capturing, though
471 # I think that it is a bug of sendeof()
472 old = sys.stdin
473 try:
474 sys.stdin = child
475 child.sendeof()
476 finally:
477 sys.stdin = old
478 child.expect('foobye')
479
480 def test_pythonstartup(self, monkeypatch, demo_script, crashing_demo_script):
481 monkeypatch.setenv('PYTHONPATH', None)
482 monkeypatch.setenv('PYTHONSTARTUP', crashing_demo_script)
483 child = self.spawn([])
484 child.expect(re.escape(banner))
485 child.expect('Traceback')
486 child.expect('NameError')
487 child.expect('>>> ')
488 child.sendline('[myvalue2]')
489 child.expect(re.escape('[11]'))
490 child.expect('>>> ')
491
492 child = self.spawn(['-i', demo_script])
493 for line in ['hello', 'goodbye', '>>> ']:
494 idx = child.expect([line, 'Hello2'])
495 assert idx == 0 # no PYTHONSTARTUP run here
496 child.sendline('myvalue2')
497 child.expect('Traceback')
498 child.expect('NameError')
499
500 def test_pythonstartup_file1(self, monkeypatch, demo_script):
501 monkeypatch.setenv('PYTHONPATH', None)
502 monkeypatch.setenv('PYTHONSTARTUP', demo_script)
503 child = self.spawn([])
504 child.expect('File: [^\n]+\.py')
505 child.expect('goodbye')
506 child.expect('>>> ')
507 child.sendline('[myvalue]')
508 child.expect(re.escape('[42]'))
509 child.expect('>>> ')
510 child.sendline('__file__')
511 child.expect('Traceback')
512 child.expect('NameError')
513
514 def test_pythonstartup_file2(self, monkeypatch, crashing_demo_script):
515 monkeypatch.setenv('PYTHONPATH', None)
516 monkeypatch.setenv('PYTHONSTARTUP', crashing_demo_script)
517 child = self.spawn([])
518 child.expect('Traceback')
519 child.expect('>>> ')
520 child.sendline('__file__')
521 child.expect('Traceback')
522 child.expect('NameError')
523
524 def test_ignore_python_startup(self, crashing_demo_script):
525 old = os.environ.get('PYTHONSTARTUP', '')
526 try:
527 os.environ['PYTHONSTARTUP'] = crashing_demo_script
528 child = self.spawn(['-E'])
529 child.expect(re.escape(banner))
530 index = child.expect(['Traceback', '>>> '])
531 assert index == 1 # no traceback
532 finally:
533 os.environ['PYTHONSTARTUP'] = old
534
535 def test_future_in_executed_script(self):
536 child = self.spawn(['-i', script_with_future])
537 child.expect('>>> ')
538 child.sendline('x=1; print(x/2, 3/4)')
539 child.expect('0.5 0.75')
540
541 def test_future_in_python_startup(self, monkeypatch):
542 monkeypatch.setenv('PYTHONSTARTUP', script_with_future)
543 child = self.spawn([])
544 child.expect('>>> ')
545 child.sendline('x=1; print(x/2, 3/4)')
546 child.expect('0.5 0.75')
547
548 def test_future_in_cmd(self):
549 child = self.spawn(['-i', '-c', 'from __future__ import division'])
550 child.expect('>>> ')
551 child.sendline('x=1; x/2; 3/4')
552 child.expect('0.5')
553 child.expect('0.75')
554
555 def test_cmd_co_name(self):
556 child = self.spawn(['-c',
557 'import sys; print(sys._getframe(0).f_code.co_name)'])
558 child.expect('<module>')
559
560 def test_ignore_python_inspect(self):
561 os.environ['PYTHONINSPECT_'] = '1'
562 try:
563 child = self.spawn(['-E', '-c', 'pass'])
564 from pexpect import EOF
565 index = child.expect(['>>> ', EOF])
566 assert index == 1 # no prompt
567 finally:
568 del os.environ['PYTHONINSPECT_']
569
570 def test_python_path_keeps_duplicates(self):
571 old = os.environ.get('PYTHONPATH', '')
572 try:
573 child = self.spawn(['-c', 'import sys; print(sys.path)'],
574 env={'PYTHONPATH': 'foobarbaz:foobarbaz'})
575 child.expect(r"\['', 'foobarbaz', 'foobarbaz', ")
576 finally:
577 os.environ['PYTHONPATH'] = old
578
579 def test_ignore_python_path(self):
580 old = os.environ.get('PYTHONPATH', '')
581 try:
582 os.environ['PYTHONPATH'] = 'foobarbaz'
583 child = self.spawn(['-E', '-c', 'import sys; print(sys.path)'])
584 from pexpect import EOF
585 index = child.expect(['foobarbaz', EOF])
586 assert index == 1 # no foobarbaz
587 finally:
588 os.environ['PYTHONPATH'] = old
589
590 def test_buffered(self):
591 line = 'import sys;print(type(sys.stdout.buffer).__name__)'
592 child = self.spawn(['-c', line])
593 child.expect('BufferedWriter')
594
595 def test_unbuffered(self):
596 # In Python3, -u affects the "binary layer" of sys.stdout.
597 line = 'import os,sys;sys.stdout.buffer.write(str(789).encode());os.read(0,1)'
598 child = self.spawn(['-u', '-c', line])
599 child.expect('789') # expect to see it before the timeout hits
600 child.sendline('X')
601
602 def test_unbuffered_write_through(self):
603 line = 'import os,sys;sys.stdout.write("a");os._exit(0)'
604 child = self.spawn(['-u', '-c', line])
605 child.expect('a')
606
607 def test_file_modes(self):
608 child = self.spawn(['-c', 'import sys; print(sys.stdout.mode)'])
609 child.expect('w')
610 child = self.spawn(['-c', 'import sys; print(sys.stderr.mode)'])
611 child.expect('w')
612 child = self.spawn(['-c', 'import sys; print(sys.stdin.mode)'])
613 child.expect('r')
614
615 def test_non_interactive_output_buffering(self):
616 import subprocess
617 code = textwrap.dedent("""
618 import sys
619 out = sys.stdout
620 print(out.isatty(), out.write_through, out.line_buffering)
621 err = sys.stderr
622 print(err.isatty(), err.write_through, err.line_buffering)
623 """)
624 args = [get_python3(), app_main, '-c', code]
625 proc = subprocess.Popen(args, stdout=subprocess.PIPE,
626 stderr=subprocess.PIPE, universal_newlines=True)
627 stdout, stderr = proc.communicate()
628 assert stdout.split() == ['False', 'False', 'False', 'False', 'False', 'True']
629
630 def test_stdio_encoding_normalized_to_canonical(self):
631 # PYTHONIOENCODING=latin1 -> sys.stdin.encoding should be 'iso8859-1'
632 # (the codec's canonical name), not 'latin1' (the alias)
633 env = os.environ.copy()
634 env['PYTHONIOENCODING'] = 'latin1'
635 args = [get_python3(), app_main, '-c',
636 'import sys; print(sys.stdin.encoding)']
637 with setpythonpath():
638 proc = subprocess.Popen(args, stdout=subprocess.PIPE,
639 stderr=subprocess.PIPE,
640 universal_newlines=True, env=env)
641 stdout, _ = proc.communicate()
642 assert stdout.strip() == 'iso8859-1'
643
644 def test_options_i_m(self, monkeypatch):
645 if sys.platform == "win32":
646 py.test.skip("close_fds is not supported on Windows platforms")
647 if not hasattr(runpy, '_run_module_as_main'):
648 py.test.skip("requires CPython >= 2.6")
649 p = os.path.join(os.path.realpath(os.path.dirname(__file__)), 'mymodule.py')
650 p = os.path.abspath(p)
651 monkeypatch.chdir(os.path.dirname(app_main))
652 child = self.spawn(['-i',
653 '-m', 'test.mymodule',
654 'extra'])
655 child.expect('mymodule running')
656 child.expect('Name: __main__')
657 child.expect(re.escape('File: ' + p))
658 child.expect(re.escape('Argv: ' + repr([p, 'extra'])))
659 child.expect('>>> ')
660 child.sendline('somevalue')
661 child.expect(re.escape(repr("foobar")))
662 child.expect('>>> ')
663 child.sendline('import sys')
664 child.sendline('"test" in sys.modules')
665 child.expect('True')
666 child.sendline('"test.mymodule" in sys.modules')
667 child.expect('False')
668 child.sendline('sys.path[0]')
669 child.expect(os.path.dirname(app_main))
670
671 def test_option_i_noexit(self):
672 child = self.spawn(['-i', '-c', 'import sys; sys.exit(1)'])
673 child.expect('Traceback')
674 child.expect('SystemExit: 1')
675
676 def test_options_u_i(self):
677 if sys.platform == "win32":
678 py.test.skip("close_fds is not supported on Windows platforms")
679 import subprocess, select, os
680 pipe = subprocess.Popen([get_python3(), app_main, "-u", "-i"],
681 stdout=subprocess.PIPE,
682 stdin=subprocess.PIPE,
683 stderr=subprocess.STDOUT,
684 bufsize=0, close_fds=True)
685 iwtd, owtd, ewtd = select.select([pipe.stdout], [], [], 5)
686 assert iwtd # else we timed out
687 data = os.read(pipe.stdout.fileno(), 1024)
688 assert data.startswith('Python')
689
690 def test_paste_several_lines_doesnt_mess_prompt(self):
691 py.test.skip("this can only work if readline is enabled")
692 child = self.spawn([])
693 child.expect('>>> ')
694 child.sendline('if 1:\n print 42\n')
695 child.expect('... print 42')
696 child.expect('... ')
697 child.expect('42')
698 child.expect('>>> ')
699
700 def test_pythoninspect(self):
701 os.environ['PYTHONINSPECT_'] = '1'
702 try:
703 path = getscript("""
704 print(6*7)
705 """)
706 child = self.spawn([path])
707 child.expect('42')
708 child.expect('>>> ')
709 finally:
710 del os.environ['PYTHONINSPECT_']
711
712 def test_set_pythoninspect(self):
713 path = getscript("""
714 import os
715 os.environ['PYTHONINSPECT'] = '1'
716 print(6*7)
717 """)
718 child = self.spawn([path])
719 child.expect('42')
720 child.expect('>>> ')
721
722 def test_clear_pythoninspect(self):
723 os.environ['PYTHONINSPECT_'] = '1'
724 try:
725 path = getscript("""
726 import os
727 del os.environ['PYTHONINSPECT']
728 """)
729 child = self.spawn([path])
730 child.expect('>>> ')
731 finally:
732 del os.environ['PYTHONINSPECT_']
733
734 def test_stdout_flushes_before_stdin_blocks(self):
735 py.test.skip("Python3 does not implement this behavior")
736 # This doesn't really test app_main.py, but a behavior that
737 # can only be checked on top of py.py with pexpect.
738 path = getscript("""
739 import sys
740 sys.stdout.write('Are you suggesting coconuts migrate? ')
741 line = sys.stdin.readline()
742 assert line.rstrip() == 'Not at all. They could be carried.'
743 print('A five ounce bird could not carry a one pound coconut.')
744 """)
745 py_py = os.path.join(pypydir, 'bin', 'pyinteractive.py')
746 child = self._spawn(sys.executable, [py_py, '-S', path])
747 child.expect('Are you suggesting coconuts migrate?', timeout=120)
748 child.sendline('Not at all. They could be carried.')
749 child.expect('A five ounce bird could not carry a one pound coconut.')
750
751 def test_no_space_before_argument(self, monkeypatch):
752 if not hasattr(runpy, '_run_module_as_main'):
753 py.test.skip("requires CPython >= 2.6")
754 child = self.spawn(['-cprint("hel" + "lo")'])
755 child.expect('hello')
756
757 monkeypatch.chdir(os.path.dirname(app_main))
758 child = self.spawn(['-mtest.mymodule'])
759 child.expect('mymodule running')
760
761 def test_ps1_only_if_interactive(self):
762 argv = ['-c', 'import sys; print(hasattr(sys, "ps1"))']
763 child = self.spawn(argv)
764 child.expect('False')
765
766
767 class TestNonInteractive:
768 def run_with_status_code(self, cmdline, senddata='', expect_prompt=False,
769 expect_banner=False, python_flags='', env=None):
770 if os.name == 'nt':
771 try:
772 import __pypy__
773 except:
774 py.test.skip('app_main cannot run on non-pypy for windows')
775 cmdline = '%s %s "%s" %s %s' % (get_python3(), python_flags,
776 app_main, python_flags, cmdline)
777 print('POPEN:', cmdline)
778 process = subprocess.Popen(
779 cmdline,
780 stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
781 shell=True, env=env,
782 universal_newlines=True
783 )
784 child_in, child_out_err = process.stdin, process.stdout
785 child_in.write(senddata)
786 child_in.close()
787 data = child_out_err.read()
788 child_out_err.close()
789 process.wait()
790 assert (banner in data) == expect_banner # no banner unless expected
791 assert ('>>> ' in data) == expect_prompt # no prompt unless expected
792 return data, process.returncode
793
794 def run(self, *args, **kwargs):
795 with setpythonpath():
796 data, status = self.run_with_status_code(*args, **kwargs)
797 return data
798
799 def test_script_on_stdin(self, demo_script):
800 for extraargs, expected_argv in [
801 ('', ['']),
802 ('-', ['-']),
803 ('- hello world', ['-', 'hello', 'world']),
804 ]:
805 data = self.run('%s < "%s"' % (extraargs, demo_script))
806 assert "hello" in data
807 assert "Name: __main__" in data
808 assert "File: <stdin>" in data
809 assert ("Exec: " + app_main) in data
810 assert ("Argv: " + repr(expected_argv)) in data
811 assert "goodbye" in data
812
813 def test_run_crashing_script(self, crashing_demo_script):
814 data = self.run('"%s"' % (crashing_demo_script,))
815 assert 'Hello2' in data
816 assert 'NameError' in data
817 assert 'Goodbye2' not in data
818
819 def test_abspath_in_main_error_traceback(self, crashing_demo_script):
820 relpath = py.path.local().bestrelpath(py.path.local(crashing_demo_script))
821 assert not os.path.isabs(relpath)
822 data = self.run('"%s"' % (relpath,))
823 assert crashing_demo_script in data
824 assert relpath not in data
825
826 def test_dotdot_in_main_filename(self, demo_script):
827 # corner case: when called like "python ../script.py"
828 # main.__filename__ should be os.getcwd() + '/' + script.py
829 filepath, filename = os.path.split(demo_script)
830 subdir = os.path.join(filepath, 'issue3881')
831 os.mkdir(subdir)
832 olddir = os.getcwd()
833 target = os.path.join('..', filename)
834 try:
835 os.chdir(subdir)
836 data = self.run(target)
837 print(data)
838 assert os.path.join(subdir, target) in data
839 finally:
840 os.chdir(olddir)
841
842 def test_crashing_script_on_stdin(self, crashing_demo_script):
843 data = self.run(' < "%s"' % (crashing_demo_script,))
844 assert 'Hello2' in data
845 assert 'NameError' in data
846 assert 'Goodbye2' not in data
847
848 def test_option_W(self):
849 data = self.run('-W d -c "print(42)"')
850 assert '42' in data
851 data = self.run('-Wd -c "print(42)"')
852 assert '42' in data
853
854 def test_option_W_crashing(self):
855 data = self.run('-W')
856 assert "Argument expected for the '-W' option" in data
857
858 def test_option_W_arg_ignored(self):
859 data = self.run('-Wc')
860 assert "Invalid -W option ignored: invalid action: 'c'" in data
861
862 def test_option_W_arg_ignored2(self):
863 data = self.run('-W-W')
864 assert "Invalid -W option ignored: invalid action:" in data
865
866 def test_option_c(self):
867 data = self.run('-c "print(6**5)"')
868 assert '7776' in data
869
870 def test_option_c_unencodable(self):
871 data, status = self.run_with_status_code(b"""-c 'print(b"\xff")'""",
872 env={'LC_ALL': 'C'})
873 assert status in (0, 1)
874 pattern = ("Unable to decode the command from the command line:"
875 if status else
876 "'\\xff' ")
877 assert data.startswith(pattern)
878
879 def test_no_pythonstartup(self, monkeypatch, demo_script, crashing_demo_script):
880 monkeypatch.setenv('PYTHONSTARTUP', crashing_demo_script)
881 data = self.run('"%s"' % (demo_script,))
882 assert 'Hello2' not in data
883 data = self.run('-c pass')
884 assert 'Hello2' not in data
885
886 def test_pythonwarnings(self, monkeypatch):
887 # PYTHONWARNINGS_ is special cased by app_main: we cannot directly set
888 # PYTHONWARNINGS because else the warnings raised from within pypy are
889 # turned in errors.
890 monkeypatch.setenv('PYTHONWARNINGS_', "once,error")
891 data = self.run('-W ignore -W default '
892 '-c "import sys; print(sys.warnoptions)"')
893 assert "['once', 'error', 'ignore', 'default']" in data
894
895 def test_option_m(self, monkeypatch):
896 if not hasattr(runpy, '_run_module_as_main'):
897 py.test.skip("requires CPython >= 2.6")
898 p = os.path.join(os.path.realpath(os.path.dirname(__file__)), 'mymodule.py')
899 p = os.path.abspath(p)
900 monkeypatch.chdir(os.path.dirname(app_main))
901 data = self.run('-m test.mymodule extra')
902 assert 'mymodule running' in data
903 assert 'Name: __main__' in data
904 # ignoring case for windows. abspath behaves different from autopath
905 # concerning drive letters right now.
906 assert ('File: ' + p) in data
907 assert ('Argv: ' + repr([p, 'extra'])) in data
908
909 def test_option_m_package(self, monkeypatch):
910 if not hasattr(runpy, '_run_module_as_main'):
911 py.test.skip("requires CPython >= 2.6")
912 p = os.path.join(os.path.realpath(os.path.dirname(__file__)),
913 'mypackage', '__main__.py')
914 p = os.path.abspath(p)
915 monkeypatch.chdir(os.path.dirname(app_main))
916 data = self.run('-m test.mypackage extra')
917 assert "__init__ argv: ['-m', 'extra']" in data
918 assert "__main__ argv: [%r, 'extra']" % p in data
919
920 def test_no_debug_ranges_xoption(self):
921 data = self.run('-X no_debug_ranges '
922 '-c "import sys; print(sys._xoptions.get(\'no_debug_ranges\'))"')
923 assert 'True' in data
924
925 def test_no_debug_ranges_envvar(self):
926 import os
927 env = os.environ.copy()
928 env['PYTHONNODEBUGRANGES'] = '1'
929 data = self.run('-c "import sys; print(sys._xoptions.get(\'no_debug_ranges\'))"',
930 env=env)
931 assert 'True' in data
932
933 def test_xoptions(self):
934 data = self.run('-Xfoo -Xbar=baz -Xquux=cdrom.com=FreeBSD -Xx=X,d=e '
935 '-c "import sys;print(sorted(sys._xoptions.items()))"')
936 expected = ("[('bar', 'baz'), ('foo', True), "
937 "('quux', 'cdrom.com=FreeBSD'), ('x', 'X,d=e')]")
938 assert expected in data
939
940 def test_pythoninspect_doesnt_override_isatty(self):
941 os.environ['PYTHONINSPECT_'] = '1'
942 try:
943 data = self.run('', senddata='6*7\nprint(2+3)\n')
944 assert data == '5\n'
945 finally:
946 del os.environ['PYTHONINSPECT_']
947
948 def test_i_flag_overrides_isatty(self):
949 data = self.run('-i', senddata='6*7\nraise SystemExit\n',
950 expect_prompt=True, expect_banner=True)
951 assert '42\n' in data
952 # if a file name is passed, the banner is never printed but
953 # we get a prompt anyway
954 cmdline = '-i %s' % getscript("""
955 print('hello world')
956 """)
957 data = self.run(cmdline, senddata='6*7\nraise SystemExit\n',
958 expect_prompt=True, expect_banner=False)
959 assert 'hello world\n' in data
960 assert '42\n' in data
961
962 def test_q_flag(self):
963 data = self.run('-iq', senddata='6*7\nraise SystemExit\n',
964 expect_prompt=True, expect_banner=False)
965 assert '42\n' in data
966
967 @py.test.mark.skipif('linux' not in sys.platform, reason="windows, sendata, and quoting problems")
968 def test_putenv_fires_interactive_within_process(self):
969 result = subprocess.call(
970 [get_python3(), app_main, '-c', 'import __pypy__'],
971 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
972 if result != 0:
973 py.test.skip("This can be only tested on PyPy with real_getenv")
974
975 # should be noninteractive when piped in
976 data = 'import os\nos.putenv("PYTHONINSPECT", "1")\n'
977 self.run('', senddata=data, expect_prompt=False)
978
979 # should go interactive with -c
980 data = data.replace('\n', ';')
981 self.run("-c '%s'" % data, expect_prompt=True)
982
983 def test_option_S_copyright(self):
984 data = self.run('-S -i', expect_prompt=True, expect_banner=True)
985 assert 'copyright' not in data
986
987 def test_non_interactive_stdout_unbuffered(self, monkeypatch):
988 monkeypatch.setenv('PYTHONUNBUFFERED', '1')
989 if os.name == 'nt':
990 try:
991 import __pypy__
992 except:
993 py.test.skip('app_main cannot run on non-pypy for windows')
994 path = getscript(r"""
995 import sys, time
996 sys.stdout.write('\x00(STDOUT)\n\x00')
997 time.sleep(1)
998 sys.stderr.write('\x00[STDERR]\n\x00')
999 time.sleep(1)
1000 # stdout flushed automatically here
1001 """)
1002 cmdline = '%s -E "%s" %s' % (get_python3(), app_main, path)
1003 print('POPEN:', cmdline)
1004 child_in, child_out_err = os.popen4(cmdline)
1005 data = child_out_err.read(11)
1006 assert data == '\x00(STDOUT)\n\x00' # from stderr
1007 data = child_out_err.read(11)
1008 assert data == '\x00[STDERR]\n\x00' # from stdout
1009 child_out_err.close()
1010 child_in.close()
1011
1012 # these tests are ported from the stdlib test suite
1013
1014 def _test_no_stdio(self, streams):
1015 code = """if 1:
1016 import os, sys
1017 for i, s in enumerate({streams}):
1018 if getattr(sys, s) is not None:
1019 os._exit(i + 1)
1020 os._exit(42)""".format(streams=streams)
1021 def preexec():
1022 if 'stdin' in streams:
1023 os.close(0)
1024 if 'stdout' in streams:
1025 os.close(1)
1026 if 'stderr' in streams:
1027 os.close(2)
1028 p = subprocess.Popen(
1029 [get_python3(), app_main, "-E", "-c", code],
1030 stdin=subprocess.PIPE,
1031 stdout=subprocess.PIPE,
1032 stderr=subprocess.PIPE,
1033 preexec_fn=preexec)
1034 out, err = p.communicate()
1035 err = re.sub(br"\[\d+ refs\]\r?\n?$", b"", err).strip()
1036 assert err == b''
1037 assert p.returncode == 42
1038
1039 @py.test.mark.skipif("os.name != 'posix'")
1040 def test_no_stdin(self):
1041 self._test_no_stdio(['stdin'])
1042
1043 @py.test.mark.skipif("os.name != 'posix'")
1044 def test_no_stdout(self):
1045 self._test_no_stdio(['stdout'])
1046
1047 @py.test.mark.skipif("os.name != 'posix'")
1048 @py.test.mark.xfail(reason="flaky untranslated: runner may reopen fd 2 before app_main.py detects EBADF")
1049 def test_no_stderr(self):
1050 self._test_no_stdio(['stderr'])
1051
1052 @py.test.mark.skipif("os.name != 'posix'")
1053 def test_no_std_streams(self):
1054 self._test_no_stdio(['stdin', 'stdout', 'stderr'])
1055
1056 def test_proper_sys_path(self, tmpdir):
1057 data = self.run('-c "import _ctypes"', python_flags='-S')
1058 if data.startswith('Traceback'):
1059 py.test.skip("'python -S' cannot import extension modules: "
1060 "see probably http://bugs.python.org/issue586680")
1061
1062 @contextmanager
1063 def chdir_and_unset_pythonpath(new_cwd):
1064 old_cwd = new_cwd.chdir()
1065 old_pythonpath = os.getenv('PYTHONPATH')
1066 os.unsetenv('PYTHONPATH')
1067 try:
1068 yield
1069 finally:
1070 old_cwd.chdir()
1071 # Can't call putenv with a None argument.
1072 if old_pythonpath is not None:
1073 os.putenv('PYTHONPATH', old_pythonpath)
1074
1075 # if we are running in a virtualenv, messing with site.py will
1076 # make runpy.py and pkgutil unavailable. They are needed to run
1077 # app_main. Copy them into the tmpdir
1078 runpy_dir = os.path.dirname(runpy.__file__)
1079 import pkgutil
1080 pkgutil_dir = os.path.dirname(pkgutil.__file__)
1081 shutil.copy(os.path.join(runpy_dir, 'runpy.py'), str(tmpdir))
1082 shutil.copy(os.path.join(pkgutil_dir, 'pkgutil.py'), str(tmpdir))
1083 tmpdir.join('site.py').write('print("SHOULD NOT RUN")')
1084 runme_py = tmpdir.join('runme.py')
1085 runme_py.write('print("some text")')
1086
1087 cmdline = str(runme_py)
1088
1089 with chdir_and_unset_pythonpath(tmpdir):
1090 data = self.run(cmdline, python_flags='-S')
1091
1092 assert data in ("'import site' failed\nsome text\n")
1093
1094 runme2_py = tmpdir.mkdir('otherpath').join('runme2.py')
1095 runme2_py.write('print("some new text")\n'
1096 'import sys\n'
1097 'print(sys.path)\n')
1098
1099 cmdline2 = str(runme2_py)
1100
1101 with chdir_and_unset_pythonpath(tmpdir):
1102 data = self.run(cmdline2, python_flags='-S')
1103 assert data.startswith("some new text\n")
1104 assert repr(str(tmpdir.join('otherpath'))) in data
1105 assert "''" not in data
1106
1107 data = self.run('-c "import sys; print(sys.path)"')
1108 assert data.startswith("[''")
1109
1110 def test_pyc_commandline_argument(self):
1111 p = getscript_pyc(self.space, "print(6*7)\n")
1112 assert os.path.isfile(p) and p.endswith('.pyc')
1113 data = self.run(p)
1114 assert data == '42\n'
1115
1116 def test_main_in_dir_commandline_argument(self):
1117 if not hasattr(runpy, '_run_module_as_main'):
1118 skip("requires CPython >= 2.6")
1119 p = getscript_in_dir('import sys; print(sys.argv[0])\n')
1120 data = self.run(p)
1121 assert data == p + '\n'
1122 data = self.run(p + os.sep)
1123 assert data == p + os.sep + '\n'
1124
1125 def test_run_module_inserts_abs_path_to_sys_path(self):
1126 if not hasattr(runpy, '_run_module_as_main'):
1127 skip("requires CPython >= 2.6")
1128 p = getscript_in_dir('import sys; print(sys.path[0])\n')
1129 data = self.run(p)
1130 assert data == os.path.abspath(p) + '\n'
1131 data = self.run(p + os.sep)
1132 assert data == os.path.abspath(p) + '\n'
1133
1134 def test_getfilesystemencoding(self):
1135 py.test.skip("encoding is only set if stdout.isatty(), test is flawed")
1136 if sys.version_info < (2, 7):
1137 skip("test requires Python >= 2.7")
1138 p = getscript_in_dir("""
1139 import sys
1140 sys.stdout.write(u'15\u20ac')
1141 sys.stdout.flush()
1142 """)
1143 env = os.environ.copy()
1144 env["LC_CTYPE"] = 'en_US.UTF-8'
1145 data = self.run(p, env=env)
1146 assert data == '15\xe2\x82\xac'
1147
1148 def test_pythonioencoding(self):
1149 if sys.version_info < (2, 7):
1150 skip("test requires Python >= 2.7")
1151 for encoding, expected in [
1152 ("iso-8859-15", "15\xa4"),
1153 ("utf-8", '15\xe2\x82\xac'),
1154 ("utf-16-le", '1\x005\x00\xac\x20'),
1155 ("iso-8859-1:ignore", "15"),
1156 ("iso-8859-1:replace", "15?"),
1157 ("iso-8859-1:backslashreplace", "15\\u20ac"),
1158 ]:
1159 p = getscript_in_dir("""
1160 import sys
1161 sys.stdout.write('15\u20ac')
1162 sys.stdout.flush()
1163 """)
1164 env = os.environ.copy()
1165 env["PYTHONIOENCODING"] = encoding
1166 data = self.run(p, env=env)
1167 assert data == expected
1168
1169 def test_pythonioencoding2(self):
1170 for encoding, expected in [
1171 ("ascii:", "ascii:strict"),
1172 (":surrogateescape", "utf-8:surrogateescape"),
1173 ]:
1174 p = getscript_in_dir("import sys; print(sys.stdout.encoding + ':' + sys.stdout.errors, end='')")
1175 env = os.environ.copy()
1176 env["PYTHONIOENCODING"] = encoding
1177 data = self.run(p, env=env)
1178 assert data == expected
1179
1180 def test_pythonioencoding_c_locale(self):
1181 for encoding, expected in [
1182 (None, "surrogateescape"),
1183 ("", "surrogateescape"),
1184 (":surrogateescape", "surrogateescape"),
1185 (":", "surrogateescape"),
1186 ("utf-8", "strict"),
1187 ("utf-8:", "strict"),
1188 ]:
1189 p = getscript_in_dir("import sys; print(sys.stdout.errors, end='')")
1190 env = os.environ.copy()
1191 env["LC_ALL"] = "C"
1192 if encoding is not None:
1193 env["PYTHONIOENCODING"] = encoding
1194 data = self.run(p, env=env)
1195 assert data == expected
1196
1197 def test_sys_exit_pythonioencoding(self):
1198 if sys.version_info < (2, 7):
1199 skip("test required Python >= 2.7")
1200 p = getscript_in_dir("""
1201 import sys
1202 sys.exit('15\u20ac')
1203 """)
1204 env = os.environ.copy()
1205 env["PYTHONIOENCODING"] = "utf-8"
1206 data, status = self.run_with_status_code(p, env=env)
1207 assert status == 1
1208 assert data.startswith("15\xe2\x82\xac")
1209
1210 def test_stderr_backslashreplace(self):
1211 if sys.version_info < (2, 7):
1212 skip("test required Python >= 2.7")
1213 p = getscript_in_dir("""
1214 import sys
1215 sys.exit('15\u20ac {}'.format((sys.stdout.errors, sys.stderr.errors)))
1216 """)
1217 env = os.environ.copy()
1218 env["PYTHONIOENCODING"] = 'ascii'
1219 data, status = self.run_with_status_code(p, env=env)
1220 assert status == 1
1221 assert data.startswith("15\\u20ac ('strict', 'backslashreplace')")
1222
1223 def test_consistent_sys_path_for_module_execution(self):
1224 # This test case ensures that the following all give the same
1225 # sys.path configuration:
1226 #
1227 # ./python -sm script_pkg.__main__
1228 # ./python -sm script_pkg
1229 #
1230 # And that these fails as unable to find the package:
1231 # ./python -Im script_pkg
1232 # ./python -Pm script_pkg
1233 work_dir = _get_next_path(ext='')
1234 script = textwrap.dedent("""
1235 import sys
1236 for d in sys.path:
1237 print(d)
1238 """)
1239 script_dir = work_dir / "script_pkg"
1240 script_dir.ensure_dir()
1241 (script_dir / '__main__.py').write(script)
1242 env = os.environ.copy()
1243 min_env = {'PATH': env['PATH']}
1244 p = subprocess.Popen([get_python3(), app_main, "-sm", "script_pkg.__main__"],
1245 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1246 cwd=str(work_dir), env=env)
1247 res = p.wait()
1248 out_by_module = p.stdout.read().splitlines()
1249 # macOS prepends '/private'
1250 assert out_by_module[0].endswith(str(work_dir))
1251 assert script_dir not in out_by_module
1252
1253 p = subprocess.Popen([get_python3(), app_main, "-sm", "script_pkg"],
1254 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1255 cwd=str(work_dir), env=env)
1256 res = p.wait()
1257 out_by_package = p.stdout.read().splitlines()
1258 assert out_by_module == out_by_package
1259
1260 p = subprocess.Popen([get_python3(), app_main, "-Im", "script_pkg"],
1261 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1262 cwd=str(work_dir), env=env)
1263 res = p.wait()
1264 stderr = p.stderr.read()
1265 traceback_lines = stderr.decode().splitlines()
1266 assert "No module named script_pkg" in traceback_lines[-1]
1267
1268 p = subprocess.Popen([get_python3(), app_main, "-Pm", "script_pkg"],
1269 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1270 cwd=str(work_dir), env=env)
1271 res = p.wait()
1272 stderr = p.stderr.read()
1273 traceback_lines = stderr.decode().splitlines()
1274 if len(traceback_lines) > 0:
1275 # Only the untranslated buildbot, stderr is empty
1276 assert "No module named script_pkg" in traceback_lines[-1]
1277
1278 def test_error_msg(self):
1279 data, status = self.run_with_status_code('does_not_exist.py')
1280 assert "can't open file" in data
1281 assert status == 2
1282
1283 @py.test.mark.skipif('config.getoption("runappdirect")')
1284 class AppTestAppMain:
1285 def setup_class(self):
1286 # ----------------------------------------
1287 # setup code for test_setup_bootstrap_path
1288 # ----------------------------------------
1289 from pypy.module.sys.version import CPYTHON_VERSION, PYPY_VERSION
1290 cpy_ver = '%d' % CPYTHON_VERSION[0]
1291 from lib_pypy._pypy_interact import irc_header
1292
1293 goal_dir = os.path.dirname(app_main)
1294 # build a directory hierarchy like which contains both bin/pypy3-c and
1295 # lib_pypy and lib-python
1296 prefix = udir.join('pathtest').ensure(dir=1)
1297 fake_exe = 'bin/pypy3-c'
1298 if sys.platform == 'win32':
1299 fake_exe = 'pypy3-c.exe'
1300 fake_exe = prefix.join(fake_exe).ensure(file=1)
1301 expected_path = [str(prefix.join(subdir).ensure(dir=1))
1302 for subdir in ('lib_pypy',
1303 'lib-python/%s' % cpy_ver)]
1304 # an empty directory from where we can't find the stdlib
1305 tmp_dir = str(udir.join('tmp').ensure(dir=1))
1306
1307 self.w_goal_dir = self.space.wrap(goal_dir)
1308 self.w_fake_exe = self.space.wrap(str(fake_exe))
1309 self.w_expected_path = self.space.wrap(expected_path)
1310 self.w_trunkdir = self.space.wrap(os.path.dirname(pypydir))
1311 self.w_is_release = self.space.wrap(PYPY_VERSION[3] == "final")
1312
1313 self.w_tmp_dir = self.space.wrap(tmp_dir)
1314
1315 foo_py = prefix.join('foo.py')
1316 foo_py.write("pass")
1317 self.w_foo_py = self.space.wrap(str(foo_py))
1318
1319 def test_setup_bootstrap_path(self):
1320 # Check how sys.path is handled depending on if we can find a copy of
1321 # the stdlib in setup_bootstrap_path.
1322 import sys, os
1323 old_sys_path = sys.path[:]
1324 old_cwd = os.getcwd()
1325
1326 # make sure cwd does not contain a stdlib
1327 if self.tmp_dir.startswith(self.trunkdir):
1328 skip('TMPDIR is inside the PyPy source')
1329 sys.path.append(self.goal_dir)
1330 tmp_pypy_c = os.path.join(self.tmp_dir, 'pypy3-c')
1331 try:
1332 os.chdir(self.tmp_dir)
1333
1334 # If we are running PyPy with a libpypy3-c, the following
1335 # lines find the stdlib anyway. Otherwise, it is not found.
1336 expected_found = (
1337 getattr(sys, 'pypy_translation_info', {})
1338 .get('translation.shared'))
1339
1340 import app_main
1341 app_main.setup_bootstrap_path(tmp_pypy_c)
1342 if not sys.platform == 'win32':
1343 assert sys.executable == ''
1344 if not expected_found:
1345 assert sys.path == old_sys_path + [self.goal_dir]
1346
1347 app_main.setup_bootstrap_path(self.fake_exe)
1348 if not sys.platform == 'win32':
1349 # an existing file is always 'executable' on windows
1350 assert sys.executable == '' # not executable!
1351 if not expected_found:
1352 assert sys.path == old_sys_path + [self.goal_dir]
1353
1354 os.chmod(self.fake_exe, 0o755)
1355 app_main.setup_bootstrap_path(self.fake_exe)
1356 assert sys.executable == self.fake_exe
1357 assert self.goal_dir not in sys.path
1358
1359 newpath = sys.path[:]
1360 if newpath[0].endswith('__extensions__'):
1361 newpath = newpath[1:]
1362 # we get at least 'expected_path', and maybe more (e.g.plat-linux2)
1363 if not expected_found:
1364 assert newpath[:len(self.expected_path)] == self.expected_path
1365 finally:
1366 sys.path[:] = old_sys_path
1367 os.chdir(old_cwd)
1368
1369 def test_trunk_can_be_prefix(self):
1370 import sys
1371 import os
1372 old_sys_path = sys.path[:]
1373 sys.path.append(self.goal_dir)
1374 if sys.platform == 'win32':
1375 exename = 'pypy3-c.exe'
1376 else:
1377 exename = 'pypy3-c'
1378 try:
1379 import app_main
1380 pypy_c = os.path.join(self.trunkdir, 'pypy', 'goal', exename)
1381 app_main.setup_bootstrap_path(pypy_c)
1382 newpath = sys.path[:]
1383 # we get at least lib_pypy
1384 # lib-python/X.Y.Z, and maybe more (e.g. plat-linux2)
1385 assert len(newpath) >= 2
1386 for p in newpath:
1387 assert p.startswith(self.trunkdir)
1388 finally:
1389 sys.path[:] = old_sys_path
1390
1391 def test_entry_point(self):
1392 import sys
1393 import os
1394 old_sys_path = sys.path[:]
1395 sys.path.append(self.goal_dir)
1396 if sys.platform == 'win32':
1397 exename = 'pypy3-c.exe'
1398 else:
1399 exename = 'pypy3-c'
1400 try:
1401 import app_main
1402 pypy_c = os.path.join(self.trunkdir, 'pypy', 'goal', exename)
1403 assert isinstance(self.foo_py, str)
1404 app_main.entry_point(pypy_c, [self.foo_py.encode("utf-8")], [self.foo_py])
1405 # assert it did not crash
1406 finally:
1407 sys.path[:] = old_sys_path