gh-92118: fix traceback of exceptions propagated from inside a contextlib.contextmanager (GH-92202)

This commit is contained in:
Irit Katriel 2022-05-04 14:40:47 -04:00 committed by GitHub
parent f8a2fab212
commit e61330b44f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 31 additions and 0 deletions

View file

@ -5,6 +5,7 @@ import os
import sys
import tempfile
import threading
import traceback
import unittest
from contextlib import * # Tests __all__
from test import support
@ -87,6 +88,32 @@ class ContextManagerTestCase(unittest.TestCase):
raise ZeroDivisionError()
self.assertEqual(state, [1, 42, 999])
def test_contextmanager_traceback(self):
@contextmanager
def f():
yield
try:
with f():
1/0
except ZeroDivisionError as e:
frames = traceback.extract_tb(e.__traceback__)
self.assertEqual(len(frames), 1)
self.assertEqual(frames[0].name, 'test_contextmanager_traceback')
self.assertEqual(frames[0].line, '1/0')
# Repeat with RuntimeError (which goes through a different code path)
try:
with f():
raise NotImplementedError(42)
except NotImplementedError as e:
frames = traceback.extract_tb(e.__traceback__)
self.assertEqual(len(frames), 1)
self.assertEqual(frames[0].name, 'test_contextmanager_traceback')
self.assertEqual(frames[0].line, 'raise NotImplementedError(42)')
def test_contextmanager_no_reraise(self):
@contextmanager
def whee():