blob: b43e20d0558ffb38c3d13c60068f035827d99b39 [file] [log] [blame]
Walter Dörwald59b23e82004-09-30 13:46:00 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Walter Dörwald59b23e82004-09-30 13:46:00 +00003
Florent Xiclunaa988e422010-03-02 16:06:24 +00004import collections, random, string
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00005import collections.abc
Antoine Pitrou7ddda782009-01-01 15:35:33 +00006import gc, weakref
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00007import pickle
Walter Dörwald59b23e82004-09-30 13:46:00 +00008
9
10class DictTest(unittest.TestCase):
Guido van Rossum47b9ff62006-08-24 00:41:19 +000011
Benjamin Petersonfb886362010-04-24 18:21:17 +000012 def test_invalid_keyword_arguments(self):
Benjamin Petersonf6096542010-11-17 22:33:12 +000013 class Custom(dict):
14 pass
15 for invalid in {1 : 2}, Custom({1 : 2}):
16 with self.assertRaises(TypeError):
17 dict(**invalid)
18 with self.assertRaises(TypeError):
19 {}.update(**invalid)
Benjamin Petersonfb886362010-04-24 18:21:17 +000020
Walter Dörwald59b23e82004-09-30 13:46:00 +000021 def test_constructor(self):
22 # calling built-in types without argument must return empty
23 self.assertEqual(dict(), {})
Florent Xiclunaa988e422010-03-02 16:06:24 +000024 self.assertIsNot(dict(), {})
Walter Dörwald59b23e82004-09-30 13:46:00 +000025
Christian Heimes99170a52007-12-19 02:07:34 +000026 def test_literal_constructor(self):
Florent Xiclunaa988e422010-03-02 16:06:24 +000027 # check literal constructor for different sized dicts
28 # (to exercise the BUILD_MAP oparg).
Christian Heimesb186d002008-03-18 15:15:01 +000029 for n in (0, 1, 6, 256, 400):
Florent Xiclunaa988e422010-03-02 16:06:24 +000030 items = [(''.join(random.sample(string.ascii_letters, 8)), i)
Christian Heimesb186d002008-03-18 15:15:01 +000031 for i in range(n)]
32 random.shuffle(items)
Florent Xiclunaa988e422010-03-02 16:06:24 +000033 formatted_items = ('{!r}: {:d}'.format(k, v) for k, v in items)
34 dictliteral = '{' + ', '.join(formatted_items) + '}'
Christian Heimes99170a52007-12-19 02:07:34 +000035 self.assertEqual(eval(dictliteral), dict(items))
Christian Heimes99170a52007-12-19 02:07:34 +000036
Walter Dörwald59b23e82004-09-30 13:46:00 +000037 def test_bool(self):
Florent Xiclunaa988e422010-03-02 16:06:24 +000038 self.assertIs(not {}, True)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000039 self.assertTrue({1: 2})
Florent Xiclunaa988e422010-03-02 16:06:24 +000040 self.assertIs(bool({}), False)
41 self.assertIs(bool({1: 2}), True)
Walter Dörwald59b23e82004-09-30 13:46:00 +000042
43 def test_keys(self):
44 d = {}
Guido van Rossume34cdd12007-02-14 17:49:04 +000045 self.assertEqual(set(d.keys()), set())
Walter Dörwald59b23e82004-09-30 13:46:00 +000046 d = {'a': 1, 'b': 2}
47 k = d.keys()
Benjamin Peterson577473f2010-01-19 00:09:57 +000048 self.assertIn('a', d)
Benjamin Peterson577473f2010-01-19 00:09:57 +000049 self.assertIn('b', d)
Walter Dörwald59b23e82004-09-30 13:46:00 +000050 self.assertRaises(TypeError, d.keys, None)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +000051 self.assertEqual(repr(dict(a=1).keys()), "dict_keys(['a'])")
Walter Dörwald59b23e82004-09-30 13:46:00 +000052
53 def test_values(self):
54 d = {}
Guido van Rossume34cdd12007-02-14 17:49:04 +000055 self.assertEqual(set(d.values()), set())
Walter Dörwald59b23e82004-09-30 13:46:00 +000056 d = {1:2}
Guido van Rossume34cdd12007-02-14 17:49:04 +000057 self.assertEqual(set(d.values()), {2})
Walter Dörwald59b23e82004-09-30 13:46:00 +000058 self.assertRaises(TypeError, d.values, None)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +000059 self.assertEqual(repr(dict(a=1).values()), "dict_values([1])")
Walter Dörwald59b23e82004-09-30 13:46:00 +000060
61 def test_items(self):
62 d = {}
Guido van Rossume34cdd12007-02-14 17:49:04 +000063 self.assertEqual(set(d.items()), set())
Walter Dörwald59b23e82004-09-30 13:46:00 +000064
65 d = {1:2}
Guido van Rossume34cdd12007-02-14 17:49:04 +000066 self.assertEqual(set(d.items()), {(1, 2)})
Walter Dörwald59b23e82004-09-30 13:46:00 +000067 self.assertRaises(TypeError, d.items, None)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +000068 self.assertEqual(repr(dict(a=1).items()), "dict_items([('a', 1)])")
Walter Dörwald59b23e82004-09-30 13:46:00 +000069
Walter Dörwald59b23e82004-09-30 13:46:00 +000070 def test_contains(self):
71 d = {}
Ezio Melottib58e0bd2010-01-23 15:40:09 +000072 self.assertNotIn('a', d)
Florent Xiclunaa988e422010-03-02 16:06:24 +000073 self.assertFalse('a' in d)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000074 self.assertTrue('a' not in d)
Walter Dörwald59b23e82004-09-30 13:46:00 +000075 d = {'a': 1, 'b': 2}
Benjamin Peterson577473f2010-01-19 00:09:57 +000076 self.assertIn('a', d)
Benjamin Peterson577473f2010-01-19 00:09:57 +000077 self.assertIn('b', d)
Benjamin Peterson577473f2010-01-19 00:09:57 +000078 self.assertNotIn('c', d)
Walter Dörwald59b23e82004-09-30 13:46:00 +000079
80 self.assertRaises(TypeError, d.__contains__)
81
82 def test_len(self):
83 d = {}
84 self.assertEqual(len(d), 0)
85 d = {'a': 1, 'b': 2}
86 self.assertEqual(len(d), 2)
87
88 def test_getitem(self):
89 d = {'a': 1, 'b': 2}
90 self.assertEqual(d['a'], 1)
91 self.assertEqual(d['b'], 2)
92 d['c'] = 3
93 d['a'] = 4
94 self.assertEqual(d['c'], 3)
95 self.assertEqual(d['a'], 4)
96 del d['b']
97 self.assertEqual(d, {'a': 4, 'c': 3})
98
99 self.assertRaises(TypeError, d.__getitem__)
100
101 class BadEq(object):
102 def __eq__(self, other):
103 raise Exc()
Guido van Rossum38938152006-08-21 23:36:26 +0000104 def __hash__(self):
105 return 24
Walter Dörwald59b23e82004-09-30 13:46:00 +0000106
107 d = {}
108 d[BadEq()] = 42
109 self.assertRaises(KeyError, d.__getitem__, 23)
110
111 class Exc(Exception): pass
112
113 class BadHash(object):
114 fail = False
115 def __hash__(self):
116 if self.fail:
117 raise Exc()
118 else:
119 return 42
120
121 x = BadHash()
122 d[x] = 42
123 x.fail = True
124 self.assertRaises(Exc, d.__getitem__, x)
125
126 def test_clear(self):
127 d = {1:1, 2:2, 3:3}
128 d.clear()
129 self.assertEqual(d, {})
130
131 self.assertRaises(TypeError, d.clear, None)
132
133 def test_update(self):
134 d = {}
135 d.update({1:100})
136 d.update({2:20})
137 d.update({1:1, 2:2, 3:3})
138 self.assertEqual(d, {1:1, 2:2, 3:3})
139
140 d.update()
141 self.assertEqual(d, {1:1, 2:2, 3:3})
142
143 self.assertRaises((TypeError, AttributeError), d.update, None)
144
145 class SimpleUserDict:
146 def __init__(self):
147 self.d = {1:1, 2:2, 3:3}
148 def keys(self):
149 return self.d.keys()
150 def __getitem__(self, i):
151 return self.d[i]
152 d.clear()
153 d.update(SimpleUserDict())
154 self.assertEqual(d, {1:1, 2:2, 3:3})
155
156 class Exc(Exception): pass
157
158 d.clear()
159 class FailingUserDict:
160 def keys(self):
161 raise Exc
162 self.assertRaises(Exc, d.update, FailingUserDict())
163
164 class FailingUserDict:
165 def keys(self):
166 class BogonIter:
167 def __init__(self):
168 self.i = 1
169 def __iter__(self):
170 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000171 def __next__(self):
Walter Dörwald59b23e82004-09-30 13:46:00 +0000172 if self.i:
173 self.i = 0
174 return 'a'
175 raise Exc
176 return BogonIter()
177 def __getitem__(self, key):
178 return key
179 self.assertRaises(Exc, d.update, FailingUserDict())
180
181 class FailingUserDict:
182 def keys(self):
183 class BogonIter:
184 def __init__(self):
185 self.i = ord('a')
186 def __iter__(self):
187 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000188 def __next__(self):
Walter Dörwald59b23e82004-09-30 13:46:00 +0000189 if self.i <= ord('z'):
190 rtn = chr(self.i)
191 self.i += 1
192 return rtn
193 raise StopIteration
194 return BogonIter()
195 def __getitem__(self, key):
196 raise Exc
197 self.assertRaises(Exc, d.update, FailingUserDict())
198
199 class badseq(object):
200 def __iter__(self):
201 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000202 def __next__(self):
Walter Dörwald59b23e82004-09-30 13:46:00 +0000203 raise Exc()
204
205 self.assertRaises(Exc, {}.update, badseq())
206
207 self.assertRaises(ValueError, {}.update, [(1, 2, 3)])
208
209 def test_fromkeys(self):
210 self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
211 d = {}
Florent Xiclunaa988e422010-03-02 16:06:24 +0000212 self.assertIsNot(d.fromkeys('abc'), d)
Walter Dörwald59b23e82004-09-30 13:46:00 +0000213 self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
214 self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0})
215 self.assertEqual(d.fromkeys([]), {})
216 def g():
217 yield 1
218 self.assertEqual(d.fromkeys(g()), {1:None})
219 self.assertRaises(TypeError, {}.fromkeys, 3)
220 class dictlike(dict): pass
221 self.assertEqual(dictlike.fromkeys('a'), {'a':None})
222 self.assertEqual(dictlike().fromkeys('a'), {'a':None})
Florent Xiclunaa988e422010-03-02 16:06:24 +0000223 self.assertIsInstance(dictlike.fromkeys('a'), dictlike)
224 self.assertIsInstance(dictlike().fromkeys('a'), dictlike)
Walter Dörwald59b23e82004-09-30 13:46:00 +0000225 class mydict(dict):
226 def __new__(cls):
Raymond Hettingerf80680d2008-02-06 00:07:11 +0000227 return collections.UserDict()
Walter Dörwald59b23e82004-09-30 13:46:00 +0000228 ud = mydict.fromkeys('ab')
229 self.assertEqual(ud, {'a':None, 'b':None})
Ezio Melottie9615932010-01-24 19:26:24 +0000230 self.assertIsInstance(ud, collections.UserDict)
Walter Dörwald59b23e82004-09-30 13:46:00 +0000231 self.assertRaises(TypeError, dict.fromkeys)
232
233 class Exc(Exception): pass
234
235 class baddict1(dict):
236 def __init__(self):
237 raise Exc()
238
239 self.assertRaises(Exc, baddict1.fromkeys, [1])
240
241 class BadSeq(object):
242 def __iter__(self):
243 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000244 def __next__(self):
Walter Dörwald59b23e82004-09-30 13:46:00 +0000245 raise Exc()
246
247 self.assertRaises(Exc, dict.fromkeys, BadSeq())
248
249 class baddict2(dict):
250 def __setitem__(self, key, value):
251 raise Exc()
252
253 self.assertRaises(Exc, baddict2.fromkeys, [1])
254
Guido van Rossum58da9312007-11-10 23:39:45 +0000255 # test fast path for dictionary inputs
256 d = dict(zip(range(6), range(6)))
257 self.assertEqual(dict.fromkeys(d, 0), dict(zip(range(6), [0]*6)))
258
Walter Dörwald59b23e82004-09-30 13:46:00 +0000259 def test_copy(self):
260 d = {1:1, 2:2, 3:3}
261 self.assertEqual(d.copy(), {1:1, 2:2, 3:3})
262 self.assertEqual({}.copy(), {})
263 self.assertRaises(TypeError, d.copy, None)
264
265 def test_get(self):
266 d = {}
Florent Xiclunaa988e422010-03-02 16:06:24 +0000267 self.assertIs(d.get('c'), None)
Walter Dörwald59b23e82004-09-30 13:46:00 +0000268 self.assertEqual(d.get('c', 3), 3)
Florent Xiclunaa988e422010-03-02 16:06:24 +0000269 d = {'a': 1, 'b': 2}
270 self.assertIs(d.get('c'), None)
Walter Dörwald59b23e82004-09-30 13:46:00 +0000271 self.assertEqual(d.get('c', 3), 3)
272 self.assertEqual(d.get('a'), 1)
273 self.assertEqual(d.get('a', 3), 1)
274 self.assertRaises(TypeError, d.get)
275 self.assertRaises(TypeError, d.get, None, None, None)
276
277 def test_setdefault(self):
278 # dict.setdefault()
279 d = {}
Florent Xiclunaa988e422010-03-02 16:06:24 +0000280 self.assertIs(d.setdefault('key0'), None)
Walter Dörwald59b23e82004-09-30 13:46:00 +0000281 d.setdefault('key0', [])
Florent Xiclunaa988e422010-03-02 16:06:24 +0000282 self.assertIs(d.setdefault('key0'), None)
Walter Dörwald59b23e82004-09-30 13:46:00 +0000283 d.setdefault('key', []).append(3)
284 self.assertEqual(d['key'][0], 3)
285 d.setdefault('key', []).append(4)
286 self.assertEqual(len(d['key']), 2)
287 self.assertRaises(TypeError, d.setdefault)
288
289 class Exc(Exception): pass
290
291 class BadHash(object):
292 fail = False
293 def __hash__(self):
294 if self.fail:
295 raise Exc()
296 else:
297 return 42
298
299 x = BadHash()
300 d[x] = 42
301 x.fail = True
302 self.assertRaises(Exc, d.setdefault, x, [])
303
Antoine Pitroue965d972012-02-27 00:45:12 +0100304 def test_setdefault_atomic(self):
305 # Issue #13521: setdefault() calls __hash__ and __eq__ only once.
306 class Hashed(object):
307 def __init__(self):
308 self.hash_count = 0
309 self.eq_count = 0
310 def __hash__(self):
311 self.hash_count += 1
312 return 42
313 def __eq__(self, other):
314 self.eq_count += 1
315 return id(self) == id(other)
316 hashed1 = Hashed()
317 y = {hashed1: 5}
318 hashed2 = Hashed()
319 y.setdefault(hashed2, [])
320 self.assertEqual(hashed1.hash_count, 1)
321 self.assertEqual(hashed2.hash_count, 1)
322 self.assertEqual(hashed1.eq_count + hashed2.eq_count, 1)
323
Walter Dörwald59b23e82004-09-30 13:46:00 +0000324 def test_popitem(self):
325 # dict.popitem()
326 for copymode in -1, +1:
327 # -1: b has same structure as a
328 # +1: b is a.copy()
329 for log2size in range(12):
330 size = 2**log2size
331 a = {}
332 b = {}
333 for i in range(size):
334 a[repr(i)] = i
335 if copymode < 0:
336 b[repr(i)] = i
337 if copymode > 0:
338 b = a.copy()
339 for i in range(size):
340 ka, va = ta = a.popitem()
341 self.assertEqual(va, int(ka))
342 kb, vb = tb = b.popitem()
343 self.assertEqual(vb, int(kb))
Florent Xiclunaa988e422010-03-02 16:06:24 +0000344 self.assertFalse(copymode < 0 and ta != tb)
345 self.assertFalse(a)
346 self.assertFalse(b)
Walter Dörwald59b23e82004-09-30 13:46:00 +0000347
348 d = {}
349 self.assertRaises(KeyError, d.popitem)
350
351 def test_pop(self):
352 # Tests for pop with specified key
353 d = {}
354 k, v = 'abc', 'def'
355 d[k] = v
356 self.assertRaises(KeyError, d.pop, 'ghi')
357
358 self.assertEqual(d.pop(k), v)
359 self.assertEqual(len(d), 0)
360
361 self.assertRaises(KeyError, d.pop, k)
362
Walter Dörwald59b23e82004-09-30 13:46:00 +0000363 self.assertEqual(d.pop(k, v), v)
364 d[k] = v
365 self.assertEqual(d.pop(k, 1), v)
366
367 self.assertRaises(TypeError, d.pop)
368
369 class Exc(Exception): pass
370
371 class BadHash(object):
372 fail = False
373 def __hash__(self):
374 if self.fail:
375 raise Exc()
376 else:
377 return 42
378
379 x = BadHash()
380 d[x] = 42
381 x.fail = True
382 self.assertRaises(Exc, d.pop, x)
383
Victor Stinner198b2912012-03-06 01:03:13 +0100384 def test_mutating_iteration(self):
Florent Xiclunaa988e422010-03-02 16:06:24 +0000385 # changing dict size during iteration
Walter Dörwald59b23e82004-09-30 13:46:00 +0000386 d = {}
387 d[1] = 1
Florent Xiclunaa988e422010-03-02 16:06:24 +0000388 with self.assertRaises(RuntimeError):
Walter Dörwald59b23e82004-09-30 13:46:00 +0000389 for i in d:
390 d[i+1] = 1
Walter Dörwald59b23e82004-09-30 13:46:00 +0000391
Victor Stinner198b2912012-03-06 01:03:13 +0100392 def test_mutating_lookup(self):
393 # changing dict during a lookup
394 class NastyKey:
395 mutate_dict = None
396
Victor Stinner28393822012-03-09 22:58:51 +0100397 def __init__(self, value):
398 self.value = value
399
Victor Stinner198b2912012-03-06 01:03:13 +0100400 def __hash__(self):
401 # hash collision!
402 return 1
403
404 def __eq__(self, other):
Victor Stinner28393822012-03-09 22:58:51 +0100405 if NastyKey.mutate_dict:
406 mydict, key = NastyKey.mutate_dict
407 NastyKey.mutate_dict = None
408 del mydict[key]
409 return self.value == other.value
Victor Stinner198b2912012-03-06 01:03:13 +0100410
Victor Stinner28393822012-03-09 22:58:51 +0100411 key1 = NastyKey(1)
412 key2 = NastyKey(2)
413 d = {key1: 1}
414 NastyKey.mutate_dict = (d, key1)
415 with self.assertRaisesRegex(RuntimeError,
416 'dictionary changed size during lookup'):
417 d[key2] = 2
Victor Stinner198b2912012-03-06 01:03:13 +0100418
Walter Dörwald59b23e82004-09-30 13:46:00 +0000419 def test_repr(self):
420 d = {}
421 self.assertEqual(repr(d), '{}')
422 d[1] = 2
423 self.assertEqual(repr(d), '{1: 2}')
424 d = {}
425 d[1] = d
426 self.assertEqual(repr(d), '{1: {...}}')
427
428 class Exc(Exception): pass
429
430 class BadRepr(object):
431 def __repr__(self):
432 raise Exc()
433
434 d = {1: BadRepr()}
435 self.assertRaises(Exc, repr, d)
436
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000437 def test_eq(self):
438 self.assertEqual({}, {})
Guido van Rossume2a383d2007-01-15 16:59:06 +0000439 self.assertEqual({1: 2}, {1: 2})
Walter Dörwald59b23e82004-09-30 13:46:00 +0000440
441 class Exc(Exception): pass
442
443 class BadCmp(object):
444 def __eq__(self, other):
445 raise Exc()
Guido van Rossum38938152006-08-21 23:36:26 +0000446 def __hash__(self):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000447 return 1
Walter Dörwald59b23e82004-09-30 13:46:00 +0000448
449 d1 = {BadCmp(): 1}
450 d2 = {1: 1}
Florent Xiclunaa988e422010-03-02 16:06:24 +0000451
452 with self.assertRaises(Exc):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000453 d1 == d2
Walter Dörwald59b23e82004-09-30 13:46:00 +0000454
Guido van Rossumaac530c2007-08-24 22:33:45 +0000455 def test_keys_contained(self):
Guido van Rossumcf2ce362007-08-24 23:49:54 +0000456 self.helper_keys_contained(lambda x: x.keys())
457 self.helper_keys_contained(lambda x: x.items())
458
459 def helper_keys_contained(self, fn):
Guido van Rossumaac530c2007-08-24 22:33:45 +0000460 # Test rich comparisons against dict key views, which should behave the
461 # same as sets.
Guido van Rossumcf2ce362007-08-24 23:49:54 +0000462 empty = fn(dict())
463 empty2 = fn(dict())
464 smaller = fn({1:1, 2:2})
465 larger = fn({1:1, 2:2, 3:3})
466 larger2 = fn({1:1, 2:2, 3:3})
467 larger3 = fn({4:1, 2:2, 3:3})
Guido van Rossumaac530c2007-08-24 22:33:45 +0000468
Guido van Rossumcf2ce362007-08-24 23:49:54 +0000469 self.assertTrue(smaller < larger)
470 self.assertTrue(smaller <= larger)
471 self.assertTrue(larger > smaller)
472 self.assertTrue(larger >= smaller)
Guido van Rossumaac530c2007-08-24 22:33:45 +0000473
Guido van Rossumcf2ce362007-08-24 23:49:54 +0000474 self.assertFalse(smaller >= larger)
475 self.assertFalse(smaller > larger)
476 self.assertFalse(larger <= smaller)
477 self.assertFalse(larger < smaller)
Guido van Rossumaac530c2007-08-24 22:33:45 +0000478
Guido van Rossumcf2ce362007-08-24 23:49:54 +0000479 self.assertFalse(smaller < larger3)
480 self.assertFalse(smaller <= larger3)
481 self.assertFalse(larger3 > smaller)
482 self.assertFalse(larger3 >= smaller)
Guido van Rossumaac530c2007-08-24 22:33:45 +0000483
484 # Inequality strictness
Guido van Rossumcf2ce362007-08-24 23:49:54 +0000485 self.assertTrue(larger2 >= larger)
486 self.assertTrue(larger2 <= larger)
487 self.assertFalse(larger2 > larger)
488 self.assertFalse(larger2 < larger)
Guido van Rossumaac530c2007-08-24 22:33:45 +0000489
Guido van Rossumcf2ce362007-08-24 23:49:54 +0000490 self.assertTrue(larger == larger2)
491 self.assertTrue(smaller != larger)
Guido van Rossumaac530c2007-08-24 22:33:45 +0000492
493 # There is an optimization on the zero-element case.
Guido van Rossumcf2ce362007-08-24 23:49:54 +0000494 self.assertTrue(empty == empty2)
495 self.assertFalse(empty != empty2)
496 self.assertFalse(empty == smaller)
497 self.assertTrue(empty != smaller)
Guido van Rossumaac530c2007-08-24 22:33:45 +0000498
499 # With the same size, an elementwise compare happens
Guido van Rossumcf2ce362007-08-24 23:49:54 +0000500 self.assertTrue(larger != larger3)
501 self.assertFalse(larger == larger3)
Guido van Rossumaac530c2007-08-24 22:33:45 +0000502
503 def test_errors_in_view_containment_check(self):
504 class C:
505 def __eq__(self, other):
506 raise RuntimeError
Florent Xiclunaa988e422010-03-02 16:06:24 +0000507
Guido van Rossumaac530c2007-08-24 22:33:45 +0000508 d1 = {1: C()}
509 d2 = {1: C()}
Florent Xiclunaa988e422010-03-02 16:06:24 +0000510 with self.assertRaises(RuntimeError):
511 d1.items() == d2.items()
512 with self.assertRaises(RuntimeError):
513 d1.items() != d2.items()
514 with self.assertRaises(RuntimeError):
515 d1.items() <= d2.items()
516 with self.assertRaises(RuntimeError):
517 d1.items() >= d2.items()
518
Guido van Rossumaac530c2007-08-24 22:33:45 +0000519 d3 = {1: C(), 2: C()}
Florent Xiclunaa988e422010-03-02 16:06:24 +0000520 with self.assertRaises(RuntimeError):
521 d2.items() < d3.items()
522 with self.assertRaises(RuntimeError):
523 d3.items() > d2.items()
Guido van Rossumaac530c2007-08-24 22:33:45 +0000524
Guido van Rossumbe534712007-08-24 23:43:52 +0000525 def test_dictview_set_operations_on_keys(self):
Guido van Rossum523259b2007-08-24 23:41:22 +0000526 k1 = {1:1, 2:2}.keys()
527 k2 = {1:1, 2:2, 3:3}.keys()
528 k3 = {4:4}.keys()
529
Florent Xiclunaa988e422010-03-02 16:06:24 +0000530 self.assertEqual(k1 - k2, set())
531 self.assertEqual(k1 - k3, {1,2})
532 self.assertEqual(k2 - k1, {3})
533 self.assertEqual(k3 - k1, {4})
534 self.assertEqual(k1 & k2, {1,2})
535 self.assertEqual(k1 & k3, set())
536 self.assertEqual(k1 | k2, {1,2,3})
537 self.assertEqual(k1 ^ k2, {3})
538 self.assertEqual(k1 ^ k3, {1,2,4})
Guido van Rossum523259b2007-08-24 23:41:22 +0000539
Guido van Rossumbe534712007-08-24 23:43:52 +0000540 def test_dictview_set_operations_on_items(self):
541 k1 = {1:1, 2:2}.items()
542 k2 = {1:1, 2:2, 3:3}.items()
543 k3 = {4:4}.items()
544
Florent Xiclunaa988e422010-03-02 16:06:24 +0000545 self.assertEqual(k1 - k2, set())
546 self.assertEqual(k1 - k3, {(1,1), (2,2)})
547 self.assertEqual(k2 - k1, {(3,3)})
548 self.assertEqual(k3 - k1, {(4,4)})
549 self.assertEqual(k1 & k2, {(1,1), (2,2)})
550 self.assertEqual(k1 & k3, set())
551 self.assertEqual(k1 | k2, {(1,1), (2,2), (3,3)})
552 self.assertEqual(k1 ^ k2, {(3,3)})
553 self.assertEqual(k1 ^ k3, {(1,1), (2,2), (4,4)})
Guido van Rossum523259b2007-08-24 23:41:22 +0000554
Guido van Rossum1d719962007-08-24 23:47:30 +0000555 def test_dictview_mixed_set_operations(self):
556 # Just a few for .keys()
Guido van Rossuma401bbe2007-08-24 23:51:55 +0000557 self.assertTrue({1:1}.keys() == {1})
558 self.assertTrue({1} == {1:1}.keys())
Florent Xiclunaa988e422010-03-02 16:06:24 +0000559 self.assertEqual({1:1}.keys() | {2}, {1, 2})
560 self.assertEqual({2} | {1:1}.keys(), {1, 2})
Guido van Rossum1d719962007-08-24 23:47:30 +0000561 # And a few for .items()
Guido van Rossuma401bbe2007-08-24 23:51:55 +0000562 self.assertTrue({1:1}.items() == {(1,1)})
563 self.assertTrue({(1,1)} == {1:1}.items())
Florent Xiclunaa988e422010-03-02 16:06:24 +0000564 self.assertEqual({1:1}.items() | {2}, {(1,1), 2})
565 self.assertEqual({2} | {1:1}.items(), {(1,1), 2})
Guido van Rossum1d719962007-08-24 23:47:30 +0000566
Guido van Rossum1968ad32006-02-25 22:38:04 +0000567 def test_missing(self):
568 # Make sure dict doesn't have a __missing__ method
Florent Xiclunaa988e422010-03-02 16:06:24 +0000569 self.assertFalse(hasattr(dict, "__missing__"))
570 self.assertFalse(hasattr({}, "__missing__"))
Guido van Rossum1968ad32006-02-25 22:38:04 +0000571 # Test several cases:
572 # (D) subclass defines __missing__ method returning a value
573 # (E) subclass defines __missing__ method raising RuntimeError
574 # (F) subclass sets __missing__ instance variable (no effect)
575 # (G) subclass doesn't define __missing__ at a all
576 class D(dict):
577 def __missing__(self, key):
578 return 42
579 d = D({1: 2, 3: 4})
580 self.assertEqual(d[1], 2)
581 self.assertEqual(d[3], 4)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000582 self.assertNotIn(2, d)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000583 self.assertNotIn(2, d.keys())
Guido van Rossum1968ad32006-02-25 22:38:04 +0000584 self.assertEqual(d[2], 42)
Florent Xiclunaa988e422010-03-02 16:06:24 +0000585
Guido van Rossum1968ad32006-02-25 22:38:04 +0000586 class E(dict):
587 def __missing__(self, key):
588 raise RuntimeError(key)
589 e = E()
Florent Xiclunaa988e422010-03-02 16:06:24 +0000590 with self.assertRaises(RuntimeError) as c:
Guido van Rossum1968ad32006-02-25 22:38:04 +0000591 e[42]
Florent Xiclunaa988e422010-03-02 16:06:24 +0000592 self.assertEqual(c.exception.args, (42,))
593
Guido van Rossum1968ad32006-02-25 22:38:04 +0000594 class F(dict):
595 def __init__(self):
596 # An instance variable __missing__ should have no effect
597 self.__missing__ = lambda key: None
598 f = F()
Florent Xiclunaa988e422010-03-02 16:06:24 +0000599 with self.assertRaises(KeyError) as c:
Guido van Rossum1968ad32006-02-25 22:38:04 +0000600 f[42]
Florent Xiclunaa988e422010-03-02 16:06:24 +0000601 self.assertEqual(c.exception.args, (42,))
602
Guido van Rossum1968ad32006-02-25 22:38:04 +0000603 class G(dict):
604 pass
605 g = G()
Florent Xiclunaa988e422010-03-02 16:06:24 +0000606 with self.assertRaises(KeyError) as c:
Guido van Rossum1968ad32006-02-25 22:38:04 +0000607 g[42]
Florent Xiclunaa988e422010-03-02 16:06:24 +0000608 self.assertEqual(c.exception.args, (42,))
Guido van Rossum1968ad32006-02-25 22:38:04 +0000609
Thomas Wouters89f507f2006-12-13 04:49:30 +0000610 def test_tuple_keyerror(self):
611 # SF #1576657
612 d = {}
Florent Xiclunaa988e422010-03-02 16:06:24 +0000613 with self.assertRaises(KeyError) as c:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000614 d[(1,)]
Florent Xiclunaa988e422010-03-02 16:06:24 +0000615 self.assertEqual(c.exception.args, ((1,),))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000616
Guido van Rossumd8faa362007-04-27 19:54:29 +0000617 def test_bad_key(self):
Mark Dickinsona56c4672009-01-27 18:17:45 +0000618 # Dictionary lookups should fail if __eq__() raises an exception.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000619 class CustomException(Exception):
620 pass
621
622 class BadDictKey:
623 def __hash__(self):
624 return hash(self.__class__)
625
626 def __eq__(self, other):
627 if isinstance(other, self.__class__):
628 raise CustomException
629 return other
630
631 d = {}
632 x1 = BadDictKey()
633 x2 = BadDictKey()
634 d[x1] = 1
635 for stmt in ['d[x2] = 2',
636 'z = d[x2]',
637 'x2 in d',
638 'd.get(x2)',
639 'd.setdefault(x2, 42)',
640 'd.pop(x2)',
641 'd.update({x2: 2})']:
Florent Xiclunaa988e422010-03-02 16:06:24 +0000642 with self.assertRaises(CustomException):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000643 exec(stmt, locals())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644
645 def test_resize1(self):
646 # Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
647 # This version got an assert failure in debug build, infinite loop in
648 # release build. Unfortunately, provoking this kind of stuff requires
649 # a mix of inserts and deletes hitting exactly the right hash codes in
650 # exactly the right order, and I can't think of a randomized approach
651 # that would be *likely* to hit a failing case in reasonable time.
652
653 d = {}
654 for i in range(5):
655 d[i] = i
656 for i in range(5):
657 del d[i]
658 for i in range(5, 9): # i==8 was the problem
659 d[i] = i
660
661 def test_resize2(self):
662 # Another dict resizing bug (SF bug #1456209).
663 # This caused Segmentation faults or Illegal instructions.
664
665 class X(object):
666 def __hash__(self):
667 return 5
668 def __eq__(self, other):
669 if resizing:
670 d.clear()
671 return False
672 d = {}
673 resizing = False
674 d[X()] = 1
675 d[X()] = 2
676 d[X()] = 3
677 d[X()] = 4
678 d[X()] = 5
679 # now trigger a resize
680 resizing = True
681 d[9] = 6
682
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000683 def test_empty_presized_dict_in_freelist(self):
684 # Bug #3537: if an empty but presized dict with a size larger
685 # than 7 was in the freelist, it triggered an assertion failure
Florent Xiclunaa988e422010-03-02 16:06:24 +0000686 with self.assertRaises(ZeroDivisionError):
687 d = {'a': 1 // 0, 'b': None, 'c': None, 'd': None, 'e': None,
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000688 'f': None, 'g': None, 'h': None}
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000689 d = {}
690
Antoine Pitrou7ddda782009-01-01 15:35:33 +0000691 def test_container_iterator(self):
692 # Bug #3680: tp_traverse was not implemented for dictiter and
693 # dictview objects.
694 class C(object):
695 pass
696 views = (dict.items, dict.values, dict.keys)
697 for v in views:
698 obj = C()
699 ref = weakref.ref(obj)
700 container = {obj: 1}
701 obj.v = v(container)
702 obj.x = iter(obj.v)
703 del obj, container
704 gc.collect()
Florent Xiclunaa988e422010-03-02 16:06:24 +0000705 self.assertIs(ref(), None, "Cycle was not collected")
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000706
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000707 def _not_tracked(self, t):
708 # Nested containers can take several collections to untrack
709 gc.collect()
710 gc.collect()
711 self.assertFalse(gc.is_tracked(t), t)
712
713 def _tracked(self, t):
714 self.assertTrue(gc.is_tracked(t), t)
715 gc.collect()
716 gc.collect()
717 self.assertTrue(gc.is_tracked(t), t)
718
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000719 @support.cpython_only
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000720 def test_track_literals(self):
721 # Test GC-optimization of dict literals
722 x, y, z, w = 1.5, "a", (1, None), []
723
724 self._not_tracked({})
725 self._not_tracked({x:(), y:x, z:1})
726 self._not_tracked({1: "a", "b": 2})
727 self._not_tracked({1: 2, (None, True, False, ()): int})
728 self._not_tracked({1: object()})
729
730 # Dicts with mutable elements are always tracked, even if those
731 # elements are not tracked right now.
732 self._tracked({1: []})
733 self._tracked({1: ([],)})
734 self._tracked({1: {}})
735 self._tracked({1: set()})
736
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000737 @support.cpython_only
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000738 def test_track_dynamic(self):
739 # Test GC-optimization of dynamically-created dicts
740 class MyObject(object):
741 pass
742 x, y, z, w, o = 1.5, "a", (1, object()), [], MyObject()
743
744 d = dict()
745 self._not_tracked(d)
746 d[1] = "a"
747 self._not_tracked(d)
748 d[y] = 2
749 self._not_tracked(d)
750 d[z] = 3
751 self._not_tracked(d)
752 self._not_tracked(d.copy())
753 d[4] = w
754 self._tracked(d)
755 self._tracked(d.copy())
756 d[4] = None
757 self._not_tracked(d)
758 self._not_tracked(d.copy())
759
760 # dd isn't tracked right now, but it may mutate and therefore d
761 # which contains it must be tracked.
762 d = dict()
763 dd = dict()
764 d[1] = dd
765 self._not_tracked(dd)
766 self._tracked(d)
767 dd[1] = d
768 self._tracked(dd)
769
770 d = dict.fromkeys([x, y, z])
771 self._not_tracked(d)
772 dd = dict()
773 dd.update(d)
774 self._not_tracked(dd)
775 d = dict.fromkeys([x, y, z, o])
776 self._tracked(d)
777 dd = dict()
778 dd.update(d)
779 self._tracked(dd)
780
781 d = dict(x=x, y=y, z=z)
782 self._not_tracked(d)
783 d = dict(x=x, y=y, z=z, w=w)
784 self._tracked(d)
785 d = dict()
786 d.update(x=x, y=y, z=z)
787 self._not_tracked(d)
788 d.update(w=w)
789 self._tracked(d)
790
791 d = dict([(x, y), (z, 1)])
792 self._not_tracked(d)
793 d = dict([(x, y), (z, w)])
794 self._tracked(d)
795 d = dict()
796 d.update([(x, y), (z, 1)])
797 self._not_tracked(d)
798 d.update([(x, y), (z, w)])
799 self._tracked(d)
800
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000801 @support.cpython_only
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000802 def test_track_subtypes(self):
803 # Dict subtypes are always tracked
804 class MyDict(dict):
805 pass
806 self._tracked(MyDict())
807
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000808 def test_iterator_pickling(self):
809 data = {1:"a", 2:"b", 3:"c"}
810 it = iter(data)
811 d = pickle.dumps(it)
812 it = pickle.loads(d)
813 self.assertEqual(sorted(it), sorted(data))
814
815 it = pickle.loads(d)
816 try:
817 drop = next(it)
818 except StopIteration:
819 return
820 d = pickle.dumps(it)
821 it = pickle.loads(d)
822 del data[drop]
823 self.assertEqual(sorted(it), sorted(data))
824
825 def test_itemiterator_pickling(self):
826 data = {1:"a", 2:"b", 3:"c"}
827 # dictviews aren't picklable, only their iterators
828 itorg = iter(data.items())
829 d = pickle.dumps(itorg)
830 it = pickle.loads(d)
831 # note that the type of type of the unpickled iterator
832 # is not necessarily the same as the original. It is
833 # merely an object supporting the iterator protocol, yielding
834 # the same objects as the original one.
835 # self.assertEqual(type(itorg), type(it))
836 self.assertTrue(isinstance(it, collections.abc.Iterator))
837 self.assertEqual(dict(it), data)
838
839 it = pickle.loads(d)
840 drop = next(it)
841 d = pickle.dumps(it)
842 it = pickle.loads(d)
843 del data[drop[0]]
844 self.assertEqual(dict(it), data)
845
846 def test_valuesiterator_pickling(self):
847 data = {1:"a", 2:"b", 3:"c"}
848 # data.values() isn't picklable, only its iterator
849 it = iter(data.values())
850 d = pickle.dumps(it)
851 it = pickle.loads(d)
852 self.assertEqual(sorted(list(it)), sorted(list(data.values())))
853
854 it = pickle.loads(d)
855 drop = next(it)
856 d = pickle.dumps(it)
857 it = pickle.loads(d)
858 values = list(it) + [drop]
859 self.assertEqual(sorted(values), sorted(list(data.values())))
Guido van Rossum1968ad32006-02-25 22:38:04 +0000860
Neal Norwitzc3e54b82006-03-24 07:38:37 +0000861from test import mapping_tests
Raymond Hettinger49c522b2004-09-30 15:07:29 +0000862
863class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
864 type2test = dict
865
866class Dict(dict):
867 pass
868
869class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
870 type2test = Dict
871
Walter Dörwald59b23e82004-09-30 13:46:00 +0000872def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000873 support.run_unittest(
Walter Dörwald59b23e82004-09-30 13:46:00 +0000874 DictTest,
Raymond Hettinger49c522b2004-09-30 15:07:29 +0000875 GeneralMappingTests,
876 SubclassMappingTests,
Walter Dörwald59b23e82004-09-30 13:46:00 +0000877 )
878
879if __name__ == "__main__":
880 test_main()