summaryrefslogtreecommitdiffstats
path: root/Lib/test/test_numeric_tower.py
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2022-09-04 12:40:24 (GMT)
committerGitHub <noreply@github.com>2022-09-04 12:40:24 (GMT)
commit4dea99f18eeef15a6d69236146793c801d12c329 (patch)
treefee9a451fbe9576f0611e3bf1afee004c70ce5ae /Lib/test/test_numeric_tower.py
parent3a56a938f375f17f39baeb4b1529793dd0eb79b8 (diff)
downloadcpython-4dea99f18eeef15a6d69236146793c801d12c329.zip
cpython-4dea99f18eeef15a6d69236146793c801d12c329.tar.gz
cpython-4dea99f18eeef15a6d69236146793c801d12c329.tar.bz2
gh-68163: Correct conversion of Rational instances to float (GH-25619) (GH-96557)
* gh-68163: Correct conversion of Rational instances to float Also document that numerator/denominator properties are instances of Integral. Co-authored-by: Mark Dickinson <dickinsm@gmail.com> (cherry picked from commit 8464b754c4168586b99e2135ccd2567e025625a9) Co-authored-by: Sergey B Kirpichev <skirpichev@gmail.com>
Diffstat (limited to 'Lib/test/test_numeric_tower.py')
-rw-r--r--Lib/test/test_numeric_tower.py28
1 files changed, 28 insertions, 0 deletions
diff --git a/Lib/test/test_numeric_tower.py b/Lib/test/test_numeric_tower.py
index c54dedb..9cd85e1 100644
--- a/Lib/test/test_numeric_tower.py
+++ b/Lib/test/test_numeric_tower.py
@@ -14,6 +14,27 @@ from fractions import Fraction as F
_PyHASH_MODULUS = sys.hash_info.modulus
_PyHASH_INF = sys.hash_info.inf
+
+class DummyIntegral(int):
+ """Dummy Integral class to test conversion of the Rational to float."""
+
+ def __mul__(self, other):
+ return DummyIntegral(super().__mul__(other))
+ __rmul__ = __mul__
+
+ def __truediv__(self, other):
+ return NotImplemented
+ __rtruediv__ = __truediv__
+
+ @property
+ def numerator(self):
+ return DummyIntegral(self)
+
+ @property
+ def denominator(self):
+ return DummyIntegral(1)
+
+
class HashTest(unittest.TestCase):
def check_equal_hash(self, x, y):
# check both that x and y are equal and that their hashes are equal
@@ -121,6 +142,13 @@ class HashTest(unittest.TestCase):
self.assertEqual(hash(F(7*_PyHASH_MODULUS, 1)), 0)
self.assertEqual(hash(F(-_PyHASH_MODULUS, 1)), 0)
+ # The numbers ABC doesn't enforce that the "true" division
+ # of integers produces a float. This tests that the
+ # Rational.__float__() method has required type conversions.
+ x = F(DummyIntegral(1), DummyIntegral(2), _normalize=False)
+ self.assertRaises(TypeError, lambda: x.numerator/x.denominator)
+ self.assertEqual(float(x), 0.5)
+
def test_hash_normalization(self):
# Test for a bug encountered while changing long_hash.
#