gh-102799: use sys.exception() instead of sys.exc_info() in tests (#103293)

This commit is contained in:
Irit Katriel 2023-04-06 11:08:25 +01:00 committed by GitHub
parent a44568b80d
commit 482b6eeadc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 68 additions and 71 deletions

View file

@ -79,7 +79,7 @@ def helper1():
TICKS += 19 TICKS += 19
lst = [] lst = []
lst.append(42) # 0 lst.append(42) # 0
sys.exc_info() # 0 sys.exception() # 0
def helper2_indirect(): def helper2_indirect():
helper2() # 50 helper2() # 50

View file

@ -537,10 +537,11 @@ class dispatcher_with_send(dispatcher):
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def compact_traceback(): def compact_traceback():
t, v, tb = sys.exc_info() exc = sys.exception()
tbinfo = [] tb = exc.__traceback__
if not tb: # Must have a traceback if not tb: # Must have a traceback
raise AssertionError("traceback does not exist") raise AssertionError("traceback does not exist")
tbinfo = []
while tb: while tb:
tbinfo.append(( tbinfo.append((
tb.tb_frame.f_code.co_filename, tb.tb_frame.f_code.co_filename,
@ -554,7 +555,7 @@ def compact_traceback():
file, function, line = tbinfo[-1] file, function, line = tbinfo[-1]
info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo]) info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo])
return (file, function, line), t, v, info return (file, function, line), type(exc), exc, info
def close_all(map=None, ignore_all=False): def close_all(map=None, ignore_all=False):
if map is None: if map is None:

View file

@ -606,7 +606,7 @@ class BaseTaskTests:
if ( if (
timed_out timed_out
and task.uncancel() == 0 and task.uncancel() == 0
and sys.exc_info()[0] is asyncio.CancelledError and type(sys.exception()) is asyncio.CancelledError
): ):
# Note the five rules that are needed here to satisfy proper # Note the five rules that are needed here to satisfy proper
# uncancellation: # uncancellation:

View file

@ -577,7 +577,7 @@ class TestCase(unittest.TestCase):
# Detect CPython bug #23353: ensure that yield/yield-from is not used # Detect CPython bug #23353: ensure that yield/yield-from is not used
# in an except block of a generator # in an except block of a generator
self.assertEqual(sys.exc_info(), (None, None, None)) self.assertIsNone(sys.exception())
self.doCleanups() self.doCleanups()
threading_helper.threading_cleanup(*self._thread_cleanup) threading_helper.threading_cleanup(*self._thread_cleanup)

View file

@ -457,7 +457,7 @@ class ClassTests(unittest.TestCase):
a = A() a = A()
self.assertEqual(_testcapi.hasattr_string(a, "attr"), True) self.assertEqual(_testcapi.hasattr_string(a, "attr"), True)
self.assertEqual(_testcapi.hasattr_string(a, "noattr"), False) self.assertEqual(_testcapi.hasattr_string(a, "noattr"), False)
self.assertEqual(sys.exc_info(), (None, None, None)) self.assertIsNone(sys.exception())
def testDel(self): def testDel(self):
x = [] x = []

View file

@ -100,7 +100,7 @@ profilee.py:88(helper2) <- 6 0.234 0.300
profilee.py:98(subhelper) <- 8 0.064 0.080 profilee.py:88(helper2) profilee.py:98(subhelper) <- 8 0.064 0.080 profilee.py:88(helper2)
{built-in method builtins.hasattr} <- 4 0.000 0.004 profilee.py:73(helper1) {built-in method builtins.hasattr} <- 4 0.000 0.004 profilee.py:73(helper1)
8 0.000 0.008 profilee.py:88(helper2) 8 0.000 0.008 profilee.py:88(helper2)
{built-in method sys.exc_info} <- 4 0.000 0.000 profilee.py:73(helper1) {built-in method sys.exception} <- 4 0.000 0.000 profilee.py:73(helper1)
{method 'append' of 'list' objects} <- 4 0.000 0.000 profilee.py:73(helper1)""" {method 'append' of 'list' objects} <- 4 0.000 0.000 profilee.py:73(helper1)"""
_ProfileOutput['print_callees'] = """\ _ProfileOutput['print_callees'] = """\
<string>:1(<module>) -> 1 0.270 1.000 profilee.py:25(testfunc) <string>:1(<module>) -> 1 0.270 1.000 profilee.py:25(testfunc)

View file

@ -334,8 +334,7 @@ class ExceptionTests(unittest.TestCase):
try: try:
_testcapi.raise_exception(BadException, 1) _testcapi.raise_exception(BadException, 1)
except TypeError as err: except TypeError as err:
exc, err, tb = sys.exc_info() co = err.__traceback__.tb_frame.f_code
co = tb.tb_frame.f_code
self.assertEqual(co.co_name, "test_capi1") self.assertEqual(co.co_name, "test_capi1")
self.assertTrue(co.co_filename.endswith('test_exceptions.py')) self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
else: else:
@ -346,8 +345,7 @@ class ExceptionTests(unittest.TestCase):
try: try:
_testcapi.raise_exception(BadException, 0) _testcapi.raise_exception(BadException, 0)
except RuntimeError as err: except RuntimeError as err:
exc, err, tb = sys.exc_info() tb = err.__traceback__.tb_next
tb = tb.tb_next
co = tb.tb_frame.f_code co = tb.tb_frame.f_code
self.assertEqual(co.co_name, "__init__") self.assertEqual(co.co_name, "__init__")
self.assertTrue(co.co_filename.endswith('test_exceptions.py')) self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
@ -888,28 +886,28 @@ class ExceptionTests(unittest.TestCase):
try: try:
raise KeyError("caught") raise KeyError("caught")
except KeyError: except KeyError:
yield sys.exc_info()[0] yield sys.exception()
yield sys.exc_info()[0] yield sys.exception()
yield sys.exc_info()[0] yield sys.exception()
g = yield_raise() g = yield_raise()
self.assertEqual(next(g), KeyError) self.assertIsInstance(next(g), KeyError)
self.assertEqual(sys.exc_info()[0], None) self.assertIsNone(sys.exception())
self.assertEqual(next(g), KeyError) self.assertIsInstance(next(g), KeyError)
self.assertEqual(sys.exc_info()[0], None) self.assertIsNone(sys.exception())
self.assertEqual(next(g), None) self.assertIsNone(next(g))
# Same test, but inside an exception handler # Same test, but inside an exception handler
try: try:
raise TypeError("foo") raise TypeError("foo")
except TypeError: except TypeError:
g = yield_raise() g = yield_raise()
self.assertEqual(next(g), KeyError) self.assertIsInstance(next(g), KeyError)
self.assertEqual(sys.exc_info()[0], TypeError) self.assertIsInstance(sys.exception(), TypeError)
self.assertEqual(next(g), KeyError) self.assertIsInstance(next(g), KeyError)
self.assertEqual(sys.exc_info()[0], TypeError) self.assertIsInstance(sys.exception(), TypeError)
self.assertEqual(next(g), TypeError) self.assertIsInstance(next(g), TypeError)
del g del g
self.assertEqual(sys.exc_info()[0], TypeError) self.assertIsInstance(sys.exception(), TypeError)
def test_generator_leaking2(self): def test_generator_leaking2(self):
# See issue 12475. # See issue 12475.
@ -924,7 +922,7 @@ class ExceptionTests(unittest.TestCase):
next(it) next(it)
except StopIteration: except StopIteration:
pass pass
self.assertEqual(sys.exc_info(), (None, None, None)) self.assertIsNone(sys.exception())
def test_generator_leaking3(self): def test_generator_leaking3(self):
# See issue #23353. When gen.throw() is called, the caller's # See issue #23353. When gen.throw() is called, the caller's
@ -933,17 +931,17 @@ class ExceptionTests(unittest.TestCase):
try: try:
yield yield
except ZeroDivisionError: except ZeroDivisionError:
yield sys.exc_info()[1] yield sys.exception()
it = g() it = g()
next(it) next(it)
try: try:
1/0 1/0
except ZeroDivisionError as e: except ZeroDivisionError as e:
self.assertIs(sys.exc_info()[1], e) self.assertIs(sys.exception(), e)
gen_exc = it.throw(e) gen_exc = it.throw(e)
self.assertIs(sys.exc_info()[1], e) self.assertIs(sys.exception(), e)
self.assertIs(gen_exc, e) self.assertIs(gen_exc, e)
self.assertEqual(sys.exc_info(), (None, None, None)) self.assertIsNone(sys.exception())
def test_generator_leaking4(self): def test_generator_leaking4(self):
# See issue #23353. When an exception is raised by a generator, # See issue #23353. When an exception is raised by a generator,
@ -952,7 +950,7 @@ class ExceptionTests(unittest.TestCase):
try: try:
1/0 1/0
except ZeroDivisionError: except ZeroDivisionError:
yield sys.exc_info()[0] yield sys.exception()
raise raise
it = g() it = g()
try: try:
@ -960,7 +958,7 @@ class ExceptionTests(unittest.TestCase):
except TypeError: except TypeError:
# The caller's exception state (TypeError) is temporarily # The caller's exception state (TypeError) is temporarily
# saved in the generator. # saved in the generator.
tp = next(it) tp = type(next(it))
self.assertIs(tp, ZeroDivisionError) self.assertIs(tp, ZeroDivisionError)
try: try:
next(it) next(it)
@ -968,15 +966,15 @@ class ExceptionTests(unittest.TestCase):
# with an exception, it shouldn't have restored the old # with an exception, it shouldn't have restored the old
# exception state (TypeError). # exception state (TypeError).
except ZeroDivisionError as e: except ZeroDivisionError as e:
self.assertIs(sys.exc_info()[1], e) self.assertIs(sys.exception(), e)
# We used to find TypeError here. # We used to find TypeError here.
self.assertEqual(sys.exc_info(), (None, None, None)) self.assertIsNone(sys.exception())
def test_generator_doesnt_retain_old_exc(self): def test_generator_doesnt_retain_old_exc(self):
def g(): def g():
self.assertIsInstance(sys.exc_info()[1], RuntimeError) self.assertIsInstance(sys.exception(), RuntimeError)
yield yield
self.assertEqual(sys.exc_info(), (None, None, None)) self.assertIsNone(sys.exception())
it = g() it = g()
try: try:
raise RuntimeError raise RuntimeError
@ -984,7 +982,7 @@ class ExceptionTests(unittest.TestCase):
next(it) next(it)
self.assertRaises(StopIteration, next, it) self.assertRaises(StopIteration, next, it)
def test_generator_finalizing_and_exc_info(self): def test_generator_finalizing_and_sys_exception(self):
# See #7173 # See #7173
def simple_gen(): def simple_gen():
yield 1 yield 1
@ -996,7 +994,7 @@ class ExceptionTests(unittest.TestCase):
return next(gen) return next(gen)
run_gen() run_gen()
gc_collect() gc_collect()
self.assertEqual(sys.exc_info(), (None, None, None)) self.assertIsNone(sys.exception())
def _check_generator_cleanup_exc_state(self, testfunc): def _check_generator_cleanup_exc_state(self, testfunc):
# Issue #12791: exception state is cleaned up as soon as a generator # Issue #12791: exception state is cleaned up as soon as a generator
@ -1067,14 +1065,14 @@ class ExceptionTests(unittest.TestCase):
class MyObject: class MyObject:
def __del__(self): def __del__(self):
nonlocal e nonlocal e
e = sys.exc_info() e = sys.exception()
e = () e = ()
try: try:
raise Exception(MyObject()) raise Exception(MyObject())
except: except:
pass pass
gc_collect() # For PyPy or other GCs. gc_collect() # For PyPy or other GCs.
self.assertEqual(e, (None, None, None)) self.assertIsNone(e)
def test_raise_does_not_create_context_chain_cycle(self): def test_raise_does_not_create_context_chain_cycle(self):
class A(Exception): class A(Exception):
@ -1692,7 +1690,7 @@ class ExceptionTests(unittest.TestCase):
raise ValueError raise ValueError
except ValueError: except ValueError:
yield 1 yield 1
self.assertEqual(sys.exc_info(), (None, None, None)) self.assertIsNone(sys.exception())
yield 2 yield 2
gen = g() gen = g()

View file

@ -234,16 +234,16 @@ class ExceptionTest(unittest.TestCase):
def test_except_throw(self): def test_except_throw(self):
def store_raise_exc_generator(): def store_raise_exc_generator():
try: try:
self.assertEqual(sys.exc_info()[0], None) self.assertIsNone(sys.exception())
yield yield
except Exception as exc: except Exception as exc:
# exception raised by gen.throw(exc) # exception raised by gen.throw(exc)
self.assertEqual(sys.exc_info()[0], ValueError) self.assertIsInstance(sys.exception(), ValueError)
self.assertIsNone(exc.__context__) self.assertIsNone(exc.__context__)
yield yield
# ensure that the exception is not lost # ensure that the exception is not lost
self.assertEqual(sys.exc_info()[0], ValueError) self.assertIsInstance(sys.exception(), ValueError)
yield yield
# we should be able to raise back the ValueError # we should be able to raise back the ValueError
@ -265,11 +265,11 @@ class ExceptionTest(unittest.TestCase):
next(make) next(make)
self.assertIsNone(cm.exception.__context__) self.assertIsNone(cm.exception.__context__)
self.assertEqual(sys.exc_info(), (None, None, None)) self.assertIsNone(sys.exception())
def test_except_next(self): def test_except_next(self):
def gen(): def gen():
self.assertEqual(sys.exc_info()[0], ValueError) self.assertIsInstance(sys.exception(), ValueError)
yield "done" yield "done"
g = gen() g = gen()
@ -277,23 +277,23 @@ class ExceptionTest(unittest.TestCase):
raise ValueError raise ValueError
except Exception: except Exception:
self.assertEqual(next(g), "done") self.assertEqual(next(g), "done")
self.assertEqual(sys.exc_info(), (None, None, None)) self.assertIsNone(sys.exception())
def test_except_gen_except(self): def test_except_gen_except(self):
def gen(): def gen():
try: try:
self.assertEqual(sys.exc_info()[0], None) self.assertIsNone(sys.exception())
yield yield
# we are called from "except ValueError:", TypeError must # we are called from "except ValueError:", TypeError must
# inherit ValueError in its context # inherit ValueError in its context
raise TypeError() raise TypeError()
except TypeError as exc: except TypeError as exc:
self.assertEqual(sys.exc_info()[0], TypeError) self.assertIsInstance(sys.exception(), TypeError)
self.assertEqual(type(exc.__context__), ValueError) self.assertEqual(type(exc.__context__), ValueError)
# here we are still called from the "except ValueError:" # here we are still called from the "except ValueError:"
self.assertEqual(sys.exc_info()[0], ValueError) self.assertIsInstance(sys.exception(), ValueError)
yield yield
self.assertIsNone(sys.exc_info()[0]) self.assertIsNone(sys.exception())
yield "done" yield "done"
g = gen() g = gen()
@ -304,7 +304,7 @@ class ExceptionTest(unittest.TestCase):
next(g) next(g)
self.assertEqual(next(g), "done") self.assertEqual(next(g), "done")
self.assertEqual(sys.exc_info(), (None, None, None)) self.assertIsNone(sys.exception())
def test_nested_gen_except_loop(self): def test_nested_gen_except_loop(self):
def gen(): def gen():
@ -330,19 +330,19 @@ class ExceptionTest(unittest.TestCase):
def gen(): def gen():
try: try:
try: try:
self.assertEqual(sys.exc_info()[0], None) self.assertIsNone(sys.exception())
yield yield
except ValueError: except ValueError:
# we are called from "except ValueError:" # we are called from "except ValueError:"
self.assertEqual(sys.exc_info()[0], ValueError) self.assertIsInstance(sys.exception(), ValueError)
raise TypeError() raise TypeError()
except Exception as exc: except Exception as exc:
self.assertEqual(sys.exc_info()[0], TypeError) self.assertIsInstance(sys.exception(), TypeError)
self.assertEqual(type(exc.__context__), ValueError) self.assertEqual(type(exc.__context__), ValueError)
# we are still called from "except ValueError:" # we are still called from "except ValueError:"
self.assertEqual(sys.exc_info()[0], ValueError) self.assertIsInstance(sys.exception(), ValueError)
yield yield
self.assertIsNone(sys.exc_info()[0]) self.assertIsNone(sys.exception())
yield "done" yield "done"
g = gen() g = gen()
@ -353,7 +353,7 @@ class ExceptionTest(unittest.TestCase):
g.throw(exc) g.throw(exc)
self.assertEqual(next(g), "done") self.assertEqual(next(g), "done")
self.assertEqual(sys.exc_info(), (None, None, None)) self.assertIsNone(sys.exception())
def test_except_throw_bad_exception(self): def test_except_throw_bad_exception(self):
class E(Exception): class E(Exception):

View file

@ -5097,8 +5097,7 @@ class BasicConfigTest(unittest.TestCase):
message = [] message = []
def dummy_handle_error(record): def dummy_handle_error(record):
_, v, _ = sys.exc_info() message.append(str(sys.exception()))
message.append(str(v))
handler.handleError = dummy_handle_error handler.handleError = dummy_handle_error
logging.debug('The Øresund Bridge joins Copenhagen to Malmö') logging.debug('The Øresund Bridge joins Copenhagen to Malmö')

View file

@ -178,7 +178,7 @@ _ProfileOutput['print_stats'] = """\
8 63.976 7.997 79.960 9.995 profilee.py:98(subhelper)""" 8 63.976 7.997 79.960 9.995 profilee.py:98(subhelper)"""
_ProfileOutput['print_callers'] = """\ _ProfileOutput['print_callers'] = """\
:0(append) <- profilee.py:73(helper1)(4) 119.964 :0(append) <- profilee.py:73(helper1)(4) 119.964
:0(exc_info) <- profilee.py:73(helper1)(4) 119.964 :0(exception) <- profilee.py:73(helper1)(4) 119.964
:0(hasattr) <- profilee.py:73(helper1)(4) 119.964 :0(hasattr) <- profilee.py:73(helper1)(4) 119.964
profilee.py:88(helper2)(8) 399.912 profilee.py:88(helper2)(8) 399.912
profilee.py:110(__getattr__) <- :0(hasattr)(12) 11.964 profilee.py:110(__getattr__) <- :0(hasattr)(12) 11.964

View file

@ -253,7 +253,7 @@ def requires_tls_version(version):
def handle_error(prefix): def handle_error(prefix):
exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) exc_format = ' '.join(traceback.format_exception(sys.exception()))
if support.verbose: if support.verbose:
sys.stdout.write(prefix + exc_format) sys.stdout.write(prefix + exc_format)

View file

@ -1211,8 +1211,7 @@ class TracebackFormatTests(unittest.TestCase):
def test_recursive_traceback_cpython_internal(self): def test_recursive_traceback_cpython_internal(self):
from _testcapi import exception_print from _testcapi import exception_print
def render_exc(): def render_exc():
exc_type, exc_value, exc_tb = sys.exc_info() exception_print(sys.exception())
exception_print(exc_value)
self._check_recursive_traceback_display(render_exc) self._check_recursive_traceback_display(render_exc)
def test_format_stack(self): def test_format_stack(self):
@ -2470,8 +2469,8 @@ class TestTracebackException(unittest.TestCase):
try: try:
1/0 1/0
finally: finally:
exc_info_context = sys.exc_info() exc = sys.exception()
exc_context = traceback.TracebackException(*exc_info_context) exc_context = traceback.TracebackException.from_exception(exc)
cause = Exception("cause") cause = Exception("cause")
raise Exception("uh oh") from cause raise Exception("uh oh") from cause
except Exception as e: except Exception as e:
@ -2492,8 +2491,8 @@ class TestTracebackException(unittest.TestCase):
try: try:
1/0 1/0
finally: finally:
exc_info_context = sys.exc_info() exc = sys.exception()
exc_context = traceback.TracebackException(*exc_info_context) exc_context = traceback.TracebackException.from_exception(exc)
raise Exception("uh oh") raise Exception("uh oh")
except Exception as e: except Exception as e:
exc_obj = e exc_obj = e
@ -2557,8 +2556,8 @@ class TestTracebackException(unittest.TestCase):
try: try:
1/0 1/0
finally: finally:
exc_info_context = sys.exc_info() exc = sys.exception()
exc_context = traceback.TracebackException(*exc_info_context) exc_context = traceback.TracebackException.from_exception(exc)
raise Exception("uh oh") raise Exception("uh oh")
except Exception as e: except Exception as e:
exc_obj = e exc_obj = e