|
| 1 | +import math |
1 | 2 | import sys
|
2 | 3 | import unittest
|
3 | 4 | from test.support import import_helper
|
4 | 5 | _testcapi = import_helper.import_module('_testcapi')
|
5 | 6 |
|
6 | 7 |
|
| 8 | +NULL = None |
7 | 9 | SIZEOF_PY_HASH_T = _testcapi.SIZEOF_VOID_P
|
8 | 10 |
|
9 | 11 |
|
@@ -31,3 +33,57 @@ def test_hash_getfuncdef(self):
|
31 | 33 | self.assertEqual(func_def.name, hash_info.algorithm)
|
32 | 34 | self.assertEqual(func_def.hash_bits, hash_info.hash_bits)
|
33 | 35 | self.assertEqual(func_def.seed_bits, hash_info.seed_bits)
|
| 36 | + |
| 37 | + def test_hash_double(self): |
| 38 | + # Test PyHash_Double() |
| 39 | + hash_double = _testcapi.hash_double |
| 40 | + marker = object() |
| 41 | + marker_hash = hash(marker) |
| 42 | + |
| 43 | + # test integers |
| 44 | + def python_hash_int(x): |
| 45 | + self.assertIsInstance(x, int) |
| 46 | + return hash(x) |
| 47 | + |
| 48 | + integers = [ |
| 49 | + *range(1, 30), |
| 50 | + 2**30 - 1, |
| 51 | + 2 ** 233, |
| 52 | + int(sys.float_info.max), |
| 53 | + ] |
| 54 | + integers.extend([-x for x in integers]) |
| 55 | + integers.append(0) |
| 56 | + |
| 57 | + for x in integers: |
| 58 | + for obj in (NULL, marker): |
| 59 | + with self.subTest(x=x, obj=obj): |
| 60 | + self.assertEqual(hash_double(float(x), obj), |
| 61 | + python_hash_int(x)) |
| 62 | + |
| 63 | + # test +inf and -inf |
| 64 | + for obj in (NULL, marker): |
| 65 | + with self.subTest(obj=obj): |
| 66 | + self.assertEqual(hash_double(float('inf')), sys.hash_info.inf) |
| 67 | + self.assertEqual(hash_double(float('-inf')), -sys.hash_info.inf) |
| 68 | + |
| 69 | + # test not-a-number (NaN) |
| 70 | + self.assertEqual(hash_double(float('nan'), marker), marker_hash) |
| 71 | + self.assertEqual(hash_double(float('nan'), NULL), sys.hash_info.nan) |
| 72 | + |
| 73 | + # special float values: compare with Python hash() function |
| 74 | + def python_hash_double(x): |
| 75 | + return hash(x) |
| 76 | + |
| 77 | + special_values = ( |
| 78 | + math.nextafter(0.0, 1.0), # smallest positive subnormal number |
| 79 | + sys.float_info.min, # smallest positive normal number |
| 80 | + sys.float_info.epsilon, |
| 81 | + sys.float_info.max, # largest positive finite number |
| 82 | + ) |
| 83 | + for x in special_values: |
| 84 | + for obj in (NULL, marker): |
| 85 | + with self.subTest(x=x, obj=obj): |
| 86 | + self.assertEqual(hash_double(x, obj), |
| 87 | + python_hash_double(x)) |
| 88 | + self.assertEqual(hash_double(-x, obj), |
| 89 | + python_hash_double(-x)) |
0 commit comments