Exemplo n.º 1
0
    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)
Exemplo n.º 2
0
 def assertFalse(self, condition, soft_assert_name, failure_message=""):
     if condition:
         if failure_message is None:
             raise SoftAssertException(
                 StringProcessor.safe_formatter(
                     "SoftAssert.IsFalse failed for: {}", soft_assert_name))
         raise SoftAssertException(
             StringProcessor.safe_formatter(
                 "SoftAssert.IsFalse failed for: {}. {}",
                 [soft_assert_name, failure_message]))
     return self.invoke_test(self.test_name, soft_assert_name,
                             failure_message)
Exemplo n.º 3
0
 def log_message(self, expected_text, actual_text, message, result):
     if result:
         self.Log.log_message(
             MessageType.SUCCESS,
             StringProcessor.safe_formatter(
                 "Soft Assert '{}' passed. Expected Value = '{}', Actual Value = '{}'.",
                 [message, expected_text, actual_text]))
     else:
         self.Log.log_message(
             MessageType.WARNING,
             StringProcessor.safe_formatter(
                 "Soft Assert '{}' failed. Expected Value = '{}', Actual Value = '{}'.",
                 [message, expected_text, actual_text]))
Exemplo n.º 4
0
    def write_to_console(self, line, message, args, message_type):
        # Just return if there is no message
        if message is None or not self.should_message_be_logged(message_type):
            return

        result = StringProcessor.safe_formatter(message, args)
        try:
            # If this a write-line command
            if line:
                print(result)
            else:
                print(result)
        except Exception as e:
            print(StringProcessor.safe_formatter(
                "Failed to write to the console because: {}", e.args))
Exemplo n.º 5
0
    def assertEquals(self,
                     expected_text,
                     actual_text,
                     soft_assert_name,
                     message=""):
        if expected_text is not actual_text:
            if message is not None:
                raise SoftAssertException(StringProcessor().safe_formatter(
                    "SoftAssert.AreEqual failed for {}.  Expected '{}' but got '{}'",
                    [soft_assert_name, expected_text, actual_text]))
            raise SoftAssertException(StringProcessor().safe_formatter(
                "SoftAssert.AreEqual failed for {}.  Expected '{}' but got '{}'.  {}",
                [soft_assert_name, expected_text, actual_text, message]))

        return self.invoke_test_text(self.test_name, expected_text,
                                     actual_text, message)
Exemplo n.º 6
0
    def get_logging_level_setting(self, default_value=None):
        value = str(self.config.get_general_value("LogLevel",
                                                  default_value)).upper()

        if value == "VERBOSE":
            # Includes this and all of those below
            return MessageType.VERBOSE.name
        elif value == "INFORMATION":
            # Includes this and all of those below
            return MessageType.INFORMATION.name
        elif value == "GENERIC":
            # Includes this and all of those below
            return MessageType.GENERIC.name
        elif value == "SUCCESS":
            # Includes this and all of those below
            return MessageType.SUCCESS.name
        elif value == "WARNING":
            # Includes this and all of those below
            return MessageType.WARNING.name
        elif value == "ERROR":
            # Includes this and all of those below
            return MessageType.ERROR.name
        elif value == "SUSPENDED":
            # Includes this and all of those below
            return MessageType.SUSPENDED.name
        else:
            raise AttributeError(
                StringProcessor.safe_formatter(
                    "Logging level value '{}' is not a valid option",
                    Config().get_general_value("LogLevel")))
Exemplo n.º 7
0
 def unknown_message_type_message(new_type):
     args = [
         new_type, os.linesep,
         "Message will be displayed with the MessageType of: ",
         MessageType.GENERIC.Name
     ]
     return StringProcessor.safe_formatter("Unknown MessageType: {}{}{}{}",
                                           args)
 def test_ThrowSingleExceptionSafeFormatter(self):
     try:
         raise SyntaxError("Format Exception")
     except SyntaxError as e:
         formatted_exception = StringProcessor.safe_exception_formatter(e)
         self.assertTrue("Format Exception" in formatted_exception)
         self.assertTrue("utilitiesUnitTest\\StringProcessorUnitTest.py" in formatted_exception)
         self.assertTrue("in test_ThrowSingleExceptionSafeFormatter" in formatted_exception)
Exemplo n.º 9
0
 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()))
