Debian Codegraph @

pypy/module/cpyext/test/test_eval.py

raw symbols SCIP
1 import sys
2 import os
3 import pytest
4 from rpython.rtyper.lltypesystem import rffi, lltype
5 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
6 from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
7 from pypy.module.cpyext.object import PyObject_Size, PyObject_GetItem
8 from pypy.module.cpyext.pythonrun import Py_AtExit
9 from pypy.module.cpyext.eval import (
10 Py_single_input, Py_file_input, Py_eval_input, PyCompilerFlags,
11 PyEval_CallObjectWithKeywords, PyObject_CallObject, PyEval_EvalCode,
12 PyRun_SimpleString, PyRun_String, PyRun_StringFlags, PyRun_File,
13 PyEval_GetLocals, PyEval_GetGlobals,
14 _PyEval_SliceIndex)
15 from pypy.module.cpyext.api import (
16 c_fopen, c_fclose, c_fileno, Py_ssize_tP)
17 from pypy.module.cpyext.pyobject import get_w_obj_and_decref
18 from pypy.interpreter.gateway import interp2app
19 from pypy.interpreter.error import OperationError
20 from pypy.interpreter.astcompiler import consts
21 from rpython.tool.udir import udir
22
23 class TestEval(BaseApiTest):
24 def test_eval(self, space):
25 w_l, w_f = space.fixedview(space.appexec([], """():
26 l = []
27 def f(arg1, arg2):
28 l.append(arg1)
29 l.append(arg2)
30 return len(l)
31 return l, f
32 """))
33
34 w_t = space.newtuple([space.wrap(1), space.wrap(2)])
35 w_res = PyEval_CallObjectWithKeywords(space, w_f, w_t, None)
36 assert space.int_w(w_res) == 2
37 assert space.len_w(w_l) == 2
38 w_f = space.appexec([], """():
39 def f(*args, **kwds):
40 assert isinstance(kwds, dict)
41 assert 'xyz' in kwds
42 return len(kwds) + len(args) * 10
43 return f
44 """)
45 w_t = space.newtuple([space.w_None, space.w_None])
46 w_d = space.newdict()
47 space.setitem(w_d, space.wrap("xyz"), space.wrap(3))
48 w_res = PyEval_CallObjectWithKeywords(space, w_f, w_t, w_d)
49 assert space.int_w(w_res) == 21
50
51 def test_call_object(self, space):
52 w_l, w_f = space.fixedview(space.appexec([], """():
53 l = []
54 def f(arg1, arg2):
55 l.append(arg1)
56 l.append(arg2)
57 return len(l)
58 return l, f
59 """))
60
61 w_t = space.newtuple([space.wrap(1), space.wrap(2)])
62 w_res = PyObject_CallObject(space, w_f, w_t)
63 assert space.int_w(w_res) == 2
64 assert space.len_w(w_l) == 2
65
66 w_f = space.appexec([], """():
67 def f(*args):
68 assert isinstance(args, tuple)
69 return len(args) + 8
70 return f
71 """)
72
73 w_t = space.newtuple([space.wrap(1), space.wrap(2)])
74 w_res = PyObject_CallObject(space, w_f, w_t)
75
76 assert space.int_w(w_res) == 10
77
78 def test_evalcode(self, space):
79 w_f = space.appexec([], """():
80 def f(*args):
81 assert isinstance(args, tuple)
82 return len(args) + 8
83 return f
84 """)
85
86 w_t = space.newtuple([space.wrap(1), space.wrap(2)])
87 w_globals = space.newdict()
88 w_locals = space.newdict()
89 space.setitem(w_locals, space.wrap("args"), w_t)
90 w_res = PyEval_EvalCode(space, w_f.code, w_globals, w_locals)
91
92 assert space.int_w(w_res) == 10
93
94 def test_run_simple_string(self, space):
95 def run(code):
96 buf = rffi.str2charp(code)
97 try:
98 return PyRun_SimpleString(space, buf)
99 finally:
100 rffi.free_charp(buf)
101
102 assert run("42 * 43") == 0 # no error
103 with pytest.raises(OperationError):
104 run("4..3 * 43")
105
106 def test_run_string(self, space):
107 def run(code, start, w_globals, w_locals):
108 buf = rffi.str2charp(code)
109 try:
110 return PyRun_String(space, buf, start, w_globals, w_locals)
111 finally:
112 rffi.free_charp(buf)
113
114 w_globals = space.newdict()
115 assert 42 * 43 == space.unwrap(
116 run("42 * 43", Py_eval_input, w_globals, w_globals))
117 # __builtins__ is added
118 assert PyObject_Size(space, w_globals) == 1
119
120 assert run("a = 42 * 43", Py_single_input,
121 w_globals, w_globals) == space.w_None
122 py_obj = PyObject_GetItem(space, w_globals, space.wrap("a"))
123 assert 42 * 43 == space.unwrap(get_w_obj_and_decref(space, py_obj))
124
125 def test_run_string_flags(self, space):
126 flags = lltype.malloc(PyCompilerFlags, flavor='raw')
127 flags.c_cf_flags = rffi.cast(rffi.INT, consts.PyCF_SOURCE_IS_UTF8)
128 flags.c_cf_feature_version = rffi.cast(rffi.INT, -1)
129 w_globals = space.newdict()
130 buf = rffi.str2charp("a = 'caf\xc3\xa9'")
131 try:
132 PyRun_StringFlags(space, buf, Py_single_input, w_globals,
133 w_globals, flags)
134 finally:
135 rffi.free_charp(buf)
136 w_a = space.getitem(w_globals, space.wrap("a"))
137 assert space.utf8_w(w_a) == u'caf\xe9'.encode("utf-8")
138 lltype.free(flags, flavor='raw')
139
140 def test_run_file(self, space):
141 filepath = udir / "cpyext_test_runfile.py"
142 filepath.write("raise ZeroDivisionError")
143 fp = c_fopen(str(filepath), "rb")
144 filename = rffi.str2charp(str(filepath))
145 w_globals = w_locals = space.newdict()
146 with raises_w(space, ZeroDivisionError):
147 PyRun_File(space, fp, filename, Py_file_input, w_globals, w_locals)
148 c_fclose(fp)
149
150 # try again, but with a closed file
151 if self.runappdirect:
152 # according to man 2 fclose, any access of fp is undefined
153 # behaviour. This crashes on some linux systems untranslated
154 fp = c_fopen(str(filepath), "rb")
155 c_fclose(fp)
156 with raises_w(space, IOError):
157 PyRun_File(space, fp, filename, Py_file_input, w_globals, w_locals)
158 rffi.free_charp(filename)
159
160 def test_getglobals(self, space):
161 assert PyEval_GetLocals(space) is None
162 assert PyEval_GetGlobals(space) is None
163
164 def cpyvars(space):
165 return space.newtuple([PyEval_GetGlobals(space),
166 PyEval_GetLocals(space)])
167 w_cpyvars = space.wrap(interp2app(cpyvars))
168
169 w_result = space.appexec([w_cpyvars], """(cpyvars):
170 x = 1
171 return cpyvars()
172 \ny = 2
173 """)
174 globals, locals = space.unwrap(w_result)
175 assert sorted(locals) == ['cpyvars', 'x']
176 assert sorted(globals) == ['__builtins__', 'anonymous', 'y']
177
178 def test_sliceindex(self, space):
179 pi = lltype.malloc(Py_ssize_tP.TO, 1, flavor='raw')
180 with pytest.raises(OperationError):
181 _PyEval_SliceIndex(space, space.w_None, pi)
182
183 assert _PyEval_SliceIndex(space, space.wrap(123), pi) == 1
184 assert pi[0] == 123
185
186 assert _PyEval_SliceIndex(space, space.wrap(1 << 66), pi) == 1
187 assert pi[0] == sys.maxint
188
189 lltype.free(pi, flavor='raw')
190
191 def test_atexit(self, space):
192 lst = []
193 def func():
194 lst.append(42)
195 Py_AtExit(space, func)
196 cpyext = space.getbuiltinmodule('cpyext')
197 cpyext.shutdown(space) # simulate shutdown
198 assert lst == [42]
199
200 class AppTestCall(AppTestCpythonExtensionBase):
201 def test_CallFunction(self):
202 module = self.import_extension('foo', [
203 ("call_func", "METH_VARARGS",
204 """
205 return PyObject_CallFunction(PyTuple_GetItem(args, 0),
206 "siiiiO", "text", 42, -41, 40, -39, Py_None);
207 """),
208 ("call_method", "METH_VARARGS",
209 """
210 return PyObject_CallMethod(PyTuple_GetItem(args, 0),
211 "count", "s", "t");
212 """),
213 ])
214 def f(*args):
215 return args
216 assert module.call_func(f) == ("text", 42, -41, 40, -39, None)
217 assert module.call_method("text") == 2
218
219 def test_CallFunction_PY_SSIZE_T_CLEAN(self):
220 module = self.import_extension('foo', [
221 ("call_func", "METH_VARARGS",
222 """
223 return PyObject_CallFunction(PyTuple_GetItem(args, 0),
224 "s#s#", "text", (Py_ssize_t)3, "othertext", (Py_ssize_t)6);
225 """),
226 ("call_method", "METH_VARARGS",
227 """
228 return PyObject_CallMethod(PyTuple_GetItem(args, 0),
229 "find", "s#", "substring", (Py_ssize_t)6);
230 """),
231 ], PY_SSIZE_T_CLEAN=True)
232 def f(*args):
233 return args
234 assert module.call_func(f) == ("tex", "othert")
235 assert module.call_method("<<subst>>") == -1
236 assert module.call_method("<<substr>>") == 2
237
238 def test_CallFunctionObjArgs(self):
239 module = self.import_extension('foo', [
240 ("call_func", "METH_VARARGS",
241 """
242 PyObject *t = PyUnicode_FromString("t");
243 PyObject *res = PyObject_CallFunctionObjArgs(
244 PyTuple_GetItem(args, 0),
245 Py_None, NULL);
246 Py_DECREF(t);
247 return res;
248 """),
249 ("call_method", "METH_VARARGS",
250 """
251 PyObject *t = PyUnicode_FromString("t");
252 PyObject *count = PyUnicode_FromString("count");
253 PyObject *res = PyObject_CallMethodObjArgs(
254 PyTuple_GetItem(args, 0),
255 count, t, NULL);
256 Py_DECREF(t);
257 Py_DECREF(count);
258 return res;
259 """),
260 ("test_callnoarg", "METH_VARARGS",
261 '''
262 PyObject *func = NULL;
263 if (!PyArg_ParseTuple(args, "O", &func)) {
264 return NULL;
265 }
266 return PyObject_CallNoArgs(func);
267 '''),
268 ("test_callonearg", "METH_VARARGS",
269 '''
270 PyObject *func = NULL, *arg = NULL;
271 if (!PyArg_ParseTuple(args, "OO", &func, &arg)) {
272 return NULL;
273 }
274 return PyObject_CallOneArg(func, arg);
275 '''),
276 ("test_callmethod_noargs", "METH_VARARGS",
277 '''
278 PyObject *func = NULL, *arg = NULL;
279 if (!PyArg_ParseTuple(args, "OO", &func, &arg)) {
280 return NULL;
281 }
282 return PyObject_CallMethodNoArgs(func, arg);
283 '''),
284 ("test_callmethod_onearg", "METH_VARARGS",
285 '''
286 PyObject *func = NULL, *name = NULL, *arg = NULL;
287 if (!PyArg_ParseTuple(args, "OOO", &func, &name, &arg)) {
288 return NULL;
289 }
290 return PyObject_CallMethodOneArg(func, name, arg);
291 '''),
292 ])
293
294 def f(*args):
295 return args
296
297 class A():
298 def meth(self, *args):
299 return args
300
301 a = A()
302 assert module.call_func(f) == (None,)
303 assert module.call_method("text") == 2
304 module.test_callnoarg(f) == ()
305 module.test_callonearg(f, 4) == (4,)
306 assert module.test_callmethod_noargs(a, "meth") == ()
307 assert module.test_callmethod_onearg(a, "meth", 4) == (4,)
308
309 def test_CompileString_and_Exec(self):
310 import sys
311 module = self.import_extension('foo', [
312 ("compile_string", "METH_NOARGS",
313 """
314 return Py_CompileString(
315 "f = lambda x: x+5", "someFile", Py_file_input);
316 """),
317 ("exec_code", "METH_O",
318 """
319 return PyImport_ExecCodeModule("cpyext_test_modname", args);
320 """),
321 ("exec_code_ex", "METH_O",
322 """
323 return PyImport_ExecCodeModuleEx("cpyext_test_modname",
324 args, "otherFile");
325 """),
326 ])
327 code = module.compile_string()
328 assert code.co_filename == "someFile"
329 assert code.co_name == "<module>"
330
331 mod = module.exec_code(code)
332 assert mod.__name__ == "cpyext_test_modname"
333 assert mod.__file__ == "someFile"
334 print(dir(mod))
335 print(mod.__dict__)
336 assert mod.f(42) == 47
337
338 mod = module.exec_code_ex(code)
339 assert mod.__name__ == "cpyext_test_modname"
340 assert mod.__file__ == "otherFile"
341 print(dir(mod))
342 print(mod.__dict__)
343 assert mod.f(42) == 47
344
345 # Clean-up
346 del sys.modules['cpyext_test_modname']
347
348 def test_merge_compiler_flags(self):
349 import sys
350 module = self.import_extension('foo', [
351 ("get_flags", "METH_NOARGS",
352 """
353 PyCompilerFlags flags;
354 int result;
355 flags.cf_flags = 0;
356 result = PyEval_MergeCompilerFlags(&flags);
357 return Py_BuildValue("ii", result, flags.cf_flags);
358 """),
359 ])
360 assert module.get_flags() == (0, 0)
361
362 ns = {'module': module}
363 if not hasattr(sys, 'pypy_version_info'): # no barry_as_FLUFL on pypy
364 exec("""from __future__ import barry_as_FLUFL \nif 1:
365 def nested_flags():
366 return module.get_flags()""", ns)
367 assert ns['nested_flags']() == (1, 0x40000)
368
369 # the division future should have no effect on Python 3
370 exec("""from __future__ import division \nif 1:
371 def nested_flags():
372 return module.get_flags()""", ns)
373 assert ns['nested_flags']() == (0, 0)
374
375 @pytest.mark.xfail("'linux' not in sys.platform", reason='Hangs the process', run=False)
376 def test_recursive_function(self):
377 module = self.import_extension('foo', [
378 ("call_recursive", "METH_NOARGS",
379 """
380 int oldlimit;
381 int recurse(void);
382 res = 0;
383 oldlimit = Py_GetRecursionLimit();
384 Py_SetRecursionLimit(oldlimit/100);
385 res = recurse();
386 Py_SetRecursionLimit(oldlimit);
387 if (PyErr_Occurred())
388 return NULL;
389 return PyLong_FromLong(res);
390 """),], prologue= '''
391 int res;
392 int recurse(void) {
393 if (Py_EnterRecursiveCall(" while calling recurse")) {
394 return -1;
395 }
396 res ++;
397 return recurse();
398 };
399 '''
400 )
401 excinfo = raises(RecursionError, module.call_recursive)
402 assert 'while calling recurse' in str(excinfo.value)
403
404 def test_build_class(self):
405 """
406 # make sure PyObject_Call generates a proper PyTypeObject,
407 # along the way verify that userslot has iter and next
408 module = self.import_extension('foo', [
409 ("object_call", "METH_O",
410 '''
411 return PyObject_Call((PyObject*)&PyType_Type, args, NULL);
412 '''),
413 ('iter', "METH_O",
414 '''
415 if (NULL == args->ob_type->tp_iter)
416 {
417 PyErr_SetString(PyExc_TypeError, "NULL tp_iter");
418 return NULL;
419 }
420 return args->ob_type->tp_iter(args);
421 '''),
422 ('next', "METH_O",
423 '''
424 if (NULL == args->ob_type->tp_iternext)
425 {
426 PyErr_SetString(PyExc_TypeError, "NULL tp_iternext");
427 return NULL;
428 }
429 return args->ob_type->tp_iternext(args);
430 '''),
431 ('await_', "METH_O",
432 '''
433 if (NULL == args->ob_type->tp_as_async->am_await)
434 {
435 PyErr_SetString(PyExc_TypeError, "NULL am_await");
436 return NULL;
437 }
438 return args->ob_type->tp_as_async->am_await(args);
439 '''),
440 ('aiter', "METH_O",
441 '''
442 if (NULL == args->ob_type->tp_as_async->am_aiter)
443 {
444 PyErr_SetString(PyExc_TypeError, "NULL am_aiter");
445 return NULL;
446 }
447 return args->ob_type->tp_as_async->am_aiter(args);
448 '''),
449 ('anext', "METH_O",
450 '''
451 if (NULL == args->ob_type->tp_as_async->am_anext)
452 {
453 PyErr_SetString(PyExc_TypeError, "NULL am_anext");
454 return NULL;
455 }
456 return args->ob_type->tp_as_async->am_anext(args);
457 '''),
458 ])
459 def __init__(self, N):
460 self.N = N
461 self.i = 0
462
463 def __iter__(self):
464 return self
465
466 def __next__(self):
467 if self.i < self.N:
468 i = self.i
469 self.i += 1
470 return i
471 raise StopIteration
472
473 d = {'__init__': __init__, '__iter__': __iter__, 'next': __next__,
474 '__next__': __next__}
475 C = module.object_call(('Iterable', (object,), d))
476 c = C(5)
477 i = module.iter(c)
478 out = []
479 try:
480 while 1:
481 out.append(module.next(i))
482 except StopIteration:
483 pass
484 assert out == [0, 1, 2, 3, 4]
485
486 def run_async(coro):
487 buffer = []
488 result = None
489 while True:
490 try:
491 buffer.append(coro.send(None))
492 except StopIteration as ex:
493 result = ex.value
494 break
495 return buffer, result
496
497 def __await__(self):
498 yield 42
499 return 100
500
501 Awaitable = module.object_call((
502 'Awaitable', (object,), {'__await__': __await__}))
503
504 async def wrapper():
505 return await Awaitable()
506
507 assert run_async(module.await_(Awaitable())) == ([42], 100)
508 assert run_async(wrapper()) == ([42], 100)
509
510 def __aiter__(self):
511 return self
512
513 async def __anext__(self):
514 if self.i < self.N:
515 res = self.i
516 self.i += 1
517 return res
518 raise StopAsyncIteration
519
520 AIter = module.object_call(('AIter', (object,),
521 {'__init__': __init__, '__aiter__': __aiter__,
522 '__anext__': __anext__}))
523
524 async def list1():
525 s = []
526 async for i in AIter(3):
527 s.append(i)
528 return s
529 async def list2():
530 s = []
531 ait = module.aiter(AIter(3))
532 try:
533 while True:
534 s.append(await module.anext(ait))
535 except StopAsyncIteration:
536 return s
537
538 assert run_async(list1()) == ([], [0, 1, 2])
539 assert run_async(list2()) == ([], [0, 1, 2])
540 """
541
542 def test_getframe(self):
543 import sys
544 module = self.import_extension('foo', [
545 ("getframe1", "METH_NOARGS",
546 """
547 PyFrameObject *x = PyEval_GetFrame();
548 Py_INCREF(x);
549 return (PyObject *)x;
550 """),], prologue="#include <frameobject.h>\n")
551 res = module.getframe1()
552 assert res is sys._getframe(0)
553
554 def test_getbuiltins(self):
555 module = self.import_extension('foo', [
556 ("getbuiltins", "METH_NOARGS",
557 """
558 /* borrowed ref */
559 PyObject *ret = PyEval_GetBuiltins();
560 Py_INCREF(ret);
561 return ret;
562 """)])
563 builtins = module.getbuiltins()
564 assert builtins is __builtins__.__dict__
565
566 def cpybuiltins():
567 return module.getbuiltins()
568 d = dict(__builtins__ = {'sum': sum}, cpybuiltins=cpybuiltins)
569 result = eval("cpybuiltins()", d, d)
570 assert len(result) == len(builtins)
571
572