bpo-43843: libregrtest uses threading.excepthook (GH-25400)

test.libregrtest now marks a test as ENV_CHANGED (altered the
execution environment) if a thread raises an exception but does not
catch it. It sets a hook on threading.excepthook. Use
--fail-env-changed option to mark the test as failed.

libregrtest regrtest_unraisable_hook() explicitly flushs
sys.stdout, sys.stderr and sys.__stderr__.
diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py
index 49a4af8..f44f17f 100644
--- a/Lib/test/test_threading.py
+++ b/Lib/test/test_threading.py
@@ -32,6 +32,11 @@
 platforms_to_skip = ('netbsd5', 'hp-ux11')
 
 
+def restore_default_excepthook(testcase):
+    testcase.addCleanup(setattr, threading, 'excepthook', threading.excepthook)
+    threading.excepthook = threading.__excepthook__
+
+
 # A trivial mutable counter.
 class Counter(object):
     def __init__(self):
@@ -427,6 +432,8 @@ def _run(self, other_ref, yet_another):
                 if self.should_raise:
                     raise SystemExit
 
+        restore_default_excepthook(self)
+
         cyclic_object = RunSelfFunction(should_raise=False)
         weak_cyclic_object = weakref.ref(cyclic_object)
         cyclic_object.thread.join()
@@ -1331,6 +1338,10 @@ def run(self):
 
 
 class ExceptHookTests(BaseTestCase):
+    def setUp(self):
+        restore_default_excepthook(self)
+        super().setUp()
+
     def test_excepthook(self):
         with support.captured_output("stderr") as stderr:
             thread = ThreadRunFail(name="excepthook thread")
@@ -1501,6 +1512,8 @@ class BarrierTests(lock_tests.BarrierTests):
 
 class MiscTestCase(unittest.TestCase):
     def test__all__(self):
+        restore_default_excepthook(self)
+
         extra = {"ThreadError"}
         not_exported = {'currentThread', 'activeCount'}
         support.check__all__(self, threading, ('threading', '_thread'),