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 701b63894f)
This commit is contained in:
Victor Stinner 2020-08-11 17:03:33 +02:00 committed by GitHub
parent 2cd58d8bb1
commit a0b57b3317
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 5 deletions

View File

@ -72,7 +72,12 @@ def regrtest_unraisable_hook(unraisable):
global orig_unraisablehook
support.environment_altered = True
print_warning("Unraisable exception")
orig_unraisablehook(unraisable)
old_stderr = sys.stderr
try:
sys.stderr = sys.__stderr__
orig_unraisablehook(unraisable)
finally:
sys.stderr = old_stderr
def setup_unraisable_hook():

View File

@ -1234,10 +1234,12 @@ class ArgsTestCase(BaseTestCase):
re.compile('%s timed out' % testname, re.MULTILINE))
def test_unraisable_exc(self):
# --fail-env-changed must catch unraisable exception
# --fail-env-changed must catch unraisable exception.
# The exceptioin must be displayed even if sys.stderr is redirected.
code = textwrap.dedent(r"""
import unittest
import weakref
from test.support import captured_stderr
class MyObject:
pass
@ -1249,9 +1251,11 @@ class ArgsTestCase(BaseTestCase):
def test_unraisable_exc(self):
obj = MyObject()
ref = weakref.ref(obj, weakref_callback)
# call weakref_callback() which logs
# an unraisable exception
obj = None
with captured_stderr() as stderr:
# call weakref_callback() which logs
# an unraisable exception
obj = None
self.assertEqual(stderr.getvalue(), '')
""")
testname = self.create_test(code=code)
@ -1260,6 +1264,7 @@ class ArgsTestCase(BaseTestCase):
env_changed=[testname],
fail_env_changed=True)
self.assertIn("Warning -- Unraisable exception", output)
self.assertIn("Exception: weakref callback bug", output)
def test_cleanup(self):
dirname = os.path.join(self.tmptestdir, "test_python_123")