Issue 2235: __hash__ is once again inherited by default, but inheritance can be blocked explicitly so that collections.Hashable remains meaningful
diff --git a/Lib/test/test_hash.py b/Lib/test/test_hash.py
index 07b65da..f3954c2 100644
--- a/Lib/test/test_hash.py
+++ b/Lib/test/test_hash.py
@@ -1,9 +1,11 @@
# test the invariant that
# iff a==b then hash(a)==hash(b)
#
+# Also test that hash implementations are inherited as expected
import unittest
from test import test_support
+from collections import Hashable
class HashEqualityTestCase(unittest.TestCase):
@@ -39,8 +41,83 @@
self.same_hash(float(0.5), complex(0.5, 0.0))
+_default_hash = object.__hash__
+class DefaultHash(object): pass
+
+_FIXED_HASH_VALUE = 42
+class FixedHash(object):
+ def __hash__(self):
+ return _FIXED_HASH_VALUE
+
+class OnlyEquality(object):
+ def __eq__(self, other):
+ return self is other
+
+class OnlyInequality(object):
+ def __ne__(self, other):
+ return self is not other
+
+class OnlyCmp(object):
+ def __cmp__(self, other):
+ return cmp(id(self), id(other))
+
+class InheritedHashWithEquality(FixedHash, OnlyEquality): pass
+class InheritedHashWithInequality(FixedHash, OnlyInequality): pass
+class InheritedHashWithCmp(FixedHash, OnlyCmp): pass
+
+class NoHash(object):
+ __hash__ = None
+
+class HashInheritanceTestCase(unittest.TestCase):
+ default_expected = [object(),
+ DefaultHash(),
+ ]
+ fixed_expected = [FixedHash(),
+ InheritedHashWithEquality(),
+ InheritedHashWithInequality(),
+ InheritedHashWithCmp(),
+ ]
+ # TODO: Change these to expecting an exception
+ # when forward porting to Py3k
+ warning_expected = [OnlyEquality(),
+ OnlyInequality(),
+ OnlyCmp(),
+ ]
+ error_expected = [NoHash()]
+
+ def test_default_hash(self):
+ for obj in self.default_expected:
+ self.assertEqual(hash(obj), _default_hash(obj))
+
+ def test_fixed_hash(self):
+ for obj in self.fixed_expected:
+ self.assertEqual(hash(obj), _FIXED_HASH_VALUE)
+
+ def test_warning_hash(self):
+ for obj in self.warning_expected:
+ # TODO: Check for the expected Py3k warning here
+ obj_hash = hash(obj)
+ self.assertEqual(obj_hash, _default_hash(obj))
+
+ def test_error_hash(self):
+ for obj in self.error_expected:
+ self.assertRaises(TypeError, hash, obj)
+
+ def test_hashable(self):
+ objects = (self.default_expected +
+ self.fixed_expected +
+ self.warning_expected)
+ for obj in objects:
+ self.assert_(isinstance(obj, Hashable), repr(obj))
+
+ def test_not_hashable(self):
+ for obj in self.error_expected:
+ self.assertFalse(isinstance(obj, Hashable), repr(obj))
+
+
def test_main():
- test_support.run_unittest(HashEqualityTestCase)
+ test_support.run_unittest(HashEqualityTestCase,
+ HashInheritanceTestCase)
if __name__ == "__main__":