def close(self):
     if os.path.exists(self.get_file_path()):
         try:
             writer = open(self.get_file_path(), "w")
             writer.write("</body></html>")
         except IOError as e:
             console_logger = ConsoleLogger()
             console_logger.log_message(MessageType.ERROR,
                                        StringProcessor.safe_formatter(self.LOG_ERROR_MESSAGE, e.getMessage()))
    def __init__(self, log_folder="", append=False, message_level=MessageType.INFORMATION,
                 log_name=DEFAULT_LOG_NAME):
        super().__init__(log_folder, append, message_level, log_name)

        try:
            writer = open(super().get_file_path(), "w")
            writer.write(self.DEFAULT_HTML_HEADER)
        except IOError as e:
            console = ConsoleLogger()
            console.log_message(MessageType.ERROR,
                                StringProcessor.safe_formatter(self.LOG_ERROR_MESSAGE, e.args))
示例#3
0
    def make_valid_file_name(new_name):
        if new_name is None or new_name == "":
            raise FileExistsError("Blank or null file name was provided")

        # Replace invalid characters
        replaced_name = new_name
        try:
            replaced_name = new_name.replace("[^a-zA-Z0-9\\._\\- ]+", "~")
        except Exception as e:
            console = ConsoleLogger()
            console.log_message(
                MessageType.ERROR,
                StringProcessor.safe_formatter(
                    "Failed to Replace Invalid Characters because: {}",
                    e.args))
        return replaced_name
 def setTestObjectTest(self):
     logger = ConsoleLogger()
     base_test_object = BaseTestObject(
         logger, self.get_fully_qualified_test_class_name())
     self.set_test_object(base_test_object)
     self.assertTrue(
         isinstance(self.get_test_object().getLogger(), ConsoleLogger),
         "Expected Test Object to be set to have a Console Logger.")
示例#5
0
    def get_logger(self, file_name):
        # Disable logging means we just send any logged messages to the console
        if self.get_logging_enabled_setting(
                self.config) == LoggingEnabled.NO.name:
            return ConsoleLogger()

        log_directory = self.get_log_directory()
        logging_level = self.get_logging_level_setting(Config())

        # value = Config().get_general_value("LogType", "CONSOLE").upper()
        value = self.config.get_general_value("LogType").upper()
        if value == "CONSOLE":
            return ConsoleLogger(logging_level)
        elif value == "TXT":
            return FileLogger(log_directory, False, file_name, logging_level)
        else:
            raise AttributeError(
                StringProcessor.safe_formatter(
                    "Log type {} is not a valid option",
                    Config().get_general_value("LogType", "CONSOLE")))
    def log_message(self, message="", args=None, message_type=MessageType.INFORMATION):
        super(FileLogger, self).log_message(message, args, message_type)
        # If the message level is greater that the current log level then do not log it.
        if super(FileLogger, self).should_message_be_logged(message_type):
            # Log the message
            try:
                writer = open(super().get_file_path(), "w")
                date_object = datetime.now()
                date_format = date_object.strftime(Logger.DEFAULT_DATE_FORMAT)
                date = date_format.format(date_object)

                # Set the style
                writer.write(self.get_text_with_color_flag(message_type))

                # Add the content
                writer.write(StringProcessor.safe_formatter("{}{}", [os.linesep, date]))
                writer.write(StringProcessor.safe_formatter("{}:\t", message_type.name()))
                writer.write(StringProcessor.safe_formatter(os.linesep + message, args))

                # Close off the style
                writer.write("</p>")

                # Close the pre tag when logging Errors
                if message_type is "ERROR":
                    writer.write("</pre>")
            except Exception as e:
                # Failed to write to the event log, write error to the console instead
                console_logger = ConsoleLogger()
                console_logger.log_message(MessageType.ERROR,
                                           StringProcessor.safe_formatter(self.LOG_ERROR_MESSAGE, e.args))
                console_logger.log_message(message_type, message, args)
示例#7
0
    def create_logger(self):
        self.loggingEnabledSetting = LoggingConfig.get_logging_level_setting(
            Config())
        self.set_logged_exceptions(list)

        if self.loggingEnabledSetting != LoggingEnabled.NO:
            log = LoggingConfig().get_logger(
                StringProcessor.safe_formatter("{} - {}", [
                    self.fullyQualifiedTestClassName,
                    str(datetime.now().strftime("uuuu-MM-dd-HH-mm-ss-SSSS"))
                ]), Config())
        else:
            log = ConsoleLogger()
        return log
 def test_HierarchicalConsoleLogger(self):
     log_level, levels = self.data()
     # Calculate a file path
     file_path = LoggingConfig().get_log_directory() + \
                 self.get_file_name(self._testMethodName + log_level, "txt")
     try:
         open(file_path).read()
         console_logger = ConsoleLogger()
         self.hierarchical_logging(console_logger, file_path, log_level,
                                   levels)
     except Exception as e:
         raise FileExistsError()
     os.remove(file_path)
     self.assertTrue(path.exists(file_path))
