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

« back to all changes in this revision

Viewing changes to pypy/interpreter/test/test_interpreter.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
import py 
 
2
import sys
 
3
 
 
4
class TestInterpreter: 
 
5
    from pypy.interpreter.pycompiler import CPythonCompiler as CompilerClass
 
6
 
 
7
    def codetest(self, source, functionname, args):
 
8
        """Compile and run the given code string, and then call its function
 
9
        named by 'functionname' with arguments 'args'."""
 
10
        from pypy.interpreter import baseobjspace
 
11
        from pypy.interpreter import pyframe, gateway, module
 
12
        space = self.space
 
13
 
 
14
        source = str(py.code.Source(source).strip()) + '\n'
 
15
 
 
16
        w = space.wrap
 
17
        w_code = space.builtin.call('compile', 
 
18
                w(source), w('<string>'), w('exec'), w(0), w(0))
 
19
 
 
20
        tempmodule = module.Module(space, w("__temp__"))
 
21
        w_glob = tempmodule.w_dict
 
22
        space.setitem(w_glob, w("__builtins__"), space.builtin)
 
23
 
 
24
        code = space.unwrap(w_code)
 
25
        code.exec_code(space, w_glob, w_glob)
 
26
 
 
27
        wrappedargs = [w(a) for a in args]
 
28
        wrappedfunc = space.getitem(w_glob, w(functionname))
 
29
        try:
 
30
            w_output = space.call_function(wrappedfunc, *wrappedargs)
 
31
        except baseobjspace.OperationError, e:
 
32
            #e.print_detailed_traceback(space)
 
33
            return '<<<%s>>>' % e.errorstr(space)
 
34
        else:
 
35
            return space.unwrap(w_output)
 
36
 
 
37
    def setup_method(self, arg):
 
38
        ec = self.space.getexecutioncontext() 
 
39
        self.saved_compiler = ec.compiler
 
40
        ec.compiler = self.CompilerClass(self.space)
 
41
 
 
42
    def teardown_method(self, arg):
 
43
        ec = self.space.getexecutioncontext() 
 
44
        ec.compiler = self.saved_compiler
 
45
 
 
46
    def test_exception_trivial(self):
 
47
        x = self.codetest('''\
 
48
                def f():
 
49
                    try:
 
50
                        raise Exception()
 
51
                    except Exception, e:
 
52
                        return 1
 
53
                    return 2
 
54
            ''', 'f', [])
 
55
        assert x == 1
 
56
 
 
57
    def test_exception(self):
 
58
        x = self.codetest('''
 
59
            def f():
 
60
                try:
 
61
                    raise Exception, 1
 
62
                except Exception, e:
 
63
                    return e.args[0]
 
64
            ''', 'f', [])
 
65
        assert x == 1
 
66
 
 
67
    def test_finally(self):
 
68
        code = '''
 
69
            def f(a):
 
70
                try:
 
71
                    if a:
 
72
                        raise Exception
 
73
                    a = -12
 
74
                finally:
 
75
                    return a
 
76
        '''
 
77
        assert self.codetest(code, 'f', [0]) == -12
 
78
        assert self.codetest(code, 'f', [1]) == 1
 
79
 
 
80
##     def test_raise(self):
 
81
##         x = self.codetest('''
 
82
## def f():
 
83
##     raise 1
 
84
## ''', 'f', [])
 
85
##         self.assertEquals(x, '<<<TypeError: exceptions must be instances or subclasses of Exception or strings (deprecated), not int>>>')
 
86
 
 
87
    def test_except2(self):
 
88
        x = self.codetest('''
 
89
            def f():
 
90
                try:
 
91
                    z = 0
 
92
                    try:
 
93
                        "x"+1
 
94
                    except TypeError, e:
 
95
                        z = 5
 
96
                        raise e
 
97
                except TypeError:
 
98
                    return z
 
99
            ''', 'f', [])
 
100
        assert x == 5
 
101
 
 
102
    def test_except3(self):
 
103
        code = '''
 
104
                def f(v):
 
105
                    z = 0
 
106
                    try:
 
107
                        z = 1//v
 
108
                    except ZeroDivisionError, e:
 
109
                        z = "infinite result"
 
110
                    return z
 
111
                '''
 
112
        assert self.codetest(code, 'f', [2]) == 0
 
113
        assert self.codetest(code, 'f', [0]) == "infinite result"
 
114
        ess = "TypeError: unsupported operand type"
 
115
        res = self.codetest(code, 'f', ['x'])
 
116
        assert res.find(ess) >= 0
 
117
        # the following (original) test was a bit too strict...:
 
118
        # self.assertEquals(self.codetest(code, 'f', ['x']), "<<<TypeError: unsupported operand type(s) for //: 'int' and 'str'>>>")
 
119
 
 
120
    def test_break(self):
 
121
        code = '''
 
122
                def f(n):
 
123
                    total = 0
 
124
                    for i in range(n):
 
125
                        try:
 
126
                            if i == 4:
 
127
                                break
 
128
                        finally:
 
129
                            total += i
 
130
                    return total
 
131
                '''
 
132
        assert self.codetest(code, 'f', [4]) == 1+2+3
 
133
        assert self.codetest(code, 'f', [9]) == 1+2+3+4
 
