Skip to content

Commit 701b638

Browse files
authored
bpo-38912: regrtest logs unraisable exception into sys.__stderr__ (GH-21718)
regrtest_unraisable_hook() temporarily replaces sys.stderr with sys.__stderr__ to help to display errors when a test captures stderr.
1 parent 4660597 commit 701b638

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

Lib/test/libregrtest/utils.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,12 @@ def regrtest_unraisable_hook(unraisable):
7272
global orig_unraisablehook
7373
support.environment_altered = True
7474
print_warning("Unraisable exception")
75-
orig_unraisablehook(unraisable)
75+
old_stderr = sys.stderr
76+
try:
77+
sys.stderr = sys.__stderr__
78+
orig_unraisablehook(unraisable)
79+
finally:
80+
sys.stderr = old_stderr
7681

7782

7883
def setup_unraisable_hook():

Lib/test/test_regrtest.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1235,10 +1235,12 @@ def test_sleep(self):
12351235
re.compile('%s timed out' % testname, re.MULTILINE))
12361236

12371237
def test_unraisable_exc(self):
1238-
# --fail-env-changed must catch unraisable exception
1238+
# --fail-env-changed must catch unraisable exception.
1239+
# The exceptioin must be displayed even if sys.stderr is redirected.
12391240
code = textwrap.dedent(r"""
12401241
import unittest
12411242
import weakref
1243+
from test.support import captured_stderr
12421244
12431245
class MyObject:
12441246
pass
@@ -1250,9 +1252,11 @@ class Tests(unittest.TestCase):
12501252
def test_unraisable_exc(self):
12511253
obj = MyObject()
12521254
ref = weakref.ref(obj, weakref_callback)
1253-
# call weakref_callback() which logs
1254-
# an unraisable exception
1255-
obj = None
1255+
with captured_stderr() as stderr:
1256+
# call weakref_callback() which logs
1257+
# an unraisable exception
1258+
obj = None
1259+
self.assertEqual(stderr.getvalue(), '')
12561260
""")
12571261
testname = self.create_test(code=code)
12581262

@@ -1261,6 +1265,7 @@ def test_unraisable_exc(self):
12611265
env_changed=[testname],
12621266
fail_env_changed=True)
12631267
self.assertIn("Warning -- Unraisable exception", output)
1268+
self.assertIn("Exception: weakref callback bug", output)
12641269

12651270
def test_cleanup(self):
12661271
dirname = os.path.join(self.tmptestdir, "test_python_123")

0 commit comments

Comments
 (0)