Debian Codegraph @

pypy/module/cpyext/test/test_sequence.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem import rffi
2 from pypy.interpreter.error import OperationError
3 from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
4 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
5 from pypy.module.cpyext.sequence import (
6 PySequence_Fast, PySequence_Contains, PySequence_Index,
7 PySequence_GetItem, PySequence_SetItem, PySequence_DelItem)
8 from pypy.module.cpyext.pyobject import get_w_obj_and_decref, from_ref
9 from pypy.module.cpyext.state import State
10 import pytest
11
12 class TestSequence(BaseApiTest):
13 def test_check(self, space, api):
14 assert api.PySequence_Check(space.newlist([]))
15 assert not api.PySequence_Check(space.newdict())
16
17 def test_sequence_api(self, space, api):
18 w_tup = space.wrap((1, 2, 3, 4))
19 assert api.PySequence_Fast(w_tup, "message") is w_tup
20
21 w_l = space.wrap([1, 2, 3, 4])
22 assert api.PySequence_Fast(w_l, "message") is w_l
23
24 py_result = api.PySequence_Fast_GET_ITEM(w_l, 1)
25 w_result = from_ref(space, py_result)
26 assert space.int_w(w_result) == 2
27 assert api.PySequence_Fast_GET_SIZE(w_l) == 4
28
29 w_set = space.wrap(set((1, 2, 3, 4)))
30 w_seq = api.PySequence_Fast(w_set, "message")
31 assert space.type(w_seq) is space.w_tuple
32 assert space.len_w(w_seq) == 4
33
34 w_seq = api.PySequence_Tuple(w_set)
35 assert space.type(w_seq) is space.w_tuple
36 assert sorted(space.unwrap(w_seq)) == [1, 2, 3, 4]
37
38 w_seq = api.PySequence_List(w_set)
39 assert space.type(w_seq) is space.w_list
40 assert sorted(space.unwrap(w_seq)) == [1, 2, 3, 4]
41
42 def test_repeat(self, space, api):
43 def test(seq, count):
44 w_seq = space.wrap(seq)
45 w_repeated = api.PySequence_Repeat(w_seq, count)
46 assert space.eq_w(w_repeated, space.wrap(seq * count))
47
48 test((1, 2, 3, 4), 3)
49 test([1, 2, 3, 4], 3)
50
51 def test_concat(self, space, api):
52 w_t1 = space.wrap(range(4))
53 w_t2 = space.wrap(range(4, 8))
54 assert space.unwrap(api.PySequence_Concat(w_t1, w_t2)) == range(8)
55
56 def test_inplace_concat(self, space, api):
57 w_t1 = space.wrap(range(4))
58 w_t2 = space.wrap(range(4, 8))
59 w_t3 = api.PySequence_InPlaceConcat(w_t1, w_t2)
60 assert space.unwrap(w_t3) == range(8)
61 assert space.unwrap(w_t1) == range(8)
62
63 def test_inplace_repeat(self, space, api):
64 w_t1 = space.wrap(range(2))
65 w_t2 = api.PySequence_InPlaceRepeat(w_t1, 3)
66 assert space.unwrap(w_t2) == [0, 1, 0, 1, 0, 1]
67
68 def test_exception(self, space):
69 message = rffi.str2charp("message")
70 with pytest.raises(OperationError) as excinfo:
71 PySequence_Fast(space, space.wrap(3), message)
72 assert excinfo.value.match(space, space.w_TypeError)
73 assert space.text_w(excinfo.value.get_w_value(space)) == "message"
74 rffi.free_charp(message)
75
76 def test_get_slice(self, space, api):
77 w_t = space.wrap([1, 2, 3, 4, 5])
78 assert space.unwrap(api.PySequence_GetSlice(w_t, 2, 4)) == [3, 4]
79 assert space.unwrap(api.PySequence_GetSlice(w_t, 1, -1)) == [2, 3, 4]
80
81 assert api.PySequence_DelSlice(w_t, 1, 4) == 0
82 assert space.eq_w(w_t, space.wrap([1, 5]))
83 assert api.PySequence_SetSlice(w_t, 1, 1, space.wrap((3,))) == 0
84 assert space.eq_w(w_t, space.wrap([1, 3, 5]))
85
86 def test_get_slice_fast(self, space, api):
87 w_t = space.wrap([1, 2, 3, 4, 5])
88 api.PyList_GetItem(w_t, 0) # converts to cpy strategy
89 assert space.unwrap(api.PySequence_GetSlice(w_t, 2, 4)) == [3, 4]
90 assert space.unwrap(api.PySequence_GetSlice(w_t, 1, -1)) == [2, 3, 4]
91
92 assert api.PySequence_DelSlice(w_t, 1, 4) == 0
93 assert space.eq_w(w_t, space.wrap([1, 5]))
94 assert api.PySequence_SetSlice(w_t, 1, 1, space.wrap((3,))) == 0
95 assert space.eq_w(w_t, space.wrap([1, 3, 5]))
96
97 def test_iter(self, space, api):
98 w_t = space.wrap((1, 2))
99 w_iter = api.PySeqIter_New(w_t)
100 assert space.unwrap(space.next(w_iter)) == 1
101 assert space.unwrap(space.next(w_iter)) == 2
102 exc = pytest.raises(OperationError, space.next, w_iter)
103 assert exc.value.match(space, space.w_StopIteration)
104
105 def test_contains(self, space):
106 w_t = space.wrap((1, 'ha'))
107 assert PySequence_Contains(space, w_t, space.wrap(u'ha'))
108 assert not PySequence_Contains(space, w_t, space.wrap(2))
109 with raises_w(space, TypeError):
110 PySequence_Contains(space, space.w_None, space.wrap(2))
111
112 def test_setitem(self, space, api):
113 state = space.fromcache(State)
114 w_value = space.wrap(42)
115
116 l = api.PyList_New(1)
117 result = api.PySequence_SetItem(l, 0, w_value)
118 assert result != -1
119 assert space.eq_w(space.getitem(l, space.wrap(0)), w_value)
120 with raises_w(space, IndexError):
121 PySequence_SetItem(space, l, 3, w_value)
122
123 t = state.C.PyTuple_New(1)
124 api.PyTuple_SetItem(t, 0, l)
125 with raises_w(space, TypeError):
126 PySequence_SetItem(space, t, 0, w_value)
127 with raises_w(space, TypeError):
128 PySequence_SetItem(space, space.newdict(), 0, w_value)
129
130 def test_delitem(self, space, api):
131 w_l = space.wrap([1, 2, 3, 4])
132 result = api.PySequence_DelItem(w_l, 2)
133 assert result == 0
134 assert space.eq_w(w_l, space.wrap([1, 2, 4]))
135 with raises_w(space, IndexError):
136 PySequence_DelItem(space, w_l, 3)
137
138 def test_getitem(self, space, api):
139 thelist = [8, 7, 6, 5, 4, 3, 2, 1]
140 w_l = space.wrap(thelist)
141 py_result = api.PySequence_GetItem(w_l, 4)
142 result = get_w_obj_and_decref(space, py_result)
143 assert space.is_true(space.eq(result, space.wrap(4)))
144 py_result = api.PySequence_ITEM(w_l, 4)
145 result = get_w_obj_and_decref(space, py_result)
146 assert space.is_true(space.eq(result, space.wrap(4)))
147 with raises_w(space, IndexError):
148 PySequence_GetItem(space, w_l, 9000)
149
150 def test_index(self, space, api):
151 thelist = [9, 8, 7, 6, 5, 4, 3, 2, 1]
152 w_l = space.wrap(thelist)
153 w_tofind = space.wrap(5)
154
155 result = api.PySequence_Index(w_l, w_tofind)
156 assert result == thelist.index(5)
157
158 w_tofind = space.wrap(9001)
159 with raises_w(space, ValueError):
160 PySequence_Index(space, w_l, w_tofind)
161
162 w_gen = space.appexec([], """():
163 return (x ** 2 for x in range(40))""")
164 w_tofind = space.wrap(16)
165 result = api.PySequence_Index(w_gen, w_tofind)
166 assert result == 4
167
168 def test_sequence_getitem(self, space, api):
169 # PySequence_GetItem() is defined to return a new reference.
170 # When it happens to be called on a list or tuple, it returns
171 # a new reference that is also kept alive by the fact that it
172 # lives in the list/tuple. Some code like PyArg_ParseTuple()
173 # relies on this fact: it decrefs the result of
174 # PySequence_GetItem() but then expects it to stay alive. Meh.
175 # Here, we check that we try hard not to break this kind of
176 # code: if written naively, it could return a fresh PyIntObject,
177 # for example.
178 w1 = space.wrap((41, 42, 43))
179 p1 = api.PySequence_GetItem(w1, 1)
180 p2 = api.PySequence_GetItem(w1, 1)
181 assert p1 == p2
182 assert p1.c_ob_refcnt > 1
183 #
184 w1 = space.wrap([41, 42, 43])
185 p1 = api.PySequence_GetItem(w1, 1)
186 p2 = api.PySequence_GetItem(w1, 1)
187 assert p1 == p2
188 assert p1.c_ob_refcnt > 1
189 p1 = api.PySequence_GetItem(w1, -1)
190 p2 = api.PySequence_GetItem(w1, 2)
191 assert p1 == p2
192
193
194 class TestCPyListStrategy(BaseApiTest):
195 def test_getitem_setitem(self, space, api):
196 w_l = space.wrap([1, 2, 3, 4])
197 api.PyList_GetItem(w_l, 0) # converts to cpy strategy
198 assert space.int_w(space.len(w_l)) == 4
199 assert space.int_w(space.getitem(w_l, space.wrap(1))) == 2
200 assert space.int_w(space.getitem(w_l, space.wrap(0))) == 1
201 e = pytest.raises(OperationError, space.getitem, w_l, space.wrap(15))
202 assert "list index out of range" in e.value.errorstr(space)
203 assert space.int_w(space.getitem(w_l, space.wrap(-1))) == 4
204 space.setitem(w_l, space.wrap(1), space.wrap(13))
205 assert space.int_w(space.getitem(w_l, space.wrap(1))) == 13
206
207 def test_manipulations(self, space, api):
208 w = space.wrap
209 w_l = w([1, 2, 3, 4])
210
211 api.PyList_GetItem(w_l, 0) # converts to cpy strategy
212 space.call_method(w_l, 'insert', w(0), w(0))
213 assert space.int_w(space.len(w_l)) == 5
214 assert space.int_w(space.getitem(w_l, w(3))) == 3
215
216 api.PyList_GetItem(w_l, 0) # converts to cpy strategy
217 space.call_method(w_l, 'sort')
218 assert space.int_w(space.len(w_l)) == 5
219 assert space.int_w(space.getitem(w_l, w(0))) == 0
220
221 api.PyList_GetItem(w_l, 0) # converts to cpy strategy
222 w_t = space.wrap(space.fixedview(w_l))
223 assert space.int_w(space.len(w_t)) == 5
224 assert space.int_w(space.getitem(w_t, w(0))) == 0
225 w_l2 = space.wrap(space.listview(w_t))
226 assert space.int_w(space.len(w_l2)) == 5
227 assert space.int_w(space.getitem(w_l2, w(0))) == 0
228
229 api.PyList_GetItem(w_l, 0) # converts to cpy strategy
230 w_sum = space.add(w_l, w_l)
231 assert space.int_w(space.len(w_sum)) == 10
232
233 api.PyList_GetItem(w_l, 0) # converts to cpy strategy
234 w_prod = space.mul(w_l, space.wrap(2))
235 assert space.int_w(space.len(w_prod)) == 10
236
237 api.PyList_GetItem(w_l, 0) # converts to cpy strategy
238 w_l.inplace_mul(2)
239 assert space.int_w(space.len(w_l)) == 10
240
241 def test_getstorage_copy(self, space, api):
242 w = space.wrap
243 w_l = w([1, 2, 3, 4])
244 api.PyList_GetItem(w_l, 0) # converts to cpy strategy
245
246 w_l1 = w([])
247 space.setitem(w_l1, space.newslice(w(0), w(0), w(1)), w_l)
248 assert map(space.unwrap, space.unpackiterable(w_l1)) == [1, 2, 3, 4]
249
250 class AppTestSequenceObject(AppTestCpythonExtensionBase):
251 def test_sequence_macro_cast(self):
252 module = self.import_extension('foo', [
253 ("test_macro_cast", "METH_NOARGS",
254 """
255 PyObject *o = PyList_New(0);
256 PyListObject* l;
257 PyList_Append(o, o);
258 l = (PyListObject*)o;
259
260 PySequence_Fast_GET_ITEM(o, 0);
261 PySequence_Fast_GET_ITEM(l, 0);
262
263 PySequence_Fast_GET_SIZE(o);
264 PySequence_Fast_GET_SIZE(l);
265
266 PySequence_ITEM(o, 0);
267 PySequence_ITEM(l, 0);
268
269 return o;
270 """
271 )
272 ])
273
274 def test_fast(self):
275 module = self.import_extension('foo', [
276 ("test_fast_sequence", "METH_VARARGS",
277 """
278 int size, i;
279 PyTypeObject * common_type;
280 PyObject *foo, **objects;
281 PyObject * seq = PyTuple_GetItem(args, 0);
282 if (seq == NULL)
283 Py_RETURN_NONE;
284 foo = PySequence_Fast(seq, "some string");
285 objects = PySequence_Fast_ITEMS(foo);
286 if (objects == NULL)
287 return NULL;
288 size = PySequence_Fast_GET_SIZE(foo);
289 for (i = 0; i < size; ++i) {
290 if (objects[i] != PySequence_Fast_GET_ITEM(foo, i))
291 return PyBool_FromLong(0);
292 }
293 common_type = size > 0 ? Py_TYPE(objects[0]) : NULL;
294 for (i = 1; i < size; ++i) {
295 if (Py_TYPE(objects[i]) != common_type) {
296 common_type = NULL;
297 break;
298 }
299 }
300 Py_DECREF(foo);
301 if (common_type == NULL)
302 return PyBool_FromLong(0);
303 Py_DECREF(common_type);
304 return PyBool_FromLong(1);
305 """)])
306 s = [1, 2, 3, 4]
307 assert module.test_fast_sequence(s[0:-1])
308 assert module.test_fast_sequence(s[::-1])
309 s = (1, 2, 3, 4)
310 assert module.test_fast_sequence(s[0:-1])
311 assert module.test_fast_sequence(s[::-1])
312 s = (1, 2) # specialized tuple
313 assert module.test_fast_sequence(s[0:-1])
314 assert module.test_fast_sequence(s[::-1])
315 s = "1234"
316 assert module.test_fast_sequence(s[0:-1])
317 assert module.test_fast_sequence(s[::-1])
318
319 def test_fast_keyerror(self):
320 module = self.import_extension('foo', [
321 ("test_fast_sequence", "METH_VARARGS",
322 """
323 PyObject *foo;
324 PyObject * seq = PyTuple_GetItem(args, 0);
325 if (seq == NULL)
326 Py_RETURN_NONE;
327 foo = PySequence_Fast(seq, "Could not convert object to sequence");
328 if (foo != NULL)
329 {
330 return foo;
331 }
332 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
333 PyErr_Clear();
334 return PyBool_FromLong(1);
335 }
336 return NULL;
337 """)])
338 class Map(object):
339 def __len__(self):
340 return 1
341
342 def __getitem__(self, index):
343 raise KeyError()
344
345 assert module.test_fast_sequence(Map()) is True
346
347 def test_getitem_c(self):
348 module = self.import_extension('foo', [
349 ("dict_assignment", "METH_VARARGS",
350 """
351 PyObject *cls = PyTuple_GetItem(args, 0);
352 PyObject *func = PyTuple_GetItem(args, 1);
353 if (cls == NULL)
354 return NULL;
355 if (func == NULL)
356 return NULL;
357 /* Assign the func to the cls.__dict__ */
358 if (PyObject_SetAttrString(cls, "__getitem__", func) != 0){
359 return NULL;
360 }
361 Py_RETURN_NONE;
362 """),
363 ("test_get_item", "METH_VARARGS",
364 """
365 PyObject *obj, *result=NULL;
366 int i;
367 if (PyArg_ParseTuple(args, "Oi:test_get_item", &obj, &i)) {
368 result = PySequence_GetItem(obj, i);
369 };
370 return result;
371 """),
372 ])
373 class A(object):
374 pass
375
376 def getitem(*args):
377 return 42
378
379 module.dict_assignment(A, getitem)
380 a = A()
381 assert a[12] == 42
382 assert module.test_get_item(a, 0) == 42
383 assert module.test_get_item(b'a', 0) == ord('a')
384 e = raises(IndexError, module.test_get_item, b'a', -2)
385 assert "bytes index out of range" in str(e.value)
386 raises(IndexError, module.test_get_item, b'a', 1)