Exemplo n.º 10
0
    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))
Exemplo n.º 11
0
    def log_verbose(self, message, args=None):
        messages = list()
        messages.append(
            StringProcessor.safe_formatter(message, args) + os.linesep)

        for element in traceback.format_exc():
            # If the stack trace element is from the com.magenic package
            # (excluding this method) append the stack trace line
            if element.startsWith("com.magenic") and not ("BaseTest.logVerbose"
                                                          in str(element)):
                messages.append(element + os.linesep)
        self.get_logger().logMessage(MessageType.VERBOSE, messages)
 def test_FileLoggerNoParameters(self):
     file_logger = FileLogger("")
     self.assertEquals(
         tempfile.TemporaryFile(), file_logger.get_directory(),
         StringProcessor.safe_formatter("Expected Directory '{}'.",
                                        file_logger.DEFAULT_LOG_FOLDER))
     self.assertEquals("FileLog.txt", file_logger.get_file_name(),
                       "Expected correct File Name.")
     self.assertEquals(MessageType.INFORMATION,
                       file_logger.get_message_type(),
                       "Expected Information Message Type.")
     os.remove(file_logger.get_file_path())
     self.assertTrue(path.exists(file_logger.get_file_path()))
    def test_FileLoggerAppendMessagingLevel(self):
        file_logger = FileLogger(True, MessageType.WARNING.value)
        self.assertEquals(
            tempfile.TemporaryFile(), file_logger.get_directory(),
            StringProcessor.safe_formatter("Expected Directory '{}'.",
                                           file_logger.DEFAULT_LOG_FOLDER))
        self.assertEquals("FileLog.txt", file_logger.get_file_name(),
                          "Expected correct File Name.")
        self.assertEquals(MessageType.WARNING.value,
                          file_logger.get_message_type(),
                          "Expected Warning Message Type.")

        os.remove(file_logger.get_file_path())
        self.assertTrue(path.exists(file_logger.get_file_path()))
    def test_FileLoggerMessageTypeOnly(self):
        html_logger = HtmlFileLogger("", False, MessageType.WARNING)
        self.assertEquals(
            html_logger.DEFAULT_LOG_FOLDER, html_logger.get_directory(),
            StringProcessor.safe_formatter("Expected Directory '{}'.",
                                           html_logger.DEFAULT_LOG_FOLDER))
        self.assertEquals("FileLog.html", html_logger.get_file_name(),
                          "Expected correct File Name.")
        self.assertEquals(MessageType.WARNING, html_logger.get_message_type(),
                          "Expected Warning Message Type.")

        file_path = html_logger.get_file_path(
        ) + "\\" + html_logger.get_file_name()
        self.assertTrue(path.exists(file_path))
Exemplo n.º 15
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
Exemplo n.º 16
0
 def get_logging_enabled_setting(self, default_value=None):
     value = str(self.config.get_general_value("Log",
                                               default_value)).upper()
     if value == "YES":
         return LoggingEnabled.YES.name
     elif value == "ONFAIL":
         return LoggingEnabled.ONFAIL.name
     elif value == "NO":
         return LoggingEnabled.NO.name
     else:
         raise NotImplementedError(
             StringProcessor.safe_formatter(
                 "Log value {} is not a valid option",
                 Config().get_general_value("Log", "NO")))
    def test_FileLoggerAppendOnly(self):
        file_logger = FileLogger("", True)
        self.assertEquals(
            file_logger.DEFAULT_LOG_FOLDER, file_logger.get_directory(),
            StringProcessor.safe_formatter("Expected Directory '{}'.",
                                           file_logger.DEFAULT_LOG_FOLDER))
        self.assertEquals("FileLog.txt", file_logger.get_file_name(),
                          "Expected correct File Name.")
        self.assertEquals(MessageType.INFORMATION.name,
                          file_logger.get_message_type(),
                          "Expected Information Message Type.")

        # os.remove(file_logger.get_file_path() + file_logger.get_file_name())
        self.assertFalse(
            path.exists(os.path.abspath(file_logger.get_file_path())))
