blob: 94306ec4a1214d93fc5ed3f8130b1e52318bb47b [file] [log] [blame]
Fred Drake13634cf2000-06-29 19:17:04 +00001# test the invariant that
2# iff a==b then hash(a)==hash(b)
3#
Nick Coghlan53663a62008-07-15 14:27:37 +00004# Also test that hash implementations are inherited as expected
Fred Drake13634cf2000-06-29 19:17:04 +00005
Barry Warsaw1e13eb02012-02-20 20:42:21 -05006import os
7import sys
8import struct
9import datetime
Fred Drake97656a12001-05-18 21:45:35 +000010import unittest
Barry Warsaw1e13eb02012-02-20 20:42:21 -050011import subprocess
12
Barry Warsaw04f357c2002-07-23 19:04:11 +000013from test import test_support
Nick Coghlan53663a62008-07-15 14:27:37 +000014from collections import Hashable
Fred Drake13634cf2000-06-29 19:17:04 +000015
Barry Warsaw1e13eb02012-02-20 20:42:21 -050016IS_64BIT = (struct.calcsize('l') == 8)
17
Fred Drake13634cf2000-06-29 19:17:04 +000018
Fred Drake97656a12001-05-18 21:45:35 +000019class HashEqualityTestCase(unittest.TestCase):
20
21 def same_hash(self, *objlist):
Fred Drakeacb117e2001-05-18 21:50:02 +000022 # Hash each object given and fail if
23 # the hash values are not all the same.
Fred Drake97656a12001-05-18 21:45:35 +000024 hashed = map(hash, objlist)
25 for h in hashed[1:]:
26 if h != hashed[0]:
Walter Dörwald70a6b492004-02-12 17:35:32 +000027 self.fail("hashed values differ: %r" % (objlist,))
Fred Drake97656a12001-05-18 21:45:35 +000028
29 def test_numeric_literals(self):
30 self.same_hash(1, 1L, 1.0, 1.0+0.0j)
Facundo Batistad544df72007-09-19 15:10:06 +000031 self.same_hash(0, 0L, 0.0, 0.0+0.0j)
32 self.same_hash(-1, -1L, -1.0, -1.0+0.0j)
33 self.same_hash(-2, -2L, -2.0, -2.0+0.0j)
Fred Drake97656a12001-05-18 21:45:35 +000034
35 def test_coerced_integers(self):
36 self.same_hash(int(1), long(1), float(1), complex(1),
37 int('1'), float('1.0'))
Facundo Batistad544df72007-09-19 15:10:06 +000038 self.same_hash(int(-2**31), long(-2**31), float(-2**31))
39 self.same_hash(int(1-2**31), long(1-2**31), float(1-2**31))
40 self.same_hash(int(2**31-1), long(2**31-1), float(2**31-1))
41 # for 64-bit platforms
42 self.same_hash(int(2**31), long(2**31), float(2**31))
43 self.same_hash(int(-2**63), long(-2**63), float(-2**63))
44 self.same_hash(int(1-2**63), long(1-2**63))
45 self.same_hash(int(2**63-1), long(2**63-1))
Fred Drake97656a12001-05-18 21:45:35 +000046
47 def test_coerced_floats(self):
48 self.same_hash(long(1.23e300), float(1.23e300))
49 self.same_hash(float(0.5), complex(0.5, 0.0))
Fred Drake13634cf2000-06-29 19:17:04 +000050
51
Nick Coghlan53663a62008-07-15 14:27:37 +000052_default_hash = object.__hash__
53class DefaultHash(object): pass
54
55_FIXED_HASH_VALUE = 42
56class FixedHash(object):
57 def __hash__(self):
58 return _FIXED_HASH_VALUE
59
60class OnlyEquality(object):
61 def __eq__(self, other):
62 return self is other
Nick Coghlan48361f52008-08-11 15:45:58 +000063 # Trick to suppress Py3k warning in 2.x
64 __hash__ = None
65del OnlyEquality.__hash__
Nick Coghlan53663a62008-07-15 14:27:37 +000066
67class OnlyInequality(object):
68 def __ne__(self, other):
69 return self is not other
70
71class OnlyCmp(object):
72 def __cmp__(self, other):
73 return cmp(id(self), id(other))
Nick Coghlan48361f52008-08-11 15:45:58 +000074 # Trick to suppress Py3k warning in 2.x
75 __hash__ = None
76del OnlyCmp.__hash__
Nick Coghlan53663a62008-07-15 14:27:37 +000077
78class InheritedHashWithEquality(FixedHash, OnlyEquality): pass
79class InheritedHashWithInequality(FixedHash, OnlyInequality): pass
80class InheritedHashWithCmp(FixedHash, OnlyCmp): pass
81
82class NoHash(object):
83 __hash__ = None
84
85class HashInheritanceTestCase(unittest.TestCase):
86 default_expected = [object(),
87 DefaultHash(),
Nick Coghlan48361f52008-08-11 15:45:58 +000088 OnlyEquality(),
89 OnlyInequality(),
90 OnlyCmp(),
Nick Coghlan53663a62008-07-15 14:27:37 +000091 ]
92 fixed_expected = [FixedHash(),
93 InheritedHashWithEquality(),
94 InheritedHashWithInequality(),
95 InheritedHashWithCmp(),
96 ]
Nick Coghlan53663a62008-07-15 14:27:37 +000097 error_expected = [NoHash()]
98
99 def test_default_hash(self):
100 for obj in self.default_expected:
101 self.assertEqual(hash(obj), _default_hash(obj))
102
103 def test_fixed_hash(self):
104 for obj in self.fixed_expected:
105 self.assertEqual(hash(obj), _FIXED_HASH_VALUE)
106
Nick Coghlan53663a62008-07-15 14:27:37 +0000107 def test_error_hash(self):
108 for obj in self.error_expected:
109 self.assertRaises(TypeError, hash, obj)
110
111 def test_hashable(self):
112 objects = (self.default_expected +
Nick Coghlan48361f52008-08-11 15:45:58 +0000113 self.fixed_expected)
Nick Coghlan53663a62008-07-15 14:27:37 +0000114 for obj in objects:
115 self.assert_(isinstance(obj, Hashable), repr(obj))
116
117 def test_not_hashable(self):
118 for obj in self.error_expected:
119 self.assertFalse(isinstance(obj, Hashable), repr(obj))
120
121
Nick Coghland4656402008-12-30 01:36:00 +0000122# Issue #4701: Check that some builtin types are correctly hashable
123# (This test only used to fail in Python 3.0, but has been included
124# in 2.x along with the lazy call to PyType_Ready in PyObject_Hash)
125class DefaultIterSeq(object):
126 seq = range(10)
127 def __len__(self):
128 return len(self.seq)
129 def __getitem__(self, index):
130 return self.seq[index]
131
132class HashBuiltinsTestCase(unittest.TestCase):
133 hashes_to_check = [xrange(10),
134 enumerate(xrange(10)),
135 iter(DefaultIterSeq()),
136 iter(lambda: 0, 0),
137 ]
138
139 def test_hashes(self):
140 _default_hash = object.__hash__
141 for obj in self.hashes_to_check:
142 self.assertEqual(hash(obj), _default_hash(obj))
143
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500144class HashRandomizationTests(unittest.TestCase):
145
146 # Each subclass should define a field "repr_", containing the repr() of
147 # an object to be tested
148
149 def get_hash_command(self, repr_):
150 return 'print(hash(%s))' % repr_
151
152 def get_hash(self, repr_, seed=None):
153 env = os.environ.copy()
154 if seed is not None:
155 env['PYTHONHASHSEED'] = str(seed)
156 else:
157 env.pop('PYTHONHASHSEED', None)
158 cmd_line = [sys.executable, '-c', self.get_hash_command(repr_)]
159 p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
160 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
161 env=env)
162 out, err = p.communicate()
163 out = test_support.strip_python_stderr(out)
164 return int(out.strip())
165
166 def test_randomized_hash(self):
167 # two runs should return different hashes
168 run1 = self.get_hash(self.repr_, seed='random')
169 run2 = self.get_hash(self.repr_, seed='random')
170 self.assertNotEqual(run1, run2)
171
172class StringlikeHashRandomizationTests(HashRandomizationTests):
173 def test_null_hash(self):
174 # PYTHONHASHSEED=0 disables the randomized hash
175 if IS_64BIT:
176 known_hash_of_obj = 1453079729188098211
177 else:
178 known_hash_of_obj = -1600925533
179
180 # Randomization is disabled by default:
181 self.assertEqual(self.get_hash(self.repr_), known_hash_of_obj)
182
183 # It can also be disabled by setting the seed to 0:
184 self.assertEqual(self.get_hash(self.repr_, seed=0), known_hash_of_obj)
185
186 def test_fixed_hash(self):
187 # test a fixed seed for the randomized hash
188 # Note that all types share the same values:
189 if IS_64BIT:
190 h = -4410911502303878509
191 else:
192 h = -206076799
193 self.assertEqual(self.get_hash(self.repr_, seed=42), h)
194
195class StrHashRandomizationTests(StringlikeHashRandomizationTests):
196 repr_ = repr('abc')
197
198 def test_empty_string(self):
199 self.assertEqual(hash(""), 0)
200
201class UnicodeHashRandomizationTests(StringlikeHashRandomizationTests):
202 repr_ = repr(u'abc')
203
204 def test_empty_string(self):
205 self.assertEqual(hash(u""), 0)
206
207class BufferHashRandomizationTests(StringlikeHashRandomizationTests):
208 repr_ = 'buffer("abc")'
209
210 def test_empty_string(self):
211 self.assertEqual(hash(buffer("")), 0)
212
213class DatetimeTests(HashRandomizationTests):
214 def get_hash_command(self, repr_):
215 return 'import datetime; print(hash(%s))' % repr_
216
217class DatetimeDateTests(DatetimeTests):
218 repr_ = repr(datetime.date(1066, 10, 14))
219
220class DatetimeDatetimeTests(DatetimeTests):
221 repr_ = repr(datetime.datetime(1, 2, 3, 4, 5, 6, 7))
222
223class DatetimeTimeTests(DatetimeTests):
224 repr_ = repr(datetime.time(0))
225
226
Fred Drake2e2be372001-09-20 21:33:42 +0000227def test_main():
Nick Coghlan53663a62008-07-15 14:27:37 +0000228 test_support.run_unittest(HashEqualityTestCase,
Nick Coghland4656402008-12-30 01:36:00 +0000229 HashInheritanceTestCase,
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500230 HashBuiltinsTestCase,
231 StrHashRandomizationTests,
232 UnicodeHashRandomizationTests,
233 BufferHashRandomizationTests,
234 DatetimeDateTests,
235 DatetimeDatetimeTests,
236 DatetimeTimeTests)
Barry Warsawb19fb242012-02-20 20:44:15 -0500237
Fred Drake2e2be372001-09-20 21:33:42 +0000238
239
240if __name__ == "__main__":
241 test_main()