def test_critical(self): log = Logging() initial = self._log_line_count() self.assertTrue(log.critical("Test Critical Message", {'key': 'value'})) after = self._log_line_count() self.assertTrue(initial + 1 == after)
def getLogger(self): """Get the logging instance Returns: Logging: The logging instance """ if not isinstance(self.__logger, Logging): self.__logger = Logging() return self.__logger
def test_init_exception(self, mock_getattr, mock_import, mock_dir_contains): log = Logging() imp = ImportTool(log) def raise_exception(): raise Exception("Test Exception") d = {'times_called': 0} #Need mutable object for nonlocal updates def return_true_once(*args, **kwargs): d['times_called'] += 1 return d['times_called'] == 1 mock_dir_contains.side_effect = return_true_once mock_req = MagicMock() mock_req.side_effect = raise_exception mock_getattr.return_value = mock_req self.assertEqual(imp.load("mock_class"), None) mock_getattr.assert_called_once() mock_req.assert_called_once()
class GreaseRouter(object): """Main GREASE CLI Router This class handles routing CLI requests as well as starting the Daemon on Windows/POSIX systems Attributes: _config (Configuration): Main Configuration Object _logger (Logging): Main Logging Instance _importTool (ImportTool): Importer Tool Instance _exit_message (str): Exit Message """ _config = Configuration(os.environ.get('GREASE_CONF', None)) _logger = Logging(_config) _importTool = ImportTool(_logger) _exit_message = None def __init__(self): self._logger.trace("Router Startup", trace=True) def StartGREASE(self): """EntryPoint for CLI scripts for GREASE Returns: None: Void Method for GREASE """ status = self.run() self.exit(status, self._exit_message) def run(self): """Route commands through GREASE Returns: int: Exit Code """ # ensure at least a sub-command has been provided if len(sys.argv) > 1: cmd, context = self.get_arguments() if cmd: # Parse long args to command context if cmd.execute(context): cmd.__del__() del cmd return 0 else: return 3 else: self._exit_message = "Command not found" return 2 else: self._logger.error("Sub-command not provided") self._exit_message = "Sub-command not provided to GREASE CLI" return 1 def exit(self, code, message=None): """Exit program with exit code Args: code (int): Exit Code message (str): Exit message if any Returns: None: Will exit program """ if message: self._logger.info("Message: [{0}]".format(message)) if code != 0: print("ERROR: {0}".format(message)) else: print(message) self._logger.debug("GREASE exit code: [{0}]".format(code), verbose=True) sys.exit(code) def get_arguments(self): """Parse CLI long arguments into dictionaries This expects arguments separated by space `--opt val`, colon `--opt:val`, or equal `--opt=val` signs Returns: object, dict: key->value pairs of arguments """ i = 1 context = {} other = [] cmd = None while i < len(sys.argv): arg = str(sys.argv[i]) if arg.startswith("--"): # Found long opt if len(arg.split("=")) > 1: # was equal separated context[arg.split("=")[0].strip("--")] = arg.split("=")[1] elif len(arg.split(":")) > 1: # was colon separated context[arg.split(":")[0].strip("--")] = arg.split(":")[1] else: if len(sys.argv) < i + 1: # we have a flag rather than an arg context[arg.strip("--")] = True i += 1 elif len(sys.argv) - 1 == i or sys.argv[i + 1].startswith( "--"): # we have a flag rather than an arg context[arg.strip("--")] = True elif sys.argv[i + 1].startswith("--"): # we have a flag rather than an arg context[arg.strip("--")] = True else: # space separated possible_imp = self._importTool.load(sys.argv[i + 1]) if not isinstance(possible_imp, Command): context[arg.strip("--")] = sys.argv[i + 1] else: cmd = possible_imp i += 1 else: possible_imp = self._importTool.load(sys.argv[i]) if isinstance(possible_imp, Command): cmd = possible_imp else: other.append(arg) i += 1 context['grease_other_args'] = other return cmd, context
def test_logging_creation_default(self): log = Logging() self.assertTrue(isinstance(log, Logging))
def test_error(self): log = Logging() initial = self._log_line_count() self.assertTrue(log.error("Test Error Message", {'key': 'value'})) after = self._log_line_count() self.assertTrue(initial + 1 == after)
def test_warning(self): log = Logging() initial = self._log_line_count() self.assertTrue(log.warning("Test Warning Message", {'key': 'value'})) after = self._log_line_count() self.assertTrue(initial + 1 == after)
def test_info(self): log = Logging() initial = self._log_line_count() self.assertTrue(log.info("Test Info Message", {'key': 'value'})) after = self._log_line_count() self.assertTrue(initial + 1 == after)
def test_config_getter(self): log = Logging() self.assertTrue(isinstance(log.getConfig(), Configuration))
def test_logging_creation_with_conf(self): conf = Configuration() log = Logging(conf) self.assertTrue(isinstance(log, Logging))
class GreaseContainer(object): """Inversion of Control Container for objects in GREASE""" _logger = None _mongo = None def __init__(self, Logger=None): if Logger and isinstance(Logger, Logging): self._logger = Logger else: self._logger = Logging() self._mongo = Mongo(self._logger.getConfig()) def getLogger(self): """Get the logging instance Returns: Logging: The logging instance """ return self._logger def getNotification(self): """Get the notifications instance Returns: tgt_grease.core.Notifications: The notifications instance """ return self._logger.getNotification() def getMongo(self): """Get the Mongo instance Returns: Mongo: Mongo Instance Connection """ return self._mongo def getCollection(self, collectionName): """Get a collection object from MongoDB Args: collectionName (str): Collection to get Returns: pymongo.collection.Collection: Collection instance """ return self.getMongo()\ .Client()\ .get_database(self.getConfig().get('Connectivity', 'MongoDB').get('db', 'grease'))\ .get_collection(collectionName) def getConfig(self): """Gets the Configuration Instance Returns: tgt_grease.core.Configuration.Configuration: the configuration instance """ return self._logger.getConfig() def ensureRegistration(self): """ :return: """ collection = self.getCollection("JobServer") if os.path.isfile(self.getConfig().greaseDir + 'grease.identity'): # check to see if identity file is valid fil = open(self.getConfig().greaseDir + 'grease.identity', 'r') nodeId = "".join(fil.read()) fil.close() server = collection.find_one({'_id': ObjectId(nodeId)}) if server: # Valid registration self.getConfig().NodeIdentity = nodeId return True else: self.getLogger().warning( "Invalid node identity found to exist!") if self.getConfig().NodeIdentity == "Unknown": # Actual registration uid = collection.insert_one({ 'jobs': 0, 'os': platform.system().lower(), 'roles': ["general"], 'prototypes': ["monitor"], 'active': True, 'activationTime': datetime.utcnow() }).inserted_id fil = open(self.getConfig().greaseDir + "grease.identity", "w") fil.write(str(uid)) fil.close() self.getConfig().NodeIdentity = uid del collection return True else: # Check the Identity is actually registered if collection.find({ '_id': ObjectId(self.getConfig().NodeIdentity) }).count(): del collection return True else: self.getLogger().error( "Invalid Node Identity::Node Identity Not Found", additional={'NodeID': self.getConfig().NodeIdentity}) del collection return False
def __init__(self, Logger=None): if Logger and isinstance(Logger, Logging): self._logger = Logger else: self._logger = Logging() self._mongo = Mongo(self._logger.getConfig())
def test_load(self): log = Logging() imp = ImportTool(log) Conf = imp.load("Configuration") self.assertTrue(isinstance(Conf, Configuration))
def test_failed_path(self): log = Logging() imp = ImportTool(log) obj = imp.load("defaultdict") self.assertFalse(obj)