def useNotifyByPubsubMessage(pubModule=None, topicMgr=None, all=True, **kwargs): '''Will cause all of pubsub's notifications of pubsub "actions" (such as new topic created, message sent, listener subscribed, etc) to be sent out as messages. Topic will be 'pubsub' subtopics, such as 'pubsub.newTopic', 'pubsub.delTopic', 'pubsub.sendMessage', etc. The 'all' and kwargs args are the same as pubsub's setNotificationFlags(), except that 'all' defaults to True. The pubModule and topicMgr are rarely needed: * The pubModule only needs to be specfied if pubsub is not installed on the system search path (ie from pubsub import ... would fail or import wrong pubsub -- such as if pubsub is within wxPython's wx.lib package). Then pbuModule is the pub module to use:: from wx.lib.pubsub import pub from wx.lib.pubsub.utils import notification notification.useNotifyByPubsubMessage(pub) * The topicMgr only needs to be specified if you are not using the default topic manager created by pubsub.pub (or by provided pubModule). ''' if pubModule is None: from pubsub import pub as pubModule if topicMgr is None: topicMgr = pubModule.getDefaultTopicMgr() notifHandler = NotifyByPubsubMessage( topicMgr ) pubModule.addNotificationHandler(notifHandler) pubModule.setNotificationFlags(all=all, **kwargs)
def test_SendNotify(): # trap the pubsub.sendMessage topic: class SendHandler: def __init__(self): self.pre = self.post = 0 def __call__(self, topic=None, stage=None, listener=None, msgTopic=pub.AUTO_TOPIC): if stage == 'pre': self.pre += 1 else: self.post += 1 assert msgTopic.getName() == 'pubsub.sendMessage' assert topic.getName() == 'testSendNotify' sh = SendHandler() pub.subscribe(sh, 'pubsub.sendMessage') pub.setNotificationFlags(sendMessage=True) # generate a message that will cause pubsub.sendMessage to be generated too assert sh.pre == 0 assert sh.post == 0 topicMgr.getOrCreateTopic('testSendNotify') pub.sendMessage('testSendNotify') assert sh.pre == 1 assert sh.post == 1
def useNotifyByPubsubMessage(pubModule=None, topicMgr=None, all=True, **kwargs): '''Will cause all of pubsub's notifications of pubsub "actions" (such as new topic created, message sent, listener subscribed, etc) to be sent out as messages. Topic will be 'pubsub' subtopics, such as 'pubsub.newTopic', 'pubsub.delTopic', 'pubsub.sendMessage', etc. The 'all' and kwargs args are the same as pubsub's setNotificationFlags(), except that 'all' defaults to True. The pubModule and topicMgr are rarely needed: * The pubModule only needs to be specfied if pubsub is not installed on the system search path (ie from pubsub import ... would fail or import wrong pubsub -- such as if pubsub is within wxPython's wx.lib package). Then pbuModule is the pub module to use:: from wx.lib.pubsub import pub from wx.lib.pubsub.utils import notification notification.useNotifyByPubsubMessage(pub) * The topicMgr only needs to be specified if you are not using the default topic manager created by pubsub.pub (or by provided pubModule). ''' if pubModule is None: from pubsub import pub as pubModule if topicMgr is None: topicMgr = pubModule.getDefaultTopicMgr() notifHandler = NotifyByPubsubMessage(topicMgr) pubModule.addNotificationHandler(notifHandler) pubModule.setNotificationFlags(all=all, **kwargs)
def testDeadListener(): # create a listener for listeners that have died class DeathListener(IgnoreNotificationsMixin): listenerStr = '' def notifyDeadListener(self, pubListener, topicObj): assert topicObj.getName() == 'sadTopic' #import pdb; pdb.set_trace() #print 'hi again' DeathListener.listenerStr = pubListener.name() dl = DeathListener() pub.addNotificationHandler( dl ) pub.setNotificationFlags(deadListener=True) # define a topic, subscribe to it, and kill its listener: class TempListener: def __call__(self, **kwargs): pass def __del__(self): # print 'being deleted' pass #def tempListener(): pass tempListener = TempListener() expectLisrStr, _ = getListenerID(tempListener) pub.subscribe(tempListener, 'sadTopic') del tempListener # verify: gc.collect() # for pypy: the gc doesn't work the same as cpython's assert DeathListener.listenerStr.startswith(expectLisrStr), \ '"%s" !~ "%s"' % (DeathListener.listenerStr, expectLisrStr) pub.addNotificationHandler(None) pub.clearNotificationHandlers()
def OnNotifyAll(self, evt): val = evt.IsChecked() self.subBtn.SetValue(val) self.unsubBtn.SetValue(val) self.sendBtn.SetValue(val) self.newTBtn.SetValue(val) self.delTBtn.SetValue(val) self.deadBtn.SetValue(val) pub.setNotificationFlags(all=val)
def test_SubscribeNotify(): class MyListener: countSub = 0 countUnsub = 0 def listenerSub(self, msgTopic=pub.AUTO_TOPIC, listener=None, topic=None, newSub=None): assert msgTopic.getName() == 'pubsub.subscribe' assert topic.getName() in ('pubsub.unsubscribe', 'testSubscribeNotify') if newSub: self.countSub += 1 def listenerUnsub(self, msgTopic=pub.AUTO_TOPIC, topic=None, listener=None, listenerRaw=None): assert topic.getName() in ('testSubscribeNotify', 'pubsub.subscribe') assert msgTopic.getName() == 'pubsub.unsubscribe' if listener is not None: self.countUnsub += 1 def listenerTest(self): raise NotImplementedError # should never get here pub.setNotificationFlags(subscribe=True, unsubscribe=True) topicMgr.getOrCreateTopic('testSubscribeNotify') tmp = MyListener() pub.subscribe(tmp.listenerSub, 'pubsub.subscribe') assert tmp.countSub == 0 # don't notify of self subscription assert tmp.countUnsub == 0 sl, ok = pub.subscribe(tmp.listenerUnsub, 'pubsub.unsubscribe') assert ok assert tmp.countSub == 1 assert tmp.countUnsub == 0 pub.subscribe(tmp.listenerTest, 'testSubscribeNotify') #assert_equal(tmp.countSub, 2) assert tmp.countUnsub == 0 pub.unsubscribe(tmp.listenerTest, 'testSubscribeNotify') #assert_equal(tmp.countSub, 2) assert tmp.countUnsub == 1 pub.unsubscribe(tmp.listenerSub, 'pubsub.subscribe') assert tmp.countSub == 2 assert tmp.countUnsub == 2 pub.unsubscribe(tmp.listenerUnsub, 'pubsub.unsubscribe') assert tmp.countSub == 2 assert tmp.countUnsub == 2 # don't notify of self unsubscription
def useNotifyByPubsubMessage(all=True, **kwargs): '''Will cause all pubsub notifications of pubsub "actions" (such as new topic created, message sent, listener died etc) to be sent out as messages of 'pubsub' subtopics, such as 'pubsub.newTopic', 'pubsub.delTopic', 'pubsub.sendMessage', etc. The arguments are those of pubsub's setNotificationFlags(), except that 'all' defaults to True instead of False. ''' from pubsub import pub notifHandler = NotifyByPubsubMessage(createTopics=True) pub.addNotificationHandler(notifHandler) pub.setNotificationFlags(all=all, **kwargs)
def useNotifyByWriteFile(fileObj=None, prefix=None, all=True, **kwargs): '''Will cause all pubsub notifications of pubsub "actions" (such as new topic created, message sent, listener died etc) to be written to specified file (or stdout if none given). The fileObj need only provide a 'write(string)' method. The first two arguments are the same as those of NotifyByWriteFile constructor. The remaining arguments are those of pubsub's setNotificationFlags(), except that 'all' defaults to True instead of False. ''' from pubsub import pub notifHandler = NotifyByWriteFile(fileObj, prefix) pub.addNotificationHandler(notifHandler) pub.setNotificationFlags(all=all, **kwargs)
def testFlagChanges(): savedFlags = pub.getNotificationFlags() pub.setNotificationFlags(all=True, sendMessage=False, deadListener=False) flags = pub.getNotificationFlags() assert not flags['sendMessage'] assert not flags['deadListener'] assert flags['newTopic'] assert flags['delTopic'] assert flags['subscribe'] assert flags['unsubscribe'] pub.setNotificationFlags(subscribe=False, deadListener=True) flags = pub.getNotificationFlags() assert not flags['sendMessage'] assert not flags['subscribe'] assert flags['newTopic'] assert flags['delTopic'] assert flags['deadListener'] assert flags['unsubscribe'] pub.setNotificationFlags(all=False, subscribe=True, unsubscribe=True) flags = pub.getNotificationFlags() assert not flags['sendMessage'] assert not flags['deadListener'] assert not flags['newTopic'] assert not flags['delTopic'] assert flags['subscribe'] assert flags['unsubscribe'] pub.setNotificationFlags(** savedFlags)
def testFlagChanges(): savedFlags = pub.getNotificationFlags() pub.setNotificationFlags(all=True, sendMessage=False, deadListener=False) flags = pub.getNotificationFlags() assert not flags['sendMessage'] assert not flags['deadListener'] assert flags['newTopic'] assert flags['delTopic'] assert flags['subscribe'] assert flags['unsubscribe'] pub.setNotificationFlags(subscribe=False, deadListener=True) flags = pub.getNotificationFlags() assert not flags['sendMessage'] assert not flags['subscribe'] assert flags['newTopic'] assert flags['delTopic'] assert flags['deadListener'] assert flags['unsubscribe'] pub.setNotificationFlags(all=False, subscribe=True, unsubscribe=True) flags = pub.getNotificationFlags() assert not flags['sendMessage'] assert not flags['deadListener'] assert not flags['newTopic'] assert not flags['delTopic'] assert flags['subscribe'] assert flags['unsubscribe'] pub.setNotificationFlags(**savedFlags)
def useNotifyByWriteFile(fileObj=None, prefix=None, pubModule=None, all=True, **kwargs): '''Will cause all pubsub notifications of pubsub "actions" (such as new topic created, message sent, listener died etc) to be written to specified file (or stdout if none given). The fileObj need only provide a 'write(string)' method. The first two arguments are the same as those of NotifyByWriteFile constructor. The 'all' and kwargs arguments are those of pubsub's setNotificationFlags(), except that 'all' defaults to True. See useNotifyByPubsubMessage() for an explanation of pubModule (typically only if pubsub inside wxPython's wx.lib)''' if pubModule is None: from pubsub import pub as pubModule notifHandler = NotifyByWriteFile(fileObj, prefix) pubModule.addNotificationHandler(notifHandler) pubModule.setNotificationFlags(all=all, **kwargs)
def test1_SubscribeNotify(): class MyListener: countSub = 0 countUnsub = 0 def listenerSub(self, msgTopic=pub.AUTO_TOPIC, listener=None, topic=None, newSub=None): assert msgTopic.getName() == 'pubsub.subscribe' assert topic.getName() in ('pubsub.unsubscribe', 'testSubscribeNotify') if newSub: self.countSub += 1 def listenerUnsub(self, msgTopic=pub.AUTO_TOPIC, topic=None, listener=None, listenerRaw=None): assert topic.getName() in ('testSubscribeNotify', 'pubsub.subscribe' ) assert msgTopic.getName() == 'pubsub.unsubscribe' if listener is not None: self.countUnsub += 1 def listenerTest(self): raise NotImplementedError # should never get here pub.setNotificationFlags(subscribe=True, unsubscribe=True) topicMgr.getOrCreateTopic('testSubscribeNotify') tmp = MyListener() pub.subscribe(tmp.listenerSub, 'pubsub.subscribe') assert tmp.countSub == 0 # don't notify of self subscription assert tmp.countUnsub == 0 sl, ok = pub.subscribe(tmp.listenerUnsub, 'pubsub.unsubscribe') assert ok assert tmp.countSub == 1 assert tmp.countUnsub == 0 pub.subscribe(tmp.listenerTest, 'testSubscribeNotify') #assert_equal(tmp.countSub, 2) assert tmp.countUnsub == 0 pub.unsubscribe(tmp.listenerTest, 'testSubscribeNotify') #assert_equal(tmp.countSub, 2) assert tmp.countUnsub == 1 pub.unsubscribe(tmp.listenerSub, 'pubsub.subscribe') assert tmp.countSub == 2 assert tmp.countUnsub == 2 pub.unsubscribe(tmp.listenerUnsub, 'pubsub.unsubscribe') assert tmp.countSub == 2 assert tmp.countUnsub == 2 # don't notify of self unsubscription
def testHandleExcept1a(): from pubsub.utils.exchandling import ExcPublisher excPublisher = ExcPublisher( pub.getDefaultTopicMgr() ) pub.setListenerExcHandler(excPublisher) # create a listener that raises an exception: from raisinglistener import getRaisingListener raisingListener = getRaisingListener() pub.setNotificationFlags(all=False) pub.subscribe(raisingListener, 'testHandleExcept1a') # first test when a listener raises an exception and exception listener also raises! class BadUncaughtExcListener: def __call__(self, listenerStr=None, excTraceback=None): raise RuntimeError('bad exception listener!') handler = BadUncaughtExcListener() pub.subscribe(handler, ExcPublisher.topicUncaughtExc) pytest.raises(pub.ExcHandlerError, pub.sendMessage, 'testHandleExcept1a') pub.unsubscribe(handler, ExcPublisher.topicUncaughtExc)
def testHandleExcept1a(): from pubsub.utils.exchandling import ExcPublisher excPublisher = ExcPublisher(pub.getDefaultTopicMgr()) pub.setListenerExcHandler(excPublisher) # create a listener that raises an exception: from raisinglistener import getRaisingListener raisingListener = getRaisingListener() pub.setNotificationFlags(all=False) pub.subscribe(raisingListener, 'testHandleExcept1a') # first test when a listener raises an exception and exception listener also raises! class BadUncaughtExcListener: def __call__(self, listenerStr=None, excTraceback=None): raise RuntimeError('bad exception listener!') handler = BadUncaughtExcListener() pub.subscribe(handler, ExcPublisher.topicUncaughtExc) pytest.raises(pub.ExcHandlerError, pub.sendMessage, 'testHandleExcept1a') pub.unsubscribe(handler, ExcPublisher.topicUncaughtExc)
def test2_SendNotify(): # trap the pubsub.sendMessage topic: class SendHandler: def __init__(self): self.pre = self.post = 0 def __call__(self, topic=None, stage=None, listener=None, msgTopic=pub.AUTO_TOPIC): if stage == 'pre': self.pre += 1 else: self.post += 1 assert msgTopic.getName() == 'pubsub.sendMessage' assert topic.getName() == 'testSendNotify' sh = SendHandler() pub.subscribe(sh, 'pubsub.sendMessage') pub.setNotificationFlags(sendMessage=True) # generate a message that will cause pubsub.sendMessage to be generated too assert sh.pre == 0 assert sh.post == 0 topicMgr.getOrCreateTopic('testSendNotify') pub.sendMessage('testSendNotify') assert sh.pre == 1 assert sh.post == 1
def OnDead(self, evt): pub.setNotificationFlags(deadListener=evt.IsChecked())
def OnDelTopic(self, evt): pub.setNotificationFlags(delTopic=evt.IsChecked())
def OnNewTopic(self, evt): pub.setNotificationFlags(newTopic=evt.IsChecked())
def OnSendMessage(self, evt): pub.setNotificationFlags(sendMessage=evt.IsChecked())
def OnUnsubscribe(self, evt): pub.setNotificationFlags(unsubscribe=evt.IsChecked())
def OnClose(self, evt): """Turn off notifications before closing down """ pub.setNotificationFlags(all=False) evt.Skip()
def testNotifications(): class Handler(INotificationHandler): def __init__(self): self.resetCounts() def resetCounts(self): self.counts = dict(send=0, sub=0, unsub=0, delt=0, newt=0, dead=0, all=0) def notifySubscribe(self, pubListener, topicObj, newSub): self.counts['sub'] += 1 def notifyUnsubscribe(self, pubListener, topicObj): self.counts['unsub'] += 1 def notifyDeadListener(self, pubListener, topicObj): self.counts['dead'] += 1 def notifySend(self, stage, topicObj, pubListener=None): if stage == 'pre': self.counts['send'] += 1 def notifyNewTopic(self, topicObj, description, required, argsDocs): self.counts['newt'] += 1 def notifyDelTopic(self, topicName): self.counts['delt'] += 1 notifiee = Handler() pub.addNotificationHandler(notifiee) pub.setNotificationFlags(all=True) def verify(**ref): gc.collect() # for pypy: the gc doesn't work the same as cpython's for key, val in notifiee.counts.items(): if key in ref: assert val == ref[key], "\n%s\n%s" % (notifiee.counts, ref) else: assert val == 0, "%s = %s, expected 0" % (key, val) notifiee.resetCounts() verify() def testListener(): pass def testListener2(): pass def testListener3(): pass class TestListener: def __call__(self): pass def __del__(self): pass testListener = TestListener() topicMgr = pub.getDefaultTopicMgr() topicMgr.getOrCreateTopic('newTopic') verify(newt=1) pub.subscribe(testListener, 'newTopic') pub.subscribe(testListener2, 'newTopic') pub.subscribe(testListener3, 'newTopic') verify(sub=3) pub.sendMessage('newTopic') verify(send=1) verify(dead=0) del testListener del testListener3 verify(dead=2) pub.unsubscribe(testListener2,'newTopic') verify(unsub=1) topicMgr.delTopic('newTopic') verify(delt=1)
# # Date: 20-Aug-2008 # Last Rev: 127 (Last revision this code was checked with) # ------------------------------------- # NOTE: The Tool and Mixin components (including the # docstrings) borrow heavily on Robin Dunn's wxInspectionTool ### Next problem: TreeCtrl doesn't send messages... import wx from pubsub import pub import pubsub.utils as utils from pubsub import pubsubconf as conf conf.setNotifierClass(utils.NotifyByPubsubMessage) pub.setNotificationFlags(all=True) ### MonitorTopics ### Three topics for Pypubsub messages to control the monitor class MonitorTopics(utils.TopicTreeDefnSimple): class monitor: """Messages controlling the monitor""" class show: """Shows or hides the monitor""" show = "Boolean value to show (True) or hide (False) the monitor" _required = ('show', ) class hide: """Hides the monitor. Same as message ('monitor.show', show=False)"""
def testNotifications(): class Handler(INotificationHandler): def __init__(self): self.resetCounts() def resetCounts(self): self.counts = dict(send=0, sub=0, unsub=0, delt=0, newt=0, dead=0, all=0) def notifySubscribe(self, pubListener, topicObj, newSub): self.counts['sub'] += 1 def notifyUnsubscribe(self, pubListener, topicObj): self.counts['unsub'] += 1 def notifyDeadListener(self, pubListener, topicObj): self.counts['dead'] += 1 def notifySend(self, stage, topicObj, pubListener=None): if stage == 'pre': self.counts['send'] += 1 def notifyNewTopic(self, topicObj, description, required, argsDocs): self.counts['newt'] += 1 def notifyDelTopic(self, topicName): self.counts['delt'] += 1 notifiee = Handler() pub.addNotificationHandler(notifiee) pub.setNotificationFlags(all=True) def verify(**ref): gc.collect() # for pypy: the gc doesn't work the same as cpython's for key, val in notifiee.counts.items(): if key in ref: assert val == ref[key], "\n%s\n%s" % (notifiee.counts, ref) else: assert val == 0, "%s = %s, expected 0" % (key, val) notifiee.resetCounts() verify() def testListener(): pass def testListener2(): pass def testListener3(): pass class TestListener: def __call__(self): pass def __del__(self): pass testListener = TestListener() topicMgr = pub.getDefaultTopicMgr() topicMgr.getOrCreateTopic('newTopic') verify(newt=1) pub.subscribe(testListener, 'newTopic') pub.subscribe(testListener2, 'newTopic') pub.subscribe(testListener3, 'newTopic') verify(sub=3) pub.sendMessage('newTopic') verify(send=1) verify(dead=0) del testListener del testListener3 verify(dead=2) pub.unsubscribe(testListener2, 'newTopic') verify(unsub=1) topicMgr.delTopic('newTopic') verify(delt=1)
# # Date: 20-Aug-2008 # Last Rev: 127 (Last revision this code was checked with) # ------------------------------------- # NOTE: The Tool and Mixin components (including the # docstrings) borrow heavily on Robin Dunn's wxInspectionTool ### Next problem: TreeCtrl doesn't send messages... import wx from pubsub import pub import pubsub.utils as utils from pubsub import pubsubconf as conf conf.setNotifierClass(utils.NotifyByPubsubMessage) pub.setNotificationFlags(all=True) ### MonitorTopics ### Three topics for Pypubsub messages to control the monitor class MonitorTopics(utils.TopicTreeDefnSimple): class monitor: """Messages controlling the monitor""" class show: """Shows or hides the monitor""" show = "Boolean value to show (True) or hide (False) the monitor" _required = ('show',) class hide: """Hides the monitor. Same as message ('monitor.show', show=False)"""