mirror of https://github.com/python/cpython
Refactor test_dict using assertRaises.
This commit is contained in:
parent
abe6331cca
commit
d8472a4545
|
@ -9,24 +9,24 @@ class DictTest(unittest.TestCase):
|
||||||
def test_constructor(self):
|
def test_constructor(self):
|
||||||
# calling built-in types without argument must return empty
|
# calling built-in types without argument must return empty
|
||||||
self.assertEqual(dict(), {})
|
self.assertEqual(dict(), {})
|
||||||
self.assertTrue(dict() is not {})
|
self.assertIsNot(dict(), {})
|
||||||
|
|
||||||
def test_literal_constructor(self):
|
def test_literal_constructor(self):
|
||||||
# check literal constructor for different sized dicts (to exercise the BUILD_MAP oparg
|
# check literal constructor for different sized dicts
|
||||||
|
# (to exercise the BUILD_MAP oparg).
|
||||||
for n in (0, 1, 6, 256, 400):
|
for n in (0, 1, 6, 256, 400):
|
||||||
items = [(''.join([random.choice(string.letters)
|
items = [(''.join(random.sample(string.letters, 8)), i)
|
||||||
for j in range(8)]),
|
|
||||||
i)
|
|
||||||
for i in range(n)]
|
for i in range(n)]
|
||||||
random.shuffle(items)
|
random.shuffle(items)
|
||||||
dictliteral = '{' + ', '.join('%r: %d' % item for item in items) + '}'
|
formatted_items = ('{!r}: {:d}'.format(k, v) for k, v in items)
|
||||||
|
dictliteral = '{' + ', '.join(formatted_items) + '}'
|
||||||
self.assertEqual(eval(dictliteral), dict(items))
|
self.assertEqual(eval(dictliteral), dict(items))
|
||||||
|
|
||||||
def test_bool(self):
|
def test_bool(self):
|
||||||
self.assertTrue(not {})
|
self.assertIs(not {}, True)
|
||||||
self.assertTrue({1: 2})
|
self.assertTrue({1: 2})
|
||||||
self.assertTrue(bool({}) is False)
|
self.assertIs(bool({}), False)
|
||||||
self.assertTrue(bool({1: 2}) is True)
|
self.assertIs(bool({1: 2}), True)
|
||||||
|
|
||||||
def test_keys(self):
|
def test_keys(self):
|
||||||
d = {}
|
d = {}
|
||||||
|
@ -57,7 +57,7 @@ class DictTest(unittest.TestCase):
|
||||||
|
|
||||||
def test_has_key(self):
|
def test_has_key(self):
|
||||||
d = {}
|
d = {}
|
||||||
self.assertTrue(not d.has_key('a'))
|
self.assertFalse(d.has_key('a'))
|
||||||
d = {'a': 1, 'b': 2}
|
d = {'a': 1, 'b': 2}
|
||||||
k = d.keys()
|
k = d.keys()
|
||||||
k.sort()
|
k.sort()
|
||||||
|
@ -68,7 +68,7 @@ class DictTest(unittest.TestCase):
|
||||||
def test_contains(self):
|
def test_contains(self):
|
||||||
d = {}
|
d = {}
|
||||||
self.assertNotIn('a', d)
|
self.assertNotIn('a', d)
|
||||||
self.assertTrue(not ('a' in d))
|
self.assertFalse('a' in d)
|
||||||
self.assertTrue('a' not in d)
|
self.assertTrue('a' not in d)
|
||||||
d = {'a': 1, 'b': 2}
|
d = {'a': 1, 'b': 2}
|
||||||
self.assertIn('a', d)
|
self.assertIn('a', d)
|
||||||
|
@ -207,7 +207,7 @@ class DictTest(unittest.TestCase):
|
||||||
def test_fromkeys(self):
|
def test_fromkeys(self):
|
||||||
self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
|
self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
|
||||||
d = {}
|
d = {}
|
||||||
self.assertTrue(not(d.fromkeys('abc') is d))
|
self.assertIsNot(d.fromkeys('abc'), d)
|
||||||
self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
|
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((4,5),0), {4:0, 5:0})
|
||||||
self.assertEqual(d.fromkeys([]), {})
|
self.assertEqual(d.fromkeys([]), {})
|
||||||
|
@ -218,8 +218,8 @@ class DictTest(unittest.TestCase):
|
||||||
class dictlike(dict): pass
|
class dictlike(dict): pass
|
||||||
self.assertEqual(dictlike.fromkeys('a'), {'a':None})
|
self.assertEqual(dictlike.fromkeys('a'), {'a':None})
|
||||||
self.assertEqual(dictlike().fromkeys('a'), {'a':None})
|
self.assertEqual(dictlike().fromkeys('a'), {'a':None})
|
||||||
self.assertTrue(type(dictlike.fromkeys('a')) is dictlike)
|
self.assertIsInstance(dictlike.fromkeys('a'), dictlike)
|
||||||
self.assertTrue(type(dictlike().fromkeys('a')) is dictlike)
|
self.assertIsInstance(dictlike().fromkeys('a'), dictlike)
|
||||||
class mydict(dict):
|
class mydict(dict):
|
||||||
def __new__(cls):
|
def __new__(cls):
|
||||||
return UserDict.UserDict()
|
return UserDict.UserDict()
|
||||||
|
@ -262,10 +262,10 @@ class DictTest(unittest.TestCase):
|
||||||
|
|
||||||
def test_get(self):
|
def test_get(self):
|
||||||
d = {}
|
d = {}
|
||||||
self.assertTrue(d.get('c') is None)
|
self.assertIs(d.get('c'), None)
|
||||||
self.assertEqual(d.get('c', 3), 3)
|
self.assertEqual(d.get('c', 3), 3)
|
||||||
d = {'a': 1, 'b': 2}
|
d = {'a': 1, 'b': 2}
|
||||||
self.assertTrue(d.get('c') is None)
|
self.assertIs(d.get('c'), None)
|
||||||
self.assertEqual(d.get('c', 3), 3)
|
self.assertEqual(d.get('c', 3), 3)
|
||||||
self.assertEqual(d.get('a'), 1)
|
self.assertEqual(d.get('a'), 1)
|
||||||
self.assertEqual(d.get('a', 3), 1)
|
self.assertEqual(d.get('a', 3), 1)
|
||||||
|
@ -275,9 +275,9 @@ class DictTest(unittest.TestCase):
|
||||||
def test_setdefault(self):
|
def test_setdefault(self):
|
||||||
# dict.setdefault()
|
# dict.setdefault()
|
||||||
d = {}
|
d = {}
|
||||||
self.assertTrue(d.setdefault('key0') is None)
|
self.assertIs(d.setdefault('key0'), None)
|
||||||
d.setdefault('key0', [])
|
d.setdefault('key0', [])
|
||||||
self.assertTrue(d.setdefault('key0') is None)
|
self.assertIs(d.setdefault('key0'), None)
|
||||||
d.setdefault('key', []).append(3)
|
d.setdefault('key', []).append(3)
|
||||||
self.assertEqual(d['key'][0], 3)
|
self.assertEqual(d['key'][0], 3)
|
||||||
d.setdefault('key', []).append(4)
|
d.setdefault('key', []).append(4)
|
||||||
|
@ -319,9 +319,9 @@ class DictTest(unittest.TestCase):
|
||||||
self.assertEqual(va, int(ka))
|
self.assertEqual(va, int(ka))
|
||||||
kb, vb = tb = b.popitem()
|
kb, vb = tb = b.popitem()
|
||||||
self.assertEqual(vb, int(kb))
|
self.assertEqual(vb, int(kb))
|
||||||
self.assertTrue(not(copymode < 0 and ta != tb))
|
self.assertFalse(copymode < 0 and ta != tb)
|
||||||
self.assertTrue(not a)
|
self.assertFalse(a)
|
||||||
self.assertTrue(not b)
|
self.assertFalse(b)
|
||||||
|
|
||||||
d = {}
|
d = {}
|
||||||
self.assertRaises(KeyError, d.popitem)
|
self.assertRaises(KeyError, d.popitem)
|
||||||
|
@ -338,8 +338,8 @@ class DictTest(unittest.TestCase):
|
||||||
|
|
||||||
self.assertRaises(KeyError, d.pop, k)
|
self.assertRaises(KeyError, d.pop, k)
|
||||||
|
|
||||||
# verify longs/ints get same value when key > 32 bits (for 64-bit archs)
|
# verify longs/ints get same value when key > 32 bits
|
||||||
# see SF bug #689659
|
# (for 64-bit archs). See SF bug #689659.
|
||||||
x = 4503599627370496L
|
x = 4503599627370496L
|
||||||
y = 4503599627370496
|
y = 4503599627370496
|
||||||
h = {x: 'anything', y: 'something else'}
|
h = {x: 'anything', y: 'something else'}
|
||||||
|
@ -367,15 +367,12 @@ class DictTest(unittest.TestCase):
|
||||||
self.assertRaises(Exc, d.pop, x)
|
self.assertRaises(Exc, d.pop, x)
|
||||||
|
|
||||||
def test_mutatingiteration(self):
|
def test_mutatingiteration(self):
|
||||||
|
# changing dict size during iteration
|
||||||
d = {}
|
d = {}
|
||||||
d[1] = 1
|
d[1] = 1
|
||||||
try:
|
with self.assertRaises(RuntimeError):
|
||||||
for i in d:
|
for i in d:
|
||||||
d[i+1] = 1
|
d[i+1] = 1
|
||||||
except RuntimeError:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
self.fail("changing dict size during iteration doesn't raise Error")
|
|
||||||
|
|
||||||
def test_repr(self):
|
def test_repr(self):
|
||||||
d = {}
|
d = {}
|
||||||
|
@ -396,8 +393,8 @@ class DictTest(unittest.TestCase):
|
||||||
self.assertRaises(Exc, repr, d)
|
self.assertRaises(Exc, repr, d)
|
||||||
|
|
||||||
def test_le(self):
|
def test_le(self):
|
||||||
self.assertTrue(not ({} < {}))
|
self.assertFalse({} < {})
|
||||||
self.assertTrue(not ({1: 2} < {1L: 2L}))
|
self.assertFalse({1: 2} < {1L: 2L})
|
||||||
|
|
||||||
class Exc(Exception): pass
|
class Exc(Exception): pass
|
||||||
|
|
||||||
|
@ -409,17 +406,14 @@ class DictTest(unittest.TestCase):
|
||||||
|
|
||||||
d1 = {BadCmp(): 1}
|
d1 = {BadCmp(): 1}
|
||||||
d2 = {1: 1}
|
d2 = {1: 1}
|
||||||
try:
|
|
||||||
|
with self.assertRaises(Exc):
|
||||||
d1 < d2
|
d1 < d2
|
||||||
except Exc:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
self.fail("< didn't raise Exc")
|
|
||||||
|
|
||||||
def test_missing(self):
|
def test_missing(self):
|
||||||
# Make sure dict doesn't have a __missing__ method
|
# Make sure dict doesn't have a __missing__ method
|
||||||
self.assertEqual(hasattr(dict, "__missing__"), False)
|
self.assertFalse(hasattr(dict, "__missing__"))
|
||||||
self.assertEqual(hasattr({}, "__missing__"), False)
|
self.assertFalse(hasattr({}, "__missing__"))
|
||||||
# Test several cases:
|
# Test several cases:
|
||||||
# (D) subclass defines __missing__ method returning a value
|
# (D) subclass defines __missing__ method returning a value
|
||||||
# (E) subclass defines __missing__ method raising RuntimeError
|
# (E) subclass defines __missing__ method raising RuntimeError
|
||||||
|
@ -434,46 +428,37 @@ class DictTest(unittest.TestCase):
|
||||||
self.assertNotIn(2, d)
|
self.assertNotIn(2, d)
|
||||||
self.assertNotIn(2, d.keys())
|
self.assertNotIn(2, d.keys())
|
||||||
self.assertEqual(d[2], 42)
|
self.assertEqual(d[2], 42)
|
||||||
|
|
||||||
class E(dict):
|
class E(dict):
|
||||||
def __missing__(self, key):
|
def __missing__(self, key):
|
||||||
raise RuntimeError(key)
|
raise RuntimeError(key)
|
||||||
e = E()
|
e = E()
|
||||||
try:
|
with self.assertRaises(RuntimeError) as c:
|
||||||
e[42]
|
e[42]
|
||||||
except RuntimeError, err:
|
self.assertEqual(c.exception.args, (42,))
|
||||||
self.assertEqual(err.args, (42,))
|
|
||||||
else:
|
|
||||||
self.fail("e[42] didn't raise RuntimeError")
|
|
||||||
class F(dict):
|
class F(dict):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
# An instance variable __missing__ should have no effect
|
# An instance variable __missing__ should have no effect
|
||||||
self.__missing__ = lambda key: None
|
self.__missing__ = lambda key: None
|
||||||
f = F()
|
f = F()
|
||||||
try:
|
with self.assertRaises(KeyError) as c:
|
||||||
f[42]
|
f[42]
|
||||||
except KeyError, err:
|
self.assertEqual(c.exception.args, (42,))
|
||||||
self.assertEqual(err.args, (42,))
|
|
||||||
else:
|
|
||||||
self.fail("f[42] didn't raise KeyError")
|
|
||||||
class G(dict):
|
class G(dict):
|
||||||
pass
|
pass
|
||||||
g = G()
|
g = G()
|
||||||
try:
|
with self.assertRaises(KeyError) as c:
|
||||||
g[42]
|
g[42]
|
||||||
except KeyError, err:
|
self.assertEqual(c.exception.args, (42,))
|
||||||
self.assertEqual(err.args, (42,))
|
|
||||||
else:
|
|
||||||
self.fail("g[42] didn't raise KeyError")
|
|
||||||
|
|
||||||
def test_tuple_keyerror(self):
|
def test_tuple_keyerror(self):
|
||||||
# SF #1576657
|
# SF #1576657
|
||||||
d = {}
|
d = {}
|
||||||
try:
|
with self.assertRaises(KeyError) as c:
|
||||||
d[(1,)]
|
d[(1,)]
|
||||||
except KeyError, e:
|
self.assertEqual(c.exception.args, ((1,),))
|
||||||
self.assertEqual(e.args, ((1,),))
|
|
||||||
else:
|
|
||||||
self.fail("missing KeyError")
|
|
||||||
|
|
||||||
def test_bad_key(self):
|
def test_bad_key(self):
|
||||||
# Dictionary lookups should fail if __cmp__() raises an exception.
|
# Dictionary lookups should fail if __cmp__() raises an exception.
|
||||||
|
@ -501,12 +486,8 @@ class DictTest(unittest.TestCase):
|
||||||
'd.setdefault(x2, 42)',
|
'd.setdefault(x2, 42)',
|
||||||
'd.pop(x2)',
|
'd.pop(x2)',
|
||||||
'd.update({x2: 2})']:
|
'd.update({x2: 2})']:
|
||||||
try:
|
with self.assertRaises(CustomException):
|
||||||
exec stmt in locals()
|
exec stmt in locals()
|
||||||
except CustomException:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
self.fail("Statement didn't raise exception")
|
|
||||||
|
|
||||||
def test_resize1(self):
|
def test_resize1(self):
|
||||||
# Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
|
# Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
|
||||||
|
@ -549,11 +530,9 @@ class DictTest(unittest.TestCase):
|
||||||
def test_empty_presized_dict_in_freelist(self):
|
def test_empty_presized_dict_in_freelist(self):
|
||||||
# Bug #3537: if an empty but presized dict with a size larger
|
# Bug #3537: if an empty but presized dict with a size larger
|
||||||
# than 7 was in the freelist, it triggered an assertion failure
|
# than 7 was in the freelist, it triggered an assertion failure
|
||||||
try:
|
with self.assertRaises(ZeroDivisionError):
|
||||||
d = {'a': 1/0, 'b': None, 'c': None, 'd': None, 'e': None,
|
d = {'a': 1 // 0, 'b': None, 'c': None, 'd': None, 'e': None,
|
||||||
'f': None, 'g': None, 'h': None}
|
'f': None, 'g': None, 'h': None}
|
||||||
except ZeroDivisionError:
|
|
||||||
pass
|
|
||||||
d = {}
|
d = {}
|
||||||
|
|
||||||
def test_container_iterator(self):
|
def test_container_iterator(self):
|
||||||
|
@ -568,7 +547,7 @@ class DictTest(unittest.TestCase):
|
||||||
obj.x = i(container)
|
obj.x = i(container)
|
||||||
del obj, container
|
del obj, container
|
||||||
gc.collect()
|
gc.collect()
|
||||||
self.assertTrue(ref() is None, "Cycle was not collected")
|
self.assertIs(ref(), None, "Cycle was not collected")
|
||||||
|
|
||||||
def _not_tracked(self, t):
|
def _not_tracked(self, t):
|
||||||
# Nested containers can take several collections to untrack
|
# Nested containers can take several collections to untrack
|
||||||
|
|
Loading…
Reference in New Issue