def test_containing_directories(self): self._create_dir('foo') sut = PluginLoader() sut.load_directory(self.plugin_dir) self.assertEqual({}, sut.plugins)
def test_load_simple_file(self): self._create('foo.py', 'class Foo(object): pass') sut = PluginLoader() sut.load_directory(self.plugin_dir) self.assertEqual(['Foo'], list(sut.plugins.keys()))
def test_ignorable_classes(self): self._create('foo.py', 'class Foo(object): pass') sut = PluginLoader() sut.load_directory(self.plugin_dir, onlyif=lambda x, y: False) self.assertEqual({}, sut.plugins)
def __init__(self, deviceRegistry): """ """ self.__deviceRegistry = deviceRegistry self.__logger = logging.getLogger("PluginRegistry") self.__pluginsloader = PluginLoader() self.__plugins = []
def test_binary_files_are_ignored(self): self.plugin_file.write(b'\0\1\2\3\4\5\6\7') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name) self.assertEqual([], list(sut.plugins.keys()))
def test_recursive_mode_off(self): self._create_dir('foo') self._create('bar.py', 'class Bazz(object): pass', 'foo') sut = PluginLoader() sut.load_directory(self.plugin_dir, recursive=False) self.assertEqual({}, sut.plugins)
def test_link_recursive(self): os.symlink(self.plugin_dir, os.path.join(self.plugin_dir, 'foo')) sut = PluginLoader() sut.load_directory(self.plugin_dir, recursive=True) self.assertEqual({}, sut.plugins)
def test_ignorable_classes_with_variable_false(self): self._write_file('class Foo(object): pass') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name, onlyif=False) self.assertEqual([], list(sut.plugins.keys()))
def test_not_ignorable_classes(self): self._write_file('class Foo(object): pass') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name, onlyif=lambda x, y, z: True) self.assertEquals('Foo', sut.plugins['Foo']().__class__.__name__)
def test_ignorable_classes(self): self._write_file('class Foo(object): pass') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name, onlyif=lambda x, y, z: False) self.assertEquals({}, sut.plugins)
def test_recursive_mode(self): self._create_dir('foo') self._create('bar.py', 'class Bazz(object): pass', 'foo') sut = PluginLoader() sut.load_directory(self.plugin_dir, recursive=True) self.assertEqual(['Bazz'], list(sut.plugins.keys()))
def test_ignorable_classes_with_variable_true(self): self._write_file('class Foo(object): pass') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name, onlyif=True) self.assertEqual(sorted(['__builtins__', 'Foo']), sorted(list(sut.plugins.keys())))
def _load_plugins(self): plugin_path = os.path.join( os.path.dirname(__file__), 'plugins', ) plugin_mgr = PluginLoader() plugin_mgr.load_directory(plugin_path, onlyif=self._check_plugin) self.plugins = [c() for n, c in plugin_mgr.plugins.items()]
def test_base_case(self): self._write_file('class Foo(object): pass') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name) self.assertEquals(['Foo'], list(sut.plugins.keys())) self.assertIsInstance(sut.plugins['Foo'], object) self.assertEquals('Foo', sut.plugins['Foo']().__class__.__name__)
def test_use_context(self): class Pattern(object): pass self._create('foo.py', 'class Foo(Bar): pass') sut = PluginLoader() sut.load_directory(self.plugin_dir, context={'Bar': Pattern}) self.assertEqual(sorted(['Foo', 'Bar']), sorted(list(sut.plugins.keys())))
def test_parameters_for_constructor(self): self._write_file('class Foo(object):\n' ' def __init__(self, a):\n' ' self.a = a') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name) plugin = sut.plugins['Foo'](5) self.assertEqual(5, plugin.a)
def test_adding_context(self): class Pattern(object): pass self.plugin_file.write(b'class Foo(Bar): pass') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name, context={'Bar': Pattern}) self.assertEqual(sorted(['Foo', 'Bar']), sorted(list(sut.plugins.keys())))
def test_two_plugins_in_a_file(self): self._write_file('class Foo(object):\n' ' pass\n' 'class Bar(object):\n' ' pass\n') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name) self.assertEqual(sorted(['Foo', 'Bar']), sorted(list(sut.plugins.keys()))) self.assertEqual('Foo', sut.plugins['Foo']().__class__.__name__) self.assertEqual('Bar', sut.plugins['Bar']().__class__.__name__)
def OnInit(self): self.settings = RideSettings() librarydatabase.initialize_database() self.preferences = Preferences(self.settings) self.namespace = Namespace(self.settings) self._controller = ChiefController(self.namespace, self.settings) self.frame = RideFrame(self, self._controller) self._editor_provider = EditorProvider() self._plugin_loader = PluginLoader(self, self._get_plugin_dirs(), context.get_core_plugins()) self._plugin_loader.enable_plugins() self.editor = self._get_editor() self.editor.show() self._load_data() self.frame.tree.populate(self.model) self.frame.tree.set_editor(self.editor) self._publish_system_info() if self._updatecheck: UpdateNotifierController( self.settings).notify_update_if_needed(UpdateDialog) wx.CallLater(200, ReleaseNotes(self).bring_to_front) return True
def __init__(self, config, logger): super(TelegramBot, self).__init__(config.get('telegrambot', 'token')) self.logger = logger self.restricted = config.getboolean('telegrambot', 'restrict_contacts') self.allowedusers = config.get('telegrambot', 'allowed_contacts').split(',') self.callbackusers = config.get('telegrambot', 'callback_contacts').split(',') self.botinfo = self.getMe() self.logger.info('Bot "' + self.botinfo['first_name'] + '" initialized. Bot id: ' + str(self.botinfo['id'])) self.logger.info("Listening...") self.useplugins = config.getboolean('telegrambot', 'loadplugins') if (self.useplugins): pluginloader = PluginLoader(self.logger) self.plugins = pluginloader.loadPlugins(self.callback) self.logger.info("Plugins are loaded") for k, v in self.plugins.iteritems(): if (k.startswith('/')): self.commands[k] = v.getdescription(k) self.plugins['/help'] = HelpPlugin(self.commands) self.logger.info("Help is: " + str(self.commands))
def main(argv): polling_interval = config.getint("EvoHome", "pollingInterval") debug_logging = False try: opts, args = getopt.getopt(argv, "hdi:", ["help", "interval", "debug="]) except getopt.GetoptError: print 'evohome-logger.py -h for help' sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): print 'evohome-logger, version 0.1' print '' print 'usage: evohome-logger.py [-h|--help] [-d|--debug <true|false>] [-i|--interval <interval>]' print '' print ' h|help : display this help page' print ' d|debug : turn on debug logging, regardless of the config.ini setting' print ' i|interval <interval> : Log temperatures every <polling interval> seconds, overriding the config.ini value' print ' If 0 is specified then temperatures are logged only once and the program exits' print '' sys.exit() elif opt in ('-i', '--interval'): if arg.isdigit(): polling_interval = int(arg) elif opt in ('-d', '--debug'): debug_logging = True if debug_logging or is_debugging_enabled('DEFAULT'): logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) global logger logger = logging.getLogger('evohome-logger::') if polling_interval == 0: logger.debug('One-off run') else: logger.debug('Polling every %s seconds', polling_interval) logger.info("==Started==") global plugins sections = filter(lambda a: a.lower() != 'DEFAULT', config.sections()) plugins = PluginLoader(sections) continue_polling = True try: while continue_polling: timestamp = datetime.utcnow() timestamp = timestamp.replace(microsecond=0) temperatures = get_temperatures() if temperatures: text_temperatures = '%s: ' % datetime.utcnow().strftime( '%Y-%m-%d %H:%M:%S') for t in temperatures: text_temperatures += "%s (%s A" % (t.zone, t.actual) if t.target is not None: text_temperatures += ", %s T" % t.target text_temperatures += ') ' logger.info(text_temperatures) for i in plugins.outputs: plugin = plugins.get(i) logger.debug('Writing temperatures to %s', plugin.plugin_name) try: plugin.write(timestamp, temperatures) except Exception, e: logger.error('Error trying to write to %s: %s', plugin.plugin_name, str(e)) if polling_interval == 0: continue_polling = False else: logger.info("Going to sleep for %s minutes", (polling_interval / 60)) time.sleep(polling_interval) except Exception, e: logger.error('An error occurred, trying again in 15 seconds: %s', str(e)) time.sleep(15)
"--offline-mode", dest="offlineMode", action="store_true", default=False, help="run in offline mode i.e don't attempt to auth via minecraft.net") parser.add_option( "-c", "--disable-console-colours", dest="disableAnsiColours", action="store_true", default=False, help="print minecraft chat colours as their equivalent ansi colours") # pluginLoader pluginLoader = PluginLoader("plugins") pluginLoader.loadPlugins(parser) (options, args) = parser.parse_args() pluginLoader.notifyOptions(options) if (options.username != ""): user = options.username else: user = raw_input("Enter your username: "******""): passwd = options.password elif (not options.offlineMode): passwd = getpass.getpass("Enter your password: ")
def test_load_empty_file(self): sut = PluginLoader() sut.load_file(self.plugin_file.name) self.assertEquals({}, sut.plugins)
async def main(): # TODO: this really needs to be replaced # probably using https://docs.python.org/3.8/library/functools.html#functools.partial global client global plugin_loader # Read config file config = Config("config.yaml") # Configure the database store = Storage(config.database_filepath) # Configuration options for the AsyncClient client_config = AsyncClientConfig( max_limit_exceeded=0, max_timeouts=0, store_sync_tokens=True, encryption_enabled=config.enable_encryption, ) # Initialize the matrix client client = AsyncClient( config.homeserver_url, config.user_id, device_id=config.device_id, store_path=config.store_filepath, config=client_config, ) # instantiate the pluginLoader plugin_loader = PluginLoader() # Set up event callbacks callbacks = Callbacks(client, store, config, plugin_loader) client.add_event_callback(callbacks.message, (RoomMessageText, )) client.add_event_callback(callbacks.invite, (InviteEvent, )) client.add_event_callback(callbacks.event_unknown, (UnknownEvent, )) client.add_response_callback(run_plugins) # Keep trying to reconnect on failure (with some time in-between) error_retries: int = 0 while True: try: # Try to login with the configured username/password try: login_response = await client.login( password=config.user_password, device_name=config.device_name, ) # Check if login failed if type(login_response) == LoginError: logger.error( f"Failed to login: {login_response.message}, retrying in 15s... ({error_retries})" ) # try logging in a few times to work around temporary login errors during homeserver restarts if error_retries < 3: error_retries += 1 await sleep(15) continue else: return False else: error_retries = 0 except LocalProtocolError as e: # There's an edge case here where the user enables encryption but hasn't installed # the correct C dependencies. In that case, a LocalProtocolError is raised on login. # Warn the user if these conditions are met. if config.enable_encryption: logger.fatal( "Failed to login and encryption is enabled. Have you installed the correct dependencies? " "https://github.com/poljar/matrix-nio#installation") return False else: # We don't know why this was raised. Throw it at the user logger.fatal(f"Error logging in: {e}") # Login succeeded! # Sync encryption keys with the server # Required for participating in encrypted rooms if client.should_upload_keys: await client.keys_upload() logger.info(f"Logged in as {config.user_id}") await client.sync_forever(timeout=30000, full_state=True) except (ClientConnectionError, ServerDisconnectedError, AttributeError, asyncio.TimeoutError) as err: logger.debug(err) logger.warning( f"Unable to connect to homeserver, retrying in 15s...") # Sleep so we don't bombard the server with login requests await sleep(15) finally: # Make sure to close the client connection on disconnect await client.close()
def test_empty_directory(self): sut = PluginLoader() sut.load_directory(self.plugin_dir) self.assertEqual({}, sut.plugins)