diff --git a/core/event.py b/core/event.py new file mode 100644 index 0000000..1aeccaa --- /dev/null +++ b/core/event.py @@ -0,0 +1,13 @@ + +callbacks = {} + +def register(event, callback, *args, **kwargs): + callbacks.setdefault(event, []).append( + lambda: callback(*args, **kwargs) + ) + +def trigger(event): + for callback in callbacks.get(event, []): + callback() + +# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 diff --git a/tests/core/test_event.py b/tests/core/test_event.py new file mode 100644 index 0000000..7a35852 --- /dev/null +++ b/tests/core/test_event.py @@ -0,0 +1,46 @@ +import unittest + +import core.event + + +class event(unittest.TestCase): + def setUp(self): + self.someEvent = 'event' + self.called = {} + self.params = [] + + def callback1(self): + self.called['callback1'] = True + + def callback2(self): + self.called['callback2'] = True + + def callback_args(self, val1, val2): + self.called['callback_args'] = True + self.params = [val1, val2] + + def callback_kwargs(self, val1, val2, key1=None, key2=None): + self.called['callback_kwargs'] = True + self.params = [val1, val2, key1, key2] + + def test_simple_callback(self): + core.event.register(self.someEvent, self.callback1) + core.event.register(self.someEvent, self.callback2) + + core.event.trigger(self.someEvent) + + self.assertEqual(2, len(self.called.keys())) + + def test_arg_callback(self): + core.event.register(self.someEvent, self.callback_args, 'a', 'b') + core.event.trigger(self.someEvent) + self.assertEqual(1, len(self.called.keys())) + self.assertEqual(['a', 'b'], self.params) + + def test_kwargs_callback(self): + core.event.register(self.someEvent, self.callback_kwargs, 'a', 'b', key1='test', key2='x') + core.event.trigger(self.someEvent) + self.assertEqual(1, len(self.called.keys())) + self.assertEqual(['a', 'b', 'test', 'x'], self.params) + +# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4