134
 
 
135
    def test_continue(self):
 
136
        code = '''
 
137
                def f(n):
 
138
                    total = 0
 
139
                    for i in range(n):
 
140
                        try:
 
141
                            if i == 4:
 
142
                                continue
 
143
                        finally:
 
144
                            total += 100
 
145
                        total += i
 
146
                    return total
 
147
                '''
 
148
        assert self.codetest(code, 'f', [4]) == 1+2+3+400
 
149
        assert self.codetest(code, 'f', [9]) == (
 
150
                          1+2+3 + 5+6+7+8+900)
 
151
 
 
152
    def test_import(self):
 
153
        # Regression test for a bug in PyFrame.IMPORT_NAME: when an
 
154
        # import statement was executed in a function without a locals dict, a
 
155
        # plain unwrapped None could be passed into space.call_function causing
 
156
        # assertion errors later on.
 
157
        real_call_function = self.space.call_function
 
158
        def safe_call_function(w_obj, *arg_w):
 
159
            for arg in arg_w:
 
160
                assert arg is not None
 
161
            return real_call_function(w_obj, *arg_w)
 
162
        self.space.call_function = safe_call_function
 
163
        code = '''
 
164
            def f():
 
165
                import sys
 
166
            '''
 
167
        self.codetest(code, 'f', [])
 
168
 
 
169
    def test_extended_arg(self):
 
170
        longexpr = 'x = x or ' + '-x' * 2500
 
171
        code = '''
 
172
                def f(x):
 
173
                    %s
 
174
                    %s
 
175
                    %s
 
176
                    %s
 
177
                    %s
 
178
                    %s
 
179
                    %s
 
180
                    %s
 
181
                    %s
 
182
                    %s
 
183
                    while x:
 
184
                        x -= 1   # EXTENDED_ARG is for the JUMP_ABSOLUTE at the end of the loop
 
185
                    return x
 
186
                ''' % ((longexpr,)*10)
 
187
        assert self.codetest(code, 'f', [3]) == 0
 
188
 
 
189
    def test_call_star_starstar(self):
 
190
        code = '''\
 
191
            def f1(n):
 
192
                return n*2
 
193
            def f38(n):
 
194
                f = f1
 
195
                r = [
 
196
                    f(n, *[]),
 
197
                    f(n),
 
198
                    apply(f, (n,)),
 
199
                    apply(f, [n]),
 
200
                    f(*(n,)),
 
201
                    f(*[n]),
 
202
                    f(n=n),
 
203
                    f(**{'n': n}),
 
204
                    apply(f, (n,), {}),
 
205
                    apply(f, [n], {}),
 
206
                    f(*(n,), **{}),
 
207
                    f(*[n], **{}),
 
208
                    f(n, **{}),
 
209
                    f(n, *[], **{}),
 
210
                    f(n=n, **{}),
 
211
                    f(n=n, *[], **{}),
 
212
                    f(*(n,), **{}),
 
213
                    f(*[n], **{}),
 
214
                    f(*[], **{'n':n}),
 
215
                    ]
 
216
                return r
 
217
            '''
 
218
        assert self.codetest(code, 'f38', [117]) == [234]*19
 
219
 
 
220
    def test_star_arg(self):
 
221
        code = ''' 
 
222
            def f(x, *y):
 
223
                return y
 
224
            def g(u, v):
 
225
                return f(u, *v)
 
226
            '''
 
227
        assert self.codetest(code, 'g', [12, ()]) ==    ()
 
228
        assert self.codetest(code, 'g', [12, (3,4)]) == (3,4)
 
229
        assert self.codetest(code, 'g', [12, []]) ==    ()
 
230
        assert self.codetest(code, 'g', [12, [3,4]]) == (3,4)
 
231
        assert self.codetest(code, 'g', [12, {}]) ==    ()
 
232
        assert self.codetest(code, 'g', [12, {3:1}]) == (3,)
 
233
 
 
234
 
 
235
class TestPyPyInterpreter(TestInterpreter):
 
236
    """Runs the previous test with the pypy parser"""
 
237
    from pypy.interpreter.pycompiler import PythonAstCompiler as CompilerClass
 
238
 
 
239
    def test_extended_arg(self):
 
240
        py.test.skip("expression too large for the recursive parser")
 
241
 
 
242
 
 
243
class AppTestInterpreter: 
 
244
    def test_trivial(self):
 
245
        x = 42
 
246
        assert x == 42
 
247
 
 
248
    def test_trivial_call(self):
 
249
        def f(): return 42
 
250
        assert f() == 42
 
251
 
 
252
    def test_trivial_call2(self):
 
253
        def f(): return 1 + 1
 
254
        assert f() == 2
 
255
 
 
256
    def test_print(self):
 
257
        import sys
 
258
        save = sys.stdout 
 
259
        class Out:
 
260
            def __init__(self):
 
261
                self.args = []
 
262
            def write(self, *args):
 
263
                self.args.extend(args)
 
264
        out = Out()
 
265
        try:
 
266
            sys.stdout = out
 
267
            print 10
 
268
            assert out.args == ['10','\n']
 
269
        finally:
 
270
            sys.stdout = save
 
271
 
 
272
    def test_identity(self):
 
273
        def f(x): return x
 
274
        assert f(666) == 666
 
275