Skip to content

Commit

Permalink
Rework exception handling in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mdickinson committed May 3, 2024
1 parent b97a36c commit cc8653e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
15 changes: 8 additions & 7 deletions traits/tests/test_ui_notifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,6 @@ def setUp(self):
self.exceptions = []
self.done = asyncio.Event()
self.obj = self.obj_factory()
trait_notifiers.push_exception_handler(self.handle_exception)
self.addCleanup(trait_notifiers.pop_exception_handler)

def enterContext(self, cm):
# Backport of Python 3.11's TestCase.enterContext method.
Expand All @@ -111,13 +109,14 @@ def enterContext(self, cm):

#### 'TestUINotifiers' protocol ###########################################

def handle_exception(self, object, name, old, new):
self.exceptions.append((object, name, old, new))

def modify_obj(self):
trait_notifiers.push_exception_handler(self.handle_exception)
trait_notifiers.push_exception_handler(
lambda *args: None, reraise_exceptions=True
)
try:
self.obj.foo = 3
except Exception as e:
self.exceptions.append(e)
finally:
trait_notifiers.pop_exception_handler()

Expand Down Expand Up @@ -167,7 +166,9 @@ def test_notification_from_separate_thread_failure_case(self):
self.assertEqual(self.notifications, [])

# ... and an error was raised
self.assertEqual(self.exceptions, [(self.obj, "foo", 0, 3)])
self.assertEqual(len(self.exceptions), 1)
self.assertIsInstance(self.exceptions[0], RuntimeError)
self.assertIn("no UI handler registered", str(self.exceptions[0]))

# ... but the attribute change was still applied.
self.assertEqual(self.obj.foo, 3)
Expand Down
4 changes: 3 additions & 1 deletion traits/trait_notifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def ui_dispatch(handler, *args, **kw):
if threading.current_thread() == threading.main_thread():
handler(*args, **kw)
elif _ui_handler is None:
raise RuntimeError("No UI handler has been set.")
raise RuntimeError("no UI handler registered for dispatch='ui'")
else:
_ui_handler(handler, *args, **kw)

Expand Down Expand Up @@ -616,6 +616,8 @@ class FastUITraitChangeNotifyWrapper(TraitChangeNotifyWrapper):
def dispatch(self, handler, *args):
if threading.current_thread() == threading.main_thread():
handler(*args)
elif _ui_handler is None:
raise RuntimeError("no UI handler registered for dispatch='ui'")
else:
_ui_handler(handler, *args)

Expand Down

0 comments on commit cc8653e

Please sign in to comment.