test_hash.py 12 KB

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