def on_close(self, event): log.debug("Exiting...") self.timer.Stop() pub.unsubscribe(self.on_download_finished, "download_finished") config.app.write() event.Skip() widgetUtils.exit_application()
def testNotifyByPrint(): capture = captureStdout() def listener1(arg1): pass pub.subscribe(listener1, 'baz') pub.sendMessage('baz', arg1=123) pub.unsubscribe(listener1, 'baz') def doa(): def listener2(): pass pub.subscribe(listener2, 'bar') doa() # listener2 should be gc'd gc.collect() # for pypy: the gc doesn't work the same as cpython's topicMgr.delTopic('baz') expect = """\ PUBSUB: New topic "baz" created PUBSUB: Subscribed listener "listener1" to topic "baz" PUBSUB: Start sending message of topic "baz" PUBSUB: Sending message of topic "baz" to listener listener1 PUBSUB: Done sending message of topic "baz" PUBSUB: Unsubscribed listener "listener1" from topic "baz" PUBSUB: New topic "bar" created PUBSUB: Subscribed listener "listener2" to topic "bar" PUBSUB: Listener "listener2" of Topic "bar" has died PUBSUB: Topic "baz" destroyed """ captured = capture.getvalue() #print captured #print repr(expect) assert captured == expect, \ '\n'.join( unified_diff(expect.splitlines(), captured.splitlines(), n=0) )
def on_close(self): """ Clean up on connection or session closing. """ # Stop listening for job updates. if self.job_listening: pub.unsubscribe(self.on_job_status, 'job.status') self.job_listening = False # Clean up any logs listeners. logger.info("Connection closed.") logger.debug("Unsubscribing %d local subscriptions.", len(self.log_subscribed)) for job_id in self.log_subscribed: self.log_job_watcher.remove_watch(job_id) pub.unsubscribe(self.log_message_update, self.configuration.get_job_message_pub_topic(job_id)) logger.debug("Closing %d remote connections.", len(self.log_remote_connections)) for remote_uuid, remote_data in self.log_remote_connections.iteritems(): remote_data['connection'].close() logger.debug("Closing complete.") # Clean up router stats. if hasattr(self, 'router_stats_output') and self.router_stats_ready: self.router_stats_output.close() # Clean up tunnels. for identifier, tunnel in self.service_tunnels.iteritems(): tunnel.close()
def endAppSDKificationListener(success, reason): from pubsub import pub pub.unsubscribe(endAppSDKificationListener, utils.topics.endAppSDKification) pub.sendMessage(utils.topics.endWriteWebApp, success=success, reason=reason)
def __request_latest(self): pub.subscribe(self._onMetrics, self.replyMetricsChannel) pub.subscribe(self._onValues, self.replyValuesChannel) pub.sendMessage('metrics.request.description',replyTo=self.replyMetricsChannel) pub.sendMessage('metrics.request.values', replyTo=self.replyValuesChannel) pub.unsubscribe(self._onMetrics, self.replyMetricsChannel) pub.unsubscribe(self._onValues, self.replyValuesChannel)
def __del__(self): """ Un subscribe to clean up week refs. """ pub.unsubscribe(self, self._unique_topic) pub.unsubscribe(self, Ether.ETHER_BACK_PLANE_TOPIC) return
def __del__(self): """ Clean up """ self._handler.activity_state(paused=True) pub.unsubscribe(self, self._unique_topic) return
def subscriber(): """ prevent pubsub topics being carried over between tests """ pub.subscribe(writer_function, "driver_open") yield pub.unsubscribe(writer_function, "driver_open")
def shutdown(self) -> None: super().shutdown() # Technically, unsubscribing is unnecessary as pypubsub holds weak # references to listeners and automatically unsubscribes listeners # that have been deleted pub.unsubscribe(self.republish, pub.ALL_TOPICS)
def OnDestroy(self, evt): """Unbind to all events before the plugin is destroyed.""" pub.unsubscribe(self.OnUpdatePatient, 'patient.updated.parsed_data') pub.unsubscribe(self.OnStructureCheck, 'structures.checked') pub.unsubscribe(self.OnIsodoseCheck, 'isodoses.checked') pub.unsubscribe(self.OnDrawingPrefsChange, '2dview.drawingprefs') pub.unsubscribe(self.OnPluginLoaded, 'plugin.loaded.2dview')
def endAppSDKificationListener(success, reason): from pubsub import pub pub.unsubscribe(endAppSDKificationListener, utils.topics.endAppSDKification) _loop.exit() global _correctResponse found = re.search(r'Network error #(40)(\d){1}:', reason) _correctResponse = (not success) and (found is not None)
def stop(self): pub.unsubscribe(self._on_polygon_model_change, MSG_SLICE_POLYGON_CHANGED) self._canvas.Unbind(PolygonEditingMode.EVT_TOMO_POLY_EDIT_MOTION) self._canvas.Unbind(PolygonEditingMode.EVT_TOMO_POLY_EDIT_LEFT_DOWN) self._canvas.Unbind(PolygonEditingMode.EVT_TOMO_POLY_EDIT_LEFT_UP) self._remove_slice_handles() self._canvas.redraw(True)
def unset_trigger(self): if not callable(self._trigger_func): return None pub.unsubscribe(self.check_change, self.get_topic()) func = self._trigger_func self._trigger_func = None keys = self._trigger_kwargs_keys self._trigger_kwargs_keys = None return func, keys
def connect_received_handler(self): pub.unsubscribe(self.connect_received_handler, 'connect-received') self.logger.debug('Connection to TinyG succeeded') self.connected = True # self.set_distance_mode(0) self.enable_flow_control() self.fetch_board_config() self.check_firmware_version()
def test_raise_event_OnStartOfRest(self): workTime = 0.1 restTime = 0.1 pomodoro = pomodorologic.Pomodoro(workTime, restTime) mocked = mock.Mock() pub.subscribe(mocked, 'onStartOfRest') pomodoro.startRest() self.assertTrue(mocked) pub.unsubscribe(mocked, 'onStartOfRest')
def completed_callback(dlg): url = dlg.uploaderFunction.get_url() pub.unsubscribe(dlg.uploaderDialog.update, "uploading") dlg.uploaderDialog.destroy() if url != 0: self.message.set_text(self.message.get_text()+url+" #audio") else: output.speak(_(u"Unable to upload the audio")) dlg.cleanup()
def sendMessage(self, topic, **kwargs): """ echo a message locally via pubsub.pub.sendMessage called by the remote side """ self.logger.debug("Received message to send: {} {}".format( topic, kwargs)) pub.unsubscribe(self.forwardMessage, topic) pub.sendMessage(topic, **kwargs) pub.subscribe(self.forwardMessage, pub.ALL_TOPICS)
def disconnect(self): unsubscribe(topicName='gui.laser.start', listener=self.start_laser) unsubscribe(topicName='gui.laser.stop', listener=self.stop_laser) unsubscribe(topicName='gui.laser.pause', listener=self.pause_laser) unsubscribe(topicName='gui.laser.cont', listener=self.continue_laser) unsubscribe(topicName='gui.request_status', listener=self.update_status) sendMessage(topicName='engine.status', text='Pulsarino disconnected!') self.close()
def __del__(self): """ Shut down """ self._handler.activity_state(paused=True) with self._lock: sub_list = deepcopy(self._subscribed_topics) for topic in sub_list: pub.unsubscribe(self, topic) return
def completed_callback(): url = dlg.uploaderFunction.get_url() pub.unsubscribe(dlg.uploaderDialog.update, "uploading") dlg.uploaderDialog.destroy() if url != 0: self.message.set_text(self.message.get_text() + url + " #audio") else: output.speak(_(u"Unable to upload the audio")) dlg.cleanup()
def test_raise_event_onEndOfRest(self): workTime = 0.01 restTime = 0.01 pomodoro = pomodorologic.Pomodoro(workTime, restTime) mocked = mock. Mock() pub.subscribe(mocked, 'onEndOfRest') pomodoro.startRest() time.sleep(0.1) self.assertTrue(mocked.called) pub.unsubscribe(mocked, 'onEndOfRest')
def job_over(self, new_building): self.release_funds() self.worker.clean_ownership() del self.builder_expert.build_jobs[self.worker.getID()] del self.bb.drones_on_way_to_build[self.worker.getID()] for handler, event in self.events.iteritems(): pub.unsubscribe(handler, event) if new_building: bb.add_unit_to_free(new_building)
def endFunctionListener(self, success, reason): from pubsub import pub pub.unsubscribe(self.endFunctionListener, utils.topics.endFunction) self.progressBar.setMaximum(100) self.progressBar.setValue(0) self.progressBar.setVisible(False) self.progressLabel.setVisible(False) self.setButtonsEnabled(status=True) # to solve module unload error from PyQt4.QtGui import QApplication QApplication.restoreOverrideCursor()
def endWriteWebAppListener(success, reason): from pubsub import pub pub.unsubscribe(endWriteWebAppListener, utils.topics.endWriteWebApp) if success: from PyQt4.QtCore import * projFile = QgsProject.instance().fileName() if projFile: appdefFile = projFile + ".appdef" saveAppdef(__appdef, appdefFile) # communicate end of function pub.sendMessage(utils.topics.endFunction, success=success, reason=reason)
def shutdown(self) -> None: pub.unsubscribe(self.prepare, pub.ALL_TOPICS) pub.unsubscribe(self.start, pub.ALL_TOPICS) pub.unsubscribe(self.list, pub.ALL_TOPICS) pub.unsubscribe(self.stop, pub.ALL_TOPICS) self.ses.shutdown() super().shutdown()
def endCreatePreviewListener(self, success, reason): from pubsub import pub pub.unsubscribe(self.endCreatePreviewListener, utils.topics.endFunction) if success: path = "file:///" + self.currentFolder.replace( "\\", "/") + "/webapp/index_debug.html" webbrowser.open_new(path) else: QgsMessageLog.logMessage("WebAppBuilder: {}".format(reason), level=QgsMessageLog.CRITICAL) QApplication.restoreOverrideCursor() QMessageBox.critical( iface.mainWindow(), "Error creating preview web app", "Could not create web app.\nCheck the QGIS log for more details." )
def endCreateAppListener(self, success, reason): self.onCreatingApp = False # reset button status and cursor self.buttonCreateOrStopApp.setText(self.createAppButtonText) QApplication.restoreOverrideCursor() from pubsub import pub pub.unsubscribe(self.endCreateAppListener, utils.topics.endFunction) if success: if pluginSetting("compileinserver"): QMessageBox.information( self, self.tr("Web app"), self.tr("Web app was correctly created and built.")) else: QMessageBox.information( self, self.tr("Web app"), self. tr("Web app file were correctly created.\n" "A web app can be built from them using Boundless WebSDK" )) elif reason: QgsMessageLog.logMessage("WebAppBuilder: {}".format(reason), level=QgsMessageLog.CRITICAL) if 'Request cancelled by user' in reason: # do nothing pass elif 'Cannot post preview webapp: Network error #5: Operation canceled' in reason: QMessageBox.critical( self, self.tr("Error creating web app"), self. tr("Network error due to a timeout.\n" "Please configure a longer timeout going to:\n" "Settings->Options->Network->Timeout for network requests (ms)." )) elif 'Permission denied' in reason: QMessageBox.critical( self, self.tr("Error creating web app"), self.tr( "Permission denied with current Connect credentials")) else: QMessageBox.critical( self, self.tr("Error creating web app"), self. tr("Could not create web app.\nCheck the QGIS log for more details." ))
def remove_listener(self, listener): """Remove a listener for a topic Args: ---- listener : dict A dictionary comprised of a "handler": handler (fct) and a "topic":"topicname" key-value pairs """ try: if pub.isSubscribed(listener["handler"], listener["topic"]): pub.unsubscribe(listener["handler"], listener["topic"]) else: logger.debug("Listener not subscribed", listener) except Exception as exc: print(f"Removing webhooks listener failed! {exc!r} occurred.") logger.warn( f"Removing webhooks listener failed! {exc!r} occurred.")
def limit_back_offStage2(self): self.logger.debug('Latch backoff stage 2') pub.unsubscribe(self.limit_back_offStage2, 'reset-received') self.set_distance_mode(1) command = self.movement_gcode + ' ' + self.limit_hit_axis_letter + \ self.backoff_distance_sign + self.backoff_distance if self.movement_gcode == 'G1': command += ' F' + \ self.main_window.ui.comboFeedRate.currentText().trimmed() self.send(command) time.sleep(1) self.backoff_distance = None subreturn = pub.subscribe(self.limit_back_offStage3, 'reset-received') self.logger.debug(str(subreturn)) self.soft_reset()
def close(self): """ Perform cleanup. """ # Unsubscriptions. pub.unsubscribe(self.msg_resource, 'resource.added') pub.unsubscribe(self.msg_resource, 'resource.removed') pub.unsubscribe(self.msg_data_capture_start, 'data_capture.start') pub.unsubscribe(self.msg_data_capture_data, 'data_capture.data') pub.unsubscribe(self.msg_data_capture_stop, 'data_capture.stop') # Ensure the thread exits. self.acq_thread.resource = None self.acq_thread.done = True if not self.running: self.running_lock.release() self.acq_thread.join() del self.acq_thread
def testHandleExcept1b(): # create a listener that raises an exception: from raisinglistener import getRaisingListener raisingListener = getRaisingListener() pub.subscribe(raisingListener, 'testHandleExcept1b') # subscribe a good exception listener and validate # create the listener for uncaught exceptions in listeners: class UncaughtExcListener: def __call__(self, listenerStr=None, excTraceback=None): # verify that information received; first the listenerStr assert listenerStr.startswith('raisingListener') # next the traceback: tb = excTraceback.traceback assert len(tb) == 2 def validateTB(tbItem, eFN, eLine, eFnN): assert tbItem[0].endswith(eFN), '%s !~ %s' % (tbItem[0], eFN) assert tbItem[1] == eLine assert tbItem[2] == eFnN validateTB(tb[0], 'raisinglistener.py', 5, 'raisingListener') validateTB(tb[1], 'raisinglistener.py', 4, 'nested') # next the formatted traceback: assert len(excTraceback.getFormattedList()) == len(tb) + 1 # finally the string for formatted traceback: msg = excTraceback.getFormattedString() #print 'Msg "%s"' % msg assert msg.startswith(' File') assert msg.endswith("name 'RuntimeError2' is not defined\n") from pubsub.utils.exchandling import ExcPublisher topic = topicMgr.getTopic(ExcPublisher.topicUncaughtExc) assert not topic.hasListeners() handler = UncaughtExcListener() pub.subscribe(handler, ExcPublisher.topicUncaughtExc) pub.sendMessage('testHandleExcept1b') # verify that listener isn't stuck in a cyclic reference by sys.exc_info() del raisingListener gc.collect() # for pypy: the gc doesn't work the same as cpython's assert not topicMgr.getTopic('testHandleExcept1b').hasListeners() pub.unsubscribe(handler, ExcPublisher.topicUncaughtExc)
def __call__(self, *args, **kwargs): try: if self.condition(**kwargs): if self.curr_event is None: ret = self.generator.next() else: pub.unsubscribe(self, self.curr_event) ret = self.generator.send(kwargs) if isinstance(ret, tuple): self.curr_event, self.condition = ret else: self.curr_event, self.condition = ret, lambda **kwargs: True # ideally this is we would modify our signature to match # but we don't know what the signature is listen, _ =pub.subscribe(self, self.curr_event) # this is a better name for the Listener listen._ListenerBase__nameID = self.name except StopIteration: pass
def limit_back_offStage3(self): # TODO check if we are backing off of a homing switch # if self.board_config[self.limit_hit_axis_letter+'zb']['value']: zero_backoff = self.board_config[ self.limit_hit_axis_letter + 'zb']['value'] self.logger.debug('Latch backoff stage 3 ' + str(zero_backoff)) pub.unsubscribe(self.limit_back_offStage3, 'reset-received') command = self.movement_gcode + ' ' + self.limit_hit_axis_letter + \ self.backoff_distance_sign + zero_backoff if self.movement_gcode == 'G1': command += ' F' + \ str(self.main_window.ui.comboFeedRate.currentText().trimmed()) self.send(command) self.set_distance_mode(0) self.backoff_distance_sign = None self.limit_hit_axis_letter = None pub.subscribe(self.limit_back_offStage4, 'idle-received')
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 testHandleExcept1b(): # create a listener that raises an exception: from raisinglistener import getRaisingListener raisingListener = getRaisingListener() pub.subscribe(raisingListener, 'testHandleExcept1b') # subscribe a good exception listener and validate # create the listener for uncaught exceptions in listeners: class UncaughtExcListener: def __call__(self, listenerStr=None, excTraceback=None): # verify that information received; first the listenerStr assert listenerStr.startswith('raisingListener') # next the traceback: tb = excTraceback.traceback assert len(tb) == 2 def validateTB(tbItem, eFN, eLine, eFnN): assert tbItem[0].endswith(eFN), '%s !~ %s' % (tbItem[0], eFN) assert tbItem[1] == eLine assert tbItem[2] == eFnN validateTB(tb[0], 'raisinglistener.py', 5, 'raisingListener') validateTB(tb[1], 'raisinglistener.py', 4, 'nested') # next the formatted traceback: assert len( excTraceback.getFormattedList() ) == len(tb)+1 # finally the string for formatted traceback: msg = excTraceback.getFormattedString() #print 'Msg "%s"' % msg assert msg.startswith(' File') assert msg.endswith("name 'RuntimeError2' is not defined\n") from pubsub.utils.exchandling import ExcPublisher topic = topicMgr.getTopic( ExcPublisher.topicUncaughtExc ) assert not topic.hasListeners() handler = UncaughtExcListener() pub.subscribe(handler, ExcPublisher.topicUncaughtExc) pub.sendMessage('testHandleExcept1b') # verify that listener isn't stuck in a cyclic reference by sys.exc_info() del raisingListener gc.collect() # for pypy: the gc doesn't work the same as cpython's assert not topicMgr.getTopic('testHandleExcept1b').hasListeners() pub.unsubscribe(handler, ExcPublisher.topicUncaughtExc)
def log_unsubscribe(self, job_id): """ Unsubscribe from the given log, cleaning up any remote connections if needed. """ logger.info("Handling unsubscribe request for %s", job_id) if self.log_subscribed.has_key(job_id): self.log_job_watcher.remove_watch(job_id) pub.unsubscribe(self.log_message_update, self.configuration.get_job_message_pub_topic(job_id)) del self.log_subscribed[job_id] logger.debug("Unsubscribed local follow for %s", job_id) if self.log_remote_subscriptions.has_key(job_id): nodeuuid = self.log_remote_subscriptions[job_id] del self.log_remote_subscriptions[job_id] logger.debug("Ref count for %s is %d", job_id, self.log_remote_connections[nodeuuid]['refcount']) self.log_remote_connections[nodeuuid]['refcount'] -= 1 if self.log_remote_connections[nodeuuid]['refcount'] < 1: logger.info("Refcount for %s dropped to zero, closing connection.", nodeuuid) remote = self.log_remote_connections[nodeuuid]['connection'] del self.log_remote_connections[nodeuuid] remote.close()
def teardown(self): logger.debug("Tearing down title scene") self.font = None self.percent_surf = None self.render_title = False self.render_percent = False pub.unsubscribe(self.on_resource_loaded, "resources.loading") pub.unsubscribe(self.on_mouse_down, "input.mouse-down") pub.unsubscribe(self.on_mouse_up, "input.mouse-up")
def close(self): """ Perform cleanup. """ # Unsubscriptions. pub.unsubscribe(self.msg_data_capture_start, 'data_capture.start') pub.unsubscribe(self.msg_data_capture_data, 'data_capture.data') pub.unsubscribe(self.msg_data_capture_stop, 'data_capture.stop')
def show_profile(self, yes) : if yes : pub.subscribe(self.on_game_started, "game_started") pub.subscribe(self.on_game_step_moved, "game_step_moved") pub.subscribe(self.on_engine_move_info, "engine_move_info") else : self.step_view.clear() pub.unsubscribe(self.on_game_started, "game_started") pub.unsubscribe(self.on_game_step_moved, "game_step_moved") pub.unsubscribe(self.on_engine_move_info, "engine_move_info")
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 newListener(self): self.callCountForNewListener += 1 pub.unsubscribe(self.newListener, 'test.change-listeners')
def finish_execution(task): loop = asyncio.get_event_loop() loop.stop() pub.unsubscribe(self.endOfRest, 'onEndOfRest') pub.unsubscribe(self.endOfWork, 'onEndOfWork')
def on_play (self, card): if not self in self.owner.items: pub.unsubscribe (self.on_play, str(self.game_state.gameid1)+'.play_event') return if card.card_type == 'sorcery': self.owner.draw ()
def limit_back_offStage4(self): pub.unsubscribe(self.limit_back_offStage4, 'idle-received') pub.sendMessage('reset-received')
def destroy (self): pub.unsubscribe (self.on_end_turn, str(self.game_state.gameid1)+'.end_turn_event') self.counter = 3 self.owner.opponent.silencers.remove (self)
def teardown(self): logger.debug("Tearing down kart select scene") self.buttons = None self.font = None pub.unsubscribe(self.on_button_clicked, "button.clicked")
def teardown(self): logger.debug("Tearing down track scene") pub.unsubscribe(self.on_key_up, "input.key-up")
def on_play (self, card): if self not in self.owner.creatures: pub.unsubscribe (self.on_play, str(self.game_state.gameid1)+'.play_event') return if card.card_type == 'creature': self.owner.health += 2
def disconnect_events(self): log.debug("Disconnecting some events...") pub.unsubscribe(self.in_post, "posted") pub.unsubscribe(self.download, "download-file") pub.unsubscribe(self.play_audio, "play-audio") pub.unsubscribe(self.authorisation_failed, "authorisation-failed") pub.unsubscribe(self.play_audios, "play-audios") pub.unsubscribe(self.view_post, "open-post") pub.unsubscribe(self.update_status_bar, "update-status-bar")
def on_end_turn (self): pub.unsubscribe (self.on_end_turn, str(self.game_state.gameid1)+'.end_turn_event') self.destroy ()
def on_end_turn (self): if self not in self.owner.creatures: pub.unsubscribe (self.on_play, str(self.game_state.gameid1)+'.play_event') return if self.owner == self.game_state.on_trait : self.counter += 1
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)
def on_end_turn (self): if not self in self.owner.items: pub.unsubscribe (self.on_end_turn, str(self.game_state.gameid1)+'.end_turn_event') return if self.owner == self.game_state.on_trait: self.owner.cur_mana = min (self.owner.cur_mana + 1, self.owner.max_mana)
def destroy (self): pub.unsubscribe (self.on_play, str(self.game_state.gameid1)+'.play_event') self.creature_strength = 6 CreatureCard.destroy (self)
def on_play (self, card): if self not in self.owner.creatures: pub.unsubscribe (self.on_play, str(self.game_state.gameid1)+'.play_event') return if card.card_type == 'item' and card.owner == self.owner: self.creature_strength += 1