Recorded merge of revisions 78582 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/trunk

........
  r78582 | florent.xicluna | 2010-03-02 17:00:00 +0100 (mar, 02 mar 2010) | 2 lines

  Refactor test_dict using assertRaises.
........
This commit is contained in:
Florent Xicluna 2010-03-02 16:06:24 +00:00
parent 6d265699e6
commit a988e42205
1 changed files with 79 additions and 92 deletions

View File

@ -1,7 +1,7 @@
import unittest import unittest
from test import support from test import support
import sys, collections, random, string import collections, random, string
import gc, weakref import gc, weakref
@ -10,24 +10,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.ascii_letters) items = [(''.join(random.sample(string.ascii_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 = {}
@ -59,7 +59,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)
@ -198,7 +198,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([]), {})
@ -209,8 +209,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 collections.UserDict() return collections.UserDict()
@ -253,10 +253,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)
@ -266,9 +266,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)
@ -310,9 +310,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)
@ -351,15 +351,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 = {}
@ -393,12 +390,9 @@ 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_keys_contained(self): def test_keys_contained(self):
self.helper_keys_contained(lambda x: x.keys()) self.helper_keys_contained(lambda x: x.keys())
@ -452,62 +446,70 @@ class DictTest(unittest.TestCase):
class C: class C:
def __eq__(self, other): def __eq__(self, other):
raise RuntimeError raise RuntimeError
d1 = {1: C()} d1 = {1: C()}
d2 = {1: C()} d2 = {1: C()}
self.assertRaises(RuntimeError, lambda: d1.items() == d2.items()) with self.assertRaises(RuntimeError):
self.assertRaises(RuntimeError, lambda: d1.items() != d2.items()) d1.items() == d2.items()
self.assertRaises(RuntimeError, lambda: d1.items() <= d2.items()) with self.assertRaises(RuntimeError):
self.assertRaises(RuntimeError, lambda: d1.items() >= d2.items()) d1.items() != d2.items()
with self.assertRaises(RuntimeError):
d1.items() <= d2.items()
with self.assertRaises(RuntimeError):
d1.items() >= d2.items()
d3 = {1: C(), 2: C()} d3 = {1: C(), 2: C()}
self.assertRaises(RuntimeError, lambda: d2.items() < d3.items()) with self.assertRaises(RuntimeError):
self.assertRaises(RuntimeError, lambda: d3.items() > d2.items()) d2.items() < d3.items()
with self.assertRaises(RuntimeError):
d3.items() > d2.items()
def test_dictview_set_operations_on_keys(self): def test_dictview_set_operations_on_keys(self):
k1 = {1:1, 2:2}.keys() k1 = {1:1, 2:2}.keys()
k2 = {1:1, 2:2, 3:3}.keys() k2 = {1:1, 2:2, 3:3}.keys()
k3 = {4:4}.keys() k3 = {4:4}.keys()
self.assertEquals(k1 - k2, set()) self.assertEqual(k1 - k2, set())
self.assertEquals(k1 - k3, {1,2}) self.assertEqual(k1 - k3, {1,2})
self.assertEquals(k2 - k1, {3}) self.assertEqual(k2 - k1, {3})
self.assertEquals(k3 - k1, {4}) self.assertEqual(k3 - k1, {4})
self.assertEquals(k1 & k2, {1,2}) self.assertEqual(k1 & k2, {1,2})
self.assertEquals(k1 & k3, set()) self.assertEqual(k1 & k3, set())
self.assertEquals(k1 | k2, {1,2,3}) self.assertEqual(k1 | k2, {1,2,3})
self.assertEquals(k1 ^ k2, {3}) self.assertEqual(k1 ^ k2, {3})
self.assertEquals(k1 ^ k3, {1,2,4}) self.assertEqual(k1 ^ k3, {1,2,4})
def test_dictview_set_operations_on_items(self): def test_dictview_set_operations_on_items(self):
k1 = {1:1, 2:2}.items() k1 = {1:1, 2:2}.items()
k2 = {1:1, 2:2, 3:3}.items() k2 = {1:1, 2:2, 3:3}.items()
k3 = {4:4}.items() k3 = {4:4}.items()
self.assertEquals(k1 - k2, set()) self.assertEqual(k1 - k2, set())
self.assertEquals(k1 - k3, {(1,1), (2,2)}) self.assertEqual(k1 - k3, {(1,1), (2,2)})
self.assertEquals(k2 - k1, {(3,3)}) self.assertEqual(k2 - k1, {(3,3)})
self.assertEquals(k3 - k1, {(4,4)}) self.assertEqual(k3 - k1, {(4,4)})
self.assertEquals(k1 & k2, {(1,1), (2,2)}) self.assertEqual(k1 & k2, {(1,1), (2,2)})
self.assertEquals(k1 & k3, set()) self.assertEqual(k1 & k3, set())
self.assertEquals(k1 | k2, {(1,1), (2,2), (3,3)}) self.assertEqual(k1 | k2, {(1,1), (2,2), (3,3)})
self.assertEquals(k1 ^ k2, {(3,3)}) self.assertEqual(k1 ^ k2, {(3,3)})
self.assertEquals(k1 ^ k3, {(1,1), (2,2), (4,4)}) self.assertEqual(k1 ^ k3, {(1,1), (2,2), (4,4)})
def test_dictview_mixed_set_operations(self): def test_dictview_mixed_set_operations(self):
# Just a few for .keys() # Just a few for .keys()
self.assertTrue({1:1}.keys() == {1}) self.assertTrue({1:1}.keys() == {1})
self.assertTrue({1} == {1:1}.keys()) self.assertTrue({1} == {1:1}.keys())
self.assertEquals({1:1}.keys() | {2}, {1, 2}) self.assertEqual({1:1}.keys() | {2}, {1, 2})
self.assertEquals({2} | {1:1}.keys(), {1, 2}) self.assertEqual({2} | {1:1}.keys(), {1, 2})
# And a few for .items() # And a few for .items()
self.assertTrue({1:1}.items() == {(1,1)}) self.assertTrue({1:1}.items() == {(1,1)})
self.assertTrue({(1,1)} == {1:1}.items()) self.assertTrue({(1,1)} == {1:1}.items())
self.assertEquals({1:1}.items() | {2}, {(1,1), 2}) self.assertEqual({1:1}.items() | {2}, {(1,1), 2})
self.assertEquals({2} | {1:1}.items(), {(1,1), 2}) self.assertEqual({2} | {1:1}.items(), {(1,1), 2})
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
@ -522,46 +524,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 as 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 as 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 as 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 as 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 __eq__() raises an exception. # Dictionary lookups should fail if __eq__() raises an exception.
@ -588,12 +581,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, locals()) exec(stmt, locals())
except CustomException:
pass
else:
self.fail("Statement %r didn't raise exception" % stmt)
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.
@ -636,11 +625,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):
@ -657,7 +644,7 @@ class DictTest(unittest.TestCase):
obj.x = iter(obj.v) obj.x = iter(obj.v)
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