Debian Codegraph @

pypy/module/cpyext/test/test_dictobject.py

raw symbols SCIP
1 import py
2 from pytest import raises
3 from rpython.rtyper.lltypesystem import rffi, lltype
4 from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
5 from pypy.module.cpyext.api import Py_ssize_tP, PyObjectP, PyTypeObjectPtr
6 from pypy.module.cpyext.pyobject import make_ref, from_ref
7 from pypy.interpreter.error import OperationError
8 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
9 from pypy.module.cpyext.dictproxyobject import *
10 from pypy.module.cpyext.dictobject import *
11 from pypy.module.cpyext.pyobject import decref
12
13 class TestDictObject(BaseApiTest):
14 def test_dict(self, space):
15 d = PyDict_New(space)
16 assert space.eq_w(d, space.newdict())
17
18 assert space.eq_w(PyDict_GetItem(space, space.wrap({"a": 72}),
19 space.wrap("a")),
20 space.wrap(72))
21
22 PyDict_SetItem(space, d, space.wrap("c"), space.wrap(42))
23 assert space.eq_w(space.getitem(d, space.wrap("c")),
24 space.wrap(42))
25
26 space.setitem(d, space.wrap("name"), space.wrap(3))
27 assert space.eq_w(PyDict_GetItem(space, d, space.wrap("name")),
28 space.wrap(3))
29
30 space.delitem(d, space.wrap("name"))
31 assert not PyDict_GetItem(space, d, space.wrap("name"))
32
33 buf = rffi.str2charp("name")
34 assert not PyDict_GetItemString(space, d, buf)
35 rffi.free_charp(buf)
36
37 assert PyDict_Contains(space, d, space.wrap("c"))
38 assert not PyDict_Contains(space, d, space.wrap("z"))
39
40 PyDict_DelItem(space, d, space.wrap("c"))
41 with raises_w(space, KeyError):
42 PyDict_DelItem(space, d, space.wrap("name"))
43 assert PyDict_Size(space, d) == 0
44
45 space.setitem(d, space.wrap("some_key"), space.wrap(3))
46 buf = rffi.str2charp("some_key")
47 PyDict_DelItemString(space, d, buf)
48 assert PyDict_Size(space, d) == 0
49 with raises_w(space, KeyError):
50 PyDict_DelItemString(space, d, buf)
51 rffi.free_charp(buf)
52
53 d = space.wrap({'a': 'b'})
54 PyDict_Clear(space, d)
55 assert PyDict_Size(space, d) == 0
56
57 def test_check(self, space):
58 d = PyDict_New(space, )
59 assert PyDict_Check(space, d)
60 assert PyDict_CheckExact(space, d)
61 sub = space.appexec([], """():
62 class D(dict):
63 pass
64 return D""")
65 d = space.call_function(sub)
66 assert PyDict_Check(space, d)
67 assert not PyDict_CheckExact(space, d)
68 i = space.wrap(2)
69 assert not PyDict_Check(space, i)
70 assert not PyDict_CheckExact(space, i)
71
72 def test_keys(self, space):
73 w_d = space.newdict()
74 space.setitem(w_d, space.wrap("a"), space.wrap("b"))
75
76 assert space.eq_w(PyDict_Keys(space, w_d), space.wrap(["a"]))
77 assert space.eq_w(PyDict_Values(space, w_d), space.wrap(["b"]))
78 assert space.eq_w(PyDict_Items(space, w_d), space.wrap([("a", "b")]))
79
80 def test_merge(self, space):
81 w_d = space.newdict()
82 space.setitem(w_d, space.wrap("a"), space.wrap("b"))
83
84 w_d2 = space.newdict()
85 space.setitem(w_d2, space.wrap("a"), space.wrap("c"))
86 space.setitem(w_d2, space.wrap("c"), space.wrap("d"))
87 space.setitem(w_d2, space.wrap("e"), space.wrap("f"))
88
89 PyDict_Merge(space, w_d, w_d2, 0)
90 assert space.unwrap(w_d) == dict(a='b', c='d', e='f')
91 PyDict_Merge(space, w_d, w_d2, 1)
92 assert space.unwrap(w_d) == dict(a='c', c='d', e='f')
93
94 def test_update(self, space):
95 w_d = space.newdict()
96 space.setitem(w_d, space.wrap("a"), space.wrap("b"))
97
98 w_d2 = PyDict_Copy(space, w_d)
99 assert not space.is_w(w_d2, w_d)
100 space.setitem(w_d, space.wrap("c"), space.wrap("d"))
101 space.setitem(w_d2, space.wrap("e"), space.wrap("f"))
102
103 PyDict_Update(space, w_d, w_d2)
104 assert space.unwrap(w_d) == dict(a='b', c='d', e='f')
105
106 def test_update_doesnt_accept_list_of_tuples(self, space):
107 w_d = space.newdict()
108 space.setitem(w_d, space.wrap("a"), space.wrap("b"))
109
110 w_d2 = space.wrap([("c", "d"), ("e", "f")])
111
112 with raises_w(space, AttributeError):
113 PyDict_Update(space, w_d, w_d2)
114 assert space.unwrap(w_d) == dict(a='b') # unchanged
115
116 def test_dictproxy(self, space):
117 w_dict = space.appexec([], """(): return {1: 2, 3: 4}""")
118 w_proxy = PyDictProxy_New(space, w_dict)
119 assert space.contains_w(w_proxy, space.newint(1))
120 raises(OperationError, space.setitem,
121 w_proxy, space.newint(1), space.w_None)
122 raises(OperationError, space.delitem,
123 w_proxy, space.newint(1))
124 raises(OperationError, space.call_method, w_proxy, 'clear')
125 assert PyDictProxy_Check(space, w_proxy)
126
127 def test_typedict1(self, space):
128 py_type = make_ref(space, space.w_int)
129 py_dict = rffi.cast(PyTypeObjectPtr, py_type).c_tp_dict
130 ppos = lltype.malloc(Py_ssize_tP.TO, 1, flavor='raw')
131
132 ppos[0] = 0
133 pkey = lltype.malloc(PyObjectP.TO, 1, flavor='raw')
134 pvalue = lltype.malloc(PyObjectP.TO, 1, flavor='raw')
135 try:
136 w_copy = space.newdict()
137 while PyDict_Next(space, py_dict, ppos, pkey, pvalue):
138 w_key = from_ref(space, pkey[0])
139 w_value = from_ref(space, pvalue[0])
140 space.setitem(w_copy, w_key, w_value)
141 finally:
142 lltype.free(ppos, flavor='raw')
143 lltype.free(pkey, flavor='raw')
144 lltype.free(pvalue, flavor='raw')
145 decref(space, py_type) # release borrowed references
146 # do something with w_copy ?
147
148 class AppTestDictObject(AppTestCpythonExtensionBase):
149 def test_dictproxytype(self):
150 module = self.import_extension('foo', [
151 ("dict_proxy", "METH_VARARGS",
152 """
153 PyObject * dict;
154 PyObject * proxydict;
155 int i;
156 if (!PyArg_ParseTuple(args, "O", &dict))
157 return NULL;
158 proxydict = PyDictProxy_New(dict);
159 #ifdef PYPY_VERSION // PyDictProxy_Check[Exact] are PyPy-specific.
160 if (!PyDictProxy_Check(proxydict)) {
161 Py_DECREF(proxydict);
162 PyErr_SetNone(PyExc_ValueError);
163 return NULL;
164 }
165 if (!PyDictProxy_CheckExact(proxydict)) {
166 Py_DECREF(proxydict);
167 PyErr_SetNone(PyExc_ValueError);
168 return NULL;
169 }
170 #endif // PYPY_VERSION
171 i = PyObject_Size(proxydict);
172 Py_DECREF(proxydict);
173 return PyLong_FromLong(i);
174 """),
175 ])
176 assert module.dict_proxy({'a': 1, 'b': 2}) == 2
177
178 def test_getitemwitherror(self):
179 module = self.import_extension('foo', [
180 ("dict_getitem", "METH_VARARGS",
181 """
182 PyObject *d, *key, *result;
183 if (!PyArg_ParseTuple(args, "OO", &d, &key)) {
184 return NULL;
185 }
186 result = PyDict_GetItemWithError(d, key);
187 if (result == NULL && !PyErr_Occurred())
188 Py_RETURN_NONE;
189 Py_XINCREF(result);
190 return result;
191 """),
192 ("dict_getitem_string", "METH_VARARGS",
193 """
194 PyObject *d, *result;
195 char * key;
196 if (!PyArg_ParseTuple(args, "Os", &d, &key)) {
197 return NULL;
198 }
199 result = _PyDict_GetItemStringWithError(d, key);
200 if (result == NULL && !PyErr_Occurred())
201 Py_RETURN_NONE;
202 Py_XINCREF(result);
203 return result;
204 """)])
205 d = {'foo': 'bar'}
206 assert module.dict_getitem(d, 'foo') == 'bar'
207 assert module.dict_getitem_string(d, 'foo') == 'bar'
208 assert module.dict_getitem(d, 'missing') is None
209 assert module.dict_getitem_string(d, 'missing') is None
210 with raises(TypeError):
211 module.dict_getitem(d, [])
212 with raises(TypeError):
213 module.dict_getitem_string(d, [])
214
215 def test_setdefault(self):
216 module = self.import_extension('foo', [
217 ("setdefault", "METH_VARARGS",
218 '''
219 PyObject *d, *key, *defaultobj, *val;
220 if (!PyArg_ParseTuple(args, "OOO", &d, &key, &defaultobj))
221 return NULL;
222 val = PyDict_SetDefault(d, key, defaultobj);
223 Py_XINCREF(val);
224 return val;
225 ''')])
226
227 class Dict(dict):
228 def setdefault(self, key, default):
229 return 42
230
231 d = Dict()
232 assert module.setdefault(d, 'x', 1) == 1
233 assert d['x'] == 1
234
235 def test_update(self):
236 module = self.import_extension('foo', [
237 ("update", "METH_VARARGS",
238 '''
239 if (PyDict_Update(PyTuple_GetItem(args, 0), PyTuple_GetItem(args, 1)))
240 return NULL;
241 Py_RETURN_NONE;
242 ''')])
243 d = {"a": 1}
244 module.update(d, {"c": 2})
245 assert d == dict(a=1, c=2)
246 d = {"a": 1}
247 raises(AttributeError, module.update, d, [("c", 2)])
248
249 def test_iter(self):
250 module = self.import_extension('foo', [
251 ("copy", "METH_O",
252 '''
253 Py_ssize_t pos = 0;
254 PyObject *key, *value;
255 PyObject* copy = PyDict_New();
256 while (PyDict_Next(args, &pos, &key, &value))
257 {
258 if (PyDict_SetItem(copy, key, value) < 0)
259 {
260 Py_DecRef(copy);
261 return NULL;
262 }
263 }
264 return copy;
265 ''')])
266 d = {1: 'xyz', 3: 'abcd'}
267 copy = module.copy(d)
268 assert len(copy) == len(d)
269 assert copy == d
270
271 def test_iterkeys(self):
272 module = self.import_extension('foo', [
273 ("keys_and_values", "METH_O",
274 '''
275 Py_ssize_t pos = 0;
276 PyObject *key, *value, *values;
277 PyObject* keys = PyList_New(0);
278 while (PyDict_Next(args, &pos, &key, NULL))
279 {
280 if (PyList_Append(keys, key) < 0)
281 {
282 Py_DecRef(keys);
283 return NULL;
284 }
285 }
286 pos = 0;
287 values = PyList_New(0);
288 while (PyDict_Next(args, &pos, NULL, &value))
289 {
290 if (PyList_Append(values, value) < 0)
291 {
292 Py_DecRef(keys);
293 Py_DecRef(values);
294 return NULL;
295 }
296 }
297 return Py_BuildValue("(NN)", keys, values);
298 ''')])
299 d = {1: 'xyz', 3: 'abcd'}
300 assert module.keys_and_values(d) == (list(d.keys()), list(d.values()))
301
302 def test_typedict2(self):
303 module = self.import_extension('foo', [
304 ("get_type_dict", "METH_O",
305 '''
306 PyObject* value = args->ob_type->tp_dict;
307 if (value == NULL) value = Py_None;
308 Py_INCREF(value);
309 return value;
310 '''),
311 ])
312 d = module.get_type_dict(1)
313 assert d['real'].__get__(1, 1) == 1
314
315 def test_advanced(self):
316 module = self.import_extension('foo', [
317 ("dict_len", "METH_O",
318 '''
319 int ret = args->ob_type->tp_as_mapping->mp_length(args);
320 return PyLong_FromLong(ret);
321 '''),
322 ("dict_setitem", "METH_VARARGS",
323 '''
324 int ret;
325 PyObject * dict = PyTuple_GetItem(args, 0);
326 if (PyTuple_Size(args) < 3 || !dict ||
327 !dict->ob_type->tp_as_mapping ||
328 !dict->ob_type->tp_as_mapping->mp_ass_subscript)
329 return PyLong_FromLong(-1);
330 ret = dict->ob_type->tp_as_mapping->mp_ass_subscript(
331 dict, PyTuple_GetItem(args, 1),
332 PyTuple_GetItem(args, 2));
333 return PyLong_FromLong(ret);
334 '''),
335 ("dict_delitem", "METH_VARARGS",
336 '''
337 int ret;
338 PyObject * dict = PyTuple_GetItem(args, 0);
339 if (PyTuple_Size(args) < 2 || !dict ||
340 !dict->ob_type->tp_as_mapping ||
341 !dict->ob_type->tp_as_mapping->mp_ass_subscript)
342 return PyLong_FromLong(-1);
343 ret = dict->ob_type->tp_as_mapping->mp_ass_subscript(
344 dict, PyTuple_GetItem(args, 1), NULL);
345 return PyLong_FromLong(ret);
346 '''),
347 ("dict_next", "METH_VARARGS",
348 '''
349 PyObject *key, *value;
350 PyObject *arg = NULL;
351 Py_ssize_t pos = 0;
352 int ret = 0;
353 if ((PyArg_ParseTuple(args, "|O", &arg))) {
354 if (arg && PyDict_Check(arg)) {
355 while (PyDict_Next(arg, &pos, &key, &value))
356 ret ++;
357 /* test no crash if pos is not reset to 0*/
358 while (PyDict_Next(arg, &pos, &key, &value))
359 ret ++;
360 }
361 }
362 return PyLong_FromLong(ret);
363 '''),
364 ("exhaust_pos", "METH_O",
365 """
366 PyObject *key, *val;
367 Py_ssize_t pos = 0;
368 while (PyDict_Next(args, &pos, &key, &val)) {
369 }
370 return PyLong_FromLong(pos);
371 """),
372 ])
373 d = {'a': 1, 'b':2}
374 assert module.dict_len(d) == 2
375 assert module.dict_setitem(d, 'a', 'c') == 0
376 assert d['a'] == 'c'
377 assert module.dict_delitem(d, 'a') == 0
378 r = module.dict_next({'a': 1, 'b': 2})
379 assert r == 2
380 assert module.exhaust_pos({'a': 1}) == 1
381
382 def test_subclassing(self):
383 module = self.import_extension('foo', [
384 ("dict_setitem", "METH_VARARGS",
385 """
386 PyObject *d, *key, *value;
387 if (!PyArg_ParseTuple(args, "OOO", &d, &key, &value)) {
388 return NULL;
389 }
390 if (PyDict_SetItem(d, key, value) < 0) {
391 return NULL;
392 }
393 Py_RETURN_NONE;
394 """),
395 ("dict_delitem", "METH_VARARGS",
396 """
397 PyObject *d, *key;
398 if (!PyArg_ParseTuple(args, "OO", &d, &key)) {
399 return NULL;
400 }
401 if (PyDict_DelItem(d, key) < 0) {
402 return NULL;
403 }
404 Py_RETURN_NONE;
405 """),
406 ("dict_getitem", "METH_VARARGS",
407 """
408 PyObject *d, *key, *result;
409 if (!PyArg_ParseTuple(args, "OO", &d, &key)) {
410 return NULL;
411 }
412 result = PyDict_GetItem(d, key);
413 Py_XINCREF(result);
414 return result;
415 """),
416 ])
417
418 class mydict(dict):
419 def __setitem__(self, key, value):
420 dict.__setitem__(self, key, 42)
421
422 def __delitem__(self, key):
423 dict.__setitem__(self, key, None)
424 d = {}
425 module.dict_setitem(d, 1, 2)
426 assert d[1] == 2
427 d = mydict()
428 d[1] = 2
429 assert d[1] == 42
430 module.dict_setitem(d, 2, 3)
431 assert d[2] == 3
432 del d[2]
433 assert d[2] is None
434 module.dict_delitem(d, 2)
435 assert 2 not in d
436
437 class mydict2(dict):
438 def __getitem__(self, key):
439 return 42
440
441 d = mydict2()
442 d[1] = 2
443 assert d[1] == 42
444 assert module.dict_getitem(d, 1) == 2
445
446 def test_getitem_error(self):
447 module = self.import_extension('foo', [
448 ("dict_getitem", "METH_VARARGS",
449 """
450 PyObject *d, *key, *result;
451 if (!PyArg_ParseTuple(args, "OO", &d, &key)) {
452 return NULL;
453 }
454 result = PyDict_GetItem(d, key);
455 if (!result) Py_RETURN_NONE;
456 Py_XINCREF(result);
457 return result;
458 """),
459 ])
460 assert module.dict_getitem(42, 43) is None
461 assert module.dict_getitem({}, []) is None
462
463 def test_contains(self):
464 module = self.import_extension('foo', [
465 ("contains", "METH_VARARGS",
466 """
467 PyObject *d, *key;
468 if (!PyArg_ParseTuple(args, "OO", &d, &key)) {
469 return NULL;
470 }
471 int ret = PyDict_Contains(d, key);
472 if (ret < 0) return NULL;
473 return PyLong_FromLong(ret);
474 """),
475 ])
476
477 class Unhashable():
478 __hash__ = None
479
480 raises(TypeError, module.contains, {}, Unhashable())
481
482 class C(dict):
483 def __contains__(self, key):
484 return dict.__contains__(self, key)
485
486 ret = module.contains(C(), 1)
487 assert ret == 0