File: test_capsule.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 (473 lines) | stat: -rw-r--r-- 17,229 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
"""
NOTE: these tests are also meant to be run as PyPy "applevel" tests.

This means that global imports will NOT be visible inside the test
functions. In particular, you have to "import pytest" inside the test in order
to be able to use e.g. pytest.raises (which on PyPy will be implemented by a
"fake pytest module")
"""
import pytest
from .support import HPyTest, DefaultExtensionTemplate

class CapsuleTemplate(DefaultExtensionTemplate):

    def DEFINE_strdup(self):
        return """
            #include <string.h>

            static char *strdup0(const char *s)
            {
                size_t n = strlen(s) + 1;
                char *copy = (char *) malloc(n * sizeof(char));
                if (copy == NULL) {
                    return NULL;
                }
                strncpy(copy, s, n);
                return copy;
            }
        """

    def DEFINE_SomeObject(self):
        return """
            #include <string.h>

            typedef struct {
                int value;
                char message[];
            } SomeObject;

            static SomeObject *create_payload(int value, char *message)
            {
                size_t n_message = strlen(message) + 1;
                SomeObject *pointer = (SomeObject *)
                        malloc(sizeof(SomeObject) + n_message * sizeof(char));
                if (pointer == NULL) {
                    return NULL;
                }
                pointer->value = value;
                strncpy(pointer->message, message, n_message);
                return pointer;
            }
        """

    def DEFINE_Capsule_New(self, destructor="NULL"):
        return """
            #include <string.h>

            static const char *_capsule_name = "some_capsule";

            #define CAPSULE_NAME _capsule_name

            HPyDef_METH(Capsule_New, "capsule_new", HPyFunc_VARARGS)
            static HPy Capsule_New_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
            {
                HPy res;
                int value;
                char *message;
                void *ptr;

                if (nargs > 0)
                {
                    if (!HPyArg_Parse(ctx, NULL, args, nargs, "is", &value, &message)) {
                        return HPy_NULL;
                    }
                    ptr = (void *) create_payload(value, message);
                    if (ptr == NULL) {
                        HPyErr_SetString(ctx, ctx->h_MemoryError, "out of memory");
                        return HPy_NULL;
                    }
                    res = HPyCapsule_New(ctx, ptr, CAPSULE_NAME, %s);
                    if (HPy_IsNull(res)) {
                        free(ptr);
                    }
                    return res;
                }
                /* just for error case testing */
                return HPyCapsule_New(ctx, NULL, CAPSULE_NAME, NULL);
            }
        """ % destructor

    def DEFINE_Payload_Free(self):
        return """
            #include <string.h>

            HPyDef_METH(Payload_Free, "payload_free", HPyFunc_O)
            static HPy Payload_Free_impl(HPyContext *ctx, HPy self, HPy arg)
            {
                const char *name = HPyCapsule_GetName(ctx, arg);
                if (name == NULL && HPyErr_Occurred(ctx)) {
                    return HPy_NULL;
                }

                void *pointer = HPyCapsule_GetPointer(ctx, arg, name);
                if (pointer == NULL && HPyErr_Occurred(ctx)) {
                    return HPy_NULL;
                }
                free(pointer);

                void *context = HPyCapsule_GetContext(ctx, arg);
                if (context == NULL && HPyErr_Occurred(ctx)) {
                    return HPy_NULL;
                }
                free(context);

                return HPy_Dup(ctx, ctx->h_None);
            }
        """

    def DEFINE_Capsule_GetName(self):
        return """
            HPyDef_METH(Capsule_GetName, "capsule_getname", HPyFunc_O)
            static HPy Capsule_GetName_impl(HPyContext *ctx, HPy self, HPy arg)
            {
                const char *name = HPyCapsule_GetName(ctx, arg);
                if (name == NULL) {
                    return HPy_NULL;
                }
                return HPyUnicode_FromString(ctx, name);
            }
        """

    def DEFINE_Capsule_GetPointer(self):
        return """
            static HPy payload_as_tuple(HPyContext *ctx, SomeObject *pointer)
            {
                HPy value = HPyLong_FromLong(ctx, pointer->value);
                HPy message = HPyUnicode_FromString(ctx, pointer->message);
                HPy result = HPyTuple_Pack(ctx, 2, value, message);
                HPy_Close(ctx, value);
                HPy_Close(ctx, message);
                return result;
            }

            HPyDef_METH(Capsule_GetPointer, "capsule_getpointer", HPyFunc_O)
            static HPy Capsule_GetPointer_impl(HPyContext *ctx, HPy self, HPy arg)
            {
                SomeObject *pointer = (SomeObject *) HPyCapsule_GetPointer(ctx, arg, CAPSULE_NAME);
                if (pointer == NULL) {
                    return HPy_NULL;
                }
                return payload_as_tuple(ctx, pointer);
            }
        """

