blob: b8bbc9a2291e7d01f45a9a223865f3585b4fc898 [file] [log] [blame]
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001# tests common to dict and UserDict
2import unittest
Raymond Hettingerf80680d2008-02-06 00:07:11 +00003import collections
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00004
5
6class BasicTestMappingProtocol(unittest.TestCase):
7 # This base class can be used to check that an object conforms to the
8 # mapping protocol
9
10 # Functions that can be useful to override to adapt to dictionary
11 # semantics
Walter Dörwald118f9312004-06-02 18:42:25 +000012 type2test = None # which class is being tested (overwrite in subclasses)
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +000013
14 def _reference(self):
15 """Return a dictionary of values which are invariant by storage
16 in the object under test."""
17 return {1:2, "key1":"value1", "key2":(1,2,3)}
18 def _empty_mapping(self):
19 """Return an empty mapping object"""
Walter Dörwald118f9312004-06-02 18:42:25 +000020 return self.type2test()
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +000021 def _full_mapping(self, data):
22 """Return a mapping object with the value contained in data
23 dictionary"""
24 x = self._empty_mapping()
25 for key, value in data.items():
26 x[key] = value
27 return x
28
29 def __init__(self, *args, **kw):
30 unittest.TestCase.__init__(self, *args, **kw)
31 self.reference = self._reference().copy()
32
33 # A (key, value) pair not in the mapping
34 key, value = self.reference.popitem()
35 self.other = {key:value}
36
37 # A (key, value) pair in the mapping
38 key, value = self.reference.popitem()
39 self.inmapping = {key:value}
40 self.reference[key] = value
41
42 def test_read(self):
43 # Test for read only operations on mapping
44 p = self._empty_mapping()
45 p1 = dict(p) #workaround for singleton objects
46 d = self._full_mapping(self.reference)
47 if d is p:
48 p = p1
49 #Indexing
50 for key, value in self.reference.items():
51 self.assertEqual(d[key], value)
Guido van Rossum07f24362007-02-11 22:59:48 +000052 knownkey = list(self.other.keys())[0]
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +000053 self.failUnlessRaises(KeyError, lambda:d[knownkey])
54 #len
55 self.assertEqual(len(p), 0)
56 self.assertEqual(len(d), len(self.reference))
Guido van Rossume2b70bc2006-08-18 22:13:04 +000057 #__contains__
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +000058 for k in self.reference:
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +000059 self.assert_(k in d)
60 for k in self.other:
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +000061 self.failIf(k in d)
62 #cmp
Guido van Rossum47b9ff62006-08-24 00:41:19 +000063 self.assertEqual(p, p)
64 self.assertEqual(d, d)
65 self.assertNotEqual(p, d)
66 self.assertNotEqual(d, p)
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +000067 #__non__zero__
68 if p: self.fail("Empty mapping must compare to False")
69 if not d: self.fail("Full mapping must compare to True")
70 # keys(), items(), iterkeys() ...
71 def check_iterandlist(iter, lst, ref):
Georg Brandla18af4e2007-04-21 15:47:16 +000072 self.assert_(hasattr(iter, '__next__'))
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +000073 self.assert_(hasattr(iter, '__iter__'))
74 x = list(iter)
75 self.assert_(set(x)==set(lst)==set(ref))
Guido van Rossum07f24362007-02-11 22:59:48 +000076 check_iterandlist(iter(d.keys()), list(d.keys()),
77 self.reference.keys())
78 check_iterandlist(iter(d), list(d.keys()), self.reference.keys())
79 check_iterandlist(iter(d.values()), list(d.values()),
80 self.reference.values())
81 check_iterandlist(iter(d.items()), list(d.items()),
82 self.reference.items())
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +000083 #get
Georg Brandla18af4e2007-04-21 15:47:16 +000084 key, value = next(iter(d.items()))
85 knownkey, knownvalue = next(iter(self.other.items()))
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +000086 self.assertEqual(d.get(key, knownvalue), value)
87 self.assertEqual(d.get(knownkey, knownvalue), knownvalue)
88 self.failIf(knownkey in d)
89
90 def test_write(self):
91 # Test for write operations on mapping
92 p = self._empty_mapping()
93 #Indexing
94 for key, value in self.reference.items():
95 p[key] = value
96 self.assertEqual(p[key], value)
97 for key in self.reference.keys():
98 del p[key]
99 self.failUnlessRaises(KeyError, lambda:p[key])
100 p = self._empty_mapping()
101 #update
102 p.update(self.reference)
103 self.assertEqual(dict(p), self.reference)
Brett Cannon67582d22007-02-21 21:57:55 +0000104 items = list(p.items())
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000105 p = self._empty_mapping()
106 p.update(items)
107 self.assertEqual(dict(p), self.reference)
108 d = self._full_mapping(self.reference)
109 #setdefault
Georg Brandla18af4e2007-04-21 15:47:16 +0000110 key, value = next(iter(d.items()))
111 knownkey, knownvalue = next(iter(self.other.items()))
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000112 self.assertEqual(d.setdefault(key, knownvalue), value)
113 self.assertEqual(d[key], value)
114 self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue)
115 self.assertEqual(d[knownkey], knownvalue)
116 #pop
117 self.assertEqual(d.pop(knownkey), knownvalue)
118 self.failIf(knownkey in d)
119 self.assertRaises(KeyError, d.pop, knownkey)
120 default = 909
121 d[knownkey] = knownvalue
122 self.assertEqual(d.pop(knownkey, default), knownvalue)
123 self.failIf(knownkey in d)
124 self.assertEqual(d.pop(knownkey, default), default)
125 #popitem
126 key, value = d.popitem()
127 self.failIf(key in d)
128 self.assertEqual(value, self.reference[key])
129 p=self._empty_mapping()
130 self.assertRaises(KeyError, p.popitem)
131
132 def test_constructor(self):
133 self.assertEqual(self._empty_mapping(), self._empty_mapping())
134
135 def test_bool(self):
136 self.assert_(not self._empty_mapping())
137 self.assert_(self.reference)
138 self.assert_(bool(self._empty_mapping()) is False)
139 self.assert_(bool(self.reference) is True)
140
141 def test_keys(self):
142 d = self._empty_mapping()
Guido van Rossum07f24362007-02-11 22:59:48 +0000143 self.assertEqual(list(d.keys()), [])
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000144 d = self.reference
Guido van Rossum07f24362007-02-11 22:59:48 +0000145 self.assert_(list(self.inmapping.keys())[0] in d.keys())
146 self.assert_(list(self.other.keys())[0] not in d.keys())
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000147 self.assertRaises(TypeError, d.keys, None)
148
149 def test_values(self):
150 d = self._empty_mapping()
Guido van Rossum07f24362007-02-11 22:59:48 +0000151 self.assertEqual(list(d.values()), [])
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000152
153 self.assertRaises(TypeError, d.values, None)
154
155 def test_items(self):
156 d = self._empty_mapping()
Guido van Rossum07f24362007-02-11 22:59:48 +0000157 self.assertEqual(list(d.items()), [])
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000158
159 self.assertRaises(TypeError, d.items, None)
160
161 def test_len(self):
162 d = self._empty_mapping()
163 self.assertEqual(len(d), 0)
164
165 def test_getitem(self):
166 d = self.reference
Guido van Rossum07f24362007-02-11 22:59:48 +0000167 self.assertEqual(d[list(self.inmapping.keys())[0]],
168 list(self.inmapping.values())[0])
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000169
170 self.assertRaises(TypeError, d.__getitem__)
171
172 def test_update(self):
173 # mapping argument
174 d = self._empty_mapping()
175 d.update(self.other)
Guido van Rossum07f24362007-02-11 22:59:48 +0000176 self.assertEqual(list(d.items()), list(self.other.items()))
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000177
178 # No argument
179 d = self._empty_mapping()
180 d.update()
181 self.assertEqual(d, self._empty_mapping())
182
183 # item sequence
184 d = self._empty_mapping()
185 d.update(self.other.items())
Guido van Rossum07f24362007-02-11 22:59:48 +0000186 self.assertEqual(list(d.items()), list(self.other.items()))
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000187
188 # Iterator
189 d = self._empty_mapping()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000190 d.update(self.other.items())
Guido van Rossum07f24362007-02-11 22:59:48 +0000191 self.assertEqual(list(d.items()), list(self.other.items()))
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000192
193 # FIXME: Doesn't work with UserDict
194 # self.assertRaises((TypeError, AttributeError), d.update, None)
195 self.assertRaises((TypeError, AttributeError), d.update, 42)
196
197 outerself = self
198 class SimpleUserDict:
199 def __init__(self):
200 self.d = outerself.reference
201 def keys(self):
202 return self.d.keys()
203 def __getitem__(self, i):
204 return self.d[i]
205 d.clear()
206 d.update(SimpleUserDict())
Guido van Rossum07f24362007-02-11 22:59:48 +0000207 i1 = sorted(d.items())
208 i2 = sorted(self.reference.items())
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000209 self.assertEqual(i1, i2)
210
211 class Exc(Exception): pass
212
213 d = self._empty_mapping()
214 class FailingUserDict:
215 def keys(self):
216 raise Exc
217 self.assertRaises(Exc, d.update, FailingUserDict())
218
219 d.clear()
220
221 class FailingUserDict:
222 def keys(self):
223 class BogonIter:
224 def __init__(self):
225 self.i = 1
226 def __iter__(self):
227 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000228 def __next__(self):
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000229 if self.i:
230 self.i = 0
231 return 'a'
232 raise Exc
233 return BogonIter()
234 def __getitem__(self, key):
235 return key
236 self.assertRaises(Exc, d.update, FailingUserDict())
237
238 class FailingUserDict:
239 def keys(self):
240 class BogonIter:
241 def __init__(self):
242 self.i = ord('a')
243 def __iter__(self):
244 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000245 def __next__(self):
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000246 if self.i <= ord('z'):
247 rtn = chr(self.i)
248 self.i += 1
249 return rtn
250 raise StopIteration
251 return BogonIter()
252 def __getitem__(self, key):
253 raise Exc
254 self.assertRaises(Exc, d.update, FailingUserDict())
255
256 d = self._empty_mapping()
257 class badseq(object):
258 def __iter__(self):
259 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000260 def __next__(self):
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000261 raise Exc()
262
263 self.assertRaises(Exc, d.update, badseq())
264
265 self.assertRaises(ValueError, d.update, [(1, 2, 3)])
266
267 # no test_fromkeys or test_copy as both os.environ and selves don't support it
268
269 def test_get(self):
270 d = self._empty_mapping()
Guido van Rossum07f24362007-02-11 22:59:48 +0000271 self.assert_(d.get(list(self.other.keys())[0]) is None)
272 self.assertEqual(d.get(list(self.other.keys())[0], 3), 3)
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000273 d = self.reference
Guido van Rossum07f24362007-02-11 22:59:48 +0000274 self.assert_(d.get(list(self.other.keys())[0]) is None)
275 self.assertEqual(d.get(list(self.other.keys())[0], 3), 3)
276 self.assertEqual(d.get(list(self.inmapping.keys())[0]),
277 list(self.inmapping.values())[0])
278 self.assertEqual(d.get(list(self.inmapping.keys())[0], 3),
279 list(self.inmapping.values())[0])
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000280 self.assertRaises(TypeError, d.get)
281 self.assertRaises(TypeError, d.get, None, None, None)
282
283 def test_setdefault(self):
284 d = self._empty_mapping()
285 self.assertRaises(TypeError, d.setdefault)
286
287 def test_popitem(self):
288 d = self._empty_mapping()
289 self.assertRaises(KeyError, d.popitem)
290 self.assertRaises(TypeError, d.popitem, 42)
291
292 def test_pop(self):
293 d = self._empty_mapping()
Guido van Rossum07f24362007-02-11 22:59:48 +0000294 k, v = list(self.inmapping.items())[0]
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000295 d[k] = v
Guido van Rossum07f24362007-02-11 22:59:48 +0000296 self.assertRaises(KeyError, d.pop, list(self.other.keys())[0])
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000297
298 self.assertEqual(d.pop(k), v)
299 self.assertEqual(len(d), 0)
300
301 self.assertRaises(KeyError, d.pop, k)
302
303
304class TestMappingProtocol(BasicTestMappingProtocol):
305 def test_constructor(self):
306 BasicTestMappingProtocol.test_constructor(self)
307 self.assert_(self._empty_mapping() is not self._empty_mapping())
Walter Dörwald118f9312004-06-02 18:42:25 +0000308 self.assertEqual(self.type2test(x=1, y=2), {"x": 1, "y": 2})
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000309
310 def test_bool(self):
311 BasicTestMappingProtocol.test_bool(self)
312 self.assert_(not self._empty_mapping())
313 self.assert_(self._full_mapping({"x": "y"}))
314 self.assert_(bool(self._empty_mapping()) is False)
315 self.assert_(bool(self._full_mapping({"x": "y"})) is True)
316
317 def test_keys(self):
318 BasicTestMappingProtocol.test_keys(self)
319 d = self._empty_mapping()
Guido van Rossumd81206d2007-02-15 03:49:08 +0000320 self.assertEqual(list(d.keys()), [])
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000321 d = self._full_mapping({'a': 1, 'b': 2})
322 k = d.keys()
323 self.assert_('a' in k)
324 self.assert_('b' in k)
325 self.assert_('c' not in k)
326
327 def test_values(self):
328 BasicTestMappingProtocol.test_values(self)
329 d = self._full_mapping({1:2})
Guido van Rossumd81206d2007-02-15 03:49:08 +0000330 self.assertEqual(list(d.values()), [2])
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000331
332 def test_items(self):
333 BasicTestMappingProtocol.test_items(self)
334
335 d = self._full_mapping({1:2})
Guido van Rossumd81206d2007-02-15 03:49:08 +0000336 self.assertEqual(list(d.items()), [(1, 2)])
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000337
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000338 def test_contains(self):
339 d = self._empty_mapping()
340 self.assert_(not ('a' in d))
341 self.assert_('a' not in d)
342 d = self._full_mapping({'a': 1, 'b': 2})
343 self.assert_('a' in d)
344 self.assert_('b' in d)
345 self.assert_('c' not in d)
346
347 self.assertRaises(TypeError, d.__contains__)
348
349 def test_len(self):
350 BasicTestMappingProtocol.test_len(self)
351 d = self._full_mapping({'a': 1, 'b': 2})
352 self.assertEqual(len(d), 2)
353
354 def test_getitem(self):
355 BasicTestMappingProtocol.test_getitem(self)
356 d = self._full_mapping({'a': 1, 'b': 2})
357 self.assertEqual(d['a'], 1)
358 self.assertEqual(d['b'], 2)
359 d['c'] = 3
360 d['a'] = 4
361 self.assertEqual(d['c'], 3)
362 self.assertEqual(d['a'], 4)
363 del d['b']
364 self.assertEqual(d, {'a': 4, 'c': 3})
365
366 self.assertRaises(TypeError, d.__getitem__)
367
368 def test_clear(self):
369 d = self._full_mapping({1:1, 2:2, 3:3})
370 d.clear()
371 self.assertEqual(d, {})
372
373 self.assertRaises(TypeError, d.clear, None)
374
375 def test_update(self):
376 BasicTestMappingProtocol.test_update(self)
377 # mapping argument
378 d = self._empty_mapping()
379 d.update({1:100})
380 d.update({2:20})
381 d.update({1:1, 2:2, 3:3})
382 self.assertEqual(d, {1:1, 2:2, 3:3})
383
384 # no argument
385 d.update()
386 self.assertEqual(d, {1:1, 2:2, 3:3})
387
388 # keyword arguments
389 d = self._empty_mapping()
390 d.update(x=100)
391 d.update(y=20)
392 d.update(x=1, y=2, z=3)
393 self.assertEqual(d, {"x":1, "y":2, "z":3})
394
395 # item sequence
396 d = self._empty_mapping()
397 d.update([("x", 100), ("y", 20)])
398 self.assertEqual(d, {"x":100, "y":20})
399
400 # Both item sequence and keyword arguments
401 d = self._empty_mapping()
402 d.update([("x", 100), ("y", 20)], x=1, y=2)
403 self.assertEqual(d, {"x":1, "y":2})
404
405 # iterator
406 d = self._full_mapping({1:3, 2:4})
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000407 d.update(self._full_mapping({1:2, 3:4, 5:6}).items())
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000408 self.assertEqual(d, {1:2, 2:4, 3:4, 5:6})
409
410 class SimpleUserDict:
411 def __init__(self):
412 self.d = {1:1, 2:2, 3:3}
413 def keys(self):
414 return self.d.keys()
415 def __getitem__(self, i):
416 return self.d[i]
417 d.clear()
418 d.update(SimpleUserDict())
419 self.assertEqual(d, {1:1, 2:2, 3:3})
420
421 def test_fromkeys(self):
Walter Dörwald118f9312004-06-02 18:42:25 +0000422 self.assertEqual(self.type2test.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000423 d = self._empty_mapping()
424 self.assert_(not(d.fromkeys('abc') is d))
425 self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
426 self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0})
427 self.assertEqual(d.fromkeys([]), {})
428 def g():
429 yield 1
430 self.assertEqual(d.fromkeys(g()), {1:None})
431 self.assertRaises(TypeError, {}.fromkeys, 3)
Walter Dörwald118f9312004-06-02 18:42:25 +0000432 class dictlike(self.type2test): pass
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000433 self.assertEqual(dictlike.fromkeys('a'), {'a':None})
434 self.assertEqual(dictlike().fromkeys('a'), {'a':None})
435 self.assert_(dictlike.fromkeys('a').__class__ is dictlike)
436 self.assert_(dictlike().fromkeys('a').__class__ is dictlike)
437 # FIXME: the following won't work with UserDict, because it's an old style class
438 # self.assert_(type(dictlike.fromkeys('a')) is dictlike)
Walter Dörwald118f9312004-06-02 18:42:25 +0000439 class mydict(self.type2test):
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000440 def __new__(cls):
Raymond Hettingerf80680d2008-02-06 00:07:11 +0000441 return collections.UserDict()
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000442 ud = mydict.fromkeys('ab')
443 self.assertEqual(ud, {'a':None, 'b':None})
444 # FIXME: the following won't work with UserDict, because it's an old style class
Raymond Hettingerf80680d2008-02-06 00:07:11 +0000445 # self.assert_(isinstance(ud, collections.UserDict))
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000446 self.assertRaises(TypeError, dict.fromkeys)
447
448 class Exc(Exception): pass
449
Walter Dörwald118f9312004-06-02 18:42:25 +0000450 class baddict1(self.type2test):
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000451 def __init__(self):
452 raise Exc()
453
454 self.assertRaises(Exc, baddict1.fromkeys, [1])
455
456 class BadSeq(object):
457 def __iter__(self):
458 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000459 def __next__(self):
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000460 raise Exc()
461
Walter Dörwald118f9312004-06-02 18:42:25 +0000462 self.assertRaises(Exc, self.type2test.fromkeys, BadSeq())
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000463
Walter Dörwald118f9312004-06-02 18:42:25 +0000464 class baddict2(self.type2test):
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000465 def __setitem__(self, key, value):
466 raise Exc()
467
468 self.assertRaises(Exc, baddict2.fromkeys, [1])
469
470 def test_copy(self):
471 d = self._full_mapping({1:1, 2:2, 3:3})
472 self.assertEqual(d.copy(), {1:1, 2:2, 3:3})
473 d = self._empty_mapping()
474 self.assertEqual(d.copy(), d)
475 self.assert_(isinstance(d.copy(), d.__class__))
476 self.assertRaises(TypeError, d.copy, None)
477
478 def test_get(self):
479 BasicTestMappingProtocol.test_get(self)
480 d = self._empty_mapping()
481 self.assert_(d.get('c') is None)
482 self.assertEqual(d.get('c', 3), 3)
483 d = self._full_mapping({'a' : 1, 'b' : 2})
484 self.assert_(d.get('c') is None)
485 self.assertEqual(d.get('c', 3), 3)
486 self.assertEqual(d.get('a'), 1)
487 self.assertEqual(d.get('a', 3), 1)
488
489 def test_setdefault(self):
490 BasicTestMappingProtocol.test_setdefault(self)
491 d = self._empty_mapping()
492 self.assert_(d.setdefault('key0') is None)
493 d.setdefault('key0', [])
494 self.assert_(d.setdefault('key0') is None)
495 d.setdefault('key', []).append(3)
496 self.assertEqual(d['key'][0], 3)
497 d.setdefault('key', []).append(4)
498 self.assertEqual(len(d['key']), 2)
499
500 def test_popitem(self):
501 BasicTestMappingProtocol.test_popitem(self)
502 for copymode in -1, +1:
503 # -1: b has same structure as a
504 # +1: b is a.copy()
505 for log2size in range(12):
506 size = 2**log2size
507 a = self._empty_mapping()
508 b = self._empty_mapping()
509 for i in range(size):
510 a[repr(i)] = i
511 if copymode < 0:
512 b[repr(i)] = i
513 if copymode > 0:
514 b = a.copy()
515 for i in range(size):
516 ka, va = ta = a.popitem()
517 self.assertEqual(va, int(ka))
518 kb, vb = tb = b.popitem()
519 self.assertEqual(vb, int(kb))
520 self.assert_(not(copymode < 0 and ta != tb))
521 self.assert_(not a)
522 self.assert_(not b)
523
524 def test_pop(self):
525 BasicTestMappingProtocol.test_pop(self)
526
527 # Tests for pop with specified key
528 d = self._empty_mapping()
529 k, v = 'abc', 'def'
530
531 # verify longs/ints get same value when key > 32 bits (for 64-bit archs)
532 # see SF bug #689659
Guido van Rossume2a383d2007-01-15 16:59:06 +0000533 x = 4503599627370496
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000534 y = 4503599627370496
535 h = self._full_mapping({x: 'anything', y: 'something else'})
536 self.assertEqual(h[x], h[y])
537
538 self.assertEqual(d.pop(k, v), v)
539 d[k] = v
540 self.assertEqual(d.pop(k, 1), v)
541
542
543class TestHashMappingProtocol(TestMappingProtocol):
544
545 def test_getitem(self):
546 TestMappingProtocol.test_getitem(self)
547 class Exc(Exception): pass
548
549 class BadEq(object):
550 def __eq__(self, other):
551 raise Exc()
Guido van Rossum38938152006-08-21 23:36:26 +0000552 def __hash__(self):
553 return 24
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000554
555 d = self._empty_mapping()
556 d[BadEq()] = 42
557 self.assertRaises(KeyError, d.__getitem__, 23)
558
559 class BadHash(object):
560 fail = False
561 def __hash__(self):
562 if self.fail:
563 raise Exc()
564 else:
565 return 42
566
567 d = self._empty_mapping()
568 x = BadHash()
569 d[x] = 42
570 x.fail = True
571 self.assertRaises(Exc, d.__getitem__, x)
572
573 def test_fromkeys(self):
574 TestMappingProtocol.test_fromkeys(self)
Walter Dörwald118f9312004-06-02 18:42:25 +0000575 class mydict(self.type2test):
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000576 def __new__(cls):
Raymond Hettingerf80680d2008-02-06 00:07:11 +0000577 return collections.UserDict()
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000578 ud = mydict.fromkeys('ab')
579 self.assertEqual(ud, {'a':None, 'b':None})
Raymond Hettingerf80680d2008-02-06 00:07:11 +0000580 self.assert_(isinstance(ud, collections.UserDict))
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000581
582 def test_pop(self):
583 TestMappingProtocol.test_pop(self)
584
585 class Exc(Exception): pass
586
587 class BadHash(object):
588 fail = False
589 def __hash__(self):
590 if self.fail:
591 raise Exc()
592 else:
593 return 42
594
595 d = self._empty_mapping()
596 x = BadHash()
597 d[x] = 42
598 x.fail = True
599 self.assertRaises(Exc, d.pop, x)
600
601 def test_mutatingiteration(self):
602 d = self._empty_mapping()
603 d[1] = 1
604 try:
605 for i in d:
606 d[i+1] = 1
607 except RuntimeError:
608 pass
609 else:
610 self.fail("changing dict size during iteration doesn't raise Error")
611
612 def test_repr(self):
613 d = self._empty_mapping()
614 self.assertEqual(repr(d), '{}')
615 d[1] = 2
616 self.assertEqual(repr(d), '{1: 2}')
617 d = self._empty_mapping()
618 d[1] = d
619 self.assertEqual(repr(d), '{1: {...}}')
620
621 class Exc(Exception): pass
622
623 class BadRepr(object):
624 def __repr__(self):
625 raise Exc()
626
627 d = self._full_mapping({1: BadRepr()})
628 self.assertRaises(Exc, repr, d)
629
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000630 def test_eq(self):
631 self.assertEqual(self._empty_mapping(), self._empty_mapping())
632 self.assertEqual(self._full_mapping({1: 2}),
Guido van Rossume2a383d2007-01-15 16:59:06 +0000633 self._full_mapping({1: 2}))
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000634
635 class Exc(Exception): pass
636
637 class BadCmp(object):
638 def __eq__(self, other):
639 raise Exc()
Guido van Rossum38938152006-08-21 23:36:26 +0000640 def __hash__(self):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000641 return 1
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000642
643 d1 = self._full_mapping({BadCmp(): 1})
644 d2 = self._full_mapping({1: 1})
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000645 self.assertRaises(Exc, lambda: BadCmp()==1)
646 self.assertRaises(Exc, lambda: d1==d2)
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000647
648 def test_setdefault(self):
649 TestMappingProtocol.test_setdefault(self)
650
651 class Exc(Exception): pass
652
653 class BadHash(object):
654 fail = False
655 def __hash__(self):
656 if self.fail:
657 raise Exc()
658 else:
659 return 42
660
661 d = self._empty_mapping()
662 x = BadHash()
663 d[x] = 42
664 x.fail = True
665 self.assertRaises(Exc, d.setdefault, x, [])