def test_xml_string_import(): xml="""<topicdefntree> <description>Test Topics showing hierarchy and topic inheritance</description> <topic id="parent"> <description>Parent with a parameter and subtopics</description> <listenerspec> <arg id="lastname">surname</arg> <arg id="name" optional="True">given name</arg> </listenerspec> <topic id="child"> <description>This is the first child</description> <listenerspec> <arg id="nick">A nickname</arg> </listenerspec> </topic> </topic> </topicdefntree>""" topicMgr.delTopic('parent') pub.clearTopicDefnProviders() assert topicMgr.getTopic('parent', True) is None assert topicMgr.getTopic('parent.child', True) is None provider = XmlTopicDefnProvider(xml) pub.addTopicDefnProvider( provider ) # to force instantiation of two topic definitions that were defined in xml, # this time we just instantiate all of them: pub.instantiateAllDefinedTopics(provider) assert topicMgr.getTopic('parent') is not None assert topicMgr.getTopic('parent.child') is not None
def test_xml_string_import(): xml = """<topicdefntree> <description>Test Topics showing hierarchy and topic inheritance</description> <topic id="parent"> <description>Parent with a parameter and subtopics</description> <listenerspec> <arg id="lastname">surname</arg> <arg id="name" optional="True">given name</arg> </listenerspec> <topic id="child"> <description>This is the first child</description> <listenerspec> <arg id="nick">A nickname</arg> </listenerspec> </topic> </topic> </topicdefntree>""" topicMgr.delTopic('parent') pub.clearTopicDefnProviders() assert topicMgr.getTopic('parent', True) is None assert topicMgr.getTopic('parent.child', True) is None provider = XmlTopicDefnProvider(xml) pub.addTopicDefnProvider(provider) # to force instantiation of two topic definitions that were defined in xml, # this time we just instantiate all of them: pub.instantiateAllDefinedTopics(provider) assert topicMgr.getTopic('parent') is not None assert topicMgr.getTopic('parent.child') is not None
def test1_xml_import(): pub.clearTopicDefnProviders() topicMgr.delTopic('parent') # verify pre: assert topicMgr.getTopic('parent', True) is None assert topicMgr.getTopic('parent.child', True) is None provider = XmlTopicDefnProvider('xmlprovider_topics.xml', TOPIC_TREE_FROM_FILE) pub.addTopicDefnProvider( provider ) # force instantiation of two topic definitions that were defined in xml: pub.sendMessage('parent', lastname='') pub.sendMessage('parent.child', lastname='', nick='') # verify post: assert topicMgr.getTopic('parent') is not None assert topicMgr.getTopic('parent.child') is not None
def test_xml_import(): pub.clearTopicDefnProviders() topicMgr.delTopic('parent') # verify pre: assert topicMgr.getTopic('parent', True) is None assert topicMgr.getTopic('parent.child', True) is None provider = XmlTopicDefnProvider('xmlprovider_topics.xml', TOPIC_TREE_FROM_FILE) pub.addTopicDefnProvider( provider ) # force instantiation of two topic definitions that were defined in xml: pub.sendMessage('parent', lastname='') pub.sendMessage('parent.child', lastname='', nick='') # verify post: assert topicMgr.getTopic('parent') is not None assert topicMgr.getTopic('parent.child') is not None
def test_module_as_class(): clear_topic_tree() assert topicMgr.getTopic('root_topic_1', True) is None assert topicMgr.getTopic('root_topic_2.sub_topic_21', True) is None # noinspection PyUnresolvedReferences import my_import_topics provider = pub.addTopicDefnProvider(my_import_topics, pub.TOPIC_TREE_FROM_CLASS) pub.instantiateAllDefinedTopics(provider) assert topicMgr.getTopic('root_topic_1') is not None assert topicMgr.getTopic('root_topic_2.subtopic_21') is not None pub.sendMessage(my_import_topics.root_topic_1)
def test_yaml_string_import(): remove_all_topics() str_yaml = """ALL_TOPICS: description: Root of all topics topics: - topic: parent description: Parent with a parameter and subtopics listenerspec: - arg: lastname description: surname - arg: name description: given name optional: true topics: - topic: child description: This is the first child listenerspec: - arg: nick description: A nickname """ topicMgr.delTopic('parent') pub.clearTopicDefnProviders() assert topicMgr.getTopic('parent', True) is None assert topicMgr.getTopic('parent.child', True) is None provider = YamlTopicDefnProvider(str_yaml) pub.addTopicDefnProvider(provider) # to force instantiation of two topic definitions that were defined in yaml, # this time we just instantiate all of them: pub.instantiateAllDefinedTopics(provider) printTreeDocs() assert topicMgr.getTopic('parent') is not None assert topicMgr.getTopic('parent.child') is not None
def test_provider(): clear_topic_tree() # create several providers that provide for different subsets of a tree: pub.addTopicDefnProvider('my_import_topics') pub.addTopicDefnProvider(topicDefns2, pub.TOPIC_TREE_FROM_STRING) pub.addTopicDefnProvider(topicDefns3, pub.TOPIC_TREE_FROM_CLASS) # adding the providers loaded the specifications, but did not create any topics: pytest.raises(TopicNameError, topicMgr.getTopic, 'root_topic_1') pytest.raises(TopicNameError, topicMgr.getTopic, 'root_topic_1.subtopic_2') # the following will create topics based on the providers added: assert topicMgr.getOrCreateTopic('root_topic_1').hasMDS() assert topicMgr.getOrCreateTopic('root_topic_1.subtopic_1').hasMDS() assert topicMgr.getOrCreateTopic( 'root_topic_1.subtopic_1.subsubtopic_11').hasMDS() assert topicMgr.getOrCreateTopic( 'root_topic_1.subtopic_1.subsubtopic_12').hasMDS() assert topicMgr.getOrCreateTopic('root_topic_1.subtopic_2').hasMDS() assert topicMgr.getOrCreateTopic( 'root_topic_1.subtopic_2.subsubtopic_21').hasMDS() # create some listeners and validate them even though none have been subscribed so the MDS # will be used in order to validate them: def sub(arg1=678): pass def sub_2(arg1=987, arg2=123): pass def sub_21(arg1, arg2=None, arg4=None): pass def isValid(topicName, listener): topic = topicMgr.getTopic(topicName) assert topic.getDescription() assert topic.hasMDS() return topic.isValid(listener) assert isValid('root_topic_1', sub) assert isValid('root_topic_1.subtopic_2', sub_2) assert isValid('root_topic_1.subtopic_2.subsubtopic_21', sub_21) def sub_21_bad(arg4): # required arg4 rather than optional! pass assert not topicMgr.getTopic( 'root_topic_1.subtopic_2.subsubtopic_21').isValid(sub_21_bad)
def test_provider(): clear_topic_tree() # create several providers that provide for different subsets of a tree: pub.addTopicDefnProvider('my_import_topics') pub.addTopicDefnProvider(topicDefns2, pub.TOPIC_TREE_FROM_STRING) pub.addTopicDefnProvider(topicDefns3, pub.TOPIC_TREE_FROM_CLASS) # adding the providers loaded the specifications, but did not create any topics: pytest.raises(TopicNameError, topicMgr.getTopic, 'root_topic_1') pytest.raises(TopicNameError, topicMgr.getTopic, 'root_topic_1.subtopic_2') # the following will create topics based on the providers added: assert topicMgr.getOrCreateTopic('root_topic_1').hasMDS() assert topicMgr.getOrCreateTopic('root_topic_1.subtopic_1').hasMDS() assert topicMgr.getOrCreateTopic('root_topic_1.subtopic_1.subsubtopic_11').hasMDS() assert topicMgr.getOrCreateTopic('root_topic_1.subtopic_1.subsubtopic_12').hasMDS() assert topicMgr.getOrCreateTopic('root_topic_1.subtopic_2').hasMDS() assert topicMgr.getOrCreateTopic('root_topic_1.subtopic_2.subsubtopic_21').hasMDS() # create some listeners and validate them even though none have been subscribed so the MDS # will be used in order to validate them: def sub(arg1=678): pass def sub_2(arg1=987, arg2=123): pass def sub_21(arg1, arg2=None, arg4=None): pass def isValid(topicName, listener): topic = topicMgr.getTopic(topicName) assert topic.getDescription() assert topic.hasMDS() return topic.isValid(listener) assert isValid('root_topic_1', sub) assert isValid('root_topic_1.subtopic_2', sub_2) assert isValid('root_topic_1.subtopic_2.subsubtopic_21', sub_21) def sub_21_bad(arg4): # required arg4 rather than optional! pass assert not topicMgr.getTopic('root_topic_1.subtopic_2.subsubtopic_21').isValid(sub_21_bad)
def test_string_prov_export(): clear_topic_tree() importStr = ''' """Tree docs, can be anything you want.""" class root_topic_1: """Root topic 1.""" class subtopic_1: """ Sub topic 1 of root topic. Docs rely on one blank line for topic doc, and indentation for each argument doc. """ def msgDataSpec(arg1, arg2=None): """ - arg1: some multiline doc for arg1 - arg2: some multiline doc for arg2 """ pass class root_topic_2: """Root topic 2.""" ''' pub.clearTopicDefnProviders() provider = pub.addTopicDefnProvider(importStr, pub.TOPIC_TREE_FROM_STRING) treeDoc = provider.getTreeDoc() assert treeDoc == """Tree docs, can be anything you want.""" root = topicMgr.getOrCreateTopic('root_topic_1.subtopic_1') assert root is not None assert topicMgr.getOrCreateTopic('root_topic_2').hasMDS() # few sanity checks def sub_1(arg1, arg2=None): pass assert root.hasMDS() assert pub.isValid(sub_1, 'root_topic_1.subtopic_1') # export tree exported = pub.exportTopicTreeSpec(rootTopic='root_topic_1', moduleDoc=treeDoc) # print(exported) expectExport = '''\ # Automatically generated by TopicTreeSpecPrinter(**kwargs). # The kwargs were: # - fileObj: StringIO # - footer: '# End of topic tree definition. Note that application may l...' # - indentStep: 4 # - treeDoc: 'Tree docs, can be anything you want....' # - width: 70 """ Tree docs, can be anything you want. """ class root_topic_1: """ Root topic 1. """ class subtopic_1: """ Sub topic 1 of root topic. Docs rely on one blank line for topic doc, and indentation for each argument doc. """ def msgDataSpec(arg1, arg2=None): """ - arg1: some multiline doc for arg1 - arg2: some multiline doc for arg2 """ # End of topic tree definition. Note that application may load # more than one definitions provider. ''' # check there are no differences from difflib import context_diff, ndiff diffs = ndiff(dedent(expectExport).splitlines(), exported.splitlines()) diffs = [d for d in diffs if not d.startswith(' ')] assert diffs == ['- ', '+ '] # now for module: provider = pub.addTopicDefnProvider('test4_prov_module_expect') pub.instantiateAllDefinedTopics(provider) modDoc = provider.getTreeDoc() assert modDoc.startswith('\nTree docs, can be anything you') pub.exportTopicTreeSpec('test4_prov_module_actual', rootTopic='root_topic_1b', moduleDoc=treeDoc) lines1 = open('test4_prov_module_actual.py', 'r').readlines() lines2 = open('test4_prov_module_expect.py', 'r').readlines() diffs = ndiff(lines1, lines2) diffs = [d for d in diffs if not d.startswith(' ')] assert not list(diffs) or list(diffs) == [ '- # - fileObj: TextIOWrapper\n', '+ # - fileObj: file\n' ] Path('test4_prov_module_actual.py').unlink()
from pubsub import pub import notifhandle import exchandle import kwargs_topics # ***** actual application ********** print('Using "kwargs" messaging protocol of pubsub v3') try: print('------- init ----------') pub.addTopicDefnProvider(kwargs_topics, pub.TOPIC_TREE_FROM_CLASS) pub.setTopicUnspecifiedFatal() import kwargs_listeners import kwargs_senders as senders print('-----------------------') senders.doSomething1() senders.doSomething2() print('------- done ----------') print('Exporting topic tree to', kwargs_topics.__name__) pub.exportTopicTreeSpec('kwargs_topics_out') except Exception:
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)""" class toggle: """Toggles the monitor to be shown or hidden""" pub.addTopicDefnProvider(MonitorTopics()) class MonitorTool: """ The MonitorTool is a singleton based on the wx.lib.inspection.InspectionTool. """ __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state if not hasattr(self, 'initialized'): self.initialized = False pub.subscribe(self.Show, 'monitor.show') print
"""\ from pubsub.utils import TopicTreeDefnSimple class MyTopicTree(TopicDefnProvider): ''' Topic tree for application. Note that hierarchy can be extended at run-time (e.g. by modules or plugins), and that more than one hierarchy can be used as specification. In this case, the first "provider" to provide a topic specification will be used. '''\ """ defaultTopicTreeSpecFooter = \ """\ # Following lines will cause the above topic tree # specification to be registered with pubsub as soon as # you import this file. from pubsub import pub pub.addTopicDefnProvider( MyTopicTree() ) """ def printTreeSpec(rootTopic=None, **kwargs): '''Prints the topic tree specification starting from rootTopic. If not specified, the whole topic tree is printed. The kwargs are the same as TopicTreeAsSpec's constructor. If no header or footer are given, the defaults are used (see defaultTopicTreeSpecHeader and defaultTopicTreeSpecFooter), such that the resulting output can be
import threading import wx from pubsub.pub import addTopicDefnProvider, TOPIC_TREE_FROM_CLASS import Topic_Def from GUI.Interface import LoggerInterface from Engine.Engine import LoggerEngine addTopicDefnProvider(Topic_Def, TOPIC_TREE_FROM_CLASS) def main(): ex = wx.App() ex.locale = wx.Locale(wx.LANGUAGE_ENGLISH) gui = LoggerInterface(parent=None) engine = LoggerEngine() print('Engine initilized: {:s}'.format(str(engine.__class__))) print('GUI initialized: {:s}'.format(str(gui.__class__))) ex.MainLoop() if __name__ == '__main__': main() for thread in threading.enumerate(): if type(thread) == threading.Timer: thread.cancel()
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)""" class toggle: """Toggles the monitor to be shown or hidden""" pub.addTopicDefnProvider(MonitorTopics()) class MonitorTool: """ The MonitorTool is a singleton based on the wx.lib.inspection.InspectionTool. """ __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state if not hasattr(self, 'initialized'): self.initialized = False pub.subscribe(self.Show, 'monitor.show') print
from __future__ import absolute_import from builtins import object import logging from abc import ABCMeta from enum import Enum from .EventNameEnum import EventNameEnum from pubsub import pub import threading from . import EventsDefinitionProviders from Marvell.pytoolsinfra.SysEventManager.BaseSysEventData import BaseSysEventData from future.utils import with_metaclass pub.addTopicDefnProvider(EventsDefinitionProviders, pub.TOPIC_TREE_FROM_CLASS) pub.setTopicUnspecifiedFatal() class SysEventManager(with_metaclass(ABCMeta, object)): """ This class is the manager class for Sending/Registering for the system events """ _dispatch_sys_event_lock = threading.Lock() _register_sys_event_lock = threading.Lock() listener_to_id = {} id_to_listener = {} sync_event_to_id_list = {} event_to_id_list = {} listener_id = 1
def AddProviderClass(newProvider): pub.addTopicDefnProvider(newProvider, pub.TOPIC_TREE_FROM_CLASS)
ide = 'ID of the command' _required = 'ide' class language: 'Events related to the program locale' class changed: 'The language was changed' class settings: 'Events related to the settings' class changed: 'Some or all of the settings were changed' settings = 'The settings' _required = 'settings' class setting: 'Events related to a specific setting' class changed: 'A setting was changed' settings = 'The settings' section = 'The section of the setting' option = 'The option which was changed' value = 'The new value' _required = 'settings', 'section', 'option', 'value' pub.addTopicDefnProvider(CommonTopicTree())
""" Reading oet.ini file value and initializing constant of feature toggle with enabling event based polling/pubsub """ import os.path from pkg_resources import resource_filename from pubsub import pub from ska_ser_logging import configure_logging from tblib import pickling_support import oet.event.topics from .features import Features # Set pypubsub to throw an error if topic in sendMessage does not correspond # to a topic in the topic tree defined in oet.event.topics pub.setTopicUnspecifiedFatal(True) # Load the topic tree definition pub.addTopicDefnProvider(oet.event.topics, pub.TOPIC_TREE_FROM_CLASS) configure_logging() pickling_support.install() FEATURES = Features.create_from_config_files( os.path.expanduser("~/oet.ini"), resource_filename(__name__, "oet.ini") )
def create_all_defined_topics(*args): prov = pub.addTopicDefnProvider(*args) return pub.instantiateAllDefinedTopics(prov)
def test_string_prov_export(): clear_topic_tree() importStr = ''' """Tree docs, can be anything you want.""" class root_topic_1: """Root topic 1.""" class subtopic_1: """ Sub topic 1 of root topic. Docs rely on one blank line for topic doc, and indentation for each argument doc. """ def msgDataSpec(arg1, arg2=None): """ - arg1: some multiline doc for arg1 - arg2: some multiline doc for arg2 """ pass class root_topic_2: """Root topic 2.""" ''' pub.clearTopicDefnProviders() provider = pub.addTopicDefnProvider(importStr, pub.TOPIC_TREE_FROM_STRING) treeDoc = provider.getTreeDoc() assert treeDoc == """Tree docs, can be anything you want.""" root = topicMgr.getOrCreateTopic('root_topic_1.subtopic_1') assert root is not None assert topicMgr.getOrCreateTopic('root_topic_2').hasMDS() # few sanity checks def sub_1(arg1, arg2=None): pass assert root.hasMDS() assert pub.isValid(sub_1, 'root_topic_1.subtopic_1') # export tree exported = pub.exportTopicTreeSpec(rootTopic='root_topic_1', moduleDoc=treeDoc) # print(exported) expectExport = '''\ # Automatically generated by TopicTreeSpecPrinter(**kwargs). # The kwargs were: # - fileObj: StringIO # - footer: '# End of topic tree definition. Note that application may l...' # - indentStep: 4 # - treeDoc: 'Tree docs, can be anything you want....' # - width: 70 """ Tree docs, can be anything you want. """ class root_topic_1: """ Root topic 1. """ class subtopic_1: """ Sub topic 1 of root topic. Docs rely on one blank line for topic doc, and indentation for each argument doc. """ def msgDataSpec(arg1, arg2=None): """ - arg1: some multiline doc for arg1 - arg2: some multiline doc for arg2 """ # End of topic tree definition. Note that application may load # more than one definitions provider. ''' # check there are no differences from difflib import context_diff, ndiff diffs = ndiff(dedent(expectExport).splitlines(), exported.splitlines()) diffs = [d for d in diffs if not d.startswith(' ')] assert diffs == ['- ', '+ '] # now for module: provider = pub.addTopicDefnProvider('test4_prov_module_expect') pub.instantiateAllDefinedTopics(provider) modDoc = provider.getTreeDoc() assert modDoc.startswith('\nTree docs, can be anything you') pub.exportTopicTreeSpec('test4_prov_module_actual', rootTopic='root_topic_1b', moduleDoc=treeDoc) lines1 = open('test4_prov_module_actual.py', 'r').readlines() lines2 = open('test4_prov_module_expect.py', 'r').readlines() diffs = ndiff(lines1, lines2) diffs = [d for d in diffs if not d.startswith(' ')] assert not list(diffs) or list(diffs) == ['- # - fileObj: TextIOWrapper\n', '+ # - fileObj: file\n'] Path('test4_prov_module_actual.py').unlink()
class closed: 'A note was closed' note = 'The closed note' _required = 'note' class move_left: 'Move the current note left' class move_right: 'Move the current note right' class edit: 'Events related to note editing' class delete_line: 'The current line should be deleted' class duplicate_lines: 'The current line or selected lines should be duplicated below' class copy_lines: 'The current line or selected lines should be duplicated above' class move_lines_down: 'The current line or selected lines should be moved down' class move_lines_up: 'The current line or selected lines should be moved up' pub.addTopicDefnProvider(TopicTree())