diff options
author | Victor Stinner <vstinner@redhat.com> | 2019-05-22 21:44:02 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-05-22 21:44:02 (GMT) |
commit | e4d300e07c33a9a77549c62d8687d8fe130c53d5 (patch) | |
tree | 165c92b9c1ff6f78bbffbcb4c7d68979091fc061 /Lib/test/support/__init__.py | |
parent | 904e34d4e6b6007986dcc585d5c553ee8ae06f95 (diff) | |
download | cpython-e4d300e07c33a9a77549c62d8687d8fe130c53d5.zip cpython-e4d300e07c33a9a77549c62d8687d8fe130c53d5.tar.gz cpython-e4d300e07c33a9a77549c62d8687d8fe130c53d5.tar.bz2 |
bpo-36829: Add test.support.catch_unraisable_exception() (GH-13490)
* Copy test_exceptions.test_unraisable() to
test_sys.UnraisableHookTest().
* Use catch_unraisable_exception() in test_coroutines,
test_exceptions, test_generators.
Diffstat (limited to 'Lib/test/support/__init__.py')
-rw-r--r-- | Lib/test/support/__init__.py | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/Lib/test/support/__init__.py b/Lib/test/support/__init__.py index 9e60d96..2fe9d9d 100644 --- a/Lib/test/support/__init__.py +++ b/Lib/test/support/__init__.py @@ -3034,3 +3034,36 @@ def collision_stats(nbins, nballs): collisions = k - occupied var = dn*(dn-1)*((dn-2)/dn)**k + meanempty * (1 - meanempty) return float(collisions), float(var.sqrt()) + + +class catch_unraisable_exception: + """ + Context manager catching unraisable exception using sys.unraisablehook. + + Usage: + + with support.catch_unraisable_exception() as cm: + ... + + # check the expected unraisable exception: use cm.unraisable + ... + + # cm.unraisable is None here (to break a reference cycle) + """ + + def __init__(self): + self.unraisable = None + self._old_hook = None + + def _hook(self, unraisable): + self.unraisable = unraisable + + def __enter__(self): + self._old_hook = sys.unraisablehook + sys.unraisablehook = self._hook + return self + + def __exit__(self, *exc_info): + # Clear the unraisable exception to explicitly break a reference cycle + self.unraisable = None + sys.unraisablehook = self._old_hook |