1 # test interactions between int, float, Decimal and Fraction
2
3 import unittest
4 import random
5 import math
6 import sys
7 import operator
8
9 from decimal import Decimal as D
10 from fractions import Fraction as F
11
12 # Constants related to the hash implementation; hash(x) is based
13 # on the reduction of x modulo the prime _PyHASH_MODULUS.
14 _PyHASH_MODULUS = sys.hash_info.modulus
15 _PyHASH_INF = sys.hash_info.inf
16
17
18 class ESC[4;38;5;81mDummyIntegral(ESC[4;38;5;149mint):
19 """Dummy Integral class to test conversion of the Rational to float."""
20
21 def __mul__(self, other):
22 return DummyIntegral(super().__mul__(other))
23 __rmul__ = __mul__
24
25 def __truediv__(self, other):
26 return NotImplemented
27 __rtruediv__ = __truediv__
28
29 @property
30 def numerator(self):
31 return DummyIntegral(self)
32
33 @property
34 def denominator(self):
35 return DummyIntegral(1)
36
37
38 class ESC[4;38;5;81mHashTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
39 def check_equal_hash(self, x, y):
40 # check both that x and y are equal and that their hashes are equal
41 self.assertEqual(hash(x), hash(y),
42 "got different hashes for {!r} and {!r}".format(x, y))
43 self.assertEqual(x, y)
44
45 def test_bools(self):
46 self.check_equal_hash(False, 0)
47 self.check_equal_hash(True, 1)
48
49 def test_integers(self):
50 # check that equal values hash equal
51
52 # exact integers
53 for i in range(-1000, 1000):
54 self.check_equal_hash(i, float(i))
55 self.check_equal_hash(i, D(i))
56 self.check_equal_hash(i, F(i))
57
58 # the current hash is based on reduction modulo 2**n-1 for some
59 # n, so pay special attention to numbers of the form 2**n and 2**n-1.
60 for i in range(100):
61 n = 2**i - 1
62 if n == int(float(n)):
63 self.check_equal_hash(n, float(n))
64 self.check_equal_hash(-n, -float(n))
65 self.check_equal_hash(n, D(n))
66 self.check_equal_hash(n, F(n))
67 self.check_equal_hash(-n, D(-n))
68 self.check_equal_hash(-n, F(-n))
69
70 n = 2**i
71 self.check_equal_hash(n, float(n))
72 self.check_equal_hash(-n, -float(n))
73 self.check_equal_hash(n, D(n))
74 self.check_equal_hash(n, F(n))
75 self.check_equal_hash(-n, D(-n))
76 self.check_equal_hash(-n, F(-n))
77
78 # random values of various sizes
79 for _ in range(1000):
80 e = random.randrange(300)
81 n = random.randrange(-10**e, 10**e)
82 self.check_equal_hash(n, D(n))
83 self.check_equal_hash(n, F(n))
84 if n == int(float(n)):
85 self.check_equal_hash(n, float(n))
86
87 def test_binary_floats(self):
88 # check that floats hash equal to corresponding Fractions and Decimals
89
90 # floats that are distinct but numerically equal should hash the same
91 self.check_equal_hash(0.0, -0.0)
92
93 # zeros
94 self.check_equal_hash(0.0, D(0))
95 self.check_equal_hash(-0.0, D(0))
96 self.check_equal_hash(-0.0, D('-0.0'))
97 self.check_equal_hash(0.0, F(0))
98
99 # infinities and nans
100 self.check_equal_hash(float('inf'), D('inf'))
101 self.check_equal_hash(float('-inf'), D('-inf'))
102
103 for _ in range(1000):
104 x = random.random() * math.exp(random.random()*200.0 - 100.0)
105 self.check_equal_hash(x, D.from_float(x))
106 self.check_equal_hash(x, F.from_float(x))
107
108 def test_complex(self):
109 # complex numbers with zero imaginary part should hash equal to
110 # the corresponding float
111
112 test_values = [0.0, -0.0, 1.0, -1.0, 0.40625, -5136.5,
113 float('inf'), float('-inf')]
114
115 for zero in -0.0, 0.0:
116 for value in test_values:
117 self.check_equal_hash(value, complex(value, zero))
118
119 def test_decimals(self):
120 # check that Decimal instances that have different representations
121 # but equal values give the same hash
122 zeros = ['0', '-0', '0.0', '-0.0e10', '000e-10']
123 for zero in zeros:
124 self.check_equal_hash(D(zero), D(0))
125
126 self.check_equal_hash(D('1.00'), D(1))
127 self.check_equal_hash(D('1.00000'), D(1))
128 self.check_equal_hash(D('-1.00'), D(-1))
129 self.check_equal_hash(D('-1.00000'), D(-1))
130 self.check_equal_hash(D('123e2'), D(12300))
131 self.check_equal_hash(D('1230e1'), D(12300))
132 self.check_equal_hash(D('12300'), D(12300))
133 self.check_equal_hash(D('12300.0'), D(12300))
134 self.check_equal_hash(D('12300.00'), D(12300))
135 self.check_equal_hash(D('12300.000'), D(12300))
136
137 def test_fractions(self):
138 # check special case for fractions where either the numerator
139 # or the denominator is a multiple of _PyHASH_MODULUS
140 self.assertEqual(hash(F(1, _PyHASH_MODULUS)), _PyHASH_INF)
141 self.assertEqual(hash(F(-1, 3*_PyHASH_MODULUS)), -_PyHASH_INF)
142 self.assertEqual(hash(F(7*_PyHASH_MODULUS, 1)), 0)
143 self.assertEqual(hash(F(-_PyHASH_MODULUS, 1)), 0)
144
145 # The numbers ABC doesn't enforce that the "true" division
146 # of integers produces a float. This tests that the
147 # Rational.__float__() method has required type conversions.
148 x = F._from_coprime_ints(DummyIntegral(1), DummyIntegral(2))
149 self.assertRaises(TypeError, lambda: x.numerator/x.denominator)
150 self.assertEqual(float(x), 0.5)
151
152 def test_hash_normalization(self):
153 # Test for a bug encountered while changing long_hash.
154 #
155 # Given objects x and y, it should be possible for y's
156 # __hash__ method to return hash(x) in order to ensure that
157 # hash(x) == hash(y). But hash(x) is not exactly equal to the
158 # result of x.__hash__(): there's some internal normalization
159 # to make sure that the result fits in a C long, and is not
160 # equal to the invalid hash value -1. This internal
161 # normalization must therefore not change the result of
162 # hash(x) for any x.
163
164 class ESC[4;38;5;81mHalibutProxy:
165 def __hash__(self):
166 return hash('halibut')
167 def __eq__(self, other):
168 return other == 'halibut'
169
170 x = {'halibut', HalibutProxy()}
171 self.assertEqual(len(x), 1)
172
173 class ESC[4;38;5;81mComparisonTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
174 def test_mixed_comparisons(self):
175
176 # ordered list of distinct test values of various types:
177 # int, float, Fraction, Decimal
178 test_values = [
179 float('-inf'),
180 D('-1e425000000'),
181 -1e308,
182 F(-22, 7),
183 -3.14,
184 -2,
185 0.0,
186 1e-320,
187 True,
188 F('1.2'),
189 D('1.3'),
190 float('1.4'),
191 F(275807, 195025),
192 D('1.414213562373095048801688724'),
193 F(114243, 80782),
194 F(473596569, 84615),
195 7e200,
196 D('infinity'),
197 ]
198 for i, first in enumerate(test_values):
199 for second in test_values[i+1:]:
200 self.assertLess(first, second)
201 self.assertLessEqual(first, second)
202 self.assertGreater(second, first)
203 self.assertGreaterEqual(second, first)
204
205 def test_complex(self):
206 # comparisons with complex are special: equality and inequality
207 # comparisons should always succeed, but order comparisons should
208 # raise TypeError.
209 z = 1.0 + 0j
210 w = -3.14 + 2.7j
211
212 for v in 1, 1.0, F(1), D(1), complex(1):
213 self.assertEqual(z, v)
214 self.assertEqual(v, z)
215
216 for v in 2, 2.0, F(2), D(2), complex(2):
217 self.assertNotEqual(z, v)
218 self.assertNotEqual(v, z)
219 self.assertNotEqual(w, v)
220 self.assertNotEqual(v, w)
221
222 for v in (1, 1.0, F(1), D(1), complex(1),
223 2, 2.0, F(2), D(2), complex(2), w):
224 for op in operator.le, operator.lt, operator.ge, operator.gt:
225 self.assertRaises(TypeError, op, z, v)
226 self.assertRaises(TypeError, op, v, z)
227
228
229 if __name__ == '__main__':
230 unittest.main()