~ubuntu-branches/ubuntu/karmic/pypy/karmic

« back to all changes in this revision

Viewing changes to pypy/translator/goal/test2/test_app_main.py

  • Committer: Bazaar Package Importer
  • Author(s): Alexandre Fayolle
  • Date: 2007-04-13 09:33:09 UTC
  • Revision ID: james.westby@ubuntu.com-20070413093309-yoojh4jcoocu2krz
Tags: upstream-1.0.0
ImportĀ upstreamĀ versionĀ 1.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
Tests for the entry point of pypy-c, app_main.py.
 
3
"""
 
4
import py
 
5
import sys, os, re
 
6
import autopath
 
7
from pypy.tool.udir import udir
 
8
 
 
9
DEMO_SCRIPT = """
 
10
print 'hello'
 
11
print 'Name:', __name__
 
12
print 'File:', __file__
 
13
import sys
 
14
print 'Exec:', sys.executable
 
15
print 'Argv:', sys.argv
 
16
print 'goodbye'
 
17
myvalue = 6*7
 
18
"""
 
19
 
 
20
CRASHING_DEMO_SCRIPT = """
 
21
print 'Hello2'
 
22
myvalue2 = 11
 
23
ooups
 
24
myvalue2 = 22
 
25
print 'Goodbye2'   # should not be reached
 
26
"""
 
27
 
 
28
banner = sys.version.splitlines()[0]
 
29
 
 
30
def relpath(path):
 
31
    # force 'path' to be a relative path, for testing purposes
 
32
    curdir = py.path.local()
 
33
    p = py.path.local(path)
 
34
    result = []
 
35
    while not p.relto(curdir):
 
36
        result.append(os.pardir)
 
37
        if curdir == curdir.dirpath():
 
38
            return str(path)     # no relative path found, give up
 
39
        curdir = curdir.dirpath()
 
40
    result.append(p.relto(curdir))
 
41
    return os.path.join(*result)
 
42
 
 
43
app_main = os.path.join(autopath.this_dir, os.pardir, 'app_main.py')
 
44
app_main = os.path.abspath(app_main)
 
45
 
 
46
demo_script_p = udir.join('demo_test_app_main.py')
 
47
demo_script_p.write(DEMO_SCRIPT)
 
48
demo_script = relpath(demo_script_p)
 
49
 
 
50
crashing_demo_script_p = udir.join('crashing_demo_test_app_main.py')
 
51
crashing_demo_script_p.write(CRASHING_DEMO_SCRIPT)
 
52
crashing_demo_script = relpath(crashing_demo_script_p)
 
53
 
 
54
 
 
55
class TestInteraction:
 
56
    """
 
57
    These tests require pexpect (UNIX-only).
 
58
    http://pexpect.sourceforge.net/
 
