[pypy-svn] r40329 - in pypy/dist/pypy/translator/goal: . test

arigo at codespeak.net arigo at codespeak.net
Mon Mar 12 14:00:51 CET 2007


Author: arigo
Date: Mon Mar 12 14:00:50 2007
New Revision: 40329

Modified:
   pypy/dist/pypy/translator/goal/app_main.py
   pypy/dist/pypy/translator/goal/test/test_app_main.py
Log:
More tests for app_main.
Only print the banner and run $PYTHONSTARTUP when not running anything
else, not every time we specify the -i option.


Modified: pypy/dist/pypy/translator/goal/app_main.py
==============================================================================
--- pypy/dist/pypy/translator/goal/app_main.py	(original)
+++ pypy/dist/pypy/translator/goal/app_main.py	Mon Mar 12 14:00:50 2007
@@ -268,10 +268,25 @@
             success = run_toplevel(run_it)
         elif run_stdin:
             if sys.stdin.isatty():
+                print_banner()
+                python_startup = os.getenv('PYTHONSTARTUP')
+                if python_startup:
+                    try:
+                        startup = open(python_startup).read()
+                    except IOError:
+                        pass
+                    else:
+                        def run_it():
+                            co_python_startup = compile(startup,
+                                                        python_startup,
+                                                        'exec')
+                            exec co_python_startup in mainmodule.__dict__
+                        run_toplevel(run_it)
                 go_interactive = True
             else:
                 def run_it():
-                    exec sys.stdin.read() in mainmodule.__dict__
+                    co_stdin = compile(sys.stdin.read(), '<stdin>', 'exec')
+                    exec co_stdin in mainmodule.__dict__
                 mainmodule.__file__ = '<stdin>'
                 success = run_toplevel(run_it)
         else:
@@ -281,20 +296,7 @@
             success = run_toplevel(execfile, sys.argv[0], mainmodule.__dict__)
             
         if go_interactive or os.getenv('PYTHONINSPECT'):
-            python_startup = os.getenv('PYTHONSTARTUP')
-            if python_startup:
-                try:
-                    startup = open(python_startup).read()
-                except IOError:
-                    pass
-                else:
-                    def run_it():
-                        exec startup in mainmodule.__dict__
-                    run_toplevel(run_it)
-            print >> sys.stderr, "debug: importing code" 
-            import code
-            print >> sys.stderr, "debug: calling code.interact()"
-            success = run_toplevel(code.interact, local=mainmodule.__dict__)
+            success = run_toplevel(interactive_console, mainmodule)
     except SystemExit, e:
         return e.code
     else:
@@ -315,10 +317,47 @@
             return resolvedirof(os.path.join(dirname, link))
     return dirname
 
+def print_banner():
+    print 'Python %s on %s' % (sys.version, sys.platform)
+    print ('Type "help", "copyright", "credits" or '
+           '"license" for more information.')
+
+def interactive_console(mainmodule):
+    # some parts of code.py are copied here because it seems to be impossible
+    # to start an interactive console without printing at least one line
+    # of banner
+    import code
+    console = code.InteractiveConsole(mainmodule.__dict__)
+    try:
+        import readline
+    except ImportError:
+        pass
+    more = 0
+    while 1:
+        try:
+            if more:
+                prompt = sys.ps2
+            else:
+                prompt = sys.ps1
+            try:
+                line = raw_input(prompt)
+            except EOFError:
+                console.write("\n")
+                break
+            else:
+                more = console.push(line)
+        except KeyboardInterrupt:
+            console.write("\nKeyboardInterrupt\n")
+            console.resetbuffer()
+            more = 0
+
+
 if __name__ == '__main__':
     # obscure! try removing the following line, see how it crashes, and
     # guess why...
     ImStillAroundDontForgetMe = sys.modules['__main__']
+    sys.ps1 = '>>>> '
+    sys.ps2 = '.... '
 
     # debugging only
     def pypy_initial_path(s):

Modified: pypy/dist/pypy/translator/goal/test/test_app_main.py
==============================================================================
--- pypy/dist/pypy/translator/goal/test/test_app_main.py	(original)
+++ pypy/dist/pypy/translator/goal/test/test_app_main.py	Mon Mar 12 14:00:50 2007
@@ -14,14 +14,19 @@
 print 'Exec:', sys.executable
 print 'Argv:', sys.argv
 print 'goodbye'
+myvalue = 6*7
 """
 
 CRASHING_DEMO_SCRIPT = """
-print 'hello'
+print 'Hello2'
+myvalue2 = 11
 ooups
