Debian Codegraph @

extra_tests/cffi_tests/cffi1/test_re_python.py

raw symbols SCIP
1 # Generated by pypy/tool/import_cffi.py
2 import sys, os
3 import pytest
4 from cffi import FFI
5 from cffi import recompiler, ffiplatform, VerificationMissing
6 from extra_tests.cffi_tests.udir import udir
7 from extra_tests.cffi_tests.support import u, is_musl
8
9
10 def setup_module(mod):
11 SRC = """
12 #include <string.h>
13 #define FOOBAR (-42)
14 static const int FOOBAZ = -43;
15 #define BIGPOS 420000000000L
16 #define BIGNEG -420000000000L
17 int add42(int x) { return x + 42; }
18 int add43(int x, ...) { return x; }
19 int globalvar42 = 1234;
20 const int globalconst42 = 4321;
21 const char *const globalconsthello = "hello";
22 struct foo_s;
23 typedef struct bar_s { int x; signed char a[]; } bar_t;
24 enum foo_e { AA, BB, CC };
25
26 void init_test_re_python(void) { } /* windows hack */
27 void PyInit__test_re_python(void) { } /* windows hack */
28 """
29 tmpdir = udir.join('test_re_python')
30 tmpdir.ensure(dir=1)
31 c_file = tmpdir.join('_test_re_python.c')
32 c_file.write(SRC)
33 ext = ffiplatform.get_extension(
34 str(c_file),
35 '_test_re_python',
36 export_symbols=['add42', 'add43', 'globalvar42',
37 'globalconst42', 'globalconsthello']
38 )
39 outputfilename = ffiplatform.compile(str(tmpdir), ext)
40
41 # test with a non-ascii char
42 ofn, oext = os.path.splitext(outputfilename)
43 if sys.platform == "win32":
44 unicode_name = ofn + (u+'\u03be') + oext
45 else:
46 unicode_name = ofn + (u+'\xe9') + oext
47 try:
48 unicode_name.encode(sys.getfilesystemencoding())
49 except UnicodeEncodeError:
50 unicode_name = None
51 if unicode_name is not None:
52 print(repr(outputfilename) + ' ==> ' + repr(unicode_name))
53 os.rename(outputfilename, unicode_name)
54 outputfilename = unicode_name
55
56 mod.extmod = outputfilename
57 mod.tmpdir = tmpdir
58 #
59 ffi = FFI()
60 ffi.cdef("""
61 #define FOOBAR -42
62 static const int FOOBAZ = -43;
63 #define BIGPOS 420000000000L
64 #define BIGNEG -420000000000L
65 int add42(int);
66 int add43(int, ...);
67 extern int globalvar42;
68 const int globalconst42;
69 const char *const globalconsthello;
70 int no_such_function(int);
71 extern int no_such_globalvar;
72 struct foo_s;
73 typedef struct bar_s { int x; signed char a[]; } bar_t;
74 enum foo_e { AA, BB, CC };
75 int strlen(const char *);
76 struct with_union { union { int a; char b; }; };
77 union with_struct { struct { int a; char b; }; };
78 struct with_struct_with_union { struct { union { int x; }; } cp; };
79 struct NVGcolor { union { float rgba[4]; struct { float r,g,b,a; }; }; };
80 typedef struct selfref { struct selfref *next; } *selfref_ptr_t;
81 """)
82 ffi.set_source('re_python_pysrc', None)
83 ffi.emit_python_code(str(tmpdir.join('re_python_pysrc.py')))
84 mod.original_ffi = ffi
85 #
86 sys.path.insert(0, str(tmpdir))
87
88
89 def test_constant():
90 from re_python_pysrc import ffi
91 assert ffi.integer_const('FOOBAR') == -42
92 assert ffi.integer_const('FOOBAZ') == -43
93
94 def test_large_constant():
95 from re_python_pysrc import ffi
96 assert ffi.integer_const('BIGPOS') == 420000000000
97 assert ffi.integer_const('BIGNEG') == -420000000000
98
99 def test_function():
100 import _cffi_backend
101 from re_python_pysrc import ffi
102 lib = ffi.dlopen(extmod)
103 assert lib.add42(-10) == 32
104 assert type(lib.add42) is _cffi_backend.FFI.CData
105
106 def test_function_with_varargs():
107 import _cffi_backend
108 from re_python_pysrc import ffi
109 lib = ffi.dlopen(extmod, 0)
110 assert lib.add43(45, ffi.cast("int", -5)) == 45
111 assert type(lib.add43) is _cffi_backend.FFI.CData
112
113 def test_dlopen_none():
114 import _cffi_backend
115 from re_python_pysrc import ffi
116 name = None
117 if sys.platform == 'win32':
118 import ctypes.util
119 name = ctypes.util.find_msvcrt()
120 if name is None:
121 pytest.skip("dlopen(None) cannot work on Windows with Python 3")
122 lib = ffi.dlopen(name)
123 assert lib.strlen(b"hello") == 5
124
125 def test_dlclose():
126 import _cffi_backend
127 from re_python_pysrc import ffi
128 lib = ffi.dlopen(extmod)
129 ffi.dlclose(lib)
130 if type(extmod) is not str: # unicode, on python 2
131 str_extmod = extmod.encode('utf-8')
132 else:
133 str_extmod = extmod
134 e = pytest.raises(ffi.error, getattr, lib, 'add42')
135 assert str(e.value) == (
136 "library '%s' has been closed" % (str_extmod,))
137 ffi.dlclose(lib) # does not raise
138
139 def test_constant_via_lib():
140 from re_python_pysrc import ffi
141 lib = ffi.dlopen(extmod)
142 assert lib.FOOBAR == -42
143 assert lib.FOOBAZ == -43
144
145 def test_opaque_struct():
146 from re_python_pysrc import ffi
147 ffi.cast("struct foo_s *", 0)
148 pytest.raises(TypeError, ffi.new, "struct foo_s *")
149
150 def test_nonopaque_struct():
151 from re_python_pysrc import ffi
152 for p in [ffi.new("struct bar_s *", [5, b"foobar"]),
153 ffi.new("bar_t *", [5, b"foobar"])]:
154 assert p.x == 5
155 assert p.a[0] == ord('f')
156 assert p.a[5] == ord('r')
157
158 def test_enum():
159 from re_python_pysrc import ffi
160 assert ffi.integer_const("BB") == 1
161 e = ffi.cast("enum foo_e", 2)
162 assert ffi.string(e) == "CC"
163
164 def test_include_1():
165 sub_ffi = FFI()
166 sub_ffi.cdef("static const int k2 = 121212;")
167 sub_ffi.include(original_ffi)
168 assert 'macro FOOBAR' in original_ffi._parser._declarations
169 assert 'macro FOOBAZ' in original_ffi._parser._declarations
170 sub_ffi.set_source('re_python_pysrc', None)
171 sub_ffi.emit_python_code(str(tmpdir.join('_re_include_1.py')))
172 #
173 if sys.version_info[:2] >= (3, 3):
174 import importlib
175 importlib.invalidate_caches() # issue 197 (but can't reproduce myself)
176 #
177 from _re_include_1 import ffi
178 assert ffi.integer_const('FOOBAR') == -42
179 assert ffi.integer_const('FOOBAZ') == -43
180 assert ffi.integer_const('k2') == 121212
181 lib = ffi.dlopen(extmod) # <- a random unrelated library would be fine
182 assert lib.FOOBAR == -42
183 assert lib.FOOBAZ == -43
184 assert lib.k2 == 121212
185 #
186 p = ffi.new("bar_t *", [5, b"foobar"])
187 assert p.a[4] == ord('a')
188
189 def test_global_var():
190 from re_python_pysrc import ffi
191 lib = ffi.dlopen(extmod)
192 assert lib.globalvar42 == 1234
193 p = ffi.addressof(lib, 'globalvar42')
194 lib.globalvar42 += 5
195 assert p[0] == 1239
196 p[0] -= 1
197 assert lib.globalvar42 == 1238
198
199 def test_global_const_int():
200 from re_python_pysrc import ffi
201 lib = ffi.dlopen(extmod)
202 assert lib.globalconst42 == 4321
203 pytest.raises(AttributeError, ffi.addressof, lib, 'globalconst42')
204
205 def test_global_const_nonint():
206 from re_python_pysrc import ffi
207 lib = ffi.dlopen(extmod)
208 assert ffi.string(lib.globalconsthello, 8) == b"hello"
209 pytest.raises(AttributeError, ffi.addressof, lib, 'globalconsthello')
210
211 def test_rtld_constants():
212 from re_python_pysrc import ffi
213 ffi.RTLD_NOW # check that we have the attributes
214 ffi.RTLD_LAZY
215 ffi.RTLD_GLOBAL
216
217 def test_no_such_function_or_global_var():
218 from re_python_pysrc import ffi
219 lib = ffi.dlopen(extmod)
220 e = pytest.raises(ffi.error, getattr, lib, 'no_such_function')
221 assert str(e.value).startswith(
222 "symbol 'no_such_function' not found in library '")
223 e = pytest.raises(ffi.error, getattr, lib, 'no_such_globalvar')
224 assert str(e.value).startswith(
225 "symbol 'no_such_globalvar' not found in library '")
226
227 def test_check_version():
228 import _cffi_backend
229 e = pytest.raises(ImportError, _cffi_backend.FFI,
230 "foobar", _version=0x2594)
231 assert str(e.value).startswith(
232 "cffi out-of-line Python module 'foobar' has unknown version")
233
234 def test_partial_enum():
235 ffi = FFI()
236 ffi.cdef("enum foo { A, B, ... };")
237 ffi.set_source('test_partial_enum', None)
238 pytest.raises(VerificationMissing, ffi.emit_python_code,
239 str(tmpdir.join('test_partial_enum.py')))
240
241 def test_anonymous_union_inside_struct():
242 # based on issue #357
243 from re_python_pysrc import ffi
244 INT = ffi.sizeof("int")
245 assert ffi.offsetof("struct with_union", "a") == 0
246 assert ffi.offsetof("struct with_union", "b") == 0
247 assert ffi.sizeof("struct with_union") == INT
248 #
249 assert ffi.offsetof("union with_struct", "a") == 0
250 assert ffi.offsetof("union with_struct", "b") == INT
251 assert ffi.sizeof("union with_struct") >= INT + 1
252 #
253 assert ffi.sizeof("struct with_struct_with_union") == INT
254 p = ffi.new("struct with_struct_with_union *")
255 assert p.cp.x == 0
256 #
257 FLOAT = ffi.sizeof("float")
258 assert ffi.sizeof("struct NVGcolor") == FLOAT * 4
259 assert ffi.offsetof("struct NVGcolor", "rgba") == 0
260 assert ffi.offsetof("struct NVGcolor", "r") == 0
261 assert ffi.offsetof("struct NVGcolor", "g") == FLOAT
262 assert ffi.offsetof("struct NVGcolor", "b") == FLOAT * 2
263 assert ffi.offsetof("struct NVGcolor", "a") == FLOAT * 3
264
265 def test_selfref():
266 # based on issue #429
267 from re_python_pysrc import ffi
268 ffi.new("selfref_ptr_t")
269
270 def test_dlopen_handle():
271 import _cffi_backend
272 from re_python_pysrc import ffi
273 if sys.platform == 'win32' or is_musl:
274 pytest.skip("uses 'dl' explicitly")
275 ffi1 = FFI()
276 ffi1.cdef("""void *dlopen(const char *filename, int flags);
277 int dlclose(void *handle);""")
278 lib1 = ffi1.dlopen('dl')
279 handle = lib1.dlopen(extmod.encode(sys.getfilesystemencoding()),
280 _cffi_backend.RTLD_LAZY)
281 assert ffi1.typeof(handle) == ffi1.typeof("void *")
282 assert handle
283
284 lib = ffi.dlopen(handle)
285 assert lib.add42(-10) == 32
286 assert type(lib.add42) is _cffi_backend.FFI.CData
287
288 err = lib1.dlclose(handle)
289 assert err == 0