1 # tests common to dict and UserDict
7 class BasicTestMappingProtocol(unittest
.TestCase
):
8 # This base class can be used to check that an object conforms to the
11 # Functions that can be useful to override to adapt to dictionary
13 type2test
= None # which class is being tested (overwrite in subclasses)
16 """Return a dictionary of values which are invariant by storage
17 in the object under test."""
18 return {1:2, "key1":"value1", "key2":(1,2,3)}
19 def _empty_mapping(self
):
20 """Return an empty mapping object"""
21 return self
.type2test()
22 def _full_mapping(self
, data
):
23 """Return a mapping object with the value contained in data
25 x
= self
._empty
_mapping
()
26 for key
, value
in data
.items():
30 def __init__(self
, *args
, **kw
):
31 unittest
.TestCase
.__init
__(self
, *args
, **kw
)
32 self
.reference
= self
._reference
().copy()
34 # A (key, value) pair not in the mapping
35 key
, value
= self
.reference
.popitem()
36 self
.other
= {key
:value
}
38 # A (key, value) pair in the mapping
39 key
, value
= self
.reference
.popitem()
40 self
.inmapping
= {key
:value
}
41 self
.reference
[key
] = value
44 # Test for read only operations on mapping
45 p
= self
._empty
_mapping
()
46 p1
= dict(p
) #workaround for singleton objects
47 d
= self
._full
_mapping
(self
.reference
)
51 for key
, value
in self
.reference
.items():
52 self
.assertEqual(d
[key
], value
)
53 knownkey
= self
.other
.keys()[0]
54 self
.assertRaises(KeyError, lambda:d
[knownkey
])
56 self
.assertEqual(len(p
), 0)
57 self
.assertEqual(len(d
), len(self
.reference
))
59 for k
in self
.reference
:
62 self
.assertNotIn(k
, d
)
64 with test_support
.check_py3k_warnings(quiet
=True):
65 for k
in self
.reference
:
66 self
.assertTrue(d
.has_key(k
))
68 self
.assertFalse(d
.has_key(k
))
70 self
.assertEqual(cmp(p
,p
), 0)
71 self
.assertEqual(cmp(d
,d
), 0)
72 self
.assertEqual(cmp(p
,d
), -1)
73 self
.assertEqual(cmp(d
,p
), 1)
75 if p
: self
.fail("Empty mapping must compare to False")
76 if not d
: self
.fail("Full mapping must compare to True")
77 # keys(), items(), iterkeys() ...
78 def check_iterandlist(iter, lst
, ref
):
79 self
.assertTrue(hasattr(iter, 'next'))
80 self
.assertTrue(hasattr(iter, '__iter__'))
82 self
.assertTrue(set(x
)==set(lst
)==set(ref
))
83 check_iterandlist(d
.iterkeys(), d
.keys(), self
.reference
.keys())
84 check_iterandlist(iter(d
), d
.keys(), self
.reference
.keys())
85 check_iterandlist(d
.itervalues(), d
.values(), self
.reference
.values())
86 check_iterandlist(d
.iteritems(), d
.items(), self
.reference
.items())
88 key
, value
= d
.iteritems().next()
89 knownkey
, knownvalue
= self
.other
.iteritems().next()
90 self
.assertEqual(d
.get(key
, knownvalue
), value
)
91 self
.assertEqual(d
.get(knownkey
, knownvalue
), knownvalue
)
92 self
.assertNotIn(knownkey
, d
)
95 # Test for write operations on mapping
96 p
= self
._empty
_mapping
()
98 for key
, value
in self
.reference
.items():
100 self
.assertEqual(p
[key
], value
)
101 for key
in self
.reference
.keys():
103 self
.assertRaises(KeyError, lambda:p
[key
])
104 p
= self
._empty
_mapping
()
106 p
.update(self
.reference
)
107 self
.assertEqual(dict(p
), self
.reference
)
109 p
= self
._empty
_mapping
()
111 self
.assertEqual(dict(p
), self
.reference
)
112 d
= self
._full
_mapping
(self
.reference
)
114 key
, value
= d
.iteritems().next()
115 knownkey
, knownvalue
= self
.other
.iteritems().next()
116 self
.assertEqual(d
.setdefault(key
, knownvalue
), value
)
117 self
.assertEqual(d
[key
], value
)
118 self
.assertEqual(d
.setdefault(knownkey
, knownvalue
), knownvalue
)
119 self
.assertEqual(d
[knownkey
], knownvalue
)
121 self
.assertEqual(d
.pop(knownkey
), knownvalue
)
122 self
.assertNotIn(knownkey
, d
)
123 self
.assertRaises(KeyError, d
.pop
, knownkey
)
125 d
[knownkey
] = knownvalue
126 self
.assertEqual(d
.pop(knownkey
, default
), knownvalue
)
127 self
.assertNotIn(knownkey
, d
)
128 self
.assertEqual(d
.pop(knownkey
, default
), default
)
130 key
, value
= d
.popitem()
131 self
.assertNotIn(key
, d
)
132 self
.assertEqual(value
, self
.reference
[key
])
133 p
=self
._empty
_mapping
()
134 self
.assertRaises(KeyError, p
.popitem
)
136 def test_constructor(self
):
137 self
.assertEqual(self
._empty
_mapping
(), self
._empty
_mapping
())
140 self
.assertTrue(not self
._empty
_mapping
())
141 self
.assertTrue(self
.reference
)
142 self
.assertTrue(bool(self
._empty
_mapping
()) is False)
143 self
.assertTrue(bool(self
.reference
) is True)
146 d
= self
._empty
_mapping
()
147 self
.assertEqual(d
.keys(), [])
149 self
.assertIn(self
.inmapping
.keys()[0], d
.keys())
150 self
.assertNotIn(self
.other
.keys()[0], d
.keys())
151 self
.assertRaises(TypeError, d
.keys
, None)
153 def test_values(self
):
154 d
= self
._empty
_mapping
()
155 self
.assertEqual(d
.values(), [])
157 self
.assertRaises(TypeError, d
.values
, None)
159 def test_items(self
):
160 d
= self
._empty
_mapping
()
161 self
.assertEqual(d
.items(), [])
163 self
.assertRaises(TypeError, d
.items
, None)
166 d
= self
._empty
_mapping
()
167 self
.assertEqual(len(d
), 0)
169 def test_getitem(self
):
171 self
.assertEqual(d
[self
.inmapping
.keys()[0]], self
.inmapping
.values()[0])
173 self
.assertRaises(TypeError, d
.__getitem
__)
175 def test_update(self
):
177 d
= self
._empty
_mapping
()
179 self
.assertEqual(d
.items(), self
.other
.items())
182 d
= self
._empty
_mapping
()
184 self
.assertEqual(d
, self
._empty
_mapping
())
187 d
= self
._empty
_mapping
()
188 d
.update(self
.other
.items())
189 self
.assertEqual(d
.items(), self
.other
.items())
192 d
= self
._empty
_mapping
()
193 d
.update(self
.other
.iteritems())
194 self
.assertEqual(d
.items(), self
.other
.items())
196 # FIXME: Doesn't work with UserDict
197 # self.assertRaises((TypeError, AttributeError), d.update, None)
198 self
.assertRaises((TypeError, AttributeError), d
.update
, 42)
201 class SimpleUserDict
:
203 self
.d
= outerself
.reference
206 def __getitem__(self
, i
):
209 d
.update(SimpleUserDict())
211 i2
= self
.reference
.items()
214 self
.assertEqual(i1
, i2
)
216 class Exc(Exception): pass
218 d
= self
._empty
_mapping
()
219 class FailingUserDict
:
222 self
.assertRaises(Exc
, d
.update
, FailingUserDict())
226 class FailingUserDict
:
239 def __getitem__(self
, key
):
241 self
.assertRaises(Exc
, d
.update
, FailingUserDict())
243 class FailingUserDict
:
251 if self
.i
<= ord('z'):
257 def __getitem__(self
, key
):
259 self
.assertRaises(Exc
, d
.update
, FailingUserDict())
261 d
= self
._empty
_mapping
()
262 class badseq(object):
268 self
.assertRaises(Exc
, d
.update
, badseq())
270 self
.assertRaises(ValueError, d
.update
, [(1, 2, 3)])
272 # no test_fromkeys or test_copy as both os.environ and selves don't support it
275 d
= self
._empty
_mapping
()
276 self
.assertTrue(d
.get(self
.other
.keys()[0]) is None)
277 self
.assertEqual(d
.get(self
.other
.keys()[0], 3), 3)
279 self
.assertTrue(d
.get(self
.other
.keys()[0]) is None)
280 self
.assertEqual(d
.get(self
.other
.keys()[0], 3), 3)
281 self
.assertEqual(d
.get(self
.inmapping
.keys()[0]), self
.inmapping
.values()[0])
282 self
.assertEqual(d
.get(self
.inmapping
.keys()[0], 3), self
.inmapping
.values()[0])
283 self
.assertRaises(TypeError, d
.get
)
284 self
.assertRaises(TypeError, d
.get
, None, None, None)
286 def test_setdefault(self
):
287 d
= self
._empty
_mapping
()
288 self
.assertRaises(TypeError, d
.setdefault
)
290 def test_popitem(self
):
291 d
= self
._empty
_mapping
()
292 self
.assertRaises(KeyError, d
.popitem
)
293 self
.assertRaises(TypeError, d
.popitem
, 42)
296 d
= self
._empty
_mapping
()
297 k
, v
= self
.inmapping
.items()[0]
299 self
.assertRaises(KeyError, d
.pop
, self
.other
.keys()[0])
301 self
.assertEqual(d
.pop(k
), v
)
302 self
.assertEqual(len(d
), 0)
304 self
.assertRaises(KeyError, d
.pop
, k
)
307 class TestMappingProtocol(BasicTestMappingProtocol
):
308 def test_constructor(self
):
309 BasicTestMappingProtocol
.test_constructor(self
)
310 self
.assertTrue(self
._empty
_mapping
() is not self
._empty
_mapping
())
311 self
.assertEqual(self
.type2test(x
=1, y
=2), {"x": 1, "y": 2})
314 BasicTestMappingProtocol
.test_bool(self
)
315 self
.assertTrue(not self
._empty
_mapping
())
316 self
.assertTrue(self
._full
_mapping
({"x": "y"}))
317 self
.assertTrue(bool(self
._empty
_mapping
()) is False)
318 self
.assertTrue(bool(self
._full
_mapping
({"x": "y"})) is True)
321 BasicTestMappingProtocol
.test_keys(self
)
322 d
= self
._empty
_mapping
()
323 self
.assertEqual(d
.keys(), [])
324 d
= self
._full
_mapping
({'a': 1, 'b': 2})
326 self
.assertIn('a', k
)
327 self
.assertIn('b', k
)
328 self
.assertNotIn('c', k
)
330 def test_values(self
):
331 BasicTestMappingProtocol
.test_values(self
)
332 d
= self
._full
_mapping
({1:2})
333 self
.assertEqual(d
.values(), [2])
335 def test_items(self
):
336 BasicTestMappingProtocol
.test_items(self
)
338 d
= self
._full
_mapping
({1:2})
339 self
.assertEqual(d
.items(), [(1, 2)])
341 def test_has_key(self
):
342 d
= self
._empty
_mapping
()
343 self
.assertTrue(not d
.has_key('a'))
344 d
= self
._full
_mapping
({'a': 1, 'b': 2})
347 self
.assertEqual(k
, ['a', 'b'])
349 self
.assertRaises(TypeError, d
.has_key
)
351 def test_contains(self
):
352 d
= self
._empty
_mapping
()
353 self
.assertNotIn('a', d
)
354 self
.assertTrue(not ('a' in d
))
355 self
.assertTrue('a' not in d
)
356 d
= self
._full
_mapping
({'a': 1, 'b': 2})
357 self
.assertIn('a', d
)
358 self
.assertIn('b', d
)
359 self
.assertNotIn('c', d
)
361 self
.assertRaises(TypeError, d
.__contains
__)
364 BasicTestMappingProtocol
.test_len(self
)
365 d
= self
._full
_mapping
({'a': 1, 'b': 2})
366 self
.assertEqual(len(d
), 2)
368 def test_getitem(self
):
369 BasicTestMappingProtocol
.test_getitem(self
)
370 d
= self
._full
_mapping
({'a': 1, 'b': 2})
371 self
.assertEqual(d
['a'], 1)
372 self
.assertEqual(d
['b'], 2)
375 self
.assertEqual(d
['c'], 3)
376 self
.assertEqual(d
['a'], 4)
378 self
.assertEqual(d
, {'a': 4, 'c': 3})
380 self
.assertRaises(TypeError, d
.__getitem
__)
382 def test_clear(self
):
383 d
= self
._full
_mapping
({1:1, 2:2, 3:3})
385 self
.assertEqual(d
, {})
387 self
.assertRaises(TypeError, d
.clear
, None)
389 def test_update(self
):
390 BasicTestMappingProtocol
.test_update(self
)
392 d
= self
._empty
_mapping
()
395 d
.update({1:1, 2:2, 3:3})
396 self
.assertEqual(d
, {1:1, 2:2, 3:3})
400 self
.assertEqual(d
, {1:1, 2:2, 3:3})
403 d
= self
._empty
_mapping
()
406 d
.update(x
=1, y
=2, z
=3)
407 self
.assertEqual(d
, {"x":1, "y":2, "z":3})
410 d
= self
._empty
_mapping
()
411 d
.update([("x", 100), ("y", 20)])
412 self
.assertEqual(d
, {"x":100, "y":20})
414 # Both item sequence and keyword arguments
415 d
= self
._empty
_mapping
()
416 d
.update([("x", 100), ("y", 20)], x
=1, y
=2)
417 self
.assertEqual(d
, {"x":1, "y":2})
420 d
= self
._full
_mapping
({1:3, 2:4})
421 d
.update(self
._full
_mapping
({1:2, 3:4, 5:6}).iteritems())
422 self
.assertEqual(d
, {1:2, 2:4, 3:4, 5:6})
424 class SimpleUserDict
:
426 self
.d
= {1:1, 2:2, 3:3}
429 def __getitem__(self
, i
):
432 d
.update(SimpleUserDict())
433 self
.assertEqual(d
, {1:1, 2:2, 3:3})
435 def test_fromkeys(self
):
436 self
.assertEqual(self
.type2test
.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
437 d
= self
._empty
_mapping
()
438 self
.assertTrue(not(d
.fromkeys('abc') is d
))
439 self
.assertEqual(d
.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
440 self
.assertEqual(d
.fromkeys((4,5),0), {4:0, 5:0})
441 self
.assertEqual(d
.fromkeys([]), {})
444 self
.assertEqual(d
.fromkeys(g()), {1:None})
445 self
.assertRaises(TypeError, {}.fromkeys
, 3)
446 class dictlike(self
.type2test
): pass
447 self
.assertEqual(dictlike
.fromkeys('a'), {'a':None})
448 self
.assertEqual(dictlike().fromkeys('a'), {'a':None})
449 self
.assertTrue(dictlike
.fromkeys('a').__class
__ is dictlike
)
450 self
.assertTrue(dictlike().fromkeys('a').__class
__ is dictlike
)
451 # FIXME: the following won't work with UserDict, because it's an old style class
452 # self.assertTrue(type(dictlike.fromkeys('a')) is dictlike)
453 class mydict(self
.type2test
):
455 return UserDict
.UserDict()
456 ud
= mydict
.fromkeys('ab')
457 self
.assertEqual(ud
, {'a':None, 'b':None})
458 # FIXME: the following won't work with UserDict, because it's an old style class
459 # self.assertIsInstance(ud, UserDict.UserDict)
460 self
.assertRaises(TypeError, dict.fromkeys
)
462 class Exc(Exception): pass
464 class baddict1(self
.type2test
):
468 self
.assertRaises(Exc
, baddict1
.fromkeys
, [1])
470 class BadSeq(object):
476 self
.assertRaises(Exc
, self
.type2test
.fromkeys
, BadSeq())
478 class baddict2(self
.type2test
):
479 def __setitem__(self
, key
, value
):
482 self
.assertRaises(Exc
, baddict2
.fromkeys
, [1])
485 d
= self
._full
_mapping
({1:1, 2:2, 3:3})
486 self
.assertEqual(d
.copy(), {1:1, 2:2, 3:3})
487 d
= self
._empty
_mapping
()
488 self
.assertEqual(d
.copy(), d
)
489 self
.assertIsInstance(d
.copy(), d
.__class
__)
490 self
.assertRaises(TypeError, d
.copy
, None)
493 BasicTestMappingProtocol
.test_get(self
)
494 d
= self
._empty
_mapping
()
495 self
.assertTrue(d
.get('c') is None)
496 self
.assertEqual(d
.get('c', 3), 3)
497 d
= self
._full
_mapping
({'a' : 1, 'b' : 2})
498 self
.assertTrue(d
.get('c') is None)
499 self
.assertEqual(d
.get('c', 3), 3)
500 self
.assertEqual(d
.get('a'), 1)
501 self
.assertEqual(d
.get('a', 3), 1)
503 def test_setdefault(self
):
504 BasicTestMappingProtocol
.test_setdefault(self
)
505 d
= self
._empty
_mapping
()
506 self
.assertTrue(d
.setdefault('key0') is None)
507 d
.setdefault('key0', [])
508 self
.assertTrue(d
.setdefault('key0') is None)
509 d
.setdefault('key', []).append(3)
510 self
.assertEqual(d
['key'][0], 3)
511 d
.setdefault('key', []).append(4)
512 self
.assertEqual(len(d
['key']), 2)
514 def test_popitem(self
):
515 BasicTestMappingProtocol
.test_popitem(self
)
516 for copymode
in -1, +1:
517 # -1: b has same structure as a
519 for log2size
in range(12):
521 a
= self
._empty
_mapping
()
522 b
= self
._empty
_mapping
()
523 for i
in range(size
):
529 for i
in range(size
):
530 ka
, va
= ta
= a
.popitem()
531 self
.assertEqual(va
, int(ka
))
532 kb
, vb
= tb
= b
.popitem()
533 self
.assertEqual(vb
, int(kb
))
534 self
.assertTrue(not(copymode
< 0 and ta
!= tb
))
535 self
.assertTrue(not a
)
536 self
.assertTrue(not b
)
539 BasicTestMappingProtocol
.test_pop(self
)
541 # Tests for pop with specified key
542 d
= self
._empty
_mapping
()
545 # verify longs/ints get same value when key > 32 bits (for 64-bit archs)
547 x
= 4503599627370496L
549 h
= self
._full
_mapping
({x
: 'anything', y
: 'something else'})
550 self
.assertEqual(h
[x
], h
[y
])
552 self
.assertEqual(d
.pop(k
, v
), v
)
554 self
.assertEqual(d
.pop(k
, 1), v
)
557 class TestHashMappingProtocol(TestMappingProtocol
):
559 def test_getitem(self
):
560 TestMappingProtocol
.test_getitem(self
)
561 class Exc(Exception): pass
564 def __eq__(self
, other
):
569 d
= self
._empty
_mapping
()
571 self
.assertRaises(KeyError, d
.__getitem
__, 23)
573 class BadHash(object):
581 d
= self
._empty
_mapping
()
585 self
.assertRaises(Exc
, d
.__getitem
__, x
)
587 def test_fromkeys(self
):
588 TestMappingProtocol
.test_fromkeys(self
)
589 class mydict(self
.type2test
):
591 return UserDict
.UserDict()
592 ud
= mydict
.fromkeys('ab')
593 self
.assertEqual(ud
, {'a':None, 'b':None})
594 self
.assertIsInstance(ud
, UserDict
.UserDict
)
597 TestMappingProtocol
.test_pop(self
)
599 class Exc(Exception): pass
601 class BadHash(object):
609 d
= self
._empty
_mapping
()
613 self
.assertRaises(Exc
, d
.pop
, x
)
615 def test_mutatingiteration(self
):
616 d
= self
._empty
_mapping
()
624 self
.fail("changing dict size during iteration doesn't raise Error")
627 d
= self
._empty
_mapping
()
628 self
.assertEqual(repr(d
), '{}')
630 self
.assertEqual(repr(d
), '{1: 2}')
631 d
= self
._empty
_mapping
()
633 self
.assertEqual(repr(d
), '{1: {...}}')
635 class Exc(Exception): pass
637 class BadRepr(object):
641 d
= self
._full
_mapping
({1: BadRepr()})
642 self
.assertRaises(Exc
, repr, d
)
645 self
.assertTrue(not (self
._empty
_mapping
() < self
._empty
_mapping
()))
646 self
.assertTrue(not (self
._full
_mapping
({1: 2}) < self
._full
_mapping
({1L: 2L})))
648 class Exc(Exception): pass
650 class BadCmp(object):
651 def __eq__(self
, other
):
656 d1
= self
._full
_mapping
({BadCmp(): 1})
657 d2
= self
._full
_mapping
({1: 1})
663 self
.fail("< didn't raise Exc")
665 def test_setdefault(self
):
666 TestMappingProtocol
.test_setdefault(self
)
668 class Exc(Exception): pass
670 class BadHash(object):
678 d
= self
._empty
_mapping
()
682 self
.assertRaises(Exc
, d
.setdefault
, x
, [])