-print 'goodbye'   # should not be reached
+myvalue2 = 22
+print 'Goodbye2'   # should not be reached
 """
 
+banner = sys.version.splitlines()[0]
+
 def relpath(path):
     # force 'path' to be a relative path, for testing purposes
     curdir = py.path.local()
@@ -60,7 +65,9 @@
             py.test.skip(str(e))
         kwds.setdefault('timeout', 10)
         print 'SPAWN:', args, kwds
-        return pexpect.spawn(*args, **kwds)
+        child = pexpect.spawn(*args, **kwds)
+        child.logfile = sys.stdout
+        return child
 
     def spawn(self, argv):
         return self._spawn(sys.executable, [app_main] + argv)
@@ -105,6 +112,100 @@
         child = self.spawn(['xxx-no-such-file-xxx'])
         child.expect(re.escape(msg))
 
+    def test_option_i(self):
+        argv = [demo_script, 'foo', 'bar']
+        child = self.spawn(['-i'] + argv)
+        idx = child.expect(['hello', re.escape(banner)])
+        assert idx == 0      # no banner
+        child.expect(re.escape('File: ' + demo_script))
+        child.expect(re.escape('Argv: ' + repr(argv)))
+        child.expect('goodbye')
+        idx = child.expect(['>>> ', re.escape(banner)])
+        assert idx == 0      # prompt, but still no banner
+        child.sendline('myvalue * 102')
+        child.expect('4284')
+        child.sendline('__name__')
+        child.expect('__main__')
+
+    def test_option_i_crashing(self):
+        argv = [crashing_demo_script, 'foo', 'bar']
+        child = self.spawn(['-i'] + argv)
+        idx = child.expect(['Hello2', re.escape(banner)])
+        assert idx == 0      # no banner
+        child.expect('NameError')
+        child.sendline('myvalue2 * 1001')
+        child.expect('11011')
+        child.sendline('import sys; sys.argv')
+        child.expect(re.escape(repr(argv)))
+        child.sendline('sys.last_type.__name__')
+        child.expect(re.escape(repr('NameError')))
+
+    def test_options_i_c(self):
+        child = self.spawn(['-i', '-c', 'x=555'])
+        idx = child.expect(['>>> ', re.escape(banner)])
+        assert idx == 0      # prompt, but no banner
+        child.sendline('x')
+        child.expect('555')
+        child.sendline('__name__')
+        child.expect('__main__')
+        child.sendline('import sys; sys.argv')
+        child.expect(re.escape("['-c']"))
+
+    def test_options_i_c_crashing(self):
+        child = self.spawn(['-i', '-c', 'x=666;foobar'])
+        child.expect('NameError')
+        idx = child.expect(['>>> ', re.escape(banner)])
+        assert idx == 0      # prompt, but no banner
+        child.sendline('x')
+        child.expect('666')
+        child.sendline('__name__')
+        child.expect('__main__')
+        child.sendline('import sys; sys.argv')
+        child.expect(re.escape("['-c']"))
+        child.sendline('sys.last_type.__name__')
+        child.expect(re.escape(repr('NameError')))
+
+    def test_atexit(self):
+        child = self.spawn([])
+        child.expect('>>> ')
+        child.sendline('def f(): print "foobye"')
+        child.sendline('')
+        child.sendline('import atexit; atexit.register(f)')
+        child.sendline('6*7')
+        child.expect('42')
+        # pexpect's sendeof() is confused by py.test capturing, though
+        # I think that it is a bug of sendeof()
+        old = sys.stdin
+        try:
+            sys.stdin = child
+            child.sendeof()
+        finally:
+            sys.stdin = old
+        child.expect('foobye')
+
+    def test_pythonstartup(self):
+        old = os.environ['PYTHONSTARTUP']
+        try:
+            os.environ['PYTHONSTARTUP'] = crashing_demo_script
+            child = self.spawn([])
+            child.expect(re.escape(banner))
+            child.expect('Traceback')
+            child.expect('NameError')
+            child.expect('>>> ')
+            child.sendline('[myvalue2]')
+            child.expect(re.escape('[11]'))
+            child.expect('>>> ')
+
+            child = self.spawn(['-i', demo_script])
+            for line in ['hello', 'goodbye', '>>> ']:
+                idx = child.expect([line, 'Hello2'])
+                assert idx == 0    # no PYTHONSTARTUP run here
+            child.sendline('myvalue2')
+            child.expect('Traceback')
+            child.expect('NameError')
+        finally:
+            os.environ['PYTHONSTARTUP'] = old
+
 
 class TestNonInteractive:
 
@@ -115,7 +216,7 @@
         child_in.close()
         data = child_out_err.read()
         child_out_err.close()
-        assert sys.version not in data     # no banner
+        assert banner not in data          # no banner
         assert '>>> ' not in data          # no prompt
         return data
 
@@ -135,12 +236,27 @@
 
     def test_run_crashing_script(self):
         data = self.run('"%s"' % (crashing_demo_script,))
-        assert 'hello' in data
+        assert 'Hello2' in data
         assert 'NameError' in data
-        assert 'goodbye' not in data
+        assert 'Goodbye2' not in data
 
     def test_crashing_script_on_stdin(self):
         data = self.run(' < "%s"' % (crashing_demo_script,))
-        assert 'hello' in data
+        assert 'Hello2' in data
         assert 'NameError' in data
-        assert 'goodbye' not in data
+        assert 'Goodbye2' not in data
+
+    def test_option_c(self):
+        data = self.run('-c "print 6**5"')
+        assert '7776' in data
+
+    def test_no_pythonstartup(self):
+        old = os.environ['PYTHONSTARTUP']
+        try:
+            os.environ['PYTHONSTARTUP'] = crashing_demo_script
+            data = self.run('"%s"' % (demo_script,))
+            assert 'Hello2' not in data
+            data = self.run('-c pass')
+            assert 'Hello2' not in data
+        finally:
+            os.environ['PYTHONSTARTUP'] = old



More information about the Pypy-commit mailing list