summaryrefslogtreecommitdiff
path: root/Lib/test/test_fractions.py
diff options
context:
space:
mode:
authorMark Dickinson <mdickinson@enthought.com>2021-10-21 23:09:47 +0100
committerGitHub <noreply@github.com>2021-10-22 00:09:47 +0200
commitd1b24775b462f4f28aa4929fd031899170793388 (patch)
treed1df75e96bb817654f96f38a48b98117e2ab570f /Lib/test/test_fractions.py
parent51375388bee7287be2d942906b48c8cf3f691e8b (diff)
downloadcpython-git-d1b24775b462f4f28aa4929fd031899170793388.tar.gz
bpo-44547: Make Fractions objects instances of typing.SupportsInt (GH-27851)
Co-authored-by: Ɓukasz Langa <lukasz@langa.pl>
Diffstat (limited to 'Lib/test/test_fractions.py')
-rw-r--r--Lib/test/test_fractions.py42
1 files changed, 42 insertions, 0 deletions
diff --git a/Lib/test/test_fractions.py b/Lib/test/test_fractions.py
index bbf7709fe9..fc46e8674f 100644
--- a/Lib/test/test_fractions.py
+++ b/Lib/test/test_fractions.py
@@ -8,6 +8,7 @@ import operator
import fractions
import functools
import sys
+import typing
import unittest
from copy import copy, deepcopy
import pickle
@@ -385,6 +386,47 @@ class FractionTest(unittest.TestCase):
self.assertTypedEquals(0.1+0j, complex(F(1,10)))
+ def testSupportsInt(self):
+ # See bpo-44547.
+ f = F(3, 2)
+ self.assertIsInstance(f, typing.SupportsInt)
+ self.assertEqual(int(f), 1)
+ self.assertEqual(type(int(f)), int)
+
+ def testIntGuaranteesIntReturn(self):
+ # Check that int(some_fraction) gives a result of exact type `int`
+ # even if the fraction is using some other Integral type for its
+ # numerator and denominator.
+
+ class CustomInt(int):
+ """
+ Subclass of int with just enough machinery to convince the Fraction
+ constructor to produce something with CustomInt numerator and
+ denominator.
+ """
+
+ @property
+ def numerator(self):
+ return self
+
+ @property
+ def denominator(self):
+ return CustomInt(1)
+
+ def __mul__(self, other):
+ return CustomInt(int(self) * int(other))
+
+ def __floordiv__(self, other):
+ return CustomInt(int(self) // int(other))
+
+ f = F(CustomInt(13), CustomInt(5))
+
+ self.assertIsInstance(f.numerator, CustomInt)
+ self.assertIsInstance(f.denominator, CustomInt)
+ self.assertIsInstance(f, typing.SupportsInt)
+ self.assertEqual(int(f), 2)
+ self.assertEqual(type(int(f)), int)
+
def testBoolGuarateesBoolReturn(self):
# Ensure that __bool__ is used on numerator which guarantees a bool
# return. See also bpo-39274.