def test_event_interceptor(): global count count = 0 hub = qcore.EventHub() hub.on_a.trigger() hub.on_b.trigger() assert_eq(0, count) assert_eq([], list(hub.on_a)) assert_eq([], list(hub.on_b)) a_handler = lambda: handler(0) b_handler = lambda: handler(1) with qcore.EventInterceptor(hub, on_a=a_handler, on_b=b_handler): assert_eq([a_handler], list(hub.on_a)) assert_eq([b_handler], list(hub.on_b)) hub.on_a.trigger() hub.on_b.trigger() assert_eq(2, count) assert_eq([], list(hub.on_a)) assert_eq([], list(hub.on_b)) hub.on_a.trigger() hub.on_b.trigger() assert_eq(2, count)
def test_events_hub_with_source(): def handler(): pass hook = qcore.EventHook() hook.subscribe(handler) assert_eq([handler], list(hook)) hub = qcore.EventHub(source={'on_something': hook}) assert_eq([handler], list(hub.on_something))
def test_event_hub(): h = qcore.EventHub() assert_eq(0, len(h)) assert_eq('EventHub({})', repr(h)) with AssertRaises(AttributeError): h.doesnt_start_with_on h_e = h.on_e assert_is_instance(h_e, qcore.EventHook) assert_eq(1, len(h)) assert_is(h_e, h['e']) assert_eq("EventHub({'e': %r})" % h_e, repr(h)) assert_is(h, h.safe_trigger('e')) assert_is(h, h.trigger('e')) h_e.subscribe(lambda: 0) assert_in('e', h) assert_not_in('f', h) h['f'] = None assert_is(None, h['f']) assert_in('f', h) assert_eq(2, len(h)) del h['f'] assert_not_in('f', h) assert_eq(1, len(h)) for k, v in h: assert_eq('e', k) assert_is(h_e, v) def bad_fn(*args): raise NotImplementedError() m = mock.MagicMock() h.on_test.subscribe(bad_fn) with AssertRaises(NotImplementedError): h.on('test', m).safe_trigger('test', 1) m.assert_called_once_with(1) m.reset_mock() h.off('test', bad_fn).trigger('test', 2, 3) m.assert_called_once_with(2, 3)
def test_events(): e = qcore.EventHook() e.subscribe(lambda *args: dump("Handler 1", *args)) e("argument") e.subscribe(lambda: fail("Handler 2")) e.subscribe(lambda: dump("Handler 3")) with AssertRaises(NotImplementedError): e() # prints 'Handler 1' with AssertRaises(NotImplementedError): e.safe_trigger() # prints 'Handler 1', 'Handler 3' h = qcore.EventHub() h.on_some_event.subscribe(lambda: dump("On some event")) h.on_some_other_event.subscribe(lambda: dump("On some other event")) h.on_some_event() h.on_some_other_event()