示例#9
0
    def __init__(self,
                 log_folder="",
                 append=False,
                 message_level=MessageType.INFORMATION,
                 log_name=DEFAULT_LOG_NAME):
        super().__init__(message_level)

        if log_folder is None or log_folder == "":
            self.directory = self.DEFAULT_LOG_FOLDER
        else:
            self.directory = log_folder

        if not os.path.exists(self.directory):
            os.makedirs(self.directory)

        name = self.make_valid_file_name(log_name)

        if not name.lower().endswith(self.extension()):
            name += self.extension()

        self.fileName = name
        self.filePath = self.directory
        self.messageType = message_level

        if path.exists(self.filePath) and not append:
            try:
                with open(self.filePath, "w") as writer:
                    # writer = open(self.filePath, "w")
                    writer.write(" ")
            except IOError as e:
                # Failed to write to the event log, write error to the console instead
                console = ConsoleLogger()
                console.log_message(
                    MessageType.ERROR,
                    StringProcessor.safe_formatter(
                        "Failed to write to event log because: {}",
                        e.strerror + self.filePath))
示例#10
0
    def teardown(self):
        try:
            self.before_logging_teardown(self.testResult)
        except Exception as e:
            self.try_to_log(MessageType.WARNING,
                            "Failed before logging teardown because: {}",
                            e.message)

        # Log the test result
        if self.testResult.getStatus() == TestResult.SUCCESS:
            self.try_to_log(MessageType.SUCCESS, "Test Passed")
        elif self.testResult.getStatus() == TestResult.FAILURE:
            self.try_to_log(MessageType.ERROR, "Test Failed")
        elif self.testResult.getStatus() == TestResult.SKIP:
            self.try_to_log(MessageType.INFORMATION, "Test was skipped")
        else:
            self.try_to_log(MessageType.WARNING,
                            "Test had an unexpected result.")

        # Cleanup log files we don't want
        try:
            if isinstance(FileLogger, self.get_logger(
            )) and self.testResult.getStatus(
            ) == TestResult.SUCCESS and self.loggingEnabledSetting == LoggingEnabled.ONFAIL:
                # Files.delete(self.getLogger()).getFilePath())
                os.remove(self.get_logger().get_file_path())
        except Exception as e:
            self.try_to_log(MessageType.WARNING,
                            "Failed to cleanup log files because: {}",
                            e.message)

        # Get the Fully Qualified Test Name
        fully_qualified_test_name = self.fullyQualifiedTestClassName

        try:
            base_test_object = self.get_test_object()
            # Release logged messages
            self.loggedExceptions.pop(fully_qualified_test_name)

            # Release the Base Test Object
            self.baseTestObjects.pop(fully_qualified_test_name,
                                     base_test_object)
        except Exception:
            pass

        # Create console logger to log subsequent messages
        self.set_test_object(
            BaseTestObject(ConsoleLogger(), fully_qualified_test_name))
        self.fullyQualifiedTestClassName.clear()
示例#11
0
 def log_message(self,
                 message="",
                 args=None,
                 message_type=MessageType.INFORMATION):
     # If the message level is greater that the current log level then do not log it.
     if self.should_message_be_logged(message_type):
         try:
             with open(self.filePath, "w") as writer:
                 writer.write(
                     StringProcessor.safe_formatter(
                         "{}{}",
                         [os.linesep,
                          int(round(time.time() * 1000))]))
                 writer.write(
                     StringProcessor.safe_formatter("{}:\t", message_type))
                 writer.write(StringProcessor.safe_formatter(message, args))
         except IOError as e:
             # Failed to write to the event log, write error to the console instead
             console = ConsoleLogger()
             console.log_message(
                 StringProcessor.safe_formatter(
                     "Failed to write to event log because: {}",
                     e.strerror), args, MessageType.ERROR)
             console.log_message(message, args, message_type)
 def getDictionary():
     base_test_object = BaseTestObject(ConsoleLogger(), str())
示例#13
0
 def __init__(self, test_name, logger=ConsoleLogger()):
     self.test_name = test_name
     self.Log = logger
示例#14
0
 def test_consoleLoggerLogMessage(self):
     console_logger = ConsoleLogger()
     console_logger.log_message("Test String {} {}", ["args1", "args2"])
     self.assertIsNotNone(console_logger)
示例#15
0
 def test_consoleLoggerWriteMessageLineSelectType(self):
     console_logger = ConsoleLogger()
     console_logger.write("TestString {}", "args1", MessageType.GENERIC)
     self.assertIsNotNone(console_logger)
示例#16
0
 def test_consoleLoggerWriteLineMessage(self):
     console_logger = ConsoleLogger()
     console_logger.write("Test String {} {}", ["args1", "args2"])
     self.assertIsNotNone(console_logger)
 def getDriverManager(self):
     baseTestObject = BaseTestObject(ConsoleLogger(), str())
 def __init__(self, fully_qualified_test_name, logger=ConsoleLogger()):
     self.Log = logger
     self.TestName = fully_qualified_test_name