File: test_re_python.py

package info (click to toggle)
pypy3 7.3.19%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 212,236 kB
  • sloc: python: 2,098,316; ansic: 540,565; sh: 21,462; asm: 14,419; cpp: 4,451; makefile: 4,209; objc: 761; xml: 530; exp: 499; javascript: 314; pascal: 244; lisp: 45; csh: 12; awk: 4
file content (288 lines) | stat: -rw-r--r-- 10,300 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import py
import sys, shutil, os
from rpython.tool.udir import udir
from pypy.interpreter.gateway import interp2app
from pypy.module._cffi_backend.newtype import _clean_cache

if sys.platform == 'win32':
    WIN32 = True
else:
    WIN32 = False

class AppTestRecompilerPython:
    spaceconfig = dict(usemodules=['_cffi_backend'])

    def setup_class(cls):
        try:
            from cffi import FFI           # <== the system one, which
            from cffi import recompiler    # needs to be at least cffi 1.0.0
            from cffi import ffiplatform
        except ImportError:
            py.test.skip("system cffi module not found or older than 1.0.0")
        space = cls.space
        SRC = """
        #define FOOBAR (-42)
        static const int FOOBAZ = -43;
        #define BIGPOS 420000000000L
        #define BIGNEG -420000000000L
        int add42(int x) { return x + 42; }
        int globalvar42 = 1234;
        const int globalconst42 = 4321;
        const char *const globalconsthello = "hello";
        struct foo_s;
        typedef struct bar_s { int x; signed char a[]; } bar_t;
        enum foo_e { AA, BB, CC };
        struct B { struct C* c; }; struct C { struct B b; };

        void init_test_re_python(void) { }      /* windows hack */
        void PyInit__test_re_python(void) { }   /* windows hack */
        """
        tmpdir = udir.join('test_re_python')
        tmpdir.ensure(dir=1)
        c_file = tmpdir.join('_test_re_python.c')
        c_file.write(SRC)
        ext = ffiplatform.get_extension(str(c_file), '_test_re_python',
            export_symbols=['add42', 'globalvar42',
                            'globalconst42', 'globalconsthello'])
        outputfilename = ffiplatform.compile(str(tmpdir), ext)
        cls.w_extmod = space.wrap(outputfilename)
        if WIN32:
            unicode_name = u'load\u03betest.dll'
        else:
            unicode_name = u'load_caf\xe9' + os.path.splitext(outputfilename)[1]
            try:
                unicode_name.encode(sys.getfilesystemencoding())
            except UnicodeEncodeError:
                unicode_name = None    # skip test_dlopen_unicode
        if unicode_name is not None:
            outputfileUname = os.path.join(unicode(udir), unicode_name)
            shutil.copyfile(outputfilename, outputfileUname)
            cls.w_extmodU = space.wrap(outputfileUname)
        #mod.tmpdir = tmpdir
        #
        ffi = FFI()
        ffi.cdef("""
        #define FOOBAR -42
        static const int FOOBAZ = -43;
        #define BIGPOS 420000000000L
        #define BIGNEG -420000000000L
        int add42(int);
        int globalvar42;
        const int globalconst42;
        const char *const globalconsthello = "hello";
        int no_such_function(int);
        int no_such_globalvar;
        struct foo_s;
        typedef struct bar_s { int x; signed char a[]; } bar_t;
        enum foo_e { AA, BB, CC };
        struct B { struct C* c; }; struct C { struct B b; };
        typedef struct selfref { struct selfref *next; } *selfref_ptr_t;

        void *dlopen(const char *filename, int flags);
        int dlclose(void *handle);
        """)
        ffi.set_source('re_python_pysrc', None)
        ffi.emit_python_code(str(tmpdir.join('re_python_pysrc.py')))
        #
        sub_ffi = FFI()
        sub_ffi.cdef("static const int k2 = 121212;")
        sub_ffi.include(ffi)
        assert 'macro FOOBAR' in ffi._parser._declarations
        assert 'macro FOOBAZ' in ffi._parser._declarations
        sub_ffi.set_source('re_py_subsrc', None)
        sub_ffi.emit_python_code(str(tmpdir.join('re_py_subsrc.py')))
        #
        cls.w_fix_path = space.appexec([space.wrap(str(tmpdir))], """(path):
            def fix_path(ignored=None):
                import _cffi_backend     # force it to be initialized
                import sys
                if path not in sys.path:
                    sys.path.insert(0, path)
            return fix_path
        """)

        cls.w_dl_libpath = space.w_None
        if sys.platform != 'win32':
            import ctypes.util
            cls.w_dl_libpath = space.wrap(ctypes.util.find_library('dl'))

    def teardown_method(self, meth):
        self.space.appexec([], """():
            import sys
            for name in ['re_py_subsrc', 're_python_pysrc']:
                if name in sys.modules:
                    del sys.modules[name]
        """)
        _clean_cache(self.space)


    def test_constant_1(self):
        self.fix_path()
        from re_python_pysrc import ffi
        assert ffi.integer_const('FOOBAR') == -42
        assert ffi.integer_const('FOOBAZ') == -43

    def test_large_constant(self):
        self.fix_path()
        from re_python_pysrc import ffi
        assert ffi.integer_const('BIGPOS') == 420000000000
        assert ffi.integer_const('BIGNEG') == -420000000000

    def test_function(self):
        import _cffi_backend
        self.fix_path()
        from re_python_pysrc import ffi
        lib = ffi.dlopen(self.extmod)
        assert lib.add42(-10) == 32
        assert type(lib.add42) is _cffi_backend.FFI.CData

    def test_dlopen_unicode(self):
        if not getattr(self, 'extmodU', None):
            skip("no unicode file name")
        import _cffi_backend, sys
        sys.pypy_initfsencoding()   # initialize space.sys.filesystemencoding
        self.fix_path()
        from re_python_pysrc import ffi
        lib = ffi.dlopen(self.extmodU)
        assert lib.add42(-10) == 32

    def test_dlclose(self):
        import _cffi_backend
        self.fix_path()
        from re_python_pysrc import ffi
        lib = ffi.dlopen(self.extmod)
        ffi.dlclose(lib)
        e = raises(ffi.error, getattr, lib, 'add42')
        assert str(e.value) == (
            "library '%s' has been closed" % (self.extmod,))
        ffi.dlclose(lib)   # does not raise

    def test_constant_via_lib(self):
        self.fix_path()
        from re_python_pysrc import ffi
        lib = ffi.dlopen(self.extmod)
        assert lib.FOOBAR == -42
        assert lib.FOOBAZ == -43

    def test_opaque_struct(self):
        self.fix_path()
        from re_python_pysrc import ffi
        ffi.cast("struct foo_s *", 0)
        raises(TypeError, ffi.new, "struct foo_s *")

    def test_nonopaque_struct(self):
        self.fix_path()
        from re_python_pysrc import ffi
        for p in [ffi.new("struct bar_s *", [5, b"foobar"]),
                  ffi.new("bar_t *", [5, b"foobar"])]:
            assert p.x == 5
            assert p.a[0] == ord('f')
            assert p.a[5] == ord('r')

    def test_enum(self):
        self.fix_path()
        from re_python_pysrc import ffi
        assert ffi.integer_const("BB") == 1
        e = ffi.cast("enum foo_e", 2)
        assert ffi.string(e) == "CC"

    def test_include_1(self):
        self.fix_path()
        from re_py_subsrc import ffi
        assert ffi.integer_const('FOOBAR') == -42
        assert ffi.integer_const('FOOBAZ') == -43
        assert ffi.integer_const('k2') == 121212
        lib = ffi.dlopen(self.extmod)     # <- a random unrelated library would be fine
        assert lib.FOOBAR == -42
        assert lib.FOOBAZ == -43
        assert lib.k2 == 121212
        #
        p = ffi.new("bar_t *", [5, b"foobar"])
        assert p.a[4] == ord('a')

    def test_global_var(self):
        self.fix_path()
        from re_python_pysrc import ffi
        lib = ffi.dlopen(self.extmod)
        assert lib.globalvar42 == 1234
        p = ffi.addressof(lib, 'globalvar42')
        lib.globalvar42 += 5
        assert p[0] == 1239
        p[0] -= 1
        assert lib.globalvar42 == 1238

    def test_global_const_int(self):
        self.fix_path()
        from re_python_pysrc import ffi
        lib = ffi.dlopen(self.extmod)
        assert lib.globalconst42 == 4321
        raises(AttributeError, ffi.addressof, lib, 'globalconst42')

    def test_global_const_nonint(self):
        self.fix_path()
        from re_python_pysrc import ffi
        lib = ffi.dlopen(self.extmod)
        assert ffi.string(lib.globalconsthello, 8) == b"hello"
        raises(AttributeError, ffi.addressof, lib, 'globalconsthello')

    def test_rtld_constants(self):
        self.fix_path()
        from re_python_pysrc import ffi
        ffi.RTLD_NOW    # check that we have the attributes
        ffi.RTLD_LAZY
        ffi.RTLD_GLOBAL

    def test_no_such_function_or_global_var(self):
        self.fix_path()
        from re_python_pysrc import ffi
        lib = ffi.dlopen(self.extmod)
        e = raises(ffi.error, getattr, lib, 'no_such_function')
        assert str(e.value).startswith(
            "symbol 'no_such_function' not found in library '")
        e = raises(ffi.error, getattr, lib, 'no_such_globalvar')
        assert str(e.value).startswith(
            "symbol 'no_such_globalvar' not found in library '")

    def test_check_version(self):
        import _cffi_backend
        e = raises(ImportError, _cffi_backend.FFI,
            "foobar", _version=0x2594)
        assert str(e.value).startswith(
            "cffi out-of-line Python module 'foobar' has unknown version")

    def test_selfref(self):
        # based on cffi issue #429
        self.fix_path()
        from re_python_pysrc import ffi
        ffi.new("selfref_ptr_t")

    @py.test.mark.skipif('WIN32', reason='uses "dl" explicitly')
    def test_dlopen_handle(self):
        import _cffi_backend, sys
        self.fix_path()
        from re_python_pysrc import ffi
        lib1 = ffi.dlopen(self.dl_libpath)
        handle = lib1.dlopen(self.extmod.encode(sys.getfilesystemencoding()),
                             _cffi_backend.RTLD_LAZY)
        assert ffi.typeof(handle) == ffi.typeof("void *")
        assert handle

        lib = ffi.dlopen(handle)
        assert lib.add42(-10) == 32
        assert type(lib.add42) is _cffi_backend.FFI.CData

        err = lib1.dlclose(handle)
        assert err == 0

    def test_rec_structs_1(self):
        self.fix_path()
        from re_python_pysrc import ffi
        sz = ffi.sizeof("struct B")
        assert sz == ffi.sizeof("int *")

    def test_rec_structs_2(self):
        self.fix_path()
        from re_python_pysrc import ffi
        sz = ffi.sizeof("struct C")
        assert sz == ffi.sizeof("int *")