59
    """
 
60
 
 
61
    def _spawn(self, *args, **kwds):
 
62
        try:
 
63
            import pexpect
 
64
        except ImportError, e:
 
65
            py.test.skip(str(e))
 
66
        kwds.setdefault('timeout', 10)
 
67
        print 'SPAWN:', args, kwds
 
68
        child = pexpect.spawn(*args, **kwds)
 
69
        child.logfile = sys.stdout
 
70
        return child
 
71
 
 
72
    def spawn(self, argv):
 
73
        return self._spawn(sys.executable, [app_main] + argv)
 
74
 
 
75
    def test_interactive(self):
 
76
        child = self.spawn([])
 
77
        child.expect('Python ')   # banner
 
78
        child.expect('>>> ')      # prompt
 
79
        child.sendline('[6*7]')
 
80
        child.expect(re.escape('[42]'))
 
81
        child.sendline('def f(x):')
 
82
        child.expect(re.escape('... '))
 
83
        child.sendline('    return x + 100')
 
84
        child.expect(re.escape('... '))
 
85
        child.sendline('')
 
86
        child.expect('>>> ')
 
87
        child.sendline('f(98)')
 
88
        child.expect('198')
 
89
        child.expect('>>> ')
 
90
        child.sendline('__name__')
 
91
        child.expect("'__main__'")
 
92
 
 
93
    def test_run_script(self):
 
94
        child = self.spawn([demo_script])
 
95
        idx = child.expect(['hello', 'Python ', '>>> '])
 
96
        assert idx == 0   # no banner or prompt
 
97
        child.expect(re.escape("Name: __main__"))
 
98
        child.expect(re.escape('File: ' + demo_script))
 
99
        child.expect(re.escape('Exec: ' + app_main))
 
100
        child.expect(re.escape('Argv: ' + repr([demo_script])))
 
101
        child.expect('goodbye')
 
102
 
 
103
    def test_run_script_with_args(self):
 
104
        argv = [demo_script, 'hello', 'world']
 
105
        child = self.spawn(argv)
 
106
        child.expect(re.escape('Argv: ' + repr(argv)))
 
107
        child.expect('goodbye')
 
108
 
 
109
    def test_no_such_script(self):
 
110
        import errno
 
111
        msg = os.strerror(errno.ENOENT)   # 'No such file or directory'
 
112
        child = self.spawn(['xxx-no-such-file-xxx'])
 
113
        child.expect(re.escape(msg))
 
114
 
 
115
    def test_option_i(self):
 
116
        argv = [demo_script, 'foo', 'bar']
 
117
        child = self.spawn(['-i'] + argv)
 
118
        idx = child.expect(['hello', re.escape(banner)])
 
119
        assert idx == 0      # no banner
 
120
        child.expect(re.escape('File: ' + demo_script))
 
121
        child.expect(re.escape('Argv: ' + repr(argv)))
 
122
        child.expect('goodbye')
 
123
        idx = child.expect(['>>> ', re.escape(banner)])
 
124
        assert idx == 0      # prompt, but still no banner
 
125
        child.sendline('myvalue * 102')
 
126
        child.expect('4284')
 
127
        child.sendline('__name__')
 
128
        child.expect('__main__')
 
129
 
 
130
    def test_option_i_crashing(self):
 
131
        argv = [crashing_demo_script, 'foo', 'bar']
 
132
        child = self.spawn(['-i'] + argv)
 
133
        idx = child.expect(['Hello2', re.escape(banner)])
 
134
        assert idx == 0      # no banner
 
135
        child.expect('NameError')
 
136
        child.sendline('myvalue2 * 1001')
 
137
        child.expect('11011')
 
138
        child.sendline('import sys; sys.argv')
 
139
        child.expect(re.escape(repr(argv)))
 
140
        child.sendline('sys.last_type.__name__')
 
141
        child.expect(re.escape(repr('NameError')))
 
142
 
 
143
    def test_options_i_c(self):
 
144
        child = self.spawn(['-i', '-c', 'x=555'])
 
145
        idx = child.expect(['>>> ', re.escape(banner)])
 
146
        assert idx == 0      # prompt, but no banner
 
147
        child.sendline('x')
 
148
        child.expect('555')
 
149
        child.sendline('__name__')
 
150
        child.expect('__main__')
 
151
        child.sendline('import sys; sys.argv')
 
152
        child.expect(re.escape("['-c']"))
 
153
 
 
154
    def test_options_i_c_crashing(self):
 
155
        child = self.spawn(['-i', '-c', 'x=666;foobar'])
 
156
        child.expect('NameError')
 
157
        idx = child.expect(['>>> ', re.escape(banner)])
 
158
        assert idx == 0      # prompt, but no banner
 
159
        child.sendline('x')
 
160
        child.expect('666')
 
161
        child.sendline('__name__')
 
162
        child.expect('__main__')
 
163
        child.sendline('import sys; sys.argv')
 
164
        child.expect(re.escape("['-c']"))
 
165
        child.sendline('sys.last_type.__name__')
 
166
        child.expect(re.escape(repr('NameError')))
 
167
 
 
168
    def test_atexit(self):
 
169
        child = self.spawn([])
 
170
        child.expect('>>> ')
 
171
        child.sendline('def f(): print "foobye"')
 
172
        child.sendline('')
 
173
        child.sendline('import atexit; atexit.register(f)')
 
174
        child.sendline('6*7')
 
175
        child.expect('42')
 
176
        # pexpect's sendeof() is confused by py.test capturing, though
 
177
        # I think that it is a bug of sendeof()
 
178
        old = sys.stdin
 
179
        try:
 
180
            sys.stdin = child
 
181
            child.sendeof()
 
182
        finally:
 
183
            sys.stdin = old
 
184
        child.expect('foobye')
 
185
 
 
186
    def test_pythonstartup(self):
 
187
        old = os.environ.get('PYTHONSTARTUP', '')
 
188
        try:
 
189
            os.environ['PYTHONSTARTUP'] = crashing_demo_script
 
190
            child = self.spawn([])
 
191
            child.expect(re.escape(banner))
 
192
            child.expect('Traceback')
 
193
            child.expect('NameError')
 
194
            child.expect('>>> ')
 
195
            child.sendline('[myvalue2]')
 
196
            child.expect(re.escape('[11]'))
 
197
            child.expect('>>> ')
 
198
 
 
199
            child = self.spawn(['-i', demo_script])
 
200
            for line in ['hello', 'goodbye', '>>> ']:
 
201
                idx = child.expect([line, 'Hello2'])
 
202
                assert idx == 0    # no PYTHONSTARTUP run here
 
203
            child.sendline('myvalue2')
 
204
            child.expect('Traceback')
 
205
            child.expect('NameError')
 
206
        finally:
 
207
            os.environ['PYTHONSTARTUP'] = old
 
208
 
 
209
    def test_unbuffered(self):
 
210
        line = 'import os,sys;sys.stdout.write(str(789));os.read(0,1)'
 
211
        child = self.spawn(['-u', '-c', line])
 
212
        child.expect('789')    # expect to see it before the timeout hits
 
213
        child.sendline('X')
 
214
 
 
215
    def test_options_i_m(self):
 
216
        p = os.path.join(autopath.this_dir, 'mymodule.py')
 
217
        p = os.path.abspath(p)
 
218
        child = self.spawn(['-i',
 
219
                            '-m', 'pypy.translator.goal.test2.mymodule',
 
220
                            'extra'])
 
221
        child.expect('mymodule running')
 
222
        child.expect('Name: __main__')
 
223
        child.expect(re.escape('File: ' + p))
 
224
        child.expect(re.escape('Argv: ' + repr([p, 'extra'])))
 
225
        child.expect('>>> ')
 
226
        #XXX the following doesn't work on CPython 2.5 either
 
227
        #child.sendline('somevalue')
 
228
        #child.expect(re.escape(repr("foobar")))
 
229
        #child.expect('>>> ')
 
230
        child.sendline('import sys')
 
231
        child.sendline('"pypy.translator.goal.test2" in sys.modules')
 
232
        child.expect('True')
 
233
        child.sendline('"pypy.translator.goal.test2.mymodule" in sys.modules')
 
234
        child.expect('False')
 
235
 
 
236
    def test_options_u_i(self):
 
237
        import subprocess, select, os
 
238
        python = sys.executable
 
239
        pipe = subprocess.Popen([python, app_main, "-u", "-i"],
 
240
                                stdout=subprocess.PIPE,
 
241
                                stdin=subprocess.PIPE,
 
242
                                stderr=subprocess.STDOUT,
 
243
                                bufsize=0, close_fds=True)
 
244
        iwtd, owtd, ewtd = select.select([pipe.stdout], [], [], 5)
 
245
        assert iwtd    # else we timed out
 
246
        data = os.read(pipe.stdout.fileno(), 1024)
 
247
        assert data.startswith('Python')
 
248
 
 
249
    def test_options_u_PYTHONINSPECT(self):
 
250
        import subprocess, select, os
 
251
        python = sys.executable
 
252
        pipe = subprocess.Popen([python, app_main, "-u"],
 
253
                                stdout=subprocess.PIPE,
 
254
                                stdin=subprocess.PIPE,
 
255
                                stderr=subprocess.STDOUT,
 
256
                                bufsize=0, close_fds=True,
 
257
                                env={'PYTHONINSPECT': '1'})
 
258
        iwtd, owtd, ewtd = select.select([pipe.stdout], [], [], 5)
 
259
        assert iwtd    # else we timed out
 
260
        data = os.read(pipe.stdout.fileno(), 1024)
 
261
        assert data.startswith('Python')
 
262
 
 
263
    def test_paste_several_lines_doesnt_mess_prompt(self):
 
264
        py.test.skip("this can only work if readline is enabled")
 
265
        child = self.spawn([])
 
266
        child.expect('>>> ')
 
267
        child.sendline('if 1:\n    print 42\n')
 
268
        child.expect('...     print 42')
 
269
        child.expect('... ')
 
270
        child.expect('42')
 
271
        child.expect('>>> ')
 
272
 
 
273
 
 
274
class TestNonInteractive:
 
275
 
 
276
    def run(self, cmdline):
 
277
        cmdline = '"%s" "%s" %s' % (sys.executable, app_main, cmdline)
 
278
        print 'POPEN:', cmdline
 
279
        child_in, child_out_err = os.popen4(cmdline)
 
280
        child_in.close()
 
281
        data = child_out_err.read()
 
282
        child_out_err.close()
 
283
        assert banner not in data          # no banner
 
284
        assert '>>> ' not in data          # no prompt
 
285
        return data
 
286
 
 
287
    def test_script_on_stdin(self):
 
288
        for extraargs, expected_argv in [
 
289
            ('',              ['']),
 
290
            ('-',             ['-']),
 
291
            ('- hello world', ['-', 'hello', 'world']),
 
292
            ]:
 
293
            data = self.run('%s < "%s"' % (extraargs, demo_script))
 
294
            assert "hello" in data
 
295
            assert "Name: __main__" in data
 
296
            assert "File: <stdin>" in data
 
297
            assert ("Exec: " + app_main) in data
 
298
            assert ("Argv: " + repr(expected_argv)) in data
 
299
            assert "goodbye" in data
 
300
 
 
301
    def test_run_crashing_script(self):
 
302
        data = self.run('"%s"' % (crashing_demo_script,))
 
303
        assert 'Hello2' in data
 
304
        assert 'NameError' in data
 
305
        assert 'Goodbye2' not in data
 
306
 
 
307
    def test_crashing_script_on_stdin(self):
 
308
        data = self.run(' < "%s"' % (crashing_demo_script,))
 
309
        assert 'Hello2' in data
 
310
        assert 'NameError' in data
 
311
        assert 'Goodbye2' not in data
 
312
 
 
313
    def test_option_c(self):
 
314
        data = self.run('-c "print 6**5"')
 
315
        assert '7776' in data
 
316
 
 
317
    def test_no_pythonstartup(self):
 
318
        old = os.environ.get('PYTHONSTARTUP', '')
 
319
        try:
 
320
            os.environ['PYTHONSTARTUP'] = crashing_demo_script
 
321
            data = self.run('"%s"' % (demo_script,))
 
322
            assert 'Hello2' not in data
 
323
            data = self.run('-c pass')
 
324
            assert 'Hello2' not in data
 
325
        finally:
 
326
            os.environ['PYTHONSTARTUP'] = old
 
327
 
 
328
    def test_option_m(self):
 
329
        p = os.path.join(autopath.this_dir, 'mymodule.py')
 
330
        p = os.path.abspath(p)
 
331
        data = self.run('-m pypy.translator.goal.test2.mymodule extra')
 
332
        assert 'mymodule running' in data
 
333
        assert 'Name: __main__' in data
 
334
        assert ('File: ' + p) in data
 
335
        assert ('Argv: ' + repr([p, 'extra'])) in data