test_hash.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 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", "siphash24"}
  41. msg = "Requires 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. 'siphash24': [
  174. # NOTE: PyUCS2 layout depends on endianess
  175. # seed 0, 'abc'
  176. [1198583518, 4596069200710135518, 1198583518, 4596069200710135518],
  177. # seed 42, 'abc'
  178. [273876886, -4501618152524544106, 273876886, -4501618152524544106],
  179. # seed 42, 'abcdefghijk'
  180. [-1745215313, 4436719588892876975, -1745215313, 4436719588892876975],
  181. # seed 0, 'äú∑ℇ'
  182. [493570806, 5749986484189612790, -1006381564, -5915111450199468540],
  183. # seed 42, 'äú∑ℇ'
  184. [-1677110816, -2947981342227738144, -1860207793, -4296699217652516017],
  185. ],
  186. 'fnv': [
  187. # seed 0, 'abc'
  188. [-1600925533, 1453079729188098211, -1600925533,
  189. 1453079729188098211],
  190. # seed 42, 'abc'
  191. [-206076799, -4410911502303878509, -1024014457,
  192. -3570150969479994130],
  193. # seed 42, 'abcdefghijk'
  194. [811136751, -5046230049376118746, -77208053 ,
  195. -4779029615281019666],
  196. # seed 0, 'äú∑ℇ'
  197. [44402817, 8998297579845987431, -1956240331,
  198. -782697888614047887],
  199. # seed 42, 'äú∑ℇ'
  200. [-283066365, -4576729883824601543, -271871407,
  201. -3927695501187247084],
  202. ]
  203. }
  204. def get_expected_hash(self, position, length):
  205. if length < sys.hash_info.cutoff:
  206. algorithm = "djba33x"
  207. else:
  208. algorithm = sys.hash_info.algorithm
  209. if sys.byteorder == 'little':
  210. platform = 1 if IS_64BIT else 0
  211. else:
  212. assert(sys.byteorder == 'big')
  213. platform = 3 if IS_64BIT else 2
  214. return self.known_hashes[algorithm][position][platform]
  215. def test_null_hash(self):
  216. # PYTHONHASHSEED=0 disables the randomized hash
  217. known_hash_of_obj = self.get_expected_hash(0, 3)
  218. # Randomization is enabled by default:
  219. self.assertNotEqual(self.get_hash(self.repr_), known_hash_of_obj)
  220. # It can also be disabled by setting the seed to 0:
  221. self.assertEqual(self.get_hash(self.repr_, seed=0), known_hash_of_obj)
  222. @skip_unless_internalhash
  223. def test_fixed_hash(self):
  224. # test a fixed seed for the randomized hash
  225. # Note that all types share the same values:
  226. h = self.get_expected_hash(1, 3)
  227. self.assertEqual(self.get_hash(self.repr_, seed=42), h)
  228. @skip_unless_internalhash
  229. def test_long_fixed_hash(self):
  230. if self.repr_long is None:
  231. return
  232. h = self.get_expected_hash(2, 11)
  233. self.assertEqual(self.get_hash(self.repr_long, seed=42), h)
  234. class StrHashRandomizationTests(StringlikeHashRandomizationTests,
  235. unittest.TestCase):
  236. repr_ = repr('abc')
  237. repr_long = repr('abcdefghijk')
  238. repr_ucs2 = repr('äú∑ℇ')
  239. @skip_unless_internalhash
  240. def test_empty_string(self):
  241. self.assertEqual(hash(""), 0)
  242. @skip_unless_internalhash
  243. def test_ucs2_string(self):
  244. h = self.get_expected_hash(3, 6)
  245. self.assertEqual(self.get_hash(self.repr_ucs2, seed=0), h)
  246. h = self.get_expected_hash(4, 6)
  247. self.assertEqual(self.get_hash(self.repr_ucs2, seed=42), h)
  248. class BytesHashRandomizationTests(StringlikeHashRandomizationTests,
  249. unittest.TestCase):
  250. repr_ = repr(b'abc')
  251. repr_long = repr(b'abcdefghijk')
  252. @skip_unless_internalhash
  253. def test_empty_string(self):
  254. self.assertEqual(hash(b""), 0)
  255. class MemoryviewHashRandomizationTests(StringlikeHashRandomizationTests,
  256. unittest.TestCase):
  257. repr_ = "memoryview(b'abc')"
  258. repr_long = "memoryview(b'abcdefghijk')"
  259. @skip_unless_internalhash
  260. def test_empty_string(self):
  261. self.assertEqual(hash(memoryview(b"")), 0)
  262. class DatetimeTests(HashRandomizationTests):
  263. def get_hash_command(self, repr_):
  264. return 'import datetime; print(hash(%s))' % repr_
  265. class DatetimeDateTests(DatetimeTests, unittest.TestCase):
  266. repr_ = repr(datetime.date(1066, 10, 14))
  267. class DatetimeDatetimeTests(DatetimeTests, unittest.TestCase):
  268. repr_ = repr(datetime.datetime(1, 2, 3, 4, 5, 6, 7))
  269. class DatetimeTimeTests(DatetimeTests, unittest.TestCase):
  270. repr_ = repr(datetime.time(0))
  271. class HashDistributionTestCase(unittest.TestCase):
  272. def test_hash_distribution(self):
  273. # check for hash collision
  274. base = "abcdefghabcdefg"
  275. for i in range(1, len(base)):
  276. prefix = base[:i]
  277. with self.subTest(prefix=prefix):
  278. s15 = set()
  279. s255 = set()
  280. for c in range(256):
  281. h = hash(prefix + chr(c))
  282. s15.add(h & 0xf)
  283. s255.add(h & 0xff)
  284. # SipHash24 distribution depends on key, usually > 60%
  285. self.assertGreater(len(s15), 8, prefix)
  286. self.assertGreater(len(s255), 128, prefix)
  287. if __name__ == "__main__":
  288. unittest.main()