[3.13] gh-123378: fix a crash in UnicodeError.__str__ (GH-124935) (#125099)

gh-123378: fix a crash in `UnicodeError.__str__` (GH-124935)
(cherry picked from commit ba14dfafd9)

Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
This commit is contained in:
Miss Islington (bot) 2024-10-08 14:06:57 +02:00 committed by GitHub
parent 4eab6e8d29
commit 84991153da
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 93 additions and 45 deletions

View file

@ -8,6 +8,7 @@ import pickle
import weakref
import errno
from codecs import BOM_UTF8
from itertools import product
from textwrap import dedent
from test.support import (captured_stderr, check_impl_detail,
@ -1336,6 +1337,29 @@ class ExceptionTests(unittest.TestCase):
for klass in klasses:
self.assertEqual(str(klass.__new__(klass)), "")
def test_unicode_error_str_does_not_crash(self):
# Test that str(UnicodeError(...)) does not crash.
# See https://github.com/python/cpython/issues/123378.
for start, end, objlen in product(
range(-5, 5),
range(-5, 5),
range(7),
):
obj = 'a' * objlen
with self.subTest('encode', objlen=objlen, start=start, end=end):
exc = UnicodeEncodeError('utf-8', obj, start, end, '')
self.assertIsInstance(str(exc), str)
with self.subTest('translate', objlen=objlen, start=start, end=end):
exc = UnicodeTranslateError(obj, start, end, '')
self.assertIsInstance(str(exc), str)
encoded = obj.encode()
with self.subTest('decode', objlen=objlen, start=start, end=end):
exc = UnicodeDecodeError('utf-8', encoded, start, end, '')
self.assertIsInstance(str(exc), str)
@no_tracing
def test_badisinstance(self):
# Bug #2542: if issubclass(e, MyException) raises an exception,