Issue #15989: Fix several occurrences of integer overflow
when result of PyLong_AsLong() narrowed to int without checks.

This is a backport of changesets 13e2e44db99d and 525407d89277.
diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py
index 56ac2c8..249dc30 100644
--- a/Lib/test/test_io.py
+++ b/Lib/test/test_io.py
@@ -31,6 +31,7 @@
 import errno
 import warnings
 import pickle
+import _testcapi
 from itertools import cycle, count
 from collections import deque, UserList
 from test import support
@@ -1903,6 +1904,14 @@
         t.write("A\rB")
         self.assertEqual(r.getvalue(), b"XY\nZA\rB")
 
+    # Issue 15989
+    def test_device_encoding(self):
+        b = self.BytesIO()
+        b.fileno = lambda: _testcapi.INT_MAX + 1
+        self.assertRaises(OverflowError, self.TextIOWrapper, b)
+        b.fileno = lambda: _testcapi.UINT_MAX + 1
+        self.assertRaises(OverflowError, self.TextIOWrapper, b)
+
     def test_encoding(self):
         # Check the encoding attribute is always set, and valid
         b = self.BytesIO()