class TestHPyCapsule(HPyTest):

    ExtensionTemplate = CapsuleTemplate

    def test_capsule_new(self):
        import pytest
        mod = self.make_module("""
            @DEFINE_SomeObject
            @DEFINE_Capsule_New
            @DEFINE_Capsule_GetName
            @DEFINE_Payload_Free

            @EXPORT(Capsule_New)
            @EXPORT(Capsule_GetName)
            @EXPORT(Payload_Free)

            @INIT
        """)
        p = mod.capsule_new(789, "Hello, World!")
        try:
            assert mod.capsule_getname(p) == "some_capsule"
        finally:
            # manually free the payload to avoid a memleak
            mod.payload_free(p)
        with pytest.raises(ValueError):
            mod.capsule_new()

    def test_capsule_getter_and_setter(self):
        import pytest
        mod = self.make_module("""
            #include <string.h>

            @DEFINE_strdup
            @DEFINE_SomeObject
            @DEFINE_Capsule_New
            @DEFINE_Capsule_GetPointer
            @DEFINE_Capsule_GetName
            @DEFINE_Payload_Free

            HPyDef_METH(Capsule_SetPointer, "capsule_setpointer", HPyFunc_VARARGS)
            static HPy Capsule_SetPointer_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
            {
                HPy capsule;
                int value;
                char *message;
                int non_null_pointer;
                if (!HPyArg_Parse(ctx, NULL, args, nargs, "Oisi",
                                  &capsule, &value, &message, &non_null_pointer)) {
                    return HPy_NULL;
                }

                /* avoid memleak; get and later free previous pointer */
                void *old_ptr= HPyCapsule_GetPointer(ctx, capsule, CAPSULE_NAME);
                if (old_ptr == NULL && HPyErr_Occurred(ctx)) {
                    return HPy_NULL;
                }

                SomeObject *pointer = NULL;
                if (non_null_pointer) {
                    pointer = create_payload(value, message);
                    if (pointer == NULL) {
                        HPyErr_SetString(ctx, ctx->h_MemoryError, "out of memory");
                        return HPy_NULL;
                    }
                }

                if (HPyCapsule_SetPointer(ctx, capsule, (void *) pointer) < 0) {
                    if (non_null_pointer) {
                        free(pointer);
                    }
                    return HPy_NULL;
                }
                free(old_ptr);
                return HPy_Dup(ctx, ctx->h_None);
            }

            HPyDef_METH(Capsule_GetContext, "capsule_getcontext", HPyFunc_O)
            static HPy Capsule_GetContext_impl(HPyContext *ctx, HPy self, HPy arg)
            {
                SomeObject *context = (SomeObject *) HPyCapsule_GetContext(ctx, arg);
                if (context == NULL) {
                    return HPyErr_Occurred(ctx) ? HPy_NULL : HPy_Dup(ctx, ctx->h_None);
                }
                return payload_as_tuple(ctx, context);
            }

            HPyDef_METH(Capsule_SetContext, "capsule_setcontext", HPyFunc_VARARGS)
            static HPy Capsule_SetContext_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
            {
                HPy capsule;
                int value;
                char *message;
                if (!HPyArg_Parse(ctx, NULL, args, nargs, "Ois", &capsule, &value, &message)) {
                    return HPy_NULL;
                }

                /* avoid memleak; get and free previous context */
                void *old_context = HPyCapsule_GetContext(ctx, capsule);
                if (old_context == NULL && HPyErr_Occurred(ctx)) {
                    return HPy_NULL;
                }
                free(old_context);

                SomeObject *context = create_payload(value, message);
                if (context == NULL) {
                    HPyErr_SetString(ctx, ctx->h_MemoryError, "out of memory");
                    return HPy_NULL;
                }
                if (HPyCapsule_SetContext(ctx, capsule, (void *) context) < 0) {
                    return HPy_NULL;
                }
                return HPy_Dup(ctx, ctx->h_None);
            }

            HPyDef_METH(Capsule_SetName, "capsule_setname", HPyFunc_VARARGS)
            static HPy Capsule_SetName_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
            {
                HPy capsule;
                const char *name;
                if (!HPyArg_Parse(ctx, NULL, args, nargs, "Os", &capsule, &name)) {
                    return HPy_NULL;
                }

                /* avoid memleak; get and free previous context */
                const char *old_name = HPyCapsule_GetName(ctx, capsule);
                if (old_name == NULL && HPyErr_Occurred(ctx)) {
                    return HPy_NULL;
                }
                if (old_name != CAPSULE_NAME) {
                    free((void *) old_name);
                }

                char *name_copy = strdup0(name);
                if (name_copy == NULL) {
                    HPyErr_SetString(ctx, ctx->h_MemoryError, "out of memory");
                    return HPy_NULL;
                }

                if (HPyCapsule_SetName(ctx, capsule, (const char *) name_copy) < 0) {
                    return HPy_NULL;
                }
                return HPy_Dup(ctx, ctx->h_None);
            }

            static HPyCapsule_Destructor invalid_dtor = { NULL, NULL };

            HPyDef_METH(Capsule_SetDestructor, "capsule_set_destructor", HPyFunc_VARARGS)
            static HPy Capsule_SetDestructor_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
            {
                HPy capsule;
                HPy null_dtor;
                HPyCapsule_Destructor *dtor;
                if (!HPyArg_Parse(ctx, NULL, args, nargs, "OO", &capsule, &null_dtor)) {
                    return HPy_NULL;
                }

                if (HPy_IsTrue(ctx, null_dtor)) {
                    dtor = NULL;
                } else {
                    dtor = &invalid_dtor;
                }

                if (HPyCapsule_SetDestructor(ctx, capsule, dtor) < 0) {
                    return HPy_NULL;
                }
                return HPy_Dup(ctx, ctx->h_None);
            }

            HPyDef_METH(Capsule_free_name, "capsule_freename", HPyFunc_O)
            static HPy Capsule_free_name_impl(HPyContext *ctx, HPy self, HPy arg)
            {
                /* avoid memleak; get and free previous context */
                const char *old_name = HPyCapsule_GetName(ctx, arg);
                if (old_name == NULL && HPyErr_Occurred(ctx)) {
                    return HPy_NULL;
                }
                if (old_name != CAPSULE_NAME) {
                    free((void *) old_name);
                }
                return HPy_Dup(ctx, ctx->h_None);
            }

            @EXPORT(Capsule_New)
            @EXPORT(Capsule_GetPointer)
            @EXPORT(Capsule_SetPointer)
            @EXPORT(Capsule_GetContext)
            @EXPORT(Capsule_SetContext)
            @EXPORT(Capsule_GetName)
            @EXPORT(Capsule_SetName)
            @EXPORT(Capsule_SetDestructor)
            @EXPORT(Capsule_free_name)
            @EXPORT(Payload_Free)

            @INIT
        """)
        p = mod.capsule_new(789, "Hello, World!")
        try:
            assert mod.capsule_getpointer(p) == (789, "Hello, World!")
            assert mod.capsule_setpointer(p, 456, "lorem ipsum", True) is None
            assert mod.capsule_getpointer(p) == (456, "lorem ipsum")

            assert mod.capsule_getcontext(p) == None
            assert mod.capsule_setcontext(p, 123, "hello") is None
            assert mod.capsule_getcontext(p) == (123, "hello")

            assert mod.capsule_getname(p) == "some_capsule"
            assert mod.capsule_setname(p, "foo") is None
            assert mod.capsule_getname(p) == "foo"

            assert mod.capsule_set_destructor(p, True) is None

            not_a_capsule = "hello"
            with pytest.raises(ValueError):
                mod.capsule_getpointer(not_a_capsule)
            with pytest.raises(ValueError):
                mod.capsule_setpointer(not_a_capsule, 0, "", True)
            with pytest.raises(ValueError):
                mod.capsule_setpointer(p, 456, "lorem ipsum", False)
            with pytest.raises(ValueError):
               mod.capsule_getcontext(not_a_capsule)
            with pytest.raises(ValueError):
               mod.capsule_setcontext(not_a_capsule, 0, "")
            with pytest.raises(ValueError):
               mod.capsule_getname(not_a_capsule)
            with pytest.raises(ValueError):
               mod.capsule_setname(not_a_capsule, "")
            with pytest.raises(ValueError):
                mod.capsule_set_destructor(not_a_capsule, True)
            with pytest.raises(ValueError):
                mod.capsule_set_destructor(p, False)
        finally:
            # manually free the payload to avoid a memleak
            mod.payload_free(p)
            mod.capsule_freename(p)

    def test_capsule_isvalid(self):
        import pytest
        mod = self.make_module("""
            @DEFINE_SomeObject
            @DEFINE_Capsule_New
            @DEFINE_Capsule_GetName
            @DEFINE_Payload_Free

            HPyDef_METH(Capsule_isvalid, "capsule_isvalid", HPyFunc_VARARGS)
            static HPy Capsule_isvalid_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
            {
                HPy capsule;
                const char *name;
                if (!HPyArg_Parse(ctx, NULL, args, nargs, "Os", &capsule, &name)) {
                    return HPy_NULL;
                }
                return HPyBool_FromLong(ctx, HPyCapsule_IsValid(ctx, capsule, name));
            }

            @EXPORT(Capsule_New)
            @EXPORT(Capsule_GetName)
            @EXPORT(Capsule_isvalid)
            @EXPORT(Payload_Free)

            @INIT
        """)
        p = mod.capsule_new(789, "Hello, World!")
        name = mod.capsule_getname(p)
        try:
            assert mod.capsule_isvalid(p, name)
            assert not mod.capsule_isvalid(p, "asdf")
            assert not mod.capsule_isvalid("asdf", name)
        finally:
            # manually free the payload to avoid a memleak since the
            # capsule doesn't have a destructor
            mod.payload_free(p)

    @pytest.mark.syncgc
    def test_capsule_new_with_destructor(self):
        import gc
        mod = self.make_module("""
            static int pointer_freed = 0;

            HPyCapsule_DESTRUCTOR(mydtor)
            static void mydtor_impl(const char *name, void *pointer, void *context)
            {
                free(pointer);
                pointer_freed = 1;
            }

            @DEFINE_SomeObject
            @DEFINE_Capsule_New(&mydtor)
            @DEFINE_Capsule_GetName
            @DEFINE_Payload_Free

            HPyDef_METH(Pointer_freed, "pointer_freed", HPyFunc_NOARGS)
            static HPy Pointer_freed_impl(HPyContext *ctx, HPy self)
            {
                return HPyBool_FromLong(ctx, pointer_freed);
            }

            @EXPORT(Capsule_New)
            @EXPORT(Capsule_GetName)
            @EXPORT(Pointer_freed)

            @INIT
        """)
        p = mod.capsule_new(789, "Hello, World!")
        assert mod.capsule_getname(p) == "some_capsule"
        del p
        self.debug_collect()
        assert mod.pointer_freed()

    def test_capsule_new_with_invalid_destructor(self):
        import pytest
        mod = self.make_module("""
            static HPyCapsule_Destructor mydtor = { NULL, NULL };

            @DEFINE_SomeObject
            @DEFINE_Capsule_New(&mydtor)
            @EXPORT(Capsule_New)
            @INIT
        """)
        with pytest.raises(ValueError):
            mod.capsule_new(789, "Hello, World!")