PageRenderTime 46ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/cpyext/test/test_eval.py

https://bitbucket.org/alex_gaynor/pypy-postgresql/
Python | 224 lines | 223 code | 1 blank | 0 comment | 0 complexity | 96c1a2b3c3f2cb5a27e0c1ce8b1dcf23 MD5 | raw file
  1. from pypy.rpython.lltypesystem import rffi, lltype
  2. from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
  3. from pypy.module.cpyext.test.test_api import BaseApiTest
  4. from pypy.module.cpyext.eval import (
  5. Py_single_input, Py_file_input, Py_eval_input)
  6. from pypy.module.cpyext.api import fopen, fclose, fileno, Py_ssize_tP
  7. from pypy.interpreter.gateway import interp2app
  8. from pypy.tool.udir import udir
  9. import sys, os
  10. class TestEval(BaseApiTest):
  11. def test_eval(self, space, api):
  12. w_l, w_f = space.fixedview(space.appexec([], """():
  13. l = []
  14. def f(arg1, arg2):
  15. l.append(arg1)
  16. l.append(arg2)
  17. return len(l)
  18. return l, f
  19. """))
  20. w_t = space.newtuple([space.wrap(1), space.wrap(2)])
  21. w_res = api.PyEval_CallObjectWithKeywords(w_f, w_t, None)
  22. assert space.int_w(w_res) == 2
  23. assert space.len_w(w_l) == 2
  24. w_f = space.appexec([], """():
  25. def f(*args, **kwds):
  26. assert isinstance(kwds, dict)
  27. assert 'xyz' in kwds
  28. return len(kwds) + len(args) * 10
  29. return f
  30. """)
  31. w_t = space.newtuple([space.w_None, space.w_None])
  32. w_d = space.newdict()
  33. space.setitem(w_d, space.wrap("xyz"), space.wrap(3))
  34. w_res = api.PyEval_CallObjectWithKeywords(w_f, w_t, w_d)
  35. assert space.int_w(w_res) == 21
  36. def test_call_object(self, space, api):
  37. w_l, w_f = space.fixedview(space.appexec([], """():
  38. l = []
  39. def f(arg1, arg2):
  40. l.append(arg1)
  41. l.append(arg2)
  42. return len(l)
  43. return l, f
  44. """))
  45. w_t = space.newtuple([space.wrap(1), space.wrap(2)])
  46. w_res = api.PyObject_CallObject(w_f, w_t)
  47. assert space.int_w(w_res) == 2
  48. assert space.len_w(w_l) == 2
  49. w_f = space.appexec([], """():
  50. def f(*args):
  51. assert isinstance(args, tuple)
  52. return len(args) + 8
  53. return f
  54. """)
  55. w_t = space.newtuple([space.wrap(1), space.wrap(2)])
  56. w_res = api.PyObject_CallObject(w_f, w_t)
  57. assert space.int_w(w_res) == 10
  58. def test_run_simple_string(self, space, api):
  59. def run(code):
  60. buf = rffi.str2charp(code)
  61. try:
  62. return api.PyRun_SimpleString(buf)
  63. finally:
  64. rffi.free_charp(buf)
  65. assert 0 == run("42 * 43")
  66. assert -1 == run("4..3 * 43")
  67. assert api.PyErr_Occurred()
  68. api.PyErr_Clear()
  69. def test_run_string(self, space, api):
  70. def run(code, start, w_globals, w_locals):
  71. buf = rffi.str2charp(code)
  72. try:
  73. return api.PyRun_String(buf, start, w_globals, w_locals)
  74. finally:
  75. rffi.free_charp(buf)
  76. w_globals = space.newdict()
  77. assert 42 * 43 == space.unwrap(
  78. run("42 * 43", Py_eval_input, w_globals, w_globals))
  79. assert api.PyObject_Size(w_globals) == 0
  80. assert run("a = 42 * 43", Py_single_input,
  81. w_globals, w_globals) == space.w_None
  82. assert 42 * 43 == space.unwrap(
  83. api.PyObject_GetItem(w_globals, space.wrap("a")))
  84. def test_run_file(self, space, api):
  85. filepath = udir / "cpyext_test_runfile.py"
  86. filepath.write("raise ZeroDivisionError")
  87. fp = fopen(str(filepath), "rb")
  88. filename = rffi.str2charp(str(filepath))
  89. w_globals = w_locals = space.newdict()
  90. api.PyRun_File(fp, filename, Py_file_input, w_globals, w_locals)
  91. fclose(fp)
  92. assert api.PyErr_Occurred() is space.w_ZeroDivisionError
  93. api.PyErr_Clear()
  94. # try again, but with a closed file
  95. fp = fopen(str(filepath), "rb")
  96. os.close(fileno(fp))
  97. api.PyRun_File(fp, filename, Py_file_input, w_globals, w_locals)
  98. fclose(fp)
  99. assert api.PyErr_Occurred() is space.w_IOError
  100. api.PyErr_Clear()
  101. rffi.free_charp(filename)
  102. def test_getbuiltins(self, space, api):
  103. assert api.PyEval_GetBuiltins() is space.builtin.w_dict
  104. def cpybuiltins(space):
  105. return api.PyEval_GetBuiltins()
  106. w_cpybuiltins = space.wrap(interp2app(cpybuiltins))
  107. w_result = space.appexec([w_cpybuiltins], """(cpybuiltins):
  108. return cpybuiltins() is __builtins__.__dict__
  109. """)
  110. assert space.is_true(w_result)
  111. w_result = space.appexec([w_cpybuiltins], """(cpybuiltins):
  112. d = dict(__builtins__={'len':len}, cpybuiltins=cpybuiltins)
  113. return eval("cpybuiltins()", d, d)
  114. """)
  115. assert space.len_w(w_result) == 1
  116. def test_getglobals(self, space, api):
  117. assert api.PyEval_GetLocals() is None
  118. assert api.PyEval_GetGlobals() is None
  119. def cpyvars(space):
  120. return space.newtuple([api.PyEval_GetGlobals(),
  121. api.PyEval_GetLocals()])
  122. w_cpyvars = space.wrap(interp2app(cpyvars))
  123. w_result = space.appexec([w_cpyvars], """(cpyvars):
  124. x = 1
  125. return cpyvars()
  126. \ny = 2
  127. """)
  128. globals, locals = space.unwrap(w_result)
  129. assert sorted(locals) == ['cpyvars', 'x']
  130. assert sorted(globals) == ['__builtins__', 'anonymous', 'y']
  131. def test_sliceindex(self, space, api):
  132. pi = lltype.malloc(Py_ssize_tP.TO, 1, flavor='raw')
  133. assert api._PyEval_SliceIndex(space.w_None, pi) == 0
  134. api.PyErr_Clear()
  135. assert api._PyEval_SliceIndex(space.wrap(123), pi) == 1
  136. assert pi[0] == 123
  137. assert api._PyEval_SliceIndex(space.wrap(1 << 66), pi) == 1
  138. assert pi[0] == sys.maxint
  139. lltype.free(pi, flavor='raw')
  140. def test_atexit(self, space, api):
  141. lst = []
  142. def func():
  143. lst.append(42)
  144. api.Py_AtExit(func)
  145. cpyext = space.getbuiltinmodule('cpyext')
  146. cpyext.shutdown(space) # simulate shutdown
  147. assert lst == [42]
  148. class AppTestCall(AppTestCpythonExtensionBase):
  149. def test_CallFunction(self):
  150. module = self.import_extension('foo', [
  151. ("call_func", "METH_VARARGS",
  152. """
  153. return PyObject_CallFunction(PyTuple_GetItem(args, 0),
  154. "siO", "text", 42, Py_None);
  155. """),
  156. ("call_method", "METH_VARARGS",
  157. """
  158. return PyObject_CallMethod(PyTuple_GetItem(args, 0),
  159. "count", "s", "t");
  160. """),
  161. ])
  162. def f(*args):
  163. return args
  164. assert module.call_func(f) == ("text", 42, None)
  165. assert module.call_method("text") == 2
  166. def test_CallFunctionObjArgs(self):
  167. module = self.import_extension('foo', [
  168. ("call_func", "METH_VARARGS",
  169. """
  170. PyObject *t = PyString_FromString("t");
  171. PyObject *res = PyObject_CallFunctionObjArgs(
  172. PyTuple_GetItem(args, 0),
  173. Py_None, NULL);
  174. Py_DECREF(t);
  175. return res;
  176. """),
  177. ("call_method", "METH_VARARGS",
  178. """
  179. PyObject *t = PyString_FromString("t");
  180. PyObject *count = PyString_FromString("count");
  181. PyObject *res = PyObject_CallMethodObjArgs(
  182. PyTuple_GetItem(args, 0),
  183. count, t, NULL);
  184. Py_DECREF(t);
  185. Py_DECREF(count);
  186. return res;
  187. """),
  188. ])
  189. def f(*args):
  190. return args
  191. assert module.call_func(f) == (None,)
  192. assert module.call_method("text") == 2