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