• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Need limited C API version 3.13 for Py_GetConstant()
2 #include "pyconfig.h"   // Py_GIL_DISABLED
3 #if !defined(Py_GIL_DISABLED) && !defined(Py_LIMITED_API)
4 #  define Py_LIMITED_API 0x030d0000
5 #endif
6 
7 #include "parts.h"
8 #include "util.h"
9 
10 
11 /* Test Py_GetConstant() */
12 static PyObject *
get_constant(PyObject * Py_UNUSED (module),PyObject * args)13 get_constant(PyObject *Py_UNUSED(module), PyObject *args)
14 {
15     int constant_id;
16     if (!PyArg_ParseTuple(args, "i", &constant_id)) {
17         return NULL;
18     }
19 
20     PyObject *obj = Py_GetConstant(constant_id);
21     if (obj == NULL) {
22         assert(PyErr_Occurred());
23         return NULL;
24     }
25     return obj;
26 }
27 
28 
29 /* Test Py_GetConstantBorrowed() */
30 static PyObject *
get_constant_borrowed(PyObject * Py_UNUSED (module),PyObject * args)31 get_constant_borrowed(PyObject *Py_UNUSED(module), PyObject *args)
32 {
33     int constant_id;
34     if (!PyArg_ParseTuple(args, "i", &constant_id)) {
35         return NULL;
36     }
37 
38     PyObject *obj = Py_GetConstantBorrowed(constant_id);
39     if (obj == NULL) {
40         assert(PyErr_Occurred());
41         return NULL;
42     }
43     return Py_NewRef(obj);
44 }
45 
46 
47 /* Test constants */
48 static PyObject *
test_constants(PyObject * Py_UNUSED (module),PyObject * Py_UNUSED (args))49 test_constants(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
50 {
51     // Test that implementation of constants in the limited C API:
52     // check that the C code compiles.
53     //
54     // Test also that constants and Py_GetConstant() return the same
55     // objects.
56     assert(Py_None == Py_GetConstant(Py_CONSTANT_NONE));
57     assert(Py_False == Py_GetConstant(Py_CONSTANT_FALSE));
58     assert(Py_True == Py_GetConstant(Py_CONSTANT_TRUE));
59     assert(Py_Ellipsis == Py_GetConstant(Py_CONSTANT_ELLIPSIS));
60     assert(Py_NotImplemented == Py_GetConstant(Py_CONSTANT_NOT_IMPLEMENTED));
61     // Other constants are tested in test_capi.test_object
62     Py_RETURN_NONE;
63 }
64 
65 static PyMethodDef test_methods[] = {
66     {"get_constant", get_constant, METH_VARARGS},
67     {"get_constant_borrowed", get_constant_borrowed, METH_VARARGS},
68     {"test_constants", test_constants, METH_NOARGS},
69     {NULL},
70 };
71 
72 int
_PyTestLimitedCAPI_Init_Object(PyObject * m)73 _PyTestLimitedCAPI_Init_Object(PyObject *m)
74 {
75     if (PyModule_AddFunctions(m, test_methods) < 0) {
76         return -1;
77     }
78 
79     return 0;
80 }
81