Debian Codegraph @

pypy/objspace/std/test/test_dictmultiobject.py

raw symbols SCIP
1 # encoding: utf-8
2 import sys
3 import py
4
5 from pypy.objspace.std.dictmultiobject import (W_DictMultiObject,
6 W_DictObject, BytesDictStrategy, ObjectDictStrategy, EmptyDictStrategy,
7 update1_dict_dict, UnicodeDictStrategy,
8 IntDictStrategy)
9 from pypy.objspace.std.longobject import W_LongObject
10 from rpython.rlib.rbigint import rbigint
11
12
13 class TestW_DictObject(object):
14 def test_empty(self):
15 d = self.space.newdict()
16 assert not self.space.is_true(d)
17 assert type(d.get_strategy()) is not ObjectDictStrategy
18
19 def test_nonempty(self):
20 space = self.space
21 wNone = space.w_None
22 d = self.space.newdict()
23 d.initialize_content([(wNone, wNone)])
24 assert space.is_true(d)
25 i = space.getitem(d, wNone)
26 equal = space.eq(i, wNone)
27 assert space.is_true(equal)
28
29 def test_setitem(self):
30 space = self.space
31 wk1 = space.wrap('key')
32 wone = space.wrap(1)
33 d = self.space.newdict()
34 d.initialize_content([(space.wrap('zero'),space.wrap(0))])
35 space.setitem(d,wk1,wone)
36 wback = space.getitem(d,wk1)
37 assert self.space.eq_w(wback,wone)
38
39 def test_delitem(self):
40 space = self.space
41 wk1 = space.wrap('key')
42 d = self.space.newdict()
43 d.initialize_content( [(space.wrap('zero'),space.wrap(0)),
44 (space.wrap('one'),space.wrap(1)),
45 (space.wrap('two'),space.wrap(2))])
46 space.delitem(d,space.wrap('one'))
47 assert self.space.eq_w(space.getitem(d,space.wrap('zero')),space.wrap(0))
48 assert self.space.eq_w(space.getitem(d,space.wrap('two')),space.wrap(2))
49 self.space.raises_w(self.space.w_KeyError,
50 space.getitem,d,space.wrap('one'))
51
52 def test_wrap_dict(self):
53 assert isinstance(self.space.wrap({}), W_DictMultiObject)
54
55
56 def test_dict_compare(self):
57 w = self.space.wrap
58 w0, w1, w2, w3 = map(w, range(4))
59 def wd(items):
60 d = self.space.newdict()
61 d.initialize_content(items)
62 return d
63 wd1 = wd([(w0, w1), (w2, w3)])
64 wd2 = wd([(w2, w3), (w0, w1)])
65 assert self.space.eq_w(wd1, wd2)
66 wd3 = wd([(w2, w2), (w0, w1)])
67 assert not self.space.eq_w(wd1, wd3)
68 wd4 = wd([(w3, w3), (w0, w1)])
69 assert not self.space.eq_w(wd1, wd4)
70 wd5 = wd([(w3, w3)])
71 assert not self.space.eq_w(wd1, wd4)
72
73 def test_dict_call(self):
74 space = self.space
75 w = space.wrap
76 def wd(items):
77 d = space.newdict()
78 d.initialize_content(items)
79 return d
80 def mydict(w_args=w(()), w_kwds=w({})):
81 return space.call(space.w_dict, w_args, w_kwds)
82 def deepwrap(lp):
83 return [[w(a),w(b)] for a,b in lp]
84 d = mydict()
85 assert self.space.eq_w(d, w({}))
86 args = w(([['a',2],[23,45]],))
87 d = mydict(args)
88 assert self.space.eq_w(d, wd(deepwrap([['a',2],[23,45]])))
89 d = mydict(args, w({'a':33, 'b':44}))
90 assert self.space.eq_w(d, wd(deepwrap([['a',33],['b',44],[23,45]])))
91 d = mydict(w_kwds=w({'a':33, 'b':44}))
92 assert self.space.eq_w(d, wd(deepwrap([['a',33],['b',44]])))
93 self.space.raises_w(space.w_TypeError, mydict, w((23,)))
94 self.space.raises_w(space.w_ValueError, mydict, w(([[1,2,3]],)))
95
96 def test_dict_pop(self):
97 space = self.space
98 w = space.wrap
99 def mydict(w_args=w(()), w_kwds=w({})):
100 return space.call(space.w_dict, w_args, w_kwds)
101 d = mydict(w_kwds=w({"1":2, "3":4}))
102 dd = mydict(w_kwds=w({"1":2, "3":4})) # means d.copy()
103 pop = space.getattr(dd, w("pop"))
104 result = space.call_function(pop, w("1"))
105 assert self.space.eq_w(result, w(2))
106 assert self.space.eq_w(space.len(dd), w(1))
107
108 dd = mydict(w_kwds=w({"1":2, "3":4})) # means d.copy()
109 pop = space.getattr(dd, w("pop"))
110 result = space.call_function(pop, w("1"), w(44))
111 assert self.space.eq_w(result, w(2))
112 assert self.space.eq_w(space.len(dd), w(1))
113 result = space.call_function(pop, w("1"), w(44))
114 assert self.space.eq_w(result, w(44))
115 assert self.space.eq_w(space.len(dd), w(1))
116
117 self.space.raises_w(space.w_KeyError, space.call_function, pop, w(33))
118
119 def test_get(self):
120 space = self.space
121 w = space.wrap
122 def mydict(w_args=w(()), w_kwds=w({})):
123 return space.call(space.w_dict, w_args, w_kwds)
124 d = mydict(w_kwds=w({"1":2, "3":4}))
125 get = space.getattr(d, w("get"))
126 assert self.space.eq_w(space.call_function(get, w("1")), w(2))
127 assert self.space.eq_w(space.call_function(get, w("1"), w(44)), w(2))
128 assert self.space.eq_w(space.call_function(get, w("33")), w(None))
129 assert self.space.eq_w(space.call_function(get, w("33"), w(44)), w(44))
130
131 def test_fromkeys_fastpath(self):
132 py.test.skip("doesn't make sense here")
133 space = self.space
134 w = space.wrap
135
136 w_l = space.newlist([w("a"),w("b")])
137 w_l.getitems = None
138 w_d = space.call_method(space.w_dict, "fromkeys", w_l)
139
140 assert space.eq_w(w_d.getitem_str("a"), space.w_None)
141 assert space.eq_w(w_d.getitem_str("b"), space.w_None)
142
143 def test_listview_bytes_dict(self):
144 w = self.space.wrap
145 wb = self.space.newbytes
146 w_d = self.space.newdict()
147 w_d.initialize_content([(wb("a"), w(1)), (wb("b"), w(2))])
148 assert self.space.listview_bytes(w_d) == ["a", "b"]
149
150 @py.test.mark.skip("possible re-enable later?")
151 def test_listview_unicode_dict(self):
152 w = self.space.wrap
153 w_d = self.space.newdict()
154 w_d.initialize_content([(w(u"a"), w(1)), (w(u"b"), w(2))])
155 assert self.space.listview_ascii(w_d) == ["a", "b"]
156
157 def test_listview_int_dict(self):
158 w = self.space.wrap
159 w_d = self.space.newdict()
160 w_d.initialize_content([(w(1), w("a")), (w(2), w("b"))])
161 assert self.space.listview_int(w_d) == [1, 2]
162
163 def test_keys_on_string_unicode_int_dict(self, monkeypatch):
164 w = self.space.wrap
165 wb = self.space.newbytes
166
167 w_d = self.space.newdict()
168 w_d.initialize_content([(w(1), wb("a")), (w(2), wb("b"))])
169 w_k = self.space.call_method(w_d, "keys")
170 w_l = self.space.call_function(self.space.w_list, w_k)
171 assert sorted(self.space.listview_int(w_l)) == [1,2]
172
173 # make sure that list(d.keys()) calls newlist_bytes for byte dicts
174 def not_allowed(*args):
175 assert False, 'should not be called'
176 monkeypatch.setattr(self.space, 'newlist', not_allowed)
177 #
178 w_d = self.space.newdict()
179 w_d.initialize_content([(wb("a"), w(1)), (wb("b"), w(6))])
180 w_k = self.space.call_method(w_d, "keys")
181 w_l = self.space.call_function(self.space.w_list, w_k)
182 assert sorted(self.space.listview_bytes(w_l)) == ["a", "b"]
183
184 #---the rest is for listview_unicode(), which is disabled---
185 # XXX: it would be nice if the test passed without monkeypatch.undo(),
186 # but we need space.newlist_unicode for it
187 # monkeypatch.undo()
188 # w_d = self.space.newdict()
189 # w_d.initialize_content([(w(u"a"), w(1)), (w(u"b"), w(6))])
190 # w_l = self.space.call_method(w_d, "keys")
191 # assert sorted(self.space.listview_unicode(w_l)) == [u"a", u"b"]
192
193 def test_update_empty_does_copy(self, monkeypatch):
194 w = self.space.wrap
195 wb = self.space.newbytes
196 w_empty = self.space.newdict()
197 w_d = self.space.newdict()
198 w_d.initialize_content([(w(1), wb("a")), (w(2), wb("b"))])
199 monkeypatch.setattr(EmptyDictStrategy, "setitem", None)
200 update1_dict_dict(self.space, w_empty, w_d)
201 assert self.space.eq_w(w_empty, w_d)
202
203
204 def test_integer_strategy_with_w_long(self):
205 space = self.space
206 w = W_LongObject(rbigint.fromlong(42))
207 w_longlong = W_LongObject(rbigint.fromlong(10**40))
208 w_d = space.newdict()
209 space.setitem(w_d, w, space.w_None)
210 assert w_d.get_strategy() is space.fromcache(IntDictStrategy)
211 #
212 space.setitem(w_d, w_longlong, space.w_None)
213 assert w_d.get_strategy() is space.fromcache(ObjectDictStrategy)
214 #
215 w_d = self.space.newdict()
216 w_d.initialize_content([(w, space.w_None)])
217 assert w_d.get_strategy() is space.fromcache(IntDictStrategy)
218 #
219 w_d = self.space.newdict()
220 w_d.initialize_content([(w_longlong, space.w_None)])
221 assert w_d.get_strategy() is space.fromcache(ObjectDictStrategy)
222
223
224 class AppTest_DictObject:
225 def setup_class(cls):
226 cls.w_on_pypy = cls.space.wrap("__pypy__" in sys.builtin_module_names)
227
228 def test_equality(self):
229 d = {1: 2}
230 f = {1: 2}
231 assert d == f
232 assert d != {1: 3}
233
234 def test_clear(self):
235 d = {1: 2, 3: 4}
236 d.clear()
237 assert len(d) == 0
238
239 def test_copy(self):
240 d = {1: 2, 3: 4}
241 dd = d.copy()
242 assert d == dd
243 assert not d is dd
244
245 def test_get(self):
246 d = {1: 2, 3: 4}
247 assert d.get(1) == 2
248 assert d.get(1, 44) == 2
249 assert d.get(33) == None
250 assert d.get(33, 44) == 44
251
252 def test_pop(self):
253 d = {1: 2, 3: 4}
254 dd = d.copy()
255 result = dd.pop(1)
256 assert result == 2
257 assert len(dd) == 1
258 dd = d.copy()
259 result = dd.pop(1, 44)
260 assert result == 2
261 assert len(dd) == 1
262 result = dd.pop(1, 44)
263 assert result == 44
264 assert len(dd) == 1
265 raises(KeyError, dd.pop, 33)
266
267 assert d.pop("abc", None) is None
268 raises(KeyError, d.pop, "abc")
269 assert len(d) == 2
270
271 def test_pop_empty_bug(self):
272 d = {}
273 assert d.pop(1, 2) == 2
274 def f(**d): return d
275 d = f()
276 assert d.pop(1, 2) == 2
277
278 def test_pop_kwargs(self):
279 def kw(**d): return d
280 d = kw(o=2, t=4)
281 dd = d.copy()
282 result = dd.pop("o")
283 assert result == 2
284 assert len(dd) == 1
285 dd = d.copy()
286 result = dd.pop("o", 44)
287 assert result == 2
288 assert len(dd) == 1
289 result = dd.pop("o", 44)
290 assert result == 44
291 assert len(dd) == 1
292 raises(KeyError, dd.pop, "33")
293
294 assert d.pop("abc", None) is None
295 raises(KeyError, d.pop, "abc")
296 assert len(d) == 2
297
298 def test_items(self):
299 d = {1: 2, 3: 4}
300 its = list(d.items())
301 its.sort()
302 assert its == [(1, 2), (3, 4)]
303
304 def test_iteritems(self):
305 d = {1: 2, 3: 4}
306 dd = d.copy()
307 for k, v in d.items():
308 assert v == dd[k]
309 del dd[k]
310 assert not dd
311
312 def test_iterkeys(self):
313 d = {1: 2, 3: 4}
314 dd = d.copy()
315 for k in d.keys():
316 del dd[k]
317 assert not dd
318
319 def test_itervalues(self):
320 d = {1: 2, 3: 4}
321 values = []
322 for k in d.values():
323 values.append(k)
324 assert values == list(d.values())
325
326 def test_reverse_keys(self):
327 d = {1: 2, 3: 4}
328 assert list(reversed(d)) == [3, 1]
329 assert list(reversed(d.keys())) == [3, 1]
330
331 def test_reverse_values(self):
332 d = {1: 2, 3: 4}
333 assert list(reversed(d.values())) == [4, 2]
334
335 def test_reverse_items(self):
336 d = {1: 2, 3: 4}
337 assert list(reversed(d.items())) == [(3, 4), (1, 2)]
338
339 def test_reversed_dict(self):
340 import __pypy__
341 def kw(**d): return d
342 for d in [{}, {1: 2, 3: 4, 5: 6}, {"a": 5, "b": 2, "c": 6}, kw(a=1, b=2)]:
343 assert list(__pypy__.reversed_dict(d)) == list(d.keys())[::-1]
344 raises(TypeError, __pypy__.reversed_dict, 42)
345
346 def test_reversed_dict_runtimeerror(self):
347 import __pypy__
348 d = {1: 2, 3: 4, 5: 6}
349 it = __pypy__.reversed_dict(d)
350 key = next(it)
351 assert key in [1, 3, 5] # on CPython, dicts are not ordered
352 del d[key]
353 raises(RuntimeError, next, it)
354
355 def test_dict_popitem_first(self):
356 import __pypy__
357 d = {"a": 5}
358 assert __pypy__.dict_popitem_first(d) == ("a", 5)
359 raises(KeyError, __pypy__.dict_popitem_first, d)
360
361 def kwdict(**k):
362 return k
363 d = kwdict(a=55)
364 assert __pypy__.dict_popitem_first(d) == ("a", 55)
365 raises(KeyError, __pypy__.dict_popitem_first, d)
366
367 def test_delitem_if_value_is(self):
368 import __pypy__
369 class X:
370 pass
371 x2 = X()
372 x3 = X()
373 d = {2: x2, 3: x3}
374 __pypy__.delitem_if_value_is(d, 2, x3)
375 assert d == {2: x2, 3: x3}
376 __pypy__.delitem_if_value_is(d, 2, x2)
377 assert d == {3: x3}
378 __pypy__.delitem_if_value_is(d, 2, x3)
379 assert d == {3: x3}
380
381 def test_move_to_end(self):
382 import __pypy__
383 raises(KeyError, __pypy__.move_to_end, {}, 'foo')
384 raises(KeyError, __pypy__.move_to_end, {}, 'foo', last=True)
385 raises(KeyError, __pypy__.move_to_end, {}, 'foo', last=False)
386 def kwdict(**k):
387 return k
388 for last in [False, True]:
389 for d, key in [({1: 2, 3: 4, 5: 6}, 3),
390 ({b"a": 5, b"b": 2, b"c": 6}, b"b"),
391 ({u"a": 5, u"b": 2, u"c": 6}, u"b"),
392 (kwdict(d=7, e=8, f=9), "e")]:
393 other_keys = [k for k in d if k != key]
394 __pypy__.move_to_end(d, key, last=last)
395 if not self.on_pypy:
396 # when running tests on CPython, the underlying
397 # dicts are not ordered. We don't get here if
398 # we're running tests on PyPy or with -A.
399 assert set(d.keys()) == set(other_keys + [key])
400 elif last:
401 assert list(d) == other_keys + [key]
402 else:
403 assert list(d) == [key] + other_keys
404 raises(KeyError, __pypy__.move_to_end, d, key * 3, last=last)
405
406 def test_keys(self):
407 d = {1: 2, 3: 4}
408 kys = list(d.keys())
409 kys.sort()
410 assert kys == [1, 3]
411
412 def test_popitem(self):
413 d = {1: 2, 3: 4}
414 it = d.popitem()
415 assert len(d) == 1
416 assert it == (1, 2) or it == (3, 4)
417 it1 = d.popitem()
418 assert len(d) == 0
419 assert (it != it1) and (it1 == (1, 2) or it1 == (3, 4))
420 raises(KeyError, d.popitem)
421
422 def test_popitem_2(self):
423 class A(object):
424 pass
425 d = A().__dict__
426 d['x'] = 5
427 it1 = d.popitem()
428 assert it1 == ('x', 5)
429 raises(KeyError, d.popitem)
430
431 def test_popitem3(self):
432 #object
433 d = {"a": 1, 2: 2, "c": 3}
434 l = []
435 while True:
436 try:
437 l.append(d.popitem())
438 except KeyError:
439 break;
440 assert ("a", 1) in l
441 assert (2, 2) in l
442 assert ("c", 3) in l
443
444 #string
445 d = {"a": 1, "b":2, "c":3}
446 l = []
447 while True:
448 try:
449 l.append(d.popitem())
450 except KeyError:
451 break;
452 assert ("a", 1) in l
453 assert ("b", 2) in l
454 assert ("c", 3) in l
455
456 def test_setdefault(self):
457 d = {1: 2, 3: 4}
458 dd = d.copy()
459 x = dd.setdefault(1, 99)
460 assert d == dd
461 assert x == 2
462 x = dd.setdefault(33, 99)
463 d[33] = 99
464 assert d == dd
465 assert x == 99
466
467 def test_setdefault_fast(self):
468 class Key(object):
469 calls = 0
470 def __hash__(self):
471 self.calls += 1
472 return object.__hash__(self)
473
474 k = Key()
475 d = {}
476 d.setdefault(k, [])
477 if self.on_pypy:
478 assert k.calls == 1
479
480 d.setdefault(k, 1)
481 if self.on_pypy:
482 assert k.calls == 2
483
484 k = Key()
485 d.setdefault(k, 42)
486 if self.on_pypy:
487 assert k.calls == 1
488
489 def test_update(self):
490 d = {1: 2, 3: 4}
491 dd = d.copy()
492 d.update({})
493 assert d == dd
494 d.update({3: 5, 6: 7})
495 assert d == {1: 2, 3: 5, 6: 7}
496
497 def test_update_iterable(self):
498 d = {}
499 d.update((('a',1),))
500 assert d == {'a': 1}
501 d.update([('a',2), ('c',3)])
502 assert d == {'a': 2, 'c': 3}
503
504 def test_update_nop(self):
505 d = {}
506 d.update()
507 assert d == {}
508
509 def test_update_kwargs(self):
510 d = {}
511 d.update(foo='bar', baz=1)
512 assert d == {'foo': 'bar', 'baz': 1}
513
514 def test_update_dict_and_kwargs(self):
515 d = {}
516 d.update({'foo': 'bar'}, baz=1)
517 assert d == {'foo': 'bar', 'baz': 1}
518
519 def test_update_error_messages(self):
520 e = raises(TypeError, {}.update, 1, 2)
521 assert str(e.value) == "update expected at most 1 argument, got 2"
522 e = raises(ValueError, {}.update, [(1, 2, 3, 4, 5)])
523 assert str(e.value) == "dictionary update sequence element #0 has length 5; 2 is required"
524
525 def test_update_keys_method(self):
526 class Foo(object):
527 def keys(self):
528 return [4, 1]
529 def __getitem__(self, key):
530 return key * 10
531 d = {}
532 d.update(Foo())
533 assert d == {1: 10, 4: 40}
534
535 def test_values(self):
536 d = {1: 2, 3: 4}
537 vals = list(d.values())
538 vals.sort()
539 assert vals == [2, 4]
540
541 def test_eq(self):
542 d1 = {1: 2, 3: 4}
543 d2 = {1: 2, 3: 4}
544 d3 = {1: 2}
545 bool = d1 == d2
546 assert bool == True
547 bool = d1 == d3
548 assert bool == False
549 bool = d1 != d2
550 assert bool == False
551 bool = d1 != d3
552 assert bool == True
553
554 def test_richcompare(self):
555 import operator
556 d1 = {1: 2, 3: 4}
557 d2 = {1: 2, 3: 5}
558 for op in 'lt', 'le', 'gt', 'ge':
559 f = getattr(operator, op)
560 raises(TypeError, f, d1, d2)
561
562 def test_str_repr(self):
563 assert '{}' == str({})
564 assert '{1: 2}' == str({1: 2})
565 assert "{'ba': 'bo'}" == str({'ba': 'bo'})
566 # NOTE: the string repr depends on hash values of 1 and 'ba'!!!
567 ok_reprs = ["{1: 2, 'ba': 'bo'}", "{'ba': 'bo', 1: 2}"]
568 assert str({1: 2, 'ba': 'bo'}) in ok_reprs
569 assert '{}' == repr({})
570 assert '{1: 2}' == repr({1: 2})
571 assert "{'ba': 'bo'}" == repr({'ba': 'bo'})
572 assert str({1: 2, 'ba': 'bo'}) in ok_reprs
573
574 # Now test self-containing dict
575 d = {}
576 d[0] = d
577 assert str(d) == '{0: {...}}'
578
579 # Mutating while repr'ing
580 class Machiavelli(object):
581 def __repr__(self):
582 d.clear()
583 return "42"
584 d = {Machiavelli(): True}
585 str(d)
586 assert d == {}
587
588 def test_new(self):
589 d = dict()
590 assert d == {}
591 args = [['a', 2], [23, 45]]
592 d = dict(args)
593 assert d == {'a': 2, 23: 45}
594 d = dict(args, a=33, b=44)
595 assert d == {'a': 33, 'b': 44, 23: 45}
596 d = dict(a=33, b=44)
597 assert d == {'a': 33, 'b': 44}
598 d = dict({'a': 33, 'b': 44})
599 assert d == {'a': 33, 'b': 44}
600 raises((TypeError, ValueError), dict, 23)
601 raises((TypeError, ValueError), dict, [[1, 2, 3]])
602
603 def test_fromkeys(self):
604 assert {}.fromkeys([1, 2], 1) == {1: 1, 2: 1}
605 assert {}.fromkeys([1, 2]) == {1: None, 2: None}
606 assert {}.fromkeys([]) == {}
607 assert {1: 0, 2: 0, 3: 0}.fromkeys([1, '1'], 'j') == (
608 {1: 'j', '1': 'j'})
609 class D(dict):
610 def __new__(cls):
611 return E()
612 class E(dict):
613 pass
614 assert isinstance(D.fromkeys([1, 2]), E)
615 assert dict.fromkeys({"a": 2, "b": 3}) == {"a": None, "b": None}
616 assert dict.fromkeys({"a": 2, 1: 3}) == {"a": None, 1: None}
617
618 def test_str_uses_repr(self):
619 class D(dict):
620 def __repr__(self):
621 return 'hi'
622 assert repr(D()) == 'hi'
623 assert str(D()) == 'hi'
624
625 def test_overridden_setitem(self):
626 class D(dict):
627 def __setitem__(self, key, value):
628 dict.__setitem__(self, key, 42)
629 d = D([('x', 'foo')], y = 'bar')
630 assert d['x'] == 'foo'
631 assert d['y'] == 'bar'
632
633 d.setdefault('z', 'baz')
634 assert d['z'] == 'baz'
635
636 d['foo'] = 'bar'
637 assert d['foo'] == 42
638
639 d.update({'w': 'foobar'})
640 assert d['w'] == 'foobar'
641
642 d = d.copy()
643 assert d['x'] == 'foo'
644
645 d3 = D.fromkeys(['x', 'y'], 'foo')
646 assert d3['x'] == 42
647 assert d3['y'] == 42
648
649 def test_overridden_setitem_customkey(self):
650 class D(dict):
651 def __setitem__(self, key, value):
652 dict.__setitem__(self, key, 42)
653 class Foo(object):
654 pass
655
656 d = D()
657 key = Foo()
658 d[key] = 'bar'
659 assert d[key] == 42
660
661 def test_repr_with_overridden_items(self):
662 class D(dict):
663 def items(self):
664 return []
665
666 d = D([("foo", "foobar")])
667 assert repr(d) == "{'foo': 'foobar'}"
668
669 def test_popitem_with_overridden_delitem(self):
670 class D(dict):
671 def __delitem__(self, key):
672 assert False
673 d = D()
674 d['a'] = 42
675 item = d.popitem()
676 assert item == ('a', 42)
677
678 def test_dict_update_overridden_getitem(self):
679 class D(dict):
680 def __getitem__(self, key):
681 return 42
682 d1 = {}
683 d2 = D(a='foo')
684 d1.update(d2)
685 assert d1['a'] == 'foo'
686 # a bit of an obscure case: now (from r78295) we get the same result
687 # as CPython does
688
689 def test_index_keyerror_unpacking(self):
690 d = {}
691 for v1 in ['Q', (1,)]:
692 try:
693 d[v1]
694 except KeyError as e:
695 v2 = e.args[0]
696 assert v1 == v2
697 else:
698 assert False, 'Expected KeyError'
699
700 def test_del_keyerror_unpacking(self):
701 d = {}
702 for v1 in ['Q', (1,)]:
703 try:
704 del d[v1]
705 except KeyError as e:
706 v2 = e.args[0]
707 assert v1 == v2
708 else:
709 assert False, 'Expected KeyError'
710
711 def test_pop_keyerror_unpacking(self):
712 d = {}
713 for v1 in ['Q', (1,)]:
714 try:
715 d.pop(v1)
716 except KeyError as e:
717 v2 = e.args[0]
718 assert v1 == v2
719 else:
720 assert False, 'Expected KeyError'
721
722 def test_pop_switching_strategy(self):
723 class Foo:
724 def __hash__(self):
725 return hash("a")
726 def __eq__(self, other):
727 return other == "a"
728 d = {"a": 42}
729 x = d.pop(Foo())
730 assert x == 42 and len(d) == 0
731 d = {"b": 43}
732 raises(KeyError, d.pop, Foo())
733
734 def test_no_len_on_dict_iter(self):
735 iterable = {1: 2, 3: 4}
736 raises(TypeError, len, iter(iterable))
737 iterable = {"1": 2, "3": 4}
738 raises(TypeError, len, iter(iterable))
739 iterable = {}
740 raises(TypeError, len, iter(iterable))
741
742 def test_missing(self):
743 class X(dict):
744 def __missing__(self, x):
745 assert x == 'hi'
746 return 42
747 assert X()['hi'] == 42
748
749 def test_missing_more(self):
750 def missing(self, x):
751 assert x == 'hi'
752 return 42
753 class SpecialDescr(object):
754 def __init__(self, impl):
755 self.impl = impl
756 def __get__(self, obj, owner):
757 return self.impl.__get__(obj, owner)
758 class X(dict):
759 __missing__ = SpecialDescr(missing)
760 assert X()['hi'] == 42
761
762 def test_empty_dict(self):
763 d = {}
764 raises(KeyError, d.popitem)
765 assert list(d.items()) == []
766 assert list(d.values()) == []
767 assert list(d.keys()) == []
768
769 def test_bytes_keys(self):
770 assert isinstance(list({b'a': 1})[0], bytes)
771
772 def test_interned_keywords(self):
773 skip("no longer works")
774 # At some point in the past, we had kwargsdict automatically
775 # intern every single key we get out of it. That's a big
776 # pointless waste of time. So the following test fails now.
777 assert list(dict(abcdef=1))[0] is 'abcdef'
778
779 def test_dict_copy(self):
780 class my_dict_1(dict):
781 def keys(self):
782 return iter(['b'])
783
784 class my_dict_2(my_dict_1):
785 __iter__ = 42
786
787 d1 = my_dict_1({'a': 1, 'b': 2})
788 assert dict(d1) == {'a': 1, 'b': 2} # doesn't use overridden keys()
789
790 d2 = my_dict_2({'a': 1, 'b': 2})
791 assert dict(d2) == {'b': 2} # uses overridden keys()
792
793 def test_or(self):
794 d = {'spam': 1, 'eggs': 2, 'cheese': 3}
795 e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
796 assert d | e == {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
797 assert e | d == {'cheese': 3, 'aardvark': 'Ethel', 'spam': 1, 'eggs': 2}
798 assert d.__or__(None) is NotImplemented
799 class mydict(dict):
800 def __or__(self, other):
801 if type(other) is not mydict:
802 return NotImplemented
803 d = self.copy()
804 d.update(other)
805 return d
806 d = mydict({1: 2})
807 assert d | mydict({3: 4}) == {1: 2, 3: 4}
808
809 # test __ror__
810 assert d | {3: 4} == {1: 2, 3: 4}
811 assert d | {1: 4} == {1: 4}
812
813
814 def test_ior(self):
815 orig = d = {'spam': 1, 'eggs': 2, 'cheese': 3}
816 e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
817 d |= e
818 assert orig == {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
819
820 d = orig = {"a": 6, "b": 7}
821 d |= [("b", 43), ("c", -1j)]
822 assert orig == {"a": 6, "b": 43, "c": -1j}
823
824
825 def test_class_getitem(self):
826 assert dict[int, str].__origin__ is dict
827 assert dict[int, str].__args__ == (int, str)
828
829
830 class AppTest_DictMultiObject(AppTest_DictObject):
831
832 def test_emptydict_unhashable(self):
833 raises(TypeError, "{}[['x']]")
834 raises(TypeError, "del {}[['x']]")
835
836 def test_string_subclass_via_setattr(self):
837 class A(object):
838 pass
839 class S(str):
840 def __hash__(self):
841 return 123
842 a = A()
843 s = S("abc")
844 setattr(a, s, 42)
845 key = next(iter(a.__dict__.keys()))
846 assert key == s
847 assert key is not s
848 assert type(key) is str
849 assert getattr(a, s) == 42
850
851 def test_setattr_string_identify(self):
852 class StrHolder(object):
853 pass
854 holder = StrHolder()
855 class A(object):
856 def __setattr__(self, attr, value):
857 holder.seen = attr
858
859 a = A()
860 s = "abc"
861 setattr(a, s, 123)
862 assert holder.seen is s
863
864 def test_internal_delitem(self):
865 class K:
866 def __hash__(self):
867 return 42
868 def __eq__(self, other):
869 if is_equal[0]:
870 is_equal[0] -= 1
871 return True
872 return False
873 is_equal = [0]
874 k1 = K()
875 k2 = K()
876 d = {k1: 1, k2: 2}
877 k3 = K()
878 is_equal = [1]
879 try:
880 x = d.pop(k3)
881 except RuntimeError:
882 # This used to give a Fatal RPython error: KeyError.
883 # Now at least it should raise an app-level RuntimeError,
884 # or just work.
885 assert len(d) == 2
886 else:
887 assert (x == 1 or x == 2) and len(d) == 1
888
889
890 class AppTestDictViews:
891 def test_dictview(self):
892 d = {1: 2, 3: 4}
893 assert len(d.keys()) == 2
894 assert len(d.items()) == 2
895 assert len(d.values()) == 2
896
897 def test_dict_keys(self):
898 d = {1: 10, "a": "ABC"}
899 keys = d.keys()
900 assert len(keys) == 2
901 assert set(keys) == set([1, "a"])
902 assert keys == set([1, "a"])
903 assert keys == frozenset([1, "a"])
904 assert keys != set([1, "a", "b"])
905 assert keys != set([1, "b"])
906 assert keys != set([1])
907 assert keys != 42
908 assert not keys == 42
909 assert 1 in keys
910 assert "a" in keys
911 assert 10 not in keys
912 assert "Z" not in keys
913 raises(TypeError, "[] in keys") # [] is unhashable
914 raises(TypeError, keys.__contains__, [])
915 assert d.keys() == d.keys()
916 e = {1: 11, "a": "def"}
917 assert d.keys() == e.keys()
918 del e["a"]
919 assert d.keys() != e.keys()
920
921 def test_dict_items(self):
922 d = {1: 10, "a": "ABC"}
923 items = d.items()
924 assert len(items) == 2
925 assert set(items) == set([(1, 10), ("a", "ABC")])
926 assert items == set([(1, 10), ("a", "ABC")])
927 assert items == frozenset([(1, 10), ("a", "ABC")])
928 assert items != set([(1, 10), ("a", "ABC"), "junk"])
929 assert items != set([(1, 10), ("a", "def")])
930 assert items != set([(1, 10)])
931 assert items != 42
932 assert not items == 42
933 assert (1, 10) in items
934 assert ("a", "ABC") in items
935 assert (1, 11) not in items
936 assert 1 not in items
937 assert () not in items
938 assert (1,) not in items
939 assert (1, 2, 3) not in items
940 raises(TypeError, "([], []) not in items") # [] is unhashable
941 raises(TypeError, items.__contains__, ([], []))
942 assert d.items() == d.items()
943 e = d.copy()
944 assert d.items() == e.items()
945 e["a"] = "def"
946 assert d.items() != e.items()
947
948 def test_dict_items_contains_with_identity(self):
949 class BadEq(object):
950 def __eq__(self, other):
951 raise ZeroDivisionError
952 def __hash__(self):
953 return 7
954 k = BadEq()
955 v = BadEq()
956 assert (k, v) in {k: v}.items()
957
958 def test_dict_mixed_keys_items(self):
959 d = {(1, 1): 11, (2, 2): 22}
960 e = {1: 1, 2: 2}
961 assert d.keys() == e.items()
962 assert d.items() != e.keys()
963
964 def test_dict_values(self):
965 d = {1: 10, "a": "ABC"}
966 values = d.values()
967 assert set(values) == set([10, "ABC"])
968 assert len(values) == 2
969 assert not values == 42
970
971 def test_dict_repr(self):
972 d = {1: 10, "a": "ABC"}
973 assert isinstance(repr(d), str)
974 r = repr(d.items())
975 assert isinstance(r, str)
976 assert (r == "dict_items([('a', 'ABC'), (1, 10)])" or
977 r == "dict_items([(1, 10), ('a', 'ABC')])")
978 r = repr(d.keys())
979 assert isinstance(r, str)
980 assert (r == "dict_keys(['a', 1])" or
981 r == "dict_keys([1, 'a'])")
982 r = repr(d.values())
983 assert isinstance(r, str)
984 assert (r == "dict_values(['ABC', 10])" or
985 r == "dict_values([10, 'ABC'])")
986 d = {'日本': '日本国'}
987 assert repr(d.items()) == "dict_items([('日本', '日本国')])"
988
989 def test_recursive_repr(self):
990 d = {1: 2}
991 d[2] = d.values()
992 assert repr(d) == '{1: 2, 2: dict_values([2, ...])}'
993
994 def test_keys_set_operations(self):
995 d1 = {'a': 1, 'b': 2}
996 d2 = {'b': 3, 'c': 2}
997 d3 = {'d': 4, 'e': 5}
998 assert d1.keys() & d1.keys() == set('ab')
999 assert d1.keys() & d2.keys() == set('b')
1000 assert d1.keys() & d3.keys() == set()
1001 assert d1.keys() & set(d1.keys()) == set('ab')
1002 assert d1.keys() & set(d2.keys()) == set('b')
1003 assert d1.keys() & set(d3.keys()) == set()
1004
1005 assert d1.keys() | d1.keys() == set('ab')
1006 assert d1.keys() | d2.keys() == set('abc')
1007 assert d1.keys() | d3.keys() == set('abde')
1008 assert d1.keys() | set(d1.keys()) == set('ab')
1009 assert d1.keys() | set(d2.keys()) == set('abc')
1010 assert d1.keys() | set(d3.keys()) == set('abde')
1011
1012 assert d1.keys() ^ d1.keys() == set()
1013 assert d1.keys() ^ d2.keys() == set('ac')
1014 assert d1.keys() ^ d3.keys() == set('abde')
1015 assert d1.keys() ^ set(d1.keys()) == set()
1016 assert d1.keys() ^ set(d2.keys()) == set('ac')
1017 assert d1.keys() ^ set(d3.keys()) == set('abde')
1018
1019 assert d1.keys() - d1.keys() == set()
1020 assert d1.keys() - d2.keys() == set('a')
1021 assert d1.keys() - d3.keys() == set('ab')
1022 assert d1.keys() - set(d1.keys()) == set()
1023 assert d1.keys() - set(d2.keys()) == set('a')
1024 assert d1.keys() - set(d3.keys()) == set('ab')
1025
1026 assert not d1.keys().isdisjoint(d1.keys())
1027 assert not d1.keys().isdisjoint(d2.keys())
1028 assert not d1.keys().isdisjoint(list(d2.keys()))
1029 assert not d1.keys().isdisjoint(set(d2.keys()))
1030
1031 assert d1.keys().isdisjoint(['x', 'y', 'z'])
1032 assert d1.keys().isdisjoint(set(['x', 'y', 'z']))
1033 assert d1.keys().isdisjoint(set(['x', 'y']))
1034 assert d1.keys().isdisjoint(['x', 'y'])
1035 assert d1.keys().isdisjoint({})
1036 assert d1.keys().isdisjoint(d3.keys())
1037
1038 de = {}
1039 assert de.keys().isdisjoint(set())
1040 assert de.keys().isdisjoint([])
1041 assert de.keys().isdisjoint(de.keys())
1042 assert de.keys().isdisjoint([1])
1043
1044
1045 def test_items_set_operations(self):
1046 d1 = {'a': 1, 'b': 2}
1047 d2 = {'a': 2, 'b': 2}
1048 d3 = {'d': 4, 'e': 5}
1049 assert d1.items() & d1.items() == set([('a', 1), ('b', 2)])
1050 assert d1.items() & d2.items() == set([('b', 2)])
1051 assert d1.items() & d3.items() == set()
1052 assert d1.items() & set(d1.items()) == set([('a', 1), ('b', 2)])
1053 assert d1.items() & set(d2.items()) == set([('b', 2)])
1054 assert d1.items() & set(d3.items()) == set()
1055
1056 assert d1.items() | d1.items() == set([('a', 1), ('b', 2)])
1057 assert (d1.items() | d2.items() ==
1058 set([('a', 1), ('a', 2), ('b', 2)]))
1059 assert (d1.items() | d3.items() ==
1060 set([('a', 1), ('b', 2), ('d', 4), ('e', 5)]))
1061 assert (d1.items() | set(d1.items()) ==
1062 set([('a', 1), ('b', 2)]))
1063 assert (d1.items() | set(d2.items()) ==
1064 set([('a', 1), ('a', 2), ('b', 2)]))
1065 assert (d1.items() | set(d3.items()) ==
1066 set([('a', 1), ('b', 2), ('d', 4), ('e', 5)]))
1067
1068 assert d1.items() ^ d1.items() == set()
1069 assert d1.items() ^ d2.items() == set([('a', 1), ('a', 2)])
1070 assert (d1.items() ^ d3.items() ==
1071 set([('a', 1), ('b', 2), ('d', 4), ('e', 5)]))
1072
1073 assert d1.items() - d1.items() == set()
1074 assert d1.items() - d2.items() == set([('a', 1)])
1075 assert d1.items() - d3.items() == set([('a', 1), ('b', 2)])
1076
1077 assert not d1.items().isdisjoint(d1.items())
1078 assert not d1.items().isdisjoint(d2.items())
1079 assert not d1.items().isdisjoint(list(d2.items()))
1080 assert not d1.items().isdisjoint(set(d2.items()))
1081 assert d1.items().isdisjoint(['x', 'y', 'z'])
1082 assert d1.items().isdisjoint(set(['x', 'y', 'z']))
1083 assert d1.items().isdisjoint(set(['x', 'y']))
1084 assert d1.items().isdisjoint({})
1085 assert d1.items().isdisjoint(d3.items())
1086
1087 de = {}
1088 assert de.items().isdisjoint(set())
1089 assert de.items().isdisjoint([])
1090 assert de.items().isdisjoint(de.items())
1091 assert de.items().isdisjoint([1])
1092
1093 def test_keys_set_operations_any_type(self):
1094 """
1095 d = {1: 'a', 2: 'b', 3: 'c'}
1096 assert d.keys() & {1} == {1}
1097 assert d.keys() & {1: 'foo'} == {1}
1098 assert d.keys() & [1, 2] == {1, 2}
1099 #
1100 assert {1} & d.keys() == {1}
1101 assert {1: 'foo'} & d.keys() == {1}
1102 assert [1, 2] & d.keys() == {1, 2}
1103 #
1104 assert d.keys() - {1} == {2, 3}
1105 assert {1, 4} - d.keys() == {4}
1106 #
1107 assert d.keys() == {1, 2, 3}
1108 assert {1, 2, 3} == d.keys()
1109 assert d.keys() == frozenset({1, 2, 3})
1110 assert frozenset({1, 2, 3}) == d.keys()
1111 assert not d.keys() != {1, 2, 3}
1112 assert not {1, 2, 3} != d.keys()
1113 assert not d.keys() != frozenset({1, 2, 3})
1114 assert not frozenset({1, 2, 3}) != d.keys()
1115 """
1116
1117 def test_items_set_operations_any_type(self):
1118 """
1119 d = {1: 'a', 2: 'b', 3: 'c'}
1120 assert d.items() & {(1, 'a')} == {(1, 'a')}
1121 assert d.items() & {(1, 'a'): 'foo'} == {(1, 'a')}
1122 assert d.items() & [(1, 'a'), (2, 'b')] == {(1, 'a'), (2, 'b')}
1123 #
1124 assert {(1, 'a')} & d.items() == {(1, 'a')}
1125 assert {(1, 'a'): 'foo'} & d.items() == {(1, 'a')}
1126 assert [(1, 'a'), (2, 'b')] & d.items() == {(1, 'a'), (2, 'b')}
1127 #
1128 assert d.items() - {(1, 'a')} == {(2, 'b'), (3, 'c')}
1129 assert {(1, 'a'), 4} - d.items() == {4}
1130 #
1131 assert d.items() == {(1, 'a'), (2, 'b'), (3, 'c')}
1132 assert {(1, 'a'), (2, 'b'), (3, 'c')} == d.items()
1133 assert d.items() == frozenset({(1, 'a'), (2, 'b'), (3, 'c')})
1134 assert frozenset({(1, 'a'), (2, 'b'), (3, 'c')}) == d.items()
1135 assert not d.items() != {(1, 'a'), (2, 'b'), (3, 'c')}
1136 assert not {(1, 'a'), (2, 'b'), (3, 'c')} != d.items()
1137 assert not d.items() != frozenset({(1, 'a'), (2, 'b'), (3, 'c')})
1138 assert not frozenset({(1, 'a'), (2, 'b'), (3, 'c')}) != d.items()
1139 """
1140
1141 def test_dictviewset_unhashable_values(self):
1142 class C:
1143 def __eq__(self, other):
1144 return True
1145 d = {1: C()}
1146 assert d.items() <= d.items()
1147
1148 def test_compare_keys_and_items(self):
1149 d1 = {1: 2}
1150 d2 = {(1, 2): 'foo'}
1151 assert d1.items() == d2.keys()
1152
1153 def test_keys_items_contained(self):
1154 def helper(fn):
1155 empty = fn(dict())
1156 empty2 = fn(dict())
1157 smaller = fn({1:1, 2:2})
1158 larger = fn({1:1, 2:2, 3:3})
1159 larger2 = fn({1:1, 2:2, 3:3})
1160 larger3 = fn({4:1, 2:2, 3:3})
1161
1162 assert smaller < larger
1163 assert smaller <= larger
1164 assert larger > smaller
1165 assert larger >= smaller
1166
1167 assert not smaller >= larger
1168 assert not smaller > larger
1169 assert not larger <= smaller
1170 assert not larger < smaller
1171
1172 assert not smaller < larger3
1173 assert not smaller <= larger3
1174 assert not larger3 > smaller
1175 assert not larger3 >= smaller
1176
1177 # Inequality strictness
1178 assert larger2 >= larger
1179 assert larger2 <= larger
1180 assert not larger2 > larger
1181 assert not larger2 < larger
1182
1183 assert larger == larger2
1184 assert smaller != larger
1185
1186 # There is an optimization on the zero-element case.
1187 assert empty == empty2
1188 assert not empty != empty2
1189 assert not empty == smaller
1190 assert empty != smaller
1191
1192 # With the same size, an elementwise compare happens
1193 assert larger != larger3
1194 assert not larger == larger3
1195
1196 helper(lambda x: x.keys())
1197 helper(lambda x: x.items())
1198
1199 def test_pickle(self):
1200 d = {1: 1, 2: 2, 3: 3}
1201 it = iter(d)
1202 first = next(it)
1203 reduced = it.__reduce__()
1204 rebuild, args = reduced
1205 new = rebuild(*args)
1206 items = set(new)
1207 assert len(items) == 2
1208 items.add(first)
1209 assert items == set(d)
1210
1211 def test_contains(self):
1212 logger = []
1213
1214 class Foo(object):
1215
1216 def __init__(self, value, name=None):
1217 self.value = value
1218 self.name = name or value
1219
1220 def __repr__(self):
1221 return '<Foo %s>' % self.name
1222
1223 def __eq__(self, other):
1224 logger.append((self, other))
1225 return self.value == other.value
1226
1227 def __hash__(self):
1228 return 42 # __eq__ will be used given all objects' hashes clash
1229
1230 foo1, foo2, foo3 = Foo(1), Foo(2), Foo(3)
1231 foo42 = Foo(42)
1232 foo_dict = {foo1: 1, foo2: 1, foo3: 1}
1233 del logger[:]
1234 foo42 in foo_dict
1235 logger_copy = set(logger[:]) # prevent re-evaluation during pytest error print
1236 assert logger_copy == {(foo3, foo42), (foo2, foo42), (foo1, foo42)}
1237
1238 del logger[:]
1239 foo2_bis = Foo(2, '2 bis')
1240 foo2_bis in foo_dict
1241 logger_copy = set(logger[:]) # prevent re-evaluation during pytest error print
1242 assert (foo2, foo2_bis) in logger_copy
1243 assert logger_copy.issubset({(foo1, foo2_bis), (foo2, foo2_bis), (foo3, foo2_bis)})
1244
1245 def test_pickle(self):
1246 d = {1: 1, 2: 2, 3: 3}
1247 it = iter(d)
1248 first = next(it)
1249 reduced = it.__reduce__()
1250 rebuild, args = reduced
1251 new = rebuild(*args)
1252 items = list(new)
1253 assert len(items) == 2
1254 items.insert(0, first)
1255 assert items == list(d)
1256
1257 def test_pickle_reversed(self):
1258 for meth in dict.keys, dict.values, dict.items:
1259 d = {1: 1, 2: 2, 3: 4}
1260 it = iter(reversed(meth(d)))
1261 first = next(it)
1262 reduced = it.__reduce__()
1263 rebuild, args = reduced
1264 new = rebuild(*args)
1265 items = list(new)
1266 assert len(items) == 2
1267 items.insert(0, first)
1268 assert items == list(reversed(meth(d)))
1269
1270 def test_mapping(self):
1271 d = {1: 2, 3: 4}
1272 class A:
1273 a = 1
1274 assert d.keys().mapping == d
1275 assert isinstance(d.keys().mapping, type(A.__dict__))
1276 assert d.items().mapping == d
1277 assert d.values().mapping == d
1278
1279
1280 class AppTestStrategies(object):
1281 def setup_class(cls):
1282 if cls.runappdirect:
1283 py.test.skip("__repr__ doesn't work on appdirect")
1284
1285 def w_get_strategy(self, obj):
1286 import __pypy__
1287 r = __pypy__.internal_repr(obj)
1288 return r[r.find("(") + 1: r.find(")")]
1289
1290 def test_empty_to_string(self):
1291 d = {}
1292 assert "EmptyDictStrategy" in self.get_strategy(d)
1293 d[b"a"] = 1
1294 assert "BytesDictStrategy" in self.get_strategy(d)
1295
1296 class O(object):
1297 pass
1298 o = O()
1299 d = o.__dict__ = {}
1300 assert "EmptyDictStrategy" in self.get_strategy(d)
1301 o.a = 1
1302 assert "UnicodeDictStrategy" in self.get_strategy(d)
1303
1304 def test_empty_to_unicode(self):
1305 d = {}
1306 assert "EmptyDictStrategy" in self.get_strategy(d)
1307 d[u"a"] = 1
1308 assert "UnicodeDictStrategy" in self.get_strategy(d)
1309 assert d["a"] == 1
1310 #assert d[b"a"] == 1 # this works in py2, but not in py3
1311 assert list(d.keys()) == ["a"]
1312 assert type(list(d.keys())[0]) is str
1313
1314 def test_setitem_str_nonascii(self):
1315 d = {}
1316 assert "EmptyDictStrategy" in self.get_strategy(d)
1317 d[u"a"] = 1
1318 assert "UnicodeDictStrategy" in self.get_strategy(d)
1319 exec("a = 1", d)
1320 assert d["a"] == 1
1321 assert "UnicodeDictStrategy" in self.get_strategy(d)
1322 exec("ä = 2", d)
1323 assert "UnicodeDictStrategy" in self.get_strategy(d)
1324 assert d["a"] == 1
1325 assert d["ä"] == 2
1326
1327 d = {}
1328 d[u"ä"] = 1
1329 assert "UnicodeDictStrategy" in self.get_strategy(d)
1330
1331 def test_empty_to_int(self):
1332 d = {}
1333 d[1] = "hi"
1334 assert "IntDictStrategy" in self.get_strategy(d)
1335
1336 def test_iter_dict_length_change(self):
1337 d = {1: 2, 3: 4, 5: 6}
1338 it = iter(d.items())
1339 d[7] = 8
1340 # 'd' is now length 4
1341 raises(RuntimeError, next, it)
1342
1343 def test_iter_dict_strategy_only_change_1(self):
1344 d = {1: 2, 3: 4, 5: 6}
1345 it = d.items()
1346 class Foo(object):
1347 def __eq__(self, other):
1348 return False
1349 def __hash__(self):
1350 return 0
1351 assert d.get(Foo()) is None # this changes the strategy of 'd'
1352 lst = list(it) # but iterating still works
1353 assert sorted(lst) == [(1, 2), (3, 4), (5, 6)]
1354
1355 def test_iter_dict_strategy_only_change_2(self):
1356 d = {1: 2, 3: 4, 5: 6}
1357 it = d.items()
1358 d['foo'] = 'bar'
1359 del d[1]
1360 # on default the strategy changes and thus we get the RuntimeError
1361 # (commented below). On py3k, we Int and String strategies don't work
1362 # yet, and thus we get the "correct" behavior
1363 items = list(it)
1364 assert set(items) == set([(3, 4), (5, 6), ('foo', 'bar')])
1365 # 'd' is still length 3, but its strategy changed. we are
1366 # getting a RuntimeError because iterating over the old storage
1367 # gives us (1, 2), but 1 is not in the dict any longer.
1368 #raises(RuntimeError, list, it)
1369
1370 def test_bytes_to_object(self):
1371 d = {b'a': 'b'}
1372 d[object()] = None
1373 assert b'a' in list(d)
1374
1375
1376 class FakeString(str):
1377
1378 hash_count = 0
1379
1380 def unwrap(self, space):
1381 self.unwrapped = True
1382 return str(self)
1383
1384 def __hash__(self):
1385 self.hash_count += 1
1386 return str.__hash__(self)
1387
1388 class FakeUnicode(unicode):
1389
1390 hash_count = 0
1391
1392 def unwrap(self, space):
1393 self.unwrapped = True
1394 return unicode(self)
1395
1396 def __hash__(self):
1397 self.hash_count += 1
1398 return unicode.__hash__(self)
1399
1400 def hash_w(self):
1401 return hash(self)
1402
1403 def eq_w(self, other):
1404 return self == other
1405
1406 def is_ascii(self):
1407 return True
1408
1409 def unwrapped(self):
1410 return True
1411
1412 # the minimal 'space' needed to use a W_DictMultiObject
1413 class FakeSpace:
1414 hash_count = 0
1415 def hash_w(self, obj):
1416 self.hash_count += 1
1417 return hash(obj)
1418 def unwrap(self, x):
1419 return x
1420 def is_true(self, x):
1421 return x
1422 def is_(self, x, y):
1423 return x is y
1424 is_w = is_
1425 def eq(self, x, y):
1426 return x == y
1427 eq_w = eq
1428 def newlist(self, l):
1429 return l
1430 def newlist_bytes(self, l):
1431 return l
1432 def newlist_text(self, l):
1433 return l
1434 def newlist_unicode(self, l):
1435 return l
1436 DictObjectCls = W_DictObject
1437 def type(self, w_obj):
1438 if isinstance(w_obj, FakeString):
1439 return str
1440 if isinstance(w_obj, FakeUnicode):
1441 return unicode
1442 return type(w_obj)
1443 w_unicode = unicode
1444 w_text = unicode
1445 w_bytes = str
1446
1447 def text_w(self, u):
1448 assert isinstance(u, unicode)
1449 return FakeUnicode(u).encode('utf8')
1450
1451 def bytes_w(self, string):
1452 assert isinstance(string, str)
1453 return string
1454
1455 def utf8_w(self, u):
1456 if isinstance(u, unicode):
1457 u = u.encode('utf8')
1458 assert isinstance(u, str)
1459 return u
1460
1461 def int_w(self, integer, allow_conversion=True):
1462 assert isinstance(integer, int)
1463 return integer
1464
1465 def float_w(self, fl, allow_conversion=True):
1466 assert isinstance(fl, float)
1467 return fl
1468
1469 def wrap(self, obj):
1470 if isinstance(obj, str):
1471 return FakeUnicode(obj.decode('ascii'))
1472 return obj
1473
1474 def newtext(self, string):
1475 if isinstance(string, str):
1476 return FakeUnicode(string.decode('utf-8'))
1477 assert isinstance(string, unicode)
1478 return FakeUnicode(string)
1479
1480 def newutf8(self, obj, lgt):
1481 return obj
1482
1483 def newbytes(self, obj):
1484 return obj
1485
1486 def new_interned_str(self, s):
1487 return s.decode('utf-8')
1488
1489 newint = newfloat = wrap
1490
1491 def isinstance_w(self, obj, klass):
1492 return isinstance(obj, klass)
1493 isinstance = isinstance_w
1494
1495 def newtuple(self, l):
1496 return tuple(l)
1497
1498 def newtuple2(self, a, b):
1499 return a, b
1500
1501 def newdict(self, module=False, instance=False):
1502 return W_DictObject.allocate_and_init_instance(
1503 self, module=module, instance=instance)
1504
1505 def view_as_kwargs(self, w_d):
1506 return w_d.view_as_kwargs() # assume it's a multidict
1507
1508 def finditem_str(self, w_dict, s):
1509 return w_dict.getitem_str(s) # assume it's a multidict
1510
1511 def setitem_str(self, w_dict, s, w_value):
1512 return w_dict.setitem_str(s, w_value) # assume it's a multidict
1513
1514 def delitem(self, w_dict, w_s):
1515 return w_dict.delitem(w_s) # assume it's a multidict
1516
1517 def allocate_instance(self, cls, type):
1518 return object.__new__(cls)
1519
1520 def fromcache(self, cls):
1521 return cls(self)
1522
1523 def _side_effects_ok(self):
1524 return True
1525
1526 w_StopIteration = StopIteration
1527 w_None = None
1528 w_NoneType = type(None, None)
1529 w_int = int
1530 w_bool = bool
1531 w_float = float
1532 StringObjectCls = FakeString
1533 UnicodeObjectCls = FakeUnicode
1534 IntObjectCls = int
1535 FloatObjectCls = float
1536 w_dict = W_DictObject
1537 iter = iter
1538 fixedview = list
1539 listview = list
1540
1541 class Config:
1542 class objspace:
1543 class std:
1544 methodcachesizeexp = 11
1545 withmethodcachecounter = False
1546 honor__builtins__ = False
1547
1548 FakeSpace.config = Config()
1549
1550
1551 class TestDictImplementation:
1552 def setup_method(self,method):
1553 self.space = FakeSpace()
1554
1555 def test_stressdict(self):
1556 from random import randint
1557 d = self.space.newdict()
1558 N = 10000
1559 pydict = {}
1560 for i in range(N):
1561 x = randint(-N, N)
1562 d.descr_setitem(self.space, x, i)
1563 pydict[x] = i
1564 for key, value in pydict.iteritems():
1565 assert value == d.descr_getitem(self.space, key)
1566
1567 class BaseTestRDictImplementation:
1568 FakeString = FakeUnicode
1569 _str_devolves = False
1570
1571 def setup_method(self,method):
1572 self.fakespace = FakeSpace()
1573 self.string = self.wrapstrorunicode("fish")
1574 self.string2 = self.wrapstrorunicode("fish2")
1575 self.impl = self.get_impl()
1576
1577 def wrapstrorunicode(self, obj):
1578 return self.fakespace.wrap(obj)
1579
1580 def get_impl(self):
1581 strategy = self.StrategyClass(self.fakespace)
1582 storage = strategy.get_empty_storage()
1583 w_dict = self.fakespace.allocate_instance(W_DictObject, None)
1584 W_DictObject.__init__(w_dict, self.fakespace, strategy, storage)
1585 return w_dict
1586
1587 def fill_impl(self):
1588 self.impl.setitem(self.string, 1000)
1589 self.impl.setitem(self.string2, 2000)
1590
1591 def check_not_devolved(self):
1592 #XXX check if strategy changed!?
1593 assert type(self.impl.get_strategy()) is self.StrategyClass
1594 #assert self.impl.r_dict_content is None
1595
1596 def test_popitem(self):
1597 self.fill_impl()
1598 assert self.impl.length() == 2
1599 a, b = self.impl.popitem()
1600 assert self.impl.length() == 1
1601 if a == self.string:
1602 assert b == 1000
1603 assert self.impl.getitem(self.string2) == 2000
1604 else:
1605 assert a == self.string2
1606 assert b == 2000
1607 if not self._str_devolves:
1608 result = self.impl.getitem_str(self.string.encode('utf-8'))
1609 else:
1610 result = self.impl.getitem(self.string)
1611 assert result == 1000
1612 self.check_not_devolved()
1613
1614 def test_setitem(self):
1615 self.impl.setitem(self.string, 1000)
1616 assert self.impl.length() == 1
1617 assert self.impl.getitem(self.string) == 1000
1618 if not self._str_devolves:
1619 result = self.impl.getitem_str(self.string.encode('utf-8'))
1620 else:
1621 result = self.impl.getitem(self.string)
1622 assert result == 1000
1623 self.check_not_devolved()
1624
1625 def test_delitem(self):
1626 self.fill_impl()
1627 assert self.impl.length() == 2
1628 self.impl.delitem(self.string2)
1629 assert self.impl.length() == 1
1630 self.impl.delitem(self.string)
1631 assert self.impl.length() == 0
1632 self.check_not_devolved()
1633
1634 def test_clear(self):
1635 self.fill_impl()
1636 assert self.impl.length() == 2
1637 self.impl.clear()
1638 assert self.impl.length() == 0
1639 self.check_not_devolved()
1640
1641
1642 def test_keys(self):
1643 self.fill_impl()
1644 keys = self.impl.w_keys() # wrapped lists = lists in the fake space
1645 keys.sort()
1646 assert keys == [self.string, self.string2]
1647 self.check_not_devolved()
1648
1649 def test_values(self):
1650 self.fill_impl()
1651 values = self.impl.values()
1652 values.sort()
1653 assert values == [1000, 2000]
1654 self.check_not_devolved()
1655
1656 def test_items(self):
1657 self.fill_impl()
1658 items = self.impl.items()
1659 items.sort()
1660 assert items == zip([self.string, self.string2], [1000, 2000])
1661 self.check_not_devolved()
1662
1663 def test_iter(self):
1664 self.fill_impl()
1665 iteratorimplementation = self.impl.iteritems()
1666 items = []
1667 while 1:
1668 item = iteratorimplementation.next_item()
1669 if item == (None, None):
1670 break
1671 items.append(item)
1672 items.sort()
1673 assert items == zip([self.string, self.string2], [1000, 2000])
1674 self.check_not_devolved()
1675
1676 def test_devolve(self):
1677 impl = self.impl
1678 for x in xrange(100):
1679 impl.setitem(self.fakespace.text_w(unicode(x)), x)
1680 impl.setitem(x, x)
1681 assert type(impl.get_strategy()) is ObjectDictStrategy
1682
1683
1684 setdefault_hash_count = 1
1685
1686 def test_setdefault_fast(self):
1687 on_pypy = "__pypy__" in sys.builtin_module_names
1688 impl = self.impl
1689 key = self.FakeString(self.string)
1690 x = impl.setdefault(key, 1)
1691 assert x == 1
1692 if on_pypy and self.FakeString is FakeString:
1693 assert key.hash_count == self.setdefault_hash_count
1694 x = impl.setdefault(key, 2)
1695 assert x == 1
1696 if on_pypy and self.FakeString is FakeString:
1697 assert key.hash_count == self.setdefault_hash_count + 1
1698
1699 def test_fallback_evil_key(self):
1700 class F(object):
1701 def __hash__(self):
1702 return hash("s")
1703 def __eq__(self, other):
1704 return other == "s"
1705
1706 d = self.get_impl()
1707 w_key = FakeString("s")
1708 d.setitem(w_key, 12)
1709 assert d.getitem(w_key) == 12
1710 assert d.getitem(F()) == d.getitem(w_key)
1711
1712 d = self.get_impl()
1713 x = d.setdefault(w_key, 12)
1714 assert x == 12
1715 x = d.setdefault(F(), 12)
1716 assert x == 12
1717
1718 d = self.get_impl()
1719 x = d.setdefault(F(), 12)
1720 assert x == 12
1721
1722 d = self.get_impl()
1723 d.setitem(w_key, 12)
1724 d.delitem(F())
1725
1726 assert w_key not in d.w_keys()
1727 assert F() not in d.w_keys()
1728
1729 class TestUnicodeDictImplementation(BaseTestRDictImplementation):
1730 StrategyClass = UnicodeDictStrategy
1731
1732 def test_str_shortcut(self):
1733 self.fill_impl()
1734 s = self.FakeString(self.string)
1735 assert self.impl.getitem(s) == 1000
1736 assert s.unwrapped
1737
1738 def test_view_as_kwargs(self):
1739 self.fill_impl()
1740 assert self.fakespace.view_as_kwargs(self.impl) == (["fish", "fish2"], [1000, 2000])
1741
1742 def test_setitem_str(self):
1743 self.impl.setitem_str(self.fakespace.text_w(self.string), 1000)
1744 assert self.impl.length() == 1
1745 assert self.impl.getitem(self.string) == 1000
1746 assert self.impl.getitem_str(str(self.string)) == 1000
1747 self.check_not_devolved()
1748
1749 def test_setitem_str(self):
1750 self.impl.setitem_str(self.fakespace.text_w(self.string), 1000)
1751 assert self.impl.length() == 1
1752 assert self.impl.getitem(self.string) == 1000
1753 assert self.impl.getitem_str(str(self.string)) == 1000
1754 self.check_not_devolved()
1755
1756 class TestBytesDictImplementation(BaseTestRDictImplementation):
1757 StrategyClass = BytesDictStrategy
1758 FakeString = FakeString
1759 _str_devolves = True
1760
1761 def wrapstrorunicode(self, obj):
1762 return self.fakespace.newbytes(obj)
1763
1764
1765 class BaseTestDevolvedDictImplementation(BaseTestRDictImplementation):
1766 def fill_impl(self):
1767 BaseTestRDictImplementation.fill_impl(self)
1768 self.impl.get_strategy().switch_to_object_strategy(self.impl)
1769
1770 def check_not_devolved(self):
1771 pass
1772
1773 class TestDevolvedUnicodeDictImplementation(BaseTestDevolvedDictImplementation):
1774 StrategyClass = UnicodeDictStrategy
1775
1776
1777 def test_module_uses_strdict():
1778 from pypy.objspace.std.celldict import ModuleDictStrategy
1779 fakespace = FakeSpace()
1780 d = fakespace.newdict(module=True)
1781 assert type(d.get_strategy()) is ModuleDictStrategy