Debian Codegraph @

pypy/module/_cppyy/test/test_crossing.py

raw symbols SCIP
1 import py, os, sys
2 from .support import setup_make, soext
3
4 from pypy.interpreter.gateway import interp2app, unwrap_spec
5 from rpython.translator.tool.cbuild import ExternalCompilationInfo
6 from rpython.translator import platform
7 from rpython.translator.gensupp import uniquemodulename
8 from rpython.tool.udir import udir
9
10 from pypy.module.cpyext import api
11 from pypy.module.cpyext.state import State
12
13 currpath = py.path.local(__file__).dirpath()
14 test_dct = str(currpath.join("crossingDict"))+soext
15
16 def setup_module(mod):
17 setup_make("crossing")
18
19
20 # from pypy/module/cpyext/test/test_cpyext.py; modified to accept more external
21 # symbols and called directly instead of import_module
22 def compile_extension_module(space, modname, **kwds):
23 """
24 Build an extension module and return the filename of the resulting native
25 code file.
26
27 modname is the name of the module, possibly including dots if it is a module
28 inside a package.
29
30 Any extra keyword arguments are passed on to ExternalCompilationInfo to
31 build the module (so specify your source with one of those).
32 """
33 state = space.fromcache(State)
34 api_library = state.api_lib
35 if sys.platform == 'win32':
36 kwds["libraries"] = []#[api_library]
37 # '%s' undefined; assuming extern returning int
38 kwds["compile_extra"] = ["/we4013"]
39 # prevent linking with PythonXX.lib
40 w_maj, w_min = space.fixedview(space.sys.get('version_info'), 5)[:2]
41 kwds["link_extra"] = ["/NODEFAULTLIB:Python%d%d.lib" %
42 (space.int_w(w_maj), space.int_w(w_min))]
43 elif sys.platform == 'darwin':
44 kwds["link_files"] = [str(api_library + '.dylib')]
45 else:
46 kwds["link_files"] = [str(api_library + '.so')]
47 if sys.platform.startswith('linux'):
48 kwds["compile_extra"]=["-Werror", "-g", "-O0"]
49 kwds["link_extra"]=["-g"]
50
51 modname = modname.split('.')[-1]
52 eci = ExternalCompilationInfo(
53 include_dirs=api.include_dirs,
54 **kwds
55 )
56 eci = eci.convert_sources_to_files()
57 dirname = (udir/uniquemodulename('module')).ensure(dir=1)
58 soname = platform.platform.compile(
59 [], eci,
60 outputfilename=str(dirname/modname),
61 standalone=False)
62 from pypy.module.imp.importing import get_so_extension
63 pydname = soname.new(purebasename=modname, ext=get_so_extension(space))
64 soname.rename(pydname)
65 return str(pydname)
66
67 class AppTestCrossing:
68 spaceconfig = dict(usemodules=['_cppyy', '_rawffi', 'itertools'])
69
70 def setup_class(cls):
71 # _cppyy specific additions (note that test_dct is loaded late
72 # to allow the generated extension module be loaded first)
73 cls.w_test_dct = cls.space.newtext(test_dct)
74 cls.w_pre_imports = cls.space.appexec([], """():
75 import ctypes, _cppyy
76 _cppyy._post_import_startup()""") # early import of ctypes
77 # prevents leak-checking complaints on ctypes' statics
78
79 def setup_method(self, func):
80 @unwrap_spec(name='text', init='text', body='text')
81 def create_cdll(space, name, init, body):
82 # the following is loosely from test_cpyext.py import_module; it
83 # is copied here to be able to tweak the call to
84 # compile_extension_module and to get a different return result
85 # than in that function
86 code = """
87 #include <Python.h>
88 /* fix for cpython 2.7 Python.h if running tests with -A
89 since pypy compiles with -fvisibility-hidden */
90 #undef PyMODINIT_FUNC
91 #define PyMODINIT_FUNC RPY_EXPORTED void
92
93 %(body)s
94
95 PyMODINIT_FUNC
96 #if PY_MAJOR_VERSION >= 3
97 PyInit_%(name)s(void)
98 #else
99 init%(name)s(void)
100 #endif
101 {
102 %(init)s
103 }
104 """ % dict(name=name, init=init, body=body)
105 kwds = dict(separate_module_sources=[code])
106 mod = compile_extension_module(space, name, **kwds)
107
108 # explicitly load the module as a CDLL rather than as a module
109 from pypy.module.imp.importing import get_so_extension
110 fullmodname = os.path.join(
111 os.path.dirname(mod), name + get_so_extension(space))
112 return space.newtext(fullmodname)
113
114 self.w_create_cdll = self.space.wrap(interp2app(create_cdll))
115
116 def test01_build_bar_extension(self):
117 """Test that builds the needed extension; runs as test to keep it loaded"""
118
119 import os, ctypes
120
121 name = 'bar'
122
123 init = """
124 #if PY_MAJOR_VERSION >= 3
125 static struct PyModuleDef moduledef = {
126 PyModuleDef_HEAD_INIT,
127 "bar", "Module Doc", -1, methods, NULL, NULL, NULL, NULL,
128 };
129 #endif
130
131 if (Py_IsInitialized()) {
132 #if PY_MAJOR_VERSION >= 3
133 PyObject *module = PyModule_Create(&moduledef);
134 #else
135 Py_InitModule("bar", methods);
136 #endif
137 }
138 """
139
140 # note: only the symbols are needed for C, none for python
141 body = """
142 RPY_EXPORTED
143 long bar_unwrap(PyObject* arg)
144 {
145 return 13;//PyLong_AsLong(arg);
146 }
147 RPY_EXPORTED
148 PyObject* bar_wrap(long l)
149 {
150 return PyLong_FromLong(l);
151 }
152 static PyMethodDef methods[] = {
153 { NULL }
154 };
155 """
156 # explicitly load the module as a CDLL rather than as a module
157 import ctypes
158 self.cmodule = ctypes.CDLL(
159 self.create_cdll(name, init, body), ctypes.RTLD_GLOBAL)
160
161 def test02_crossing_dict(self):
162 """Test availability of all needed classes in the dict"""
163
164 import _cppyy, ctypes
165 lib = ctypes.CDLL(self.test_dct, ctypes.RTLD_GLOBAL)
166
167 assert _cppyy.gbl.crossing == _cppyy.gbl.crossing
168 crossing = _cppyy.gbl.crossing
169
170 assert crossing.A == crossing.A
171
172 @py.test.mark.dont_track_allocations("fine when running standalone, though?!")
173 def test03_send_pyobject(self):
174 """Test sending a true pyobject to C++"""
175
176 import _cppyy
177 crossing = _cppyy.gbl.crossing
178
179 a = crossing.A()
180 assert a.unwrap(13) == 13
181
182 @py.test.mark.dont_track_allocations("fine when running standalone, though?!")
183 def test04_send_and_receive_pyobject(self):
184 """Test receiving a true pyobject from C++"""
185
186 import _cppyy
187 crossing = _cppyy.gbl.crossing
188
189 a = crossing.A()
190
191 assert a.wrap(41) == 41