2004-09-30 10:46:00 -03:00
|
|
|
import unittest
|
|
|
|
from test import test_support
|
|
|
|
|
2008-02-23 13:40:11 -04:00
|
|
|
import UserDict, random, string
|
2009-01-01 10:11:22 -04:00
|
|
|
import gc, weakref
|
2018-02-02 10:29:02 -04:00
|
|
|
import sys
|
2004-09-30 10:46:00 -03:00
|
|
|
|
|
|
|
|
|
|
|
class DictTest(unittest.TestCase):
|
|
|
|
def test_constructor(self):
|
|
|
|
# calling built-in types without argument must return empty
|
|
|
|
self.assertEqual(dict(), {})
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertIsNot(dict(), {})
|
2004-09-30 10:46:00 -03:00
|
|
|
|
2007-12-18 20:21:06 -04:00
|
|
|
def test_literal_constructor(self):
|
2010-03-02 12:00:00 -04:00
|
|
|
# check literal constructor for different sized dicts
|
|
|
|
# (to exercise the BUILD_MAP oparg).
|
2008-03-18 02:12:41 -03:00
|
|
|
for n in (0, 1, 6, 256, 400):
|
2010-03-02 12:00:00 -04:00
|
|
|
items = [(''.join(random.sample(string.letters, 8)), i)
|
2008-03-18 02:12:41 -03:00
|
|
|
for i in range(n)]
|
|
|
|
random.shuffle(items)
|
2010-03-02 12:00:00 -04:00
|
|
|
formatted_items = ('{!r}: {:d}'.format(k, v) for k, v in items)
|
|
|
|
dictliteral = '{' + ', '.join(formatted_items) + '}'
|
2007-12-18 20:21:06 -04:00
|
|
|
self.assertEqual(eval(dictliteral), dict(items))
|
|
|
|
|
2004-09-30 10:46:00 -03:00
|
|
|
def test_bool(self):
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertIs(not {}, True)
|
2009-06-30 19:57:08 -03:00
|
|
|
self.assertTrue({1: 2})
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertIs(bool({}), False)
|
|
|
|
self.assertIs(bool({1: 2}), True)
|
2004-09-30 10:46:00 -03:00
|
|
|
|
|
|
|
def test_keys(self):
|
|
|
|
d = {}
|
|
|
|
self.assertEqual(d.keys(), [])
|
|
|
|
d = {'a': 1, 'b': 2}
|
|
|
|
k = d.keys()
|
2013-10-04 21:01:37 -03:00
|
|
|
self.assertEqual(set(k), {'a', 'b'})
|
|
|
|
self.assertIn('a', k)
|
|
|
|
self.assertIn('b', k)
|
2010-01-08 15:04:16 -04:00
|
|
|
self.assertTrue(d.has_key('a'))
|
|
|
|
self.assertTrue(d.has_key('b'))
|
2004-09-30 10:46:00 -03:00
|
|
|
self.assertRaises(TypeError, d.keys, None)
|
|
|
|
|
|
|
|
def test_values(self):
|
|
|
|
d = {}
|
|
|
|
self.assertEqual(d.values(), [])
|
|
|
|
d = {1:2}
|
|
|
|
self.assertEqual(d.values(), [2])
|
|
|
|
|
|
|
|
self.assertRaises(TypeError, d.values, None)
|
|
|
|
|
|
|
|
def test_items(self):
|
|
|
|
d = {}
|
|
|
|
self.assertEqual(d.items(), [])
|
|
|
|
|
|
|
|
d = {1:2}
|
|
|
|
self.assertEqual(d.items(), [(1, 2)])
|
|
|
|
|
|
|
|
self.assertRaises(TypeError, d.items, None)
|
|
|
|
|
|
|
|
def test_has_key(self):
|
|
|
|
d = {}
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertFalse(d.has_key('a'))
|
2004-09-30 10:46:00 -03:00
|
|
|
d = {'a': 1, 'b': 2}
|
|
|
|
k = d.keys()
|
|
|
|
k.sort()
|
|
|
|
self.assertEqual(k, ['a', 'b'])
|
|
|
|
|
2010-01-08 15:04:16 -04:00
|
|
|
self.assertRaises(TypeError, d.has_key)
|
|
|
|
|
2004-09-30 10:46:00 -03:00
|
|
|
def test_contains(self):
|
|
|
|
d = {}
|
2010-01-23 19:04:36 -04:00
|
|
|
self.assertNotIn('a', d)
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertFalse('a' in d)
|
2009-06-30 19:57:08 -03:00
|
|
|
self.assertTrue('a' not in d)
|
2004-09-30 10:46:00 -03:00
|
|
|
d = {'a': 1, 'b': 2}
|
2010-01-23 19:04:36 -04:00
|
|
|
self.assertIn('a', d)
|
|
|
|
self.assertIn('b', d)
|
|
|
|
self.assertNotIn('c', d)
|
2004-09-30 10:46:00 -03:00
|
|
|
|
|
|
|
self.assertRaises(TypeError, d.__contains__)
|
|
|
|
|
|
|
|
def test_len(self):
|
|
|
|
d = {}
|
|
|
|
self.assertEqual(len(d), 0)
|
|
|
|
d = {'a': 1, 'b': 2}
|
|
|
|
self.assertEqual(len(d), 2)
|
|
|
|
|
|
|
|
def test_getitem(self):
|
|
|
|
d = {'a': 1, 'b': 2}
|
|
|
|
self.assertEqual(d['a'], 1)
|
|
|
|
self.assertEqual(d['b'], 2)
|
|
|
|
d['c'] = 3
|
|
|
|
d['a'] = 4
|
|
|
|
self.assertEqual(d['c'], 3)
|
|
|
|
self.assertEqual(d['a'], 4)
|
|
|
|
del d['b']
|
|
|
|
self.assertEqual(d, {'a': 4, 'c': 3})
|
|
|
|
|
|
|
|
self.assertRaises(TypeError, d.__getitem__)
|
|
|
|
|
|
|
|
class BadEq(object):
|
|
|
|
def __eq__(self, other):
|
|
|
|
raise Exc()
|
2007-11-21 20:55:51 -04:00
|
|
|
def __hash__(self):
|
|
|
|
return 24
|
2004-09-30 10:46:00 -03:00
|
|
|
|
|
|
|
d = {}
|
|
|
|
d[BadEq()] = 42
|
|
|
|
self.assertRaises(KeyError, d.__getitem__, 23)
|
|
|
|
|
|
|
|
class Exc(Exception): pass
|
|
|
|
|
|
|
|
class BadHash(object):
|
|
|
|
fail = False
|
|
|
|
def __hash__(self):
|
|
|
|
if self.fail:
|
|
|
|
raise Exc()
|
|
|
|
else:
|
|
|
|
return 42
|
|
|
|
|
|
|
|
x = BadHash()
|
|
|
|
d[x] = 42
|
|
|
|
x.fail = True
|
|
|
|
self.assertRaises(Exc, d.__getitem__, x)
|
|
|
|
|
|
|
|
def test_clear(self):
|
|
|
|
d = {1:1, 2:2, 3:3}
|
|
|
|
d.clear()
|
|
|
|
self.assertEqual(d, {})
|
|
|
|
|
|
|
|
self.assertRaises(TypeError, d.clear, None)
|
|
|
|
|
|
|
|
def test_update(self):
|
|
|
|
d = {}
|
|
|
|
d.update({1:100})
|
|
|
|
d.update({2:20})
|
|
|
|
d.update({1:1, 2:2, 3:3})
|
|
|
|
self.assertEqual(d, {1:1, 2:2, 3:3})
|
|
|
|
|
|
|
|
d.update()
|
|
|
|
self.assertEqual(d, {1:1, 2:2, 3:3})
|
|
|
|
|
|
|
|
self.assertRaises((TypeError, AttributeError), d.update, None)
|
|
|
|
|
|
|
|
class SimpleUserDict:
|
|
|
|
def __init__(self):
|
|
|
|
self.d = {1:1, 2:2, 3:3}
|
|
|
|
def keys(self):
|
|
|
|
return self.d.keys()
|
|
|
|
def __getitem__(self, i):
|
|
|
|
return self.d[i]
|
|
|
|
d.clear()
|
|
|
|
d.update(SimpleUserDict())
|
|
|
|
self.assertEqual(d, {1:1, 2:2, 3:3})
|
|
|
|
|
|
|
|
class Exc(Exception): pass
|
|
|
|
|
|
|
|
d.clear()
|
|
|
|
class FailingUserDict:
|
|
|
|
def keys(self):
|
|
|
|
raise Exc
|
|
|
|
self.assertRaises(Exc, d.update, FailingUserDict())
|
|
|
|
|
|
|
|
class FailingUserDict:
|
|
|
|
def keys(self):
|
|
|
|
class BogonIter:
|
|
|
|
def __init__(self):
|
|
|
|
self.i = 1
|
|
|
|
def __iter__(self):
|
|
|
|
return self
|
|
|
|
def next(self):
|
|
|
|
if self.i:
|
|
|
|
self.i = 0
|
|
|
|
return 'a'
|
|
|
|
raise Exc
|
|
|
|
return BogonIter()
|
|
|
|
def __getitem__(self, key):
|
|
|
|
return key
|
|
|
|
self.assertRaises(Exc, d.update, FailingUserDict())
|
|
|
|
|
|
|
|
class FailingUserDict:
|
|
|
|
def keys(self):
|
|
|
|
class BogonIter:
|
|
|
|
def __init__(self):
|
|
|
|
self.i = ord('a')
|
|
|
|
def __iter__(self):
|
|
|
|
return self
|
|
|
|
def next(self):
|
|
|
|
if self.i <= ord('z'):
|
|
|
|
rtn = chr(self.i)
|
|
|
|
self.i += 1
|
|
|
|
return rtn
|
|
|
|
raise StopIteration
|
|
|
|
return BogonIter()
|
|
|
|
def __getitem__(self, key):
|
|
|
|
raise Exc
|
|
|
|
self.assertRaises(Exc, d.update, FailingUserDict())
|
|
|
|
|
|
|
|
class badseq(object):
|
|
|
|
def __iter__(self):
|
|
|
|
return self
|
|
|
|
def next(self):
|
|
|
|
raise Exc()
|
|
|
|
|
|
|
|
self.assertRaises(Exc, {}.update, badseq())
|
|
|
|
|
|
|
|
self.assertRaises(ValueError, {}.update, [(1, 2, 3)])
|
|
|
|
|
|
|
|
def test_fromkeys(self):
|
|
|
|
self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
|
|
|
|
d = {}
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertIsNot(d.fromkeys('abc'), d)
|
2004-09-30 10:46:00 -03:00
|
|
|
self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
|
|
|
|
self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0})
|
|
|
|
self.assertEqual(d.fromkeys([]), {})
|
|
|
|
def g():
|
|
|
|
yield 1
|
|
|
|
self.assertEqual(d.fromkeys(g()), {1:None})
|
|
|
|
self.assertRaises(TypeError, {}.fromkeys, 3)
|
|
|
|
class dictlike(dict): pass
|
|
|
|
self.assertEqual(dictlike.fromkeys('a'), {'a':None})
|
|
|
|
self.assertEqual(dictlike().fromkeys('a'), {'a':None})
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertIsInstance(dictlike.fromkeys('a'), dictlike)
|
|
|
|
self.assertIsInstance(dictlike().fromkeys('a'), dictlike)
|
2004-09-30 10:46:00 -03:00
|
|
|
class mydict(dict):
|
|
|
|
def __new__(cls):
|
|
|
|
return UserDict.UserDict()
|
|
|
|
ud = mydict.fromkeys('ab')
|
|
|
|
self.assertEqual(ud, {'a':None, 'b':None})
|
2010-01-24 12:58:36 -04:00
|
|
|
self.assertIsInstance(ud, UserDict.UserDict)
|
2004-09-30 10:46:00 -03:00
|
|
|
self.assertRaises(TypeError, dict.fromkeys)
|
|
|
|
|
|
|
|
class Exc(Exception): pass
|
|
|
|
|
|
|
|
class baddict1(dict):
|
|
|
|
def __init__(self):
|
|
|
|
raise Exc()
|
|
|
|
|
|
|
|
self.assertRaises(Exc, baddict1.fromkeys, [1])
|
|
|
|
|
|
|
|
class BadSeq(object):
|
|
|
|
def __iter__(self):
|
|
|
|
return self
|
|
|
|
def next(self):
|
|
|
|
raise Exc()
|
|
|
|
|
|
|
|
self.assertRaises(Exc, dict.fromkeys, BadSeq())
|
|
|
|
|
|
|
|
class baddict2(dict):
|
|
|
|
def __setitem__(self, key, value):
|
|
|
|
raise Exc()
|
|
|
|
|
|
|
|
self.assertRaises(Exc, baddict2.fromkeys, [1])
|
|
|
|
|
2007-11-06 22:26:17 -04:00
|
|
|
# test fast path for dictionary inputs
|
|
|
|
d = dict(zip(range(6), range(6)))
|
|
|
|
self.assertEqual(dict.fromkeys(d, 0), dict(zip(range(6), [0]*6)))
|
|
|
|
|
2012-10-31 15:05:55 -03:00
|
|
|
class baddict3(dict):
|
|
|
|
def __new__(cls):
|
|
|
|
return d
|
|
|
|
d = {i : i for i in range(10)}
|
|
|
|
res = d.copy()
|
|
|
|
res.update(a=None, b=None, c=None)
|
|
|
|
self.assertEqual(baddict3.fromkeys({"a", "b", "c"}), res)
|
|
|
|
|
2004-09-30 10:46:00 -03:00
|
|
|
def test_copy(self):
|
|
|
|
d = {1:1, 2:2, 3:3}
|
|
|
|
self.assertEqual(d.copy(), {1:1, 2:2, 3:3})
|
|
|
|
self.assertEqual({}.copy(), {})
|
|
|
|
self.assertRaises(TypeError, d.copy, None)
|
|
|
|
|
|
|
|
def test_get(self):
|
|
|
|
d = {}
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertIs(d.get('c'), None)
|
2004-09-30 10:46:00 -03:00
|
|
|
self.assertEqual(d.get('c', 3), 3)
|
2010-03-02 12:00:00 -04:00
|
|
|
d = {'a': 1, 'b': 2}
|
|
|
|
self.assertIs(d.get('c'), None)
|
2004-09-30 10:46:00 -03:00
|
|
|
self.assertEqual(d.get('c', 3), 3)
|
|
|
|
self.assertEqual(d.get('a'), 1)
|
|
|
|
self.assertEqual(d.get('a', 3), 1)
|
|
|
|
self.assertRaises(TypeError, d.get)
|
|
|
|
self.assertRaises(TypeError, d.get, None, None, None)
|
|
|
|
|
|
|
|
def test_setdefault(self):
|
|
|
|
# dict.setdefault()
|
|
|
|
d = {}
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertIs(d.setdefault('key0'), None)
|
2004-09-30 10:46:00 -03:00
|
|
|
d.setdefault('key0', [])
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertIs(d.setdefault('key0'), None)
|
2004-09-30 10:46:00 -03:00
|
|
|
d.setdefault('key', []).append(3)
|
|
|
|
self.assertEqual(d['key'][0], 3)
|
|
|
|
d.setdefault('key', []).append(4)
|
|
|
|
self.assertEqual(len(d['key']), 2)
|
|
|
|
self.assertRaises(TypeError, d.setdefault)
|
|
|
|
|
|
|
|
class Exc(Exception): pass
|
|
|
|
|
|
|
|
class BadHash(object):
|
|
|
|
fail = False
|
|
|
|
def __hash__(self):
|
|
|
|
if self.fail:
|
|
|
|
raise Exc()
|
|
|
|
else:
|
|
|
|
return 42
|
|
|
|
|
|
|
|
x = BadHash()
|
|
|
|
d[x] = 42
|
|
|
|
x.fail = True
|
|
|
|
self.assertRaises(Exc, d.setdefault, x, [])
|
|
|
|
|
2012-02-26 19:45:12 -04:00
|
|
|
def test_setdefault_atomic(self):
|
|
|
|
# Issue #13521: setdefault() calls __hash__ and __eq__ only once.
|
|
|
|
class Hashed(object):
|
|
|
|
def __init__(self):
|
|
|
|
self.hash_count = 0
|
|
|
|
self.eq_count = 0
|
|
|
|
def __hash__(self):
|
|
|
|
self.hash_count += 1
|
|
|
|
return 42
|
|
|
|
def __eq__(self, other):
|
|
|
|
self.eq_count += 1
|
|
|
|
return id(self) == id(other)
|
|
|
|
hashed1 = Hashed()
|
|
|
|
y = {hashed1: 5}
|
|
|
|
hashed2 = Hashed()
|
|
|
|
y.setdefault(hashed2, [])
|
|
|
|
self.assertEqual(hashed1.hash_count, 1)
|
|
|
|
self.assertEqual(hashed2.hash_count, 1)
|
|
|
|
self.assertEqual(hashed1.eq_count + hashed2.eq_count, 1)
|
|
|
|
|
2004-09-30 10:46:00 -03:00
|
|
|
def test_popitem(self):
|
|
|
|
# dict.popitem()
|
|
|
|
for copymode in -1, +1:
|
|
|
|
# -1: b has same structure as a
|
|
|
|
# +1: b is a.copy()
|
|
|
|
for log2size in range(12):
|
|
|
|
size = 2**log2size
|
|
|
|
a = {}
|
|
|
|
b = {}
|
|
|
|
for i in range(size):
|
|
|
|
a[repr(i)] = i
|
|
|
|
if copymode < 0:
|
|
|
|
b[repr(i)] = i
|
|
|
|
if copymode > 0:
|
|
|
|
b = a.copy()
|
|
|
|
for i in range(size):
|
|
|
|
ka, va = ta = a.popitem()
|
|
|
|
self.assertEqual(va, int(ka))
|
|
|
|
kb, vb = tb = b.popitem()
|
|
|
|
self.assertEqual(vb, int(kb))
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertFalse(copymode < 0 and ta != tb)
|
|
|
|
self.assertFalse(a)
|
|
|
|
self.assertFalse(b)
|
2004-09-30 10:46:00 -03:00
|
|
|
|
|
|
|
d = {}
|
|
|
|
self.assertRaises(KeyError, d.popitem)
|
|
|
|
|
|
|
|
def test_pop(self):
|
|
|
|
# Tests for pop with specified key
|
|
|
|
d = {}
|
|
|
|
k, v = 'abc', 'def'
|
|
|
|
d[k] = v
|
|
|
|
self.assertRaises(KeyError, d.pop, 'ghi')
|
|
|
|
|
|
|
|
self.assertEqual(d.pop(k), v)
|
|
|
|
self.assertEqual(len(d), 0)
|
|
|
|
|
|
|
|
self.assertRaises(KeyError, d.pop, k)
|
|
|
|
|
2010-03-02 12:00:00 -04:00
|
|
|
# verify longs/ints get same value when key > 32 bits
|
|
|
|
# (for 64-bit archs). See SF bug #689659.
|
2004-09-30 10:46:00 -03:00
|
|
|
x = 4503599627370496L
|
|
|
|
y = 4503599627370496
|
|
|
|
h = {x: 'anything', y: 'something else'}
|
|
|
|
self.assertEqual(h[x], h[y])
|
|
|
|
|
|
|
|
self.assertEqual(d.pop(k, v), v)
|
|
|
|
d[k] = v
|
|
|
|
self.assertEqual(d.pop(k, 1), v)
|
|
|
|
|
|
|
|
self.assertRaises(TypeError, d.pop)
|
|
|
|
|
|
|
|
class Exc(Exception): pass
|
|
|
|
|
|
|
|
class BadHash(object):
|
|
|
|
fail = False
|
|
|
|
def __hash__(self):
|
|
|
|
if self.fail:
|
|
|
|
raise Exc()
|
|
|
|
else:
|
|
|
|
return 42
|
|
|
|
|
|
|
|
x = BadHash()
|
|
|
|
d[x] = 42
|
|
|
|
x.fail = True
|
|
|
|
self.assertRaises(Exc, d.pop, x)
|
|
|
|
|
|
|
|
def test_mutatingiteration(self):
|
2010-03-02 12:00:00 -04:00
|
|
|
# changing dict size during iteration
|
2004-09-30 10:46:00 -03:00
|
|
|
d = {}
|
|
|
|
d[1] = 1
|
2010-03-02 12:00:00 -04:00
|
|
|
with self.assertRaises(RuntimeError):
|
2004-09-30 10:46:00 -03:00
|
|
|
for i in d:
|
|
|
|
d[i+1] = 1
|
|
|
|
|
|
|
|
def test_repr(self):
|
|
|
|
d = {}
|
|
|
|
self.assertEqual(repr(d), '{}')
|
|
|
|
d[1] = 2
|
|
|
|
self.assertEqual(repr(d), '{1: 2}')
|
|
|
|
d = {}
|
|
|
|
d[1] = d
|
|
|
|
self.assertEqual(repr(d), '{1: {...}}')
|
|
|
|
|
|
|
|
class Exc(Exception): pass
|
|
|
|
|
|
|
|
class BadRepr(object):
|
|
|
|
def __repr__(self):
|
|
|
|
raise Exc()
|
|
|
|
|
|
|
|
d = {1: BadRepr()}
|
|
|
|
self.assertRaises(Exc, repr, d)
|
|
|
|
|
2018-02-02 10:29:02 -04:00
|
|
|
def test_repr_deep(self):
|
|
|
|
d = {}
|
|
|
|
for i in range(sys.getrecursionlimit() + 100):
|
|
|
|
d = {1: d}
|
|
|
|
self.assertRaises(RuntimeError, repr, d)
|
|
|
|
|
2004-09-30 10:46:00 -03:00
|
|
|
def test_le(self):
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertFalse({} < {})
|
|
|
|
self.assertFalse({1: 2} < {1L: 2L})
|
2004-09-30 10:46:00 -03:00
|
|
|
|
|
|
|
class Exc(Exception): pass
|
|
|
|
|
|
|
|
class BadCmp(object):
|
|
|
|
def __eq__(self, other):
|
|
|
|
raise Exc()
|
2007-11-21 20:55:51 -04:00
|
|
|
def __hash__(self):
|
|
|
|
return 42
|
2004-09-30 10:46:00 -03:00
|
|
|
|
|
|
|
d1 = {BadCmp(): 1}
|
|
|
|
d2 = {1: 1}
|
2010-03-02 12:00:00 -04:00
|
|
|
|
|
|
|
with self.assertRaises(Exc):
|
2010-01-08 15:04:16 -04:00
|
|
|
d1 < d2
|
2004-09-30 10:46:00 -03:00
|
|
|
|
2006-02-25 18:38:04 -04:00
|
|
|
def test_missing(self):
|
|
|
|
# Make sure dict doesn't have a __missing__ method
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertFalse(hasattr(dict, "__missing__"))
|
|
|
|
self.assertFalse(hasattr({}, "__missing__"))
|
2006-02-25 18:38:04 -04:00
|
|
|
# Test several cases:
|
|
|
|
# (D) subclass defines __missing__ method returning a value
|
|
|
|
# (E) subclass defines __missing__ method raising RuntimeError
|
|
|
|
# (F) subclass sets __missing__ instance variable (no effect)
|
2015-11-02 09:06:09 -04:00
|
|
|
# (G) subclass doesn't define __missing__ at all
|
2006-02-25 18:38:04 -04:00
|
|
|
class D(dict):
|
|
|
|
def __missing__(self, key):
|
|
|
|
return 42
|
|
|
|
d = D({1: 2, 3: 4})
|
|
|
|
self.assertEqual(d[1], 2)
|
|
|
|
self.assertEqual(d[3], 4)
|
2010-01-23 19:04:36 -04:00
|
|
|
self.assertNotIn(2, d)
|
|
|
|
self.assertNotIn(2, d.keys())
|
2006-02-25 18:38:04 -04:00
|
|
|
self.assertEqual(d[2], 42)
|
2010-03-02 12:00:00 -04:00
|
|
|
|
2006-02-25 18:38:04 -04:00
|
|
|
class E(dict):
|
|
|
|
def __missing__(self, key):
|
|
|
|
raise RuntimeError(key)
|
|
|
|
e = E()
|
2010-03-02 12:00:00 -04:00
|
|
|
with self.assertRaises(RuntimeError) as c:
|
2006-02-25 18:38:04 -04:00
|
|
|
e[42]
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertEqual(c.exception.args, (42,))
|
|
|
|
|
2006-02-25 18:38:04 -04:00
|
|
|
class F(dict):
|
|
|
|
def __init__(self):
|
|
|
|
# An instance variable __missing__ should have no effect
|
|
|
|
self.__missing__ = lambda key: None
|
|
|
|
f = F()
|
2010-03-02 12:00:00 -04:00
|
|
|
with self.assertRaises(KeyError) as c:
|
2006-02-25 18:38:04 -04:00
|
|
|
f[42]
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertEqual(c.exception.args, (42,))
|
|
|
|
|
2006-02-25 18:38:04 -04:00
|
|
|
class G(dict):
|
|
|
|
pass
|
|
|
|
g = G()
|
2010-03-02 12:00:00 -04:00
|
|
|
with self.assertRaises(KeyError) as c:
|
2006-02-25 18:38:04 -04:00
|
|
|
g[42]
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertEqual(c.exception.args, (42,))
|
2006-02-25 18:38:04 -04:00
|
|
|
|
2006-10-29 14:31:42 -04:00
|
|
|
def test_tuple_keyerror(self):
|
|
|
|
# SF #1576657
|
|
|
|
d = {}
|
2010-03-02 12:00:00 -04:00
|
|
|
with self.assertRaises(KeyError) as c:
|
2006-10-29 14:31:42 -04:00
|
|
|
d[(1,)]
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertEqual(c.exception.args, ((1,),))
|
2007-03-12 15:07:52 -03:00
|
|
|
|
2007-03-12 12:57:19 -03:00
|
|
|
def test_bad_key(self):
|
|
|
|
# Dictionary lookups should fail if __cmp__() raises an exception.
|
|
|
|
class CustomException(Exception):
|
|
|
|
pass
|
2007-03-12 15:07:52 -03:00
|
|
|
|
2007-03-12 12:57:19 -03:00
|
|
|
class BadDictKey:
|
|
|
|
def __hash__(self):
|
|
|
|
return hash(self.__class__)
|
|
|
|
|
|
|
|
def __cmp__(self, other):
|
|
|
|
if isinstance(other, self.__class__):
|
|
|
|
raise CustomException
|
|
|
|
return other
|
2007-03-12 15:07:52 -03:00
|
|
|
|
2007-03-12 12:57:19 -03:00
|
|
|
d = {}
|
|
|
|
x1 = BadDictKey()
|
|
|
|
x2 = BadDictKey()
|
|
|
|
d[x1] = 1
|
|
|
|
for stmt in ['d[x2] = 2',
|
|
|
|
'z = d[x2]',
|
|
|
|
'x2 in d',
|
|
|
|
'd.has_key(x2)',
|
|
|
|
'd.get(x2)',
|
|
|
|
'd.setdefault(x2, 42)',
|
|
|
|
'd.pop(x2)',
|
|
|
|
'd.update({x2: 2})']:
|
2010-03-02 12:00:00 -04:00
|
|
|
with self.assertRaises(CustomException):
|
2010-01-08 15:04:16 -04:00
|
|
|
exec stmt in locals()
|
2007-03-12 12:57:19 -03:00
|
|
|
|
|
|
|
def test_resize1(self):
|
|
|
|
# Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
|
|
|
|
# This version got an assert failure in debug build, infinite loop in
|
|
|
|
# release build. Unfortunately, provoking this kind of stuff requires
|
|
|
|
# a mix of inserts and deletes hitting exactly the right hash codes in
|
|
|
|
# exactly the right order, and I can't think of a randomized approach
|
|
|
|
# that would be *likely* to hit a failing case in reasonable time.
|
2007-03-12 15:07:52 -03:00
|
|
|
|
2007-03-12 12:57:19 -03:00
|
|
|
d = {}
|
|
|
|
for i in range(5):
|
|
|
|
d[i] = i
|
|
|
|
for i in range(5):
|
|
|
|
del d[i]
|
|
|
|
for i in range(5, 9): # i==8 was the problem
|
|
|
|
d[i] = i
|
|
|
|
|
|
|
|
def test_resize2(self):
|
|
|
|
# Another dict resizing bug (SF bug #1456209).
|
|
|
|
# This caused Segmentation faults or Illegal instructions.
|
2007-03-12 15:07:52 -03:00
|
|
|
|
2007-03-12 12:57:19 -03:00
|
|
|
class X(object):
|
|
|
|
def __hash__(self):
|
|
|
|
return 5
|
|
|
|
def __eq__(self, other):
|
|
|
|
if resizing:
|
|
|
|
d.clear()
|
|
|
|
return False
|
|
|
|
d = {}
|
|
|
|
resizing = False
|
|
|
|
d[X()] = 1
|
|
|
|
d[X()] = 2
|
|
|
|
d[X()] = 3
|
|
|
|
d[X()] = 4
|
|
|
|
d[X()] = 5
|
|
|
|
# now trigger a resize
|
|
|
|
resizing = True
|
|
|
|
d[9] = 6
|
2006-10-29 14:31:42 -04:00
|
|
|
|
2008-08-11 06:07:59 -03:00
|
|
|
def test_empty_presized_dict_in_freelist(self):
|
|
|
|
# Bug #3537: if an empty but presized dict with a size larger
|
|
|
|
# than 7 was in the freelist, it triggered an assertion failure
|
2010-03-02 12:00:00 -04:00
|
|
|
with self.assertRaises(ZeroDivisionError):
|
|
|
|
d = {'a': 1 // 0, 'b': None, 'c': None, 'd': None, 'e': None,
|
2008-08-11 06:07:59 -03:00
|
|
|
'f': None, 'g': None, 'h': None}
|
|
|
|
d = {}
|
|
|
|
|
2009-01-01 10:11:22 -04:00
|
|
|
def test_container_iterator(self):
|
2009-01-01 11:38:03 -04:00
|
|
|
# Bug #3680: tp_traverse was not implemented for dictiter objects
|
2009-01-01 10:11:22 -04:00
|
|
|
class C(object):
|
|
|
|
pass
|
|
|
|
iterators = (dict.iteritems, dict.itervalues, dict.iterkeys)
|
|
|
|
for i in iterators:
|
|
|
|
obj = C()
|
|
|
|
ref = weakref.ref(obj)
|
|
|
|
container = {obj: 1}
|
|
|
|
obj.x = i(container)
|
|
|
|
del obj, container
|
|
|
|
gc.collect()
|
2010-03-02 12:00:00 -04:00
|
|
|
self.assertIs(ref(), None, "Cycle was not collected")
|
2008-08-11 06:07:59 -03:00
|
|
|
|
2009-03-23 15:41:45 -03:00
|
|
|
def _not_tracked(self, t):
|
|
|
|
# Nested containers can take several collections to untrack
|
|
|
|
gc.collect()
|
|
|
|
gc.collect()
|
|
|
|
self.assertFalse(gc.is_tracked(t), t)
|
|
|
|
|
|
|
|
def _tracked(self, t):
|
|
|
|
self.assertTrue(gc.is_tracked(t), t)
|
|
|
|
gc.collect()
|
|
|
|
gc.collect()
|
|
|
|
self.assertTrue(gc.is_tracked(t), t)
|
|
|
|
|
2010-06-23 17:29:26 -03:00
|
|
|
@test_support.cpython_only
|
2009-03-23 15:41:45 -03:00
|
|
|
def test_track_literals(self):
|
|
|
|
# Test GC-optimization of dict literals
|
|
|
|
x, y, z, w = 1.5, "a", (1, None), []
|
|
|
|
|
|
|
|
self._not_tracked({})
|
|
|
|
self._not_tracked({x:(), y:x, z:1})
|
|
|
|
self._not_tracked({1: "a", "b": 2})
|
|
|
|
self._not_tracked({1: 2, (None, True, False, ()): int})
|
|
|
|
self._not_tracked({1: object()})
|
|
|
|
|
|
|
|
# Dicts with mutable elements are always tracked, even if those
|
|
|
|
# elements are not tracked right now.
|
|
|
|
self._tracked({1: []})
|
|
|
|
self._tracked({1: ([],)})
|
|
|
|
self._tracked({1: {}})
|
|
|
|
self._tracked({1: set()})
|
|
|
|
|
2010-06-23 17:29:26 -03:00
|
|
|
@test_support.cpython_only
|
2009-03-23 15:41:45 -03:00
|
|
|
def test_track_dynamic(self):
|
|
|
|
# Test GC-optimization of dynamically-created dicts
|
|
|
|
class MyObject(object):
|
|
|
|
pass
|
|
|
|
x, y, z, w, o = 1.5, "a", (1, object()), [], MyObject()
|
|
|
|
|
|
|
|
d = dict()
|
|
|
|
self._not_tracked(d)
|
|
|
|
d[1] = "a"
|
|
|
|
self._not_tracked(d)
|
|
|
|
d[y] = 2
|
|
|
|
self._not_tracked(d)
|
|
|
|
d[z] = 3
|
|
|
|
self._not_tracked(d)
|
|
|
|
self._not_tracked(d.copy())
|
|
|
|
d[4] = w
|
|
|
|
self._tracked(d)
|
|
|
|
self._tracked(d.copy())
|
|
|
|
d[4] = None
|
|
|
|
self._not_tracked(d)
|
|
|
|
self._not_tracked(d.copy())
|
|
|
|
|
|
|
|
# dd isn't tracked right now, but it may mutate and therefore d
|
|
|
|
# which contains it must be tracked.
|
|
|
|
d = dict()
|
|
|
|
dd = dict()
|
|
|
|
d[1] = dd
|
|
|
|
self._not_tracked(dd)
|
|
|
|
self._tracked(d)
|
|
|
|
dd[1] = d
|
|
|
|
self._tracked(dd)
|
|
|
|
|
|
|
|
d = dict.fromkeys([x, y, z])
|
|
|
|
self._not_tracked(d)
|
|
|
|
dd = dict()
|
|
|
|
dd.update(d)
|
|
|
|
self._not_tracked(dd)
|
|
|
|
d = dict.fromkeys([x, y, z, o])
|
|
|
|
self._tracked(d)
|
|
|
|
dd = dict()
|
|
|
|
dd.update(d)
|
|
|
|
self._tracked(dd)
|
|
|
|
|
|
|
|
d = dict(x=x, y=y, z=z)
|
|
|
|
self._not_tracked(d)
|
|
|
|
d = dict(x=x, y=y, z=z, w=w)
|
|
|
|
self._tracked(d)
|
|
|
|
d = dict()
|
|
|
|
d.update(x=x, y=y, z=z)
|
|
|
|
self._not_tracked(d)
|
|
|
|
d.update(w=w)
|
|
|
|
self._tracked(d)
|
|
|
|
|
|
|
|
d = dict([(x, y), (z, 1)])
|
|
|
|
self._not_tracked(d)
|
|
|
|
d = dict([(x, y), (z, w)])
|
|
|
|
self._tracked(d)
|
|
|
|
d = dict()
|
|
|
|
d.update([(x, y), (z, 1)])
|
|
|
|
self._not_tracked(d)
|
|
|
|
d.update([(x, y), (z, w)])
|
|
|
|
self._tracked(d)
|
|
|
|
|
2010-06-23 17:29:26 -03:00
|
|
|
@test_support.cpython_only
|
2009-03-23 15:41:45 -03:00
|
|
|
def test_track_subtypes(self):
|
|
|
|
# Dict subtypes are always tracked
|
|
|
|
class MyDict(dict):
|
|
|
|
pass
|
|
|
|
self._tracked(MyDict())
|
|
|
|
|
2006-02-25 18:38:04 -04:00
|
|
|
|
2016-03-30 14:43:06 -03:00
|
|
|
def test_free_after_iterating(self):
|
|
|
|
test_support.check_free_after_iterating(self, iter, dict)
|
|
|
|
test_support.check_free_after_iterating(self, lambda d: d.iterkeys(), dict)
|
|
|
|
test_support.check_free_after_iterating(self, lambda d: d.itervalues(), dict)
|
|
|
|
test_support.check_free_after_iterating(self, lambda d: d.iteritems(), dict)
|
|
|
|
test_support.check_free_after_iterating(self, lambda d: iter(d.viewkeys()), dict)
|
|
|
|
test_support.check_free_after_iterating(self, lambda d: iter(d.viewvalues()), dict)
|
|
|
|
test_support.check_free_after_iterating(self, lambda d: iter(d.viewitems()), dict)
|
|
|
|
|
2017-05-20 14:05:27 -03:00
|
|
|
def test_equal_operator_modifying_operand(self):
|
|
|
|
# test fix for seg fault reported in issue 27945 part 3.
|
|
|
|
class X(object):
|
|
|
|
def __del__(self):
|
|
|
|
dict_b.clear()
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
dict_a.clear()
|
|
|
|
return True
|
|
|
|
|
|
|
|
def __hash__(self):
|
|
|
|
return 13
|
|
|
|
|
|
|
|
dict_a = {X(): 0}
|
|
|
|
dict_b = {X(): X()}
|
|
|
|
self.assertTrue(dict_a == dict_b)
|
|
|
|
|
|
|
|
def test_fromkeys_operator_modifying_dict_operand(self):
|
|
|
|
# test fix for seg fault reported in issue 27945 part 4a.
|
|
|
|
class X(int):
|
|
|
|
def __hash__(self):
|
|
|
|
return 13
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
if len(d) > 1:
|
|
|
|
d.clear()
|
|
|
|
return False
|
|
|
|
|
|
|
|
d = {} # this is required to exist so that d can be constructed!
|
|
|
|
d = {X(1): 1, X(2): 2}
|
|
|
|
try:
|
|
|
|
dict.fromkeys(d) # shouldn't crash
|
|
|
|
except RuntimeError: # implementation defined
|
|
|
|
pass
|
|
|
|
|
|
|
|
def test_fromkeys_operator_modifying_set_operand(self):
|
|
|
|
# test fix for seg fault reported in issue 27945 part 4b.
|
|
|
|
class X(int):
|
|
|
|
def __hash__(self):
|
|
|
|
return 13
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
if len(d) > 1:
|
|
|
|
d.clear()
|
|
|
|
return False
|
|
|
|
|
|
|
|
d = {} # this is required to exist so that d can be constructed!
|
|
|
|
d = {X(1), X(2)}
|
|
|
|
try:
|
|
|
|
dict.fromkeys(d) # shouldn't crash
|
|
|
|
except RuntimeError: # implementation defined
|
|
|
|
pass
|
|
|
|
|
|
|
|
def test_dictitems_contains_use_after_free(self):
|
|
|
|
class X(object):
|
|
|
|
def __eq__(self, other):
|
|
|
|
d.clear()
|
|
|
|
return NotImplemented
|
|
|
|
|
|
|
|
__hash__ = object.__hash__ # silence Py3k warning
|
|
|
|
|
|
|
|
d = {0: set()}
|
|
|
|
try:
|
|
|
|
(0, X()) in d.iteritems() # shouldn't crash
|
|
|
|
except RuntimeError: # implementation defined
|
|
|
|
pass
|
|
|
|
|
|
|
|
def test_init_use_after_free(self):
|
|
|
|
class X(object):
|
|
|
|
def __hash__(self):
|
|
|
|
pair[:] = []
|
|
|
|
return 13
|
|
|
|
|
|
|
|
pair = [X(), 123]
|
|
|
|
dict([pair])
|
|
|
|
|
|
|
|
def test_oob_indexing_dictiter_iternextitem(self):
|
|
|
|
class X(int):
|
|
|
|
def __del__(self):
|
|
|
|
d.clear()
|
|
|
|
|
|
|
|
d = {i: X(i) for i in range(8)}
|
|
|
|
|
|
|
|
def iter_and_mutate():
|
|
|
|
for result in d.iteritems():
|
|
|
|
if result[0] == 2:
|
|
|
|
d[2] = None # free d[2] --> X(2).__del__ was called
|
|
|
|
|
|
|
|
self.assertRaises(RuntimeError, iter_and_mutate)
|
|
|
|
|
|
|
|
|
2006-04-03 01:45:34 -03:00
|
|
|
from test import mapping_tests
|
2004-09-30 12:07:29 -03:00
|
|
|
|
|
|
|
class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
|
|
|
|
type2test = dict
|
|
|
|
|
|
|
|
class Dict(dict):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
|
|
|
|
type2test = Dict
|
|
|
|
|
2004-09-30 10:46:00 -03:00
|
|
|
def test_main():
|
2010-03-17 10:52:48 -03:00
|
|
|
with test_support.check_py3k_warnings(
|
|
|
|
('dict(.has_key..| inequality comparisons) not supported in 3.x',
|
|
|
|
DeprecationWarning)):
|
|
|
|
test_support.run_unittest(
|
|
|
|
DictTest,
|
|
|
|
GeneralMappingTests,
|
|
|
|
SubclassMappingTests,
|
|
|
|
)
|
2004-09-30 10:46:00 -03:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
test_main()
|