1
1
# test the invariant that
2
2
# iff a==b then hash(a)==hash(b)
4
# Also test that hash implementations are inherited as expected
6
7
from test import test_support
8
from collections import Hashable
9
11
class HashEqualityTestCase(unittest.TestCase):
39
41
self.same_hash(float(0.5), complex(0.5, 0.0))
44
_default_hash = object.__hash__
45
class DefaultHash(object): pass
47
_FIXED_HASH_VALUE = 42
48
class FixedHash(object):
50
return _FIXED_HASH_VALUE
52
class OnlyEquality(object):
53
def __eq__(self, other):
55
# Trick to suppress Py3k warning in 2.x
57
del OnlyEquality.__hash__
59
class OnlyInequality(object):
60
def __ne__(self, other):
61
return self is not other
63
class OnlyCmp(object):
64
def __cmp__(self, other):
65
return cmp(id(self), id(other))
66
# Trick to suppress Py3k warning in 2.x
70
class InheritedHashWithEquality(FixedHash, OnlyEquality): pass
71
class InheritedHashWithInequality(FixedHash, OnlyInequality): pass
72
class InheritedHashWithCmp(FixedHash, OnlyCmp): pass
77
class HashInheritanceTestCase(unittest.TestCase):
78
default_expected = [object(),
84
fixed_expected = [FixedHash(),
85
InheritedHashWithEquality(),
86
InheritedHashWithInequality(),
87
InheritedHashWithCmp(),
89
error_expected = [NoHash()]
91
def test_default_hash(self):
92
for obj in self.default_expected:
93
self.assertEqual(hash(obj), _default_hash(obj))
95
def test_fixed_hash(self):
96
for obj in self.fixed_expected:
97
self.assertEqual(hash(obj), _FIXED_HASH_VALUE)
99
def test_error_hash(self):
100
for obj in self.error_expected:
101
self.assertRaises(TypeError, hash, obj)
103
def test_hashable(self):
104
objects = (self.default_expected +
107
self.assert_(isinstance(obj, Hashable), repr(obj))
109
def test_not_hashable(self):
110
for obj in self.error_expected:
111
self.assertFalse(isinstance(obj, Hashable), repr(obj))
43
test_support.run_unittest(HashEqualityTestCase)
115
test_support.run_unittest(HashEqualityTestCase,
116
HashInheritanceTestCase)
46
119
if __name__ == "__main__":