diff options
| author | Victor Stinner <vstinner@python.org> | 2023-08-24 21:55:30 (GMT) |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-08-24 21:55:30 (GMT) |
| commit | be436e08b8bd9fcd2202d6ce4d924bba7551e96f (patch) | |
| tree | df142099ae50383af0e76ed09f5b4d8d1cc15d3e /Lib/test/test_capi/test_long.py | |
| parent | feb9a49c9c09d08cb8c24cb74d90a218de6af244 (diff) | |
| download | cpython-be436e08b8bd9fcd2202d6ce4d924bba7551e96f.zip cpython-be436e08b8bd9fcd2202d6ce4d924bba7551e96f.tar.gz cpython-be436e08b8bd9fcd2202d6ce4d924bba7551e96f.tar.bz2 | |
gh-108444: Add PyLong_AsInt() public function (#108445)
* Rename _PyLong_AsInt() to PyLong_AsInt().
* Add documentation.
* Add test.
* For now, keep _PyLong_AsInt() as an alias to PyLong_AsInt().
Diffstat (limited to 'Lib/test/test_capi/test_long.py')
| -rw-r--r-- | Lib/test/test_capi/test_long.py | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/Lib/test/test_capi/test_long.py b/Lib/test/test_capi/test_long.py index 8928fd9..101fe1f 100644 --- a/Lib/test/test_capi/test_long.py +++ b/Lib/test/test_capi/test_long.py @@ -34,6 +34,36 @@ class LongTests(unittest.TestCase): self.assertEqual(_testcapi.call_long_compact_api(sys.maxsize), (False, -1)) + def test_long_asint(self): + PyLong_AsInt = _testcapi.PyLong_AsInt + INT_MIN = _testcapi.INT_MIN + INT_MAX = _testcapi.INT_MAX + + # round trip (object -> int -> object) + for value in (INT_MIN, INT_MAX, -1, 0, 1, 123): + with self.subTest(value=value): + self.assertEqual(PyLong_AsInt(value), value) + + # use __index__(), not __int__() + class MyIndex: + def __index__(self): + return 10 + def __int__(self): + return 22 + self.assertEqual(PyLong_AsInt(MyIndex()), 10) + + # bound checking + with self.assertRaises(OverflowError): + PyLong_AsInt(INT_MIN - 1) + with self.assertRaises(OverflowError): + PyLong_AsInt(INT_MAX + 1) + + # invalid type + for value in (1.0, b'2', '3'): + with self.subTest(value=value): + with self.assertRaises(TypeError): + PyLong_AsInt(value) + if __name__ == "__main__": unittest.main() |
