Debian Codegraph @

pypy/module/cpyext/test/test_userslots.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem import rffi
2 from pypy.module.cpyext.pyobject import make_ref, from_ref
3 from pypy.module.cpyext.api import generic_cpy_call
4 from pypy.module.cpyext.typeobject import PyTypeObjectPtr
5 from pypy.module.cpyext.test.test_api import BaseApiTest
6 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
7
8
9 class TestAppLevelObject(BaseApiTest):
10 def test_nb_add_from_python(self, space, api):
11 w_date = space.appexec([], """():
12 class DateType(object):
13 def __add__(self, other):
14 return 'sum!'
15 return DateType()
16 """)
17 w_datetype = space.type(w_date)
18 py_date = make_ref(space, w_date)
19 py_datetype = rffi.cast(PyTypeObjectPtr, make_ref(space, w_datetype))
20 assert py_datetype.c_tp_as_number
21 assert py_datetype.c_tp_as_number.c_nb_add
22 w_obj = generic_cpy_call(space, py_datetype.c_tp_as_number.c_nb_add,
23 py_date, py_date)
24 assert space.text_w(w_obj) == 'sum!'
25
26 def test_tp_new_from_python(self, space, api):
27 w_date = space.appexec([], """():
28 class Date(object):
29 def __new__(cls, year, month, day):
30 self = object.__new__(cls)
31 self.year = year
32 self.month = month
33 self.day = day
34 return self
35 return Date
36 """)
37 py_datetype = rffi.cast(PyTypeObjectPtr, make_ref(space, w_date))
38 one = space.newint(1)
39 arg = space.newtuple([one, one, one])
40 # call w_date.__new__
41 w_obj = space.call_function(w_date, one, one, one)
42 w_year = space.getattr(w_obj, space.newtext('year'))
43 assert space.int_w(w_year) == 1
44
45 w_obj = generic_cpy_call(space, py_datetype.c_tp_new, py_datetype,
46 arg, space.newdict({}))
47 w_year = space.getattr(w_obj, space.newtext('year'))
48 assert space.int_w(w_year) == 1
49
50 def test_descr_slots(self, space, api):
51 w_descr = space.appexec([], """():
52 class Descr(object):
53 def __get__(self, obj, type):
54 return 42 + (obj is None)
55 def __set__(self, obj, value):
56 obj.append('set')
57 def __delete__(self, obj):
58 obj.append('del')
59 return Descr()
60 """)
61 w_descrtype = space.type(w_descr)
62 py_descr = make_ref(space, w_descr)
63 py_descrtype = rffi.cast(PyTypeObjectPtr, make_ref(space, w_descrtype))
64 w_obj = space.newlist([])
65 py_obj = make_ref(space, w_obj)
66 w_res = generic_cpy_call(space, py_descrtype.c_tp_descr_get,
67 py_descr, py_obj, py_obj)
68 assert space.int_w(w_res) == 42
69 assert generic_cpy_call(
70 space, py_descrtype.c_tp_descr_set,
71 py_descr, py_obj, make_ref(space, space.w_None)) == 0
72 assert generic_cpy_call(
73 space, py_descrtype.c_tp_descr_set,
74 py_descr, py_obj, None) == 0
75 assert space.eq_w(w_obj, space.wrap(['set', 'del']))
76 #
77 # unbound __get__(self, NULL, type)
78 w_res = generic_cpy_call(space, py_descrtype.c_tp_descr_get,
79 py_descr, None, space.w_int)
80 assert space.int_w(w_res) == 43
81
82 class AppTestUserSlots(AppTestCpythonExtensionBase):
83 def test_tp_hash_from_python(self):
84 # to see that the functions are being used,
85 # run pytest with -s
86 module = self.import_extension('foo', [
87 ("use_hash", "METH_O",
88 '''
89 long hash = args->ob_type->tp_hash(args);
90 return PyLong_FromLong(hash);
91 ''')])
92 class C(object):
93 def __hash__(self):
94 return -23
95 c = C()
96 # uses the userslot slot_tp_hash
97 ret = module.use_hash(C())
98 assert hash(c) == ret
99 # uses the slotdef renamed cpyext_tp_hash_int
100 ret = module.use_hash(3)
101 assert hash(3) == ret
102
103 def test_tp_str(self):
104 module = self.import_extension('foo', [
105 ("tp_str", "METH_VARARGS",
106 '''
107 PyTypeObject *type = (PyTypeObject *)PyTuple_GET_ITEM(args, 0);
108 PyObject *obj = PyTuple_GET_ITEM(args, 1);
109 if (!type->tp_str)
110 {
111 PyErr_SetString(PyExc_ValueError, "no tp_str");
112 return NULL;
113 }
114 return type->tp_str(obj);
115 '''
116 )
117 ])
118 class C:
119 def __str__(self):
120 return "text"
121 assert module.tp_str(type(C()), C()) == "text"
122 class D(int):
123 def __str__(self):
124 return "more text"
125 assert module.tp_str(int, D(42)) == "42"
126 class A(object):
127 pass
128 s = module.tp_str(type(A()), A())
129 assert 'A object' in s
130
131 def test_tp_deallocate(self):
132 module = self.import_extension('foo', [
133 ("get_cnt", "METH_NOARGS",
134 '''
135 return PyLong_FromLong(foocnt);
136 '''),
137 ("get__timestamp", "METH_NOARGS",
138 '''
139 PyObject * one = PyLong_FromLong(1);
140 PyObject * a = PyTuple_Pack(3, one, one, one);
141 PyObject * k = NULL;
142 obj = _Timestamp.tp_new(&_Timestamp, a, k);
143 Py_DECREF(one);
144 return obj;
145 '''),
146 ("get_timestamp", "METH_NOARGS",
147 '''
148 PyObject * one = PyLong_FromLong(1);
149 PyObject * a = PyTuple_Pack(3, one, one, one);
150 PyObject * k = NULL;
151 obj = Timestamp.tp_new(&Timestamp, a, k);
152 Py_DECREF(one);
153 return obj;
154 '''),
155 ], prologue='''
156 static int foocnt = 0;
157 static PyTypeObject* datetime_cls = NULL;
158 static PyObject * obj = NULL;
159 static PyObject*
160 _timestamp_new(PyTypeObject* t, PyObject* a, PyObject* k)
161 {
162 foocnt ++;
163 return datetime_cls->tp_new(t, a, k);
164 }
165
166 static PyObject*
167 timestamp_new(PyTypeObject* t, PyObject* a, PyObject* k)
168 {
169 return datetime_cls->tp_new(t, a, k);
170 }
171
172 static void
173 _timestamp_dealloc(PyObject *op)
174 {
175 foocnt --;
176 datetime_cls->tp_dealloc(op);
177 }
178
179
180 static PyTypeObject _Timestamp = {
181 PyVarObject_HEAD_INIT(NULL, 0)
182 "foo._Timestamp", /* tp_name*/
183 0, /* tp_basicsize*/
184 0, /* tp_itemsize */
185 _timestamp_dealloc /* tp_dealloc */
186 };
187 static PyTypeObject Timestamp = {
188 PyVarObject_HEAD_INIT(NULL, 0)
189 "foo.Timestamp", /* tp_name*/
190 0, /* tp_basicsize*/
191 0 /* tp_itemsize */
192 };
193 PyObject * mod1;
194 PyObject * dt;
195 ''', more_init='''
196 mod1 = PyImport_ImportModule("datetime");
197 if (mod1 == NULL) INITERROR;
198 dt = PyUnicode_FromString("datetime");
199 datetime_cls = (PyTypeObject*)PyObject_GetAttr(mod1, dt);
200 if (datetime_cls == NULL) INITERROR;
201 _Timestamp.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
202 _Timestamp.tp_base = datetime_cls;
203 _Timestamp.tp_new = _timestamp_new;
204 Py_DECREF(mod1);
205 Py_DECREF(dt);
206 if (PyType_Ready(&_Timestamp) < 0) INITERROR;
207
208 Timestamp.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
209 Timestamp.tp_base = &_Timestamp;
210 Timestamp.tp_new = timestamp_new;
211 Timestamp.tp_dealloc = datetime_cls->tp_dealloc;
212 if (PyType_Ready(&Timestamp) < 0) INITERROR;
213 ''')
214 # _Timestamp has __new__, __del__ and
215 # inherits from datetime.datetime
216 # Timestamp has __new__, default __del__ (subtype_dealloc) and
217 # inherits from _Timestamp
218 import gc, sys
219 cnt = module.get_cnt()
220 assert cnt == 0
221 obj = module.get__timestamp() #_Timestamp
222 cnt = module.get_cnt()
223 assert cnt == 1
224 assert obj.year == 1
225 del obj
226 self.debug_collect()
227 cnt = module.get_cnt()
228 assert cnt == 0
229
230 obj = module.get_timestamp() #Timestamp
231 cnt = module.get_cnt()
232 assert cnt == 0
233 assert obj.year == 1
234 # XXX calling Timestamp.tp_dealloc which is subtype_dealloc
235 # causes infinite recursion
236 del obj
237 self.debug_collect()
238 cnt = module.get_cnt()
239 assert cnt == 0
240
241 def test_rpow_cpyext(self):
242 module = self.import_module("pow_mod", filename="gh5207")
243 assert hasattr(module, 'pow')
244 res = pow(1, module.pow(), module.pow())
245 assert res == 123
246 with raises(TypeError):
247 # XXX: this is the part of the logic that is still wrong
248 pow(1, 2, module.pow())