Exemplo n.º 18
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 test_FileLoggerAppendOnly(self):
        html_logger = HtmlFileLogger("", True)
        self.assertEquals(
            html_logger.DEFAULT_LOG_FOLDER, html_logger.get_directory(),
            StringProcessor.safe_formatter("Expected Directory '{}'.",
                                           html_logger.DEFAULT_LOG_FOLDER))
        self.assertEquals("FileLog.html", html_logger.get_file_name(),
                          "Expected correct File Name.")
        self.assertEquals(MessageType.INFORMATION.name,
                          html_logger.get_message_type(),
                          "Expected Information Message Type.")

        file_path = html_logger.get_file_path(
        ) + "\\" + html_logger.get_file_name()
        self.assertFalse(path.exists(file_path))
Exemplo n.º 20
0
    def try_to_log(self, message_type, message, args=None):
        # Get the formatted message
        formatted_message = StringProcessor.safe_formatter(message, args)

        try:
            # Write to the log
            self.get_logger().logMessage(message_type, formatted_message)

            # If this was an error and written to a file, add it to the console
            # output as well
            if message_type == MessageType.ERROR and not isinstance(
                    ConsoleLogger, self.get_logger()):
                print(formatted_message)
        except Exception as e:
            print(formatted_message)
            print("Logging failed because: " + e.message)
Exemplo n.º 21
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
Exemplo n.º 22
0
    def get_file(self):
        # default config.xml file name.
        config_file = pathlib.Path(__file__).with_name("config.xml")

        try:
            if path.exists(config_file):
                tree = ElementTree.parse(config_file)
                root = tree.getroot()

                new_config_values = {}

                for parent in root:
                    new_config_values[parent.tag] = {}
                    for child in parent:
                        new_config_values[parent.tag][child.tag] = child.text
                return new_config_values
        except Exception as e:
            raise TimeoutError(StringProcessor.safe_formatter(
                "Exception creating the xml configuration object from the file : " + e.args))
Exemplo n.º 23
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")))
Exemplo n.º 24
0
    def close(self, closing=False):
        if not closing:
            if self.managerStore is None:
                return
            self.logger.logMessage(MessageType.VERBOSE, "Start dispose")

            # for (final DriverManager<?> singleDriver : this.managerStore.values()) {
            for singleDriver in self.managerStore:
                if singleDriver is not None:
                    try:
                        singleDriver.close()
                    except Exception as e:
                        # raise DriverDisposalException(StringProcessor.safe_formatter("Unable to properly dispose of
                        # driver"), e)
                        raise Error(
                            StringProcessor.safe_formatter(
                                "Unable to properly dispose of driver"), e)
                self.managerStore = None
                self.logger.logMessage(MessageType.VERBOSE, "End dispose")

            self.isClosed = True
Exemplo n.º 25
0
    def log_final_assert_data(self):
        message = ""

        message += StringProcessor.safe_formatter(
            "Total number of Asserts: {1}. Passed Asserts = {2} Failed Asserts = {2}{3}",
            [
                self.NumberOfAsserts, self.NumberOfPassedAsserts,
                self.NumberOfFailedAsserts, os.linesep
            ])

        if len(self.listOfExceptions) > 0:
            message_type = MessageType.ERROR.value
            message += "List of failed exceptions:"

            for exception in self.listOfExceptions:
                # Will log all the exceptions that were caught in Asserts to the log file.
                message += exception
        else:
            # There are no exceptions that were caught in Asserts.
            message_type = MessageType.INFORMATION.value
            message += "There are no failed exceptions in the Asserts."

        self.Log.log_message(type, message)
Exemplo n.º 26
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))
 def test_StringFormatterCheckForStringFormat(self):
     message = StringProcessor.safe_formatter('This {} should return {}', ["Test", "Test"])
     self.assertEqual("This Test should return Test", message)
Exemplo n.º 28
0
 def test_getLogDirectoryTest(self):
     default_path = os.path.abspath(os.path.dirname(__file__)) + "\\Logs"
     self.assertEquals(LoggingConfig().get_log_directory(), default_path,
                       StringProcessor.safe_formatter("Expected Default Path '{}'.", default_path))
 def test_SingleExceptionSafeFormatter(self):
     format_exception = SyntaxError("Format Exception")
     formatted_exception = StringProcessor.safe_exception_formatter(format_exception)
     self.assertTrue("Format Exception" in formatted_exception)
 def test_SafeFormatterMessage(self):
     successful = StringProcessor.safe_formatter("This is a message.")
     self.assertEqual(successful, "This is a message.")