def test_remove_callback(self): listener_collection = collections.Listener() cb = lambda x: x cb2 = lambda y: y listener_collection.add(cb) assert len(listener_collection) == 1 listener_collection.add(cb2) listener_collection.remove(cb) assert len(listener_collection) == 1
def test_sort_priority(self): listener_collection = collections.Listener() cb1 = lambda x: x cb2 = lambda y: y cb3 = lambda z: z listener_collection.add(cb1, priority=10) listener_collection.add(cb2, priority=30) listener_collection.add(cb3, priority=20) listener_collection.sort_priority() assert listener_collection[0][0] == cb2 assert listener_collection[2][0] == cb1 assert listener_collection[1][0] == cb3
def remove(self, event, callback=None): """Remove an event listener from the dispatcher. Removes an event listener from the relevant Listener. If no callback is specified, all event listeners for that event are removed. Args: string event: The name of the event callable callback: A callable function to be triggered Returns: Listener: A list of listeners attached to the event """ event = str(event) if event not in self or not callback: self.events[event] = collections.Listener() if callback: self.events[event].remove(callback) return self.events[event]
def add(self, event, callback, priority=1, only_once=False): """Add an event listener to the dispatcher. Adds an event listener to the relevant event listener collection. If a listener is set to once_only, it will be removed when the event is triggered on the EventDispatcher. Args: string event: The name of the event callable callback: A callable function to be triggered int priority: The priority of the listener (higher == more important) boolean once_only: When triggered, the listener will be removed Returns: ListCollection: A list of listeners attached to the event """ event = str(event) if event not in self.events: self.events[event] = collections.Listener() self.events[event].add(callback, int(priority), bool(only_once)) return self.events[event]
def test_create_listener(self): assert repr(collections.Listener() ) == '<watson.events.collections.Listener callbacks:0>'
def test_collection_has_callback(self): listener_collection = collections.Listener() cb = lambda x: x listener_collection.add(cb) assert cb in listener_collection
def test_add_invalid_callback(self): listener_collection = collections.Listener() listener_collection.add('test')
def test_add_callback(self): listener_collection = collections.Listener() listener_collection.add(lambda x: x, priority=1) assert repr(listener_collection ) == '<watson.events.collections.Listener callbacks:1>'