Skip to content

Commit a0b57b3

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

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
@@ -1234,10 +1234,12 @@ def test_sleep(self):
12341234
re.compile('%s timed out' % testname, re.MULTILINE))
12351235

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

@@ -1260,6 +1264,7 @@ def test_unraisable_exc(self):
12601264
env_changed=[testname],
12611265
fail_env_changed=True)
12621266
self.assertIn("Warning -- Unraisable exception", output)
1267+
self.assertIn("Exception: weakref callback bug", output)
12631268

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

0 commit comments

Comments
 (0)