Debian Codegraph @

lib-python/3/test/test_hash.py

raw symbols SCIP
1 # test the invariant that
2 # iff a==b then hash(a)==hash(b)
3 #
4 # Also test that hash implementations are inherited as expected
5
6 import datetime
7 import os
8 import sys
9 import unittest
10 from test.support.script_helper import assert_python_ok
11 from test.support import impl_detail, check_impl_detail
12 from collections.abc import Hashable
13
14 IS_64BIT = sys.maxsize > 2**32
15
16 def lcg(x, length=16):
17 """Linear congruential generator"""
18 if x == 0:
19 return bytes(length)
20 out = bytearray(length)
21 for i in range(length):
22 x = (214013 * x + 2531011) & 0x7fffffff
23 out[i] = (x >> 16) & 0xff
24 return bytes(out)
25
26 def pysiphash(uint64):
27 """Convert SipHash24 output to Py_hash_t
28 """
29 assert 0 <= uint64 < (1 << 64)
30 # simple unsigned to signed int64
31 if uint64 > (1 << 63) - 1:
32 int64 = uint64 - (1 << 64)
33 else:
34 int64 = uint64
35 # mangle uint64 to uint32
36 uint32 = (uint64 ^ uint64 >> 32) & 0xffffffff
37 # simple unsigned to signed int32
38 if uint32 > (1 << 31) - 1:
39 int32 = uint32 - (1 << 32)
40 else:
41 int32 = uint32
42 return int32, int64
43
44 def skip_unless_internalhash(test):
45 """Skip decorator for tests that depend on SipHash24 or FNV"""
46 ok = sys.hash_info.algorithm in {"fnv", "siphash13", "siphash24"}
47 msg = "Requires SipHash13, SipHash24 or FNV"
48 return test if ok else unittest.skip(msg)(test)
49
50
51 class HashEqualityTestCase(unittest.TestCase):
52
53 def same_hash(self, *objlist):
54 # Hash each object given and fail if
55 # the hash values are not all the same.
56 hashed = list(map(hash, objlist))
57 for h in hashed[1:]:
58 if h != hashed[0]:
59 self.fail("hashed values differ: %r" % (objlist,))
60
61 def test_numeric_literals(self):
62 self.same_hash(1, 1, 1.0, 1.0+0.0j)
63 self.same_hash(0, 0.0, 0.0+0.0j)
64 self.same_hash(-1, -1.0, -1.0+0.0j)
65 self.same_hash(-2, -2.0, -2.0+0.0j)
66
67 def test_coerced_integers(self):
68 self.same_hash(int(1), int(1), float(1), complex(1),
69 int('1'), float('1.0'))
70 self.same_hash(int(-2**31), float(-2**31))
71 self.same_hash(int(1-2**31), float(1-2**31))
72 self.same_hash(int(2**31-1), float(2**31-1))
73 # for 64-bit platforms
74 self.same_hash(int(2**31), float(2**31))
75 self.same_hash(int(-2**63), float(-2**63))
76 self.same_hash(int(2**63), float(2**63))
77
78 def test_coerced_floats(self):
79 self.same_hash(int(1.23e300), float(1.23e300))
80 self.same_hash(float(0.5), complex(0.5, 0.0))
81
82 def test_unaligned_buffers(self):
83 # The hash function for bytes-like objects shouldn't have
84 # alignment-dependent results (example in issue #16427).
85 b = b"123456789abcdefghijklmnopqrstuvwxyz" * 128
86 for i in range(16):
87 for j in range(16):
88 aligned = b[i:128+j]
89 unaligned = memoryview(b)[i:128+j]
90 self.assertEqual(hash(aligned), hash(unaligned))
91
92
93 _default_hash = object.__hash__
94 class DefaultHash(object): pass
95
96 _FIXED_HASH_VALUE = 42
97 class FixedHash(object):
98 def __hash__(self):
99 return _FIXED_HASH_VALUE
100
101 class OnlyEquality(object):
102 def __eq__(self, other):
103 return self is other
104
105 class OnlyInequality(object):
106 def __ne__(self, other):
107 return self is not other
108
109 class InheritedHashWithEquality(FixedHash, OnlyEquality): pass
110 class InheritedHashWithInequality(FixedHash, OnlyInequality): pass
111
112 class NoHash(object):
113 __hash__ = None
114
115 class HashInheritanceTestCase(unittest.TestCase):
116 default_expected = [object(),
117 DefaultHash(),
118 OnlyInequality(),
119 ]
120 fixed_expected = [FixedHash(),
121 InheritedHashWithEquality(),
122 InheritedHashWithInequality(),
123 ]
124 error_expected = [NoHash(),
125 OnlyEquality(),
126 ]
127
128 def test_default_hash(self):
129 for obj in self.default_expected:
130 self.assertEqual(hash(obj), _default_hash(obj))
131
132 def test_fixed_hash(self):
133 for obj in self.fixed_expected:
134 self.assertEqual(hash(obj), _FIXED_HASH_VALUE)
135
136 def test_error_hash(self):
137 for obj in self.error_expected:
138 self.assertRaises(TypeError, hash, obj)
139
140 def test_hashable(self):
141 objects = (self.default_expected +
142 self.fixed_expected)
143 for obj in objects:
144 self.assertIsInstance(obj, Hashable)
145
146 def test_not_hashable(self):
147 for obj in self.error_expected:
148 self.assertNotIsInstance(obj, Hashable)
149
150
151 # Issue #4701: Check that some builtin types are correctly hashable
152 class DefaultIterSeq(object):
153 seq = range(10)
154 def __len__(self):
155 return len(self.seq)
156 def __getitem__(self, index):
157 return self.seq[index]
158
159 class HashBuiltinsTestCase(unittest.TestCase):
160 hashes_to_check = [enumerate(range(10)),
161 iter(DefaultIterSeq()),
162 iter(lambda: 0, 0),
163 ]
164
165 def test_hashes(self):
166 _default_hash = object.__hash__
167 for obj in self.hashes_to_check:
168 self.assertEqual(hash(obj), _default_hash(obj))
169
170 class HashRandomizationTests:
171
172 # Each subclass should define a field "repr_", containing the repr() of
173 # an object to be tested
174
175 def get_hash_command(self, repr_):
176 return 'print(hash(eval(%a)))' % repr_
177
178 def get_hash(self, repr_, seed=None):
179 env = os.environ.copy()
180 env['__cleanenv'] = True # signal to assert_python not to do a copy
181 # of os.environ on its own
182 if seed is not None:
183 env['PYTHONHASHSEED'] = str(seed)
184 else:
185 env.pop('PYTHONHASHSEED', None)
186 out = assert_python_ok(
187 '-c', self.get_hash_command(repr_),
188 **env)
189 stdout = out[1].strip()
190 return int(stdout)
191
192 def test_randomized_hash(self):
193 # two runs should return different hashes
194 run1 = self.get_hash(self.repr_, seed='random')
195 run2 = self.get_hash(self.repr_, seed='random')
196 self.assertNotEqual(run1, run2)
197
198 class StringlikeHashRandomizationTests(HashRandomizationTests):
199 repr_ = None
200 repr_long = None
201
202 # 32bit little, 64bit little, 32bit big, 64bit big
203 known_hashes = {
204 'djba33x': [ # only used for small strings
205 # seed 0, 'abc'
206 [193485960, 193485960, 193485960, 193485960],
207 # seed 42, 'abc'
208 [-678966196, 573763426263223372, -820489388, -4282905804826039665],
209 ],
210 'siphash13': [
211 # NOTE: PyUCS2 layout depends on endianness
212 # seed 0, 'abc'
213 [69611762, -4594863902769663758, 69611762, -4594863902769663758],
214 # seed 42, 'abc'
215 [-975800855, 3869580338025362921, -975800855, 3869580338025362921],
216 # seed 42, 'abcdefghijk'
217 [-595844228, 7764564197781545852, -595844228, 7764564197781545852],
218 # seed 0, 'äú∑ℇ'
219 [-1093288643, -2810468059467891395, -1041341092, 4925090034378237276],
220 # seed 42, 'äú∑ℇ'
221 [-585999602, -2845126246016066802, -817336969, -2219421378907968137],
222 ],
223 'siphash24': [
224 # NOTE: PyUCS2 layout depends on endianness
225 # seed 0, 'abc'
226 [1198583518, 4596069200710135518, 1198583518, 4596069200710135518],
227 # seed 42, 'abc'
228 [273876886, -4501618152524544106, 273876886, -4501618152524544106],
229 # seed 42, 'abcdefghijk'
230 [-1745215313, 4436719588892876975, -1745215313, 4436719588892876975],
231 # seed 0, 'äú∑ℇ'
232 [493570806, 5749986484189612790, -1006381564, -5915111450199468540],
233 # seed 42, 'äú∑ℇ'
234 [-1677110816, -2947981342227738144, -1860207793, -4296699217652516017],
235 ],
236 'fnv': [
237 # seed 0, 'abc'
238 [-1600925533, 1453079729188098211, -1600925533,
239 1453079729188098211],
240 # seed 42, 'abc'
241 [-206076799, -4410911502303878509, -1024014457,
242 -3570150969479994130],
243 # seed 42, 'abcdefghijk'
244 [811136751, -5046230049376118746, -77208053 ,
245 -4779029615281019666],
246 # seed 0, 'äú∑ℇ'
247 [44402817, 8998297579845987431, -1956240331,
248 -782697888614047887],
249 # seed 42, 'äú∑ℇ'
250 [-283066365, -4576729883824601543, -271871407,
251 -3927695501187247084],
252 ]
253 }
254
255 def get_expected_hash(self, position, length):
256 if length < sys.hash_info.cutoff:
257 algorithm = "djba33x"
258 else:
259 algorithm = sys.hash_info.algorithm
260 if sys.byteorder == 'little':
261 platform = 1 if IS_64BIT else 0
262 else:
263 assert(sys.byteorder == 'big')
264 platform = 3 if IS_64BIT else 2
265 return self.known_hashes[algorithm][position][platform]
266
267 def test_null_hash(self):
268 # PYTHONHASHSEED=0 disables the randomized hash
269 known_hash_of_obj = self.get_expected_hash(0, 3)
270
271 # Randomization is enabled by default:
272 self.assertNotEqual(self.get_hash(self.repr_), known_hash_of_obj)
273
274 # It can also be disabled by setting the seed to 0:
275 self.assertEqual(self.get_hash(self.repr_, seed=0), known_hash_of_obj)
276
277 @skip_unless_internalhash
278 def test_fixed_hash(self):
279 # test a fixed seed for the randomized hash
280 # Note that all types share the same values:
281 h = self.get_expected_hash(1, 3)
282 self.assertEqual(self.get_hash(self.repr_, seed=42), h)
283
284 @skip_unless_internalhash
285 def test_long_fixed_hash(self):
286 if self.repr_long is None:
287 return
288 h = self.get_expected_hash(2, 11)
289 self.assertEqual(self.get_hash(self.repr_long, seed=42), h)
290
291
292 class StrHashRandomizationTests(StringlikeHashRandomizationTests,
293 unittest.TestCase):
294 repr_ = repr('abc')
295 repr_long = repr('abcdefghijk')
296 repr_ucs2 = repr('äú∑ℇ')
297
298 @impl_detail("hash('') != 0 on PyPy", pypy=False)
299 @skip_unless_internalhash
300 def test_empty_string(self):
301 self.assertEqual(hash(""), 0)
302
303 @impl_detail("hash(ucs2) differs on PyPy if unichar is 4 bytes", pypy=False)
304 @skip_unless_internalhash
305 def test_ucs2_string(self):
306 h = self.get_expected_hash(3, 6)
307 self.assertEqual(self.get_hash(self.repr_ucs2, seed=0), h)
308 h = self.get_expected_hash(4, 6)
309 self.assertEqual(self.get_hash(self.repr_ucs2, seed=42), h)
310
311 class BytesHashRandomizationTests(StringlikeHashRandomizationTests,
312 unittest.TestCase):
313 repr_ = repr(b'abc')
314 repr_long = repr(b'abcdefghijk')
315
316 @impl_detail("hash('') != 0 on PyPy", pypy=False)
317 @skip_unless_internalhash
318 def test_empty_string(self):
319 self.assertEqual(hash(b""), 0)
320
321 class MemoryviewHashRandomizationTests(StringlikeHashRandomizationTests,
322 unittest.TestCase):
323 repr_ = "memoryview(b'abc')"
324 repr_long = "memoryview(b'abcdefghijk')"
325
326 @impl_detail("hash('') != 0 on PyPy", pypy=False)
327 @skip_unless_internalhash
328 def test_empty_string(self):
329 self.assertEqual(hash(memoryview(b"")), 0)
330
331 class DatetimeTests(HashRandomizationTests):
332 def get_hash_command(self, repr_):
333 return 'import datetime; print(hash(%s))' % repr_
334
335 class DatetimeDateTests(DatetimeTests, unittest.TestCase):
336 repr_ = repr(datetime.date(1066, 10, 14))
337
338 class DatetimeDatetimeTests(DatetimeTests, unittest.TestCase):
339 repr_ = repr(datetime.datetime(1, 2, 3, 4, 5, 6, 7))
340
341 class DatetimeTimeTests(DatetimeTests, unittest.TestCase):
342 repr_ = repr(datetime.time(0))
343
344
345 class HashDistributionTestCase(unittest.TestCase):
346
347 def test_hash_distribution(self):
348 # check for hash collision
349 base = "abcdefghabcdefg"
350 for i in range(1, len(base)):
351 prefix = base[:i]
352 with self.subTest(prefix=prefix):
353 s15 = set()
354 s255 = set()
355 for c in range(256):
356 h = hash(prefix + chr(c))
357 s15.add(h & 0xf)
358 s255.add(h & 0xff)
359 # SipHash24 distribution depends on key, usually > 60%
360 self.assertGreater(len(s15), 8, prefix)
361 self.assertGreater(len(s255), 128, prefix)
362
363 if __name__ == "__main__":
364 unittest.main()