Debian Codegraph @

pypy/interpreter/test/test_interpreter.py

raw symbols SCIP
1 import py
2 import sys
3 from pypy.interpreter import gateway, module, error
4
5 class TestInterpreter:
6
7 def codetest(self, source, functionname, args, kwargs={}):
8 """Compile and run the given code string, and then call its function
9 named by 'functionname' with arguments 'args'."""
10 space = self.space
11
12 source = str(py.code.Source(source).strip()) + '\n'
13
14 w = space.wrap
15 w_code = space.builtin.call('compile',
16 w(source), w('<string>'), w('exec'), w(0), w(0))
17
18 tempmodule = module.Module(space, w("__temp__"))
19 w_glob = tempmodule.w_dict
20 space.setitem(w_glob, w("__builtins__"), space.builtin)
21
22 code = space.unwrap(w_code)
23 code.exec_code(space, w_glob, w_glob)
24
25 wrappedargs = w(args)
26 wrappedkwargs = w(kwargs)
27 wrappedfunc = space.getitem(w_glob, w(functionname))
28 try:
29 w_output = space.call(wrappedfunc, wrappedargs, wrappedkwargs)
30 except error.OperationError as e:
31 #e.print_detailed_traceback(space)
32 return '<<<%s>>>' % e.errorstr(space)
33 else:
34 return space.unwrap(w_output)
35
36 def test_import(self):
37 # Regression test for a bug in PyFrame.IMPORT_NAME: when an
38 # import statement was executed in a function without a locals dict, a
39 # plain unwrapped None could be passed into space.call_function causing
40 # assertion errors later on.
41 real_call_function = self.space.call_function
42 def safe_call_function(w_obj, *arg_w):
43 for arg in arg_w:
44 assert arg is not None
45 return real_call_function(w_obj, *arg_w)
46 self.space.call_function = safe_call_function
47 code = '''
48 def f():
49 import sys
50 '''
51 self.codetest(code, 'f', [])
52
53 def test_import_default_arg(self):
54 # CPython does not always call __import__() with 5 arguments,
55 # but only if the 5th one is not -1.
56 real_call_function = self.space.call_function
57 space = self.space
58 def safe_call_function(w_obj, *arg_w):
59 assert not arg_w or not space.eq_w(arg_w[-1], space.wrap(-1))
60 return real_call_function(w_obj, *arg_w)
61 self.space.call_function = safe_call_function
62 try:
63 code = '''
64 def f():
65 import sys
66 '''
67 self.codetest(code, 'f', [])
68 finally:
69 del self.space.call_function
70
71 def test_call_star_starstar(self):
72 code = '''\
73 def f1(n):
74 return n*2
75 def f38(n):
76 f = f1
77 r = [
78 f(n, *[]),
79 f(n),
80 f(*(n,)),
81 f(*[n]),
82 f(n=n),
83 f(**{'n': n}),
84 f(*(n,), **{}),
85 f(*[n], **{}),
86 f(n, **{}),
87 f(n, *[], **{}),
88 f(n=n, **{}),
89 f(n=n, *[], **{}),
90 f(*(n,), **{}),
91 f(*[n], **{}),
92 f(*[], **{'n':n}),
93 ]
94 return r
95 '''
96 assert self.codetest(code, 'f38', [117]) == [234]*15
97
98 def test_star_arg(self):
99 code = '''
100 def f(x, *y):
101 return y
102 def g(u, v):
103 return f(u, *v)
104 '''
105 assert self.codetest(code, 'g', [12, ()]) == ()
106 assert self.codetest(code, 'g', [12, (3,4)]) == (3,4)
107 assert self.codetest(code, 'g', [12, []]) == ()
108 assert self.codetest(code, 'g', [12, [3,4]]) == (3,4)
109 assert self.codetest(code, 'g', [12, {}]) == ()
110 assert self.codetest(code, 'g', [12, {3:1}]) == (3,)
111
112 def test_star_arg_after_keyword_arg(self):
113 code = '''
114 def f(a, b):
115 return a - b
116 def g(a, b):
117 return f(b=b, *(a,))
118 '''
119 assert self.codetest(code, 'g', [40, 2]) == 38
120
121 def test_closure(self):
122 code = '''
123 def f(x, y):
124 def g(u, v):
125 return u - v + 7*x
126 return g
127 def callme(x, u, v):
128 return f(x, 123)(u, v)
129 '''
130 assert self.codetest(code, 'callme', [1, 2, 3]) == 6
131
132 def test_import_statement(self):
133 for x in range(10):
134 import os
135 code = '''
136 def f():
137 for x in range(10):
138 import os
139 return os.name
140 '''
141 assert self.codetest(code, 'f', []) == os.name
142
143 def test_kwonlyargs_with_kwarg(self):
144 code = """ def f():
145 def g(a, *arg, c, **kw):
146 return [a, arg, c, kw]
147 return g(1, 2, 3, c=4, d=5)
148 """
149 exp = [1, (2, 3), 4, {"d" : 5}]
150 assert self.codetest(code, "f", []) == exp
151
152 def test_kwonlyargs_default_parameters(self):
153 code = """ def f(a, b, c=3, d=4):
154 return a, b, c, d
155 """
156 assert self.codetest(code, "f", [1, 2]) == (1, 2, 3, 4)
157
158 def test_kwonlyargs_order(self):
159 code = """ def f(a, b, *, c, d):
160 return a, b, c, d
161 """
162 assert self.codetest(code, "f", [1, 2], {"d" : 4, "c" : 3}) == (1, 2, 3, 4)
163
164 def test_build_set_unpack(self):
165 code = """ def f():
166 return {*range(4), 4, *(5, 6, 7)}
167 """
168 space = self.space
169 res = self.codetest(code, "f", [])
170 l_res = space.call_function(space.w_list, res)
171 assert space.unwrap(l_res) == [0, 1, 2, 3, 4, 5, 6, 7]
172
173 def test_build_set_unpack_exception(self):
174 code = """ if 1:
175 def g():
176 yield 1
177 yield 2
178 raise TypeError
179 def f():
180 try:
181 {*g(), 1, 2}
182 except TypeError:
183 return True
184 return False
185 """
186 assert self.codetest(code, "f", [])
187
188 def test_build_tuple_unpack(self):
189 code = """ def f():
190 return (*range(4), 4)
191 """
192 assert self.codetest(code, "f", []) == (0, 1, 2, 3, 4)
193
194 def test_build_list_unpack(self):
195 code = """ def f():
196 return [*range(4), 4]
197 """
198 assert self.codetest(code, "f", []) == [0, 1, 2, 3, 4]
199
200 def test_build_map_unpack(self):
201 code = """
202 def f():
203 return {'x': 1, **{'y': 2}}
204 def g():
205 return {**()}
206 """
207 assert self.codetest(code, "f", []) == {'x': 1, 'y': 2}
208 res = self.codetest(code, 'g', [])
209 assert "TypeError:" in res
210 assert "'tuple' object is not a mapping" in res
211
212 def test_build_map_unpack_with_call(self):
213 code = """
214 def f(a,b,c,d):
215 return a+b,c+d
216 def g1():
217 return f(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4})
218 def g2():
219 return f(**{'a': 1, 'c': 3}, **[])
220 def g3():
221 return f(**{'a': 1, 'c': 3}, **{1: 3})
222 def g4():
223 return f(**{'a': 1, 'c': 3}, **{'a': 2})
224 """
225 assert self.codetest(code, "g1", []) == (3, 7)
226 resg2 = self.codetest(code, 'g2', [])
227 assert "TypeError:" in resg2
228 assert "argument after ** must be a mapping, not list" in resg2
229 resg3 = self.codetest(code, 'g3', [])
230 assert "TypeError:" in resg3
231 assert "keywords must be strings" in resg3
232 resg4 = self.codetest(code, 'g4', [])
233 assert "TypeError:" in resg4
234 assert "got multiple values for keyword argument 'a'" in resg4
235
236 def test_build_map_unpack_with_call_mapping_lies_about_length(self):
237 code = """
238 class M:
239 def keys(self):
240 return ['a', 'b', 'c']
241 def __getitem__(self, key):
242 return 1
243 def __len__(self):
244 return 2
245
246 def f(**kwargs): return kwargs
247 def g():
248 return f(**{'a': 3}, **M())
249 """
250 resg = self.codetest(code, 'g', [])
251 assert "TypeError:" in resg
252 assert "got multiple values for keyword argument 'a'" in resg
253
254 try:
255 from hypothesis import given, strategies
256 except ImportError:
257 pass
258 else:
259 class TestHypothesisInterpreter(TestInterpreter):
260 @given(strategies.lists(strategies.one_of(strategies.none(),
261 strategies.lists(strategies.none()))))
262 def test_build_map_order(self, shape):
263 value = [10]
264 def build_expr(shape):
265 if shape is None:
266 value[0] += 1
267 return '0: %d' % value[0]
268 else:
269 return '**{%s}' % (', '.join(
270 [build_expr(shape1) for shape1 in shape]),)
271
272 expr = build_expr(shape)[2:]
273 code = """
274 def f():
275 return %s
276 """ % (expr, )
277 res = self.codetest(code, 'f', [])
278 if value[0] == 10:
279 expected = {}
280 else:
281 expected = {0: value[0]}
282 assert res == expected, "got %r for %r" % (res, expr)
283
284
285 class AppTestInterpreter:
286 def test_trivial(self):
287 x = 42
288 assert x == 42
289
290 def test_trivial_call(self):
291 def f(): return 42
292 assert f() == 42
293
294 def test_trivial_call2(self):
295 def f(): return 1 + 1
296 assert f() == 2
297
298 def test_print(self):
299 import sys
300 save = sys.stdout
301 class Out(object):
302 def __init__(self):
303 self.args = []
304 def write(self, *args):
305 self.args.extend(args)
306 out = Out()
307 try:
308 sys.stdout = out
309 print(10)
310 assert out.args == ['10','\n']
311 finally:
312 sys.stdout = save
313
314 def test_print_unicode(self):
315 import sys
316
317 save = sys.stdout
318 class Out(object):
319 def __init__(self):
320 self.data = []
321 def write(self, x):
322 self.data.append((type(x), x))
323 sys.stdout = out = Out()
324 try:
325 print(chr(0xa2))
326 assert out.data == [(str, chr(0xa2)), (str, "\n")]
327 out.data = []
328 out.encoding = "cp424" # ignored!
329 print(chr(0xa2))
330 assert out.data == [(str, chr(0xa2)), (str, "\n")]
331 del out.data[:]
332 del out.encoding
333 print("foo\t", "bar\n", "trick", "baz\n")
334 assert out.data == [(str, "foo\t"),
335 (str, " "),
336 (str, "bar\n"),
337 (str, " "),
338 (str, "trick"),
339 (str, " "),
340 (str, "baz\n"),
341 (str, "\n")]
342 finally:
343 sys.stdout = save
344
345 def test_print_strange_object(self):
346 import sys
347
348 class A(object):
349 def __getattribute__(self, name):
350 print("seeing", name)
351 def __str__(self):
352 return 'A!!'
353 save = sys.stdout
354 class Out(object):
355 def __init__(self):
356 self.data = []
357 def write(self, x):
358 self.data.append((type(x), x))
359 sys.stdout = out = Out()
360 try:
361 a = A()
362 assert out.data == []
363 print(a)
364 assert out.data == [(str, 'A!!'),
365 (str, '\n')]
366 finally:
367 sys.stdout = save
368
369 def test_identity(self):
370 def f(x): return x
371 assert f(666) == 666
372
373 def test_raise_recursion(self):
374 def f(): f()
375 try:
376 f()
377 except RecursionError as e:
378 assert str(e) == "maximum recursion depth exceeded"
379 else:
380 assert 0, "should have raised!"
381
382 def test_kwonlyargs_mixed_args(self):
383 """
384 def mixedargs_sum(a, b=0, *args, k1, k2=0):
385 return a + b + k1 + k2 + sum(args)
386 assert mixedargs_sum.__code__.co_varnames == ("a", "b", "k1", "k2", "args")
387 assert mixedargs_sum(1, k1=2) == 1 + 2
388 """
389
390 def test_kwonlyargs_lambda(self):
391 """
392 l = lambda x, y, *, k=20: x+y+k
393 assert l(1, 2) == 1 + 2 + 20
394 assert l(1, 2, k=10) == 1 + 2 + 10
395 """
396
397 def test_kwonlyarg_mangling(self):
398 """
399 class X:
400 def f(self, *, __a=42):
401 return __a
402 assert X().f() == 42
403 """
404
405 def test_kwonlyarg_required(self):
406 """
407 def f(*, a=5, b):
408 return (a, b)
409 assert f(b=10) == (5, 10)
410 assert f(a=7, b=12) == (7, 12)
411 raises(TypeError, f)
412 raises(TypeError, f, 1)
413 raises(TypeError, f, 1, 1)
414 raises(TypeError, f, a=1)
415 raises(TypeError, f, 1, a=1)
416 raises(TypeError, f, 1, b=1)
417 """
418
419 def test_extended_unpacking_short(self):
420 """
421 class Seq:
422 def __getitem__(self, i):
423 if i >= 0 and i < 3: return i
424 raise IndexError
425 try:
426 a, *b, c, d, e = Seq()
427 except ValueError as e:
428 assert str(e) == "not enough values to unpack (expected at least 4, got 3)"
429 else:
430 assert False, "Expected ValueError"
431 """
432
433 def test_errormsg_unpacking(self):
434 """
435 with raises(TypeError) as excinfo:
436 a, b, c = 1
437 assert str(excinfo.value) == "cannot unpack non-iterable int object"
438
439 with raises(TypeError) as excinfo:
440 a, *b, c = 1
441 assert str(excinfo.value) == "cannot unpack non-iterable int object"
442
443 with raises(TypeError) as excinfo:
444 for a, b in range(10):
445 pass
446 assert str(excinfo.value) == "cannot unpack non-iterable int object"
447 """