Beispiel #1
0
    def log_exception(self,
                      message,
                      exception,
                      log_level=LOG_LEVEL.ERROR,
                      timestamp=None,
                      **kwargs):
        """
        If the log_level of the printer is greater than DEBUG, it prints
        only the message. If it is DEBUG or lower, it shows the message
        along with the traceback of the exception.

        :param message:   The message to print.
        :param exception: The exception to print.
        :param log_level: The log_level of this message (not used when
                          logging the traceback. Tracebacks always have
                          a level of DEBUG).
        :param timestamp: The time at which this log occured. Defaults to
                          the current time.
        :param kwargs:    Keyword arguments to be passed when logging the
                          message (not used when logging the traceback).
        """
        if not isinstance(exception, BaseException):
            raise TypeError("log_exception can only log derivatives of "
                            "BaseException.")

        traceback_str = "\n".join(
            traceback.format_exception(type(exception), exception,
                                       exception.__traceback__))

        self.log(log_level, message, timestamp=timestamp, **kwargs)
        self.log_message(
            LogMessage(LOG_LEVEL.DEBUG,
                       "Exception was:" + "\n" + traceback_str,
                       timestamp=timestamp), **kwargs)
Beispiel #2
0
    def test_logging(self):
        uut = ListLogPrinter()
        ts = datetime.today()
        ts_str = ts.strftime("%X")

        uut.log_level = LOG_LEVEL.INFO
        uut.warn("Test value", timestamp=ts)
        uut.print("Test 2", timestamp=ts)  # Should go to INFO
        uut.debug("Test 2", timestamp=ts)  # Should not be logged

        self.assertEqual(uut.logs, [
            LogMessage(LOG_LEVEL.WARNING, "Test value", timestamp=ts),
            LogMessage(LOG_LEVEL.INFO, "Test 2", timestamp=ts)
        ])

        self.assertRaises(TypeError, uut.log_message, "message")
Beispiel #3
0
class LogPrinterTest(unittest.TestCase):
    log_message = LogMessage(LOG_LEVEL.ERROR,
                             Constants.COMPLEX_TEST_STRING)

    def test_get_printer(self):
        self.assertIs(LogPrinter(None).printer, None)
        printer = Printer()
        self.assertIs(LogPrinter(printer).printer, printer)

    def test_logging(self):
        uut = LogPrinter(timestamp_format='')
        uut.logger = mock.MagicMock()
        uut.log_message(self.log_message)

        msg = Constants.COMPLEX_TEST_STRING
        uut.logger.log.assert_called_with(logging.ERROR, msg)

        uut = LogPrinter(log_level=LOG_LEVEL.DEBUG)
        uut.logger = mock.MagicMock()

        uut.log(LOG_LEVEL.ERROR, Constants.COMPLEX_TEST_STRING)
        uut.logger.log.assert_called_with(logging.ERROR, msg)

        uut.debug(Constants.COMPLEX_TEST_STRING, 'd')
        uut.logger.log.assert_called_with(logging.DEBUG, msg + ' d')

        uut.log_level = LOG_LEVEL.DEBUG
        uut.log_exception('Something failed.', NotImplementedError(msg))
        uut.logger.log.assert_any_call(logging.ERROR, 'Something failed.')
        uut.logger.log.assert_called_with(
            logging.INFO,
            'Exception was:\n{exception}: {msg}'.format(
                exception='NotImplementedError',
                msg=msg))

    def test_raises(self):
        uut = LogPrinter(NullPrinter())
        self.assertRaises(TypeError, uut.log, 5)
        self.assertRaises(TypeError, uut.log_exception, 'message', 5)
        self.assertRaises(TypeError, uut.log_message, 5)

    def test_log_level(self):
        uut = LogPrinter()
        self.assertEqual(uut.log_level, logging.DEBUG)
        uut.log_level = logging.INFO
        self.assertEqual(uut.log_level, logging.INFO)

    def test_get_state(self):
        uut = LogPrinter()
        self.assertNotIn('logger', uut.__getstate__())

    def test_set_state(self):
        uut = LogPrinter()
        state = uut.__getstate__()
        uut.__setstate__(state)
        self.assertIs(uut.logger, logging.getLogger())

    def test_no_printer(self):
        uut = LogPrinter()
        self.assertIs(uut.logger, logging.getLogger())
Beispiel #4
0
    def test_construction(self):
        # take a look if defaults are good
        self.assertEqual(self.uut.log_level, LOG_LEVEL.DEBUG)
        self.assertEqual(self.uut.message, "test message")
        self.assertEqual(self.uut.timestamp, self.timestamp)

        # see that arguments are processed right
        self.uut = LogMessage(LOG_LEVEL.WARNING,
                              "   a msg  ",
                              5,
                              "  ",
                              timestamp=self.timestamp)
        self.assertEqual(self.uut.log_level, LOG_LEVEL.WARNING)
        self.assertEqual(self.uut.message, "   a msg   5")
        self.assertEqual(self.uut.timestamp, self.timestamp)

        self.assertRaises(ValueError, LogMessage, LOG_LEVEL.DEBUG, "")
        self.assertRaises(ValueError, LogMessage, 5, "test")
    def test_logging(self):
        uut = ListLogPrinter()
        ts = datetime.today()

        uut.log_level = LOG_LEVEL.INFO
        uut.warn('Test value', timestamp=ts)
        uut.print('Test 2', timestamp=ts)  # Should go to INFO
        uut.debug('Test 2', timestamp=ts)  # Should not be logged

        self.assertEqual(uut.logs,
                         [LogMessage(LOG_LEVEL.WARNING,
                                     'Test value',
                                     timestamp=ts),
                          LogMessage(LOG_LEVEL.INFO,
                                     'Test 2',
                                     timestamp=ts)])

        self.assertRaises(TypeError, uut.log_message, 'message')
Beispiel #6
0
 def test_equals(self):
     self.assertEqual(LogMessage(LOG_LEVEL.DEBUG, "test message"),
                      LogMessage(LOG_LEVEL.DEBUG, "test message"))
     self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, "test message"),
                         LogMessage(LOG_LEVEL.WARNING, "test message"))
     self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, "test message"),
                         LogMessage(LOG_LEVEL.DEBUG, "test"))
     self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, "test message"), 5)
Beispiel #7
0
    def __send_msg(self, log_level, delimiter, *args):
        if self.message_queue is None:
            return

        if len(args) == 0:
            return

        self.message_queue.put(LogMessage(log_level,
                                          str(delimiter).join(args)),
                               timeout=self.TIMEOUT)
Beispiel #8
0
    def __send_msg(self, log_level, delimiter, *args):
        if self.message_queue is None:
            return

        if len(args) == 0:
            return

        msg = ""
        for i in range(len(args) - 1):
            msg += str(args[i]) + str(delimiter)
        msg += str(args[-1])

        self.message_queue.put(LogMessage(log_level, msg),
                               timeout=self.TIMEOUT)
Beispiel #9
0
    def log_exception(self,
                      message,
                      exception,
                      log_level=LOG_LEVEL.ERROR,
                      timestamp=None,
                      **kwargs):
        if not isinstance(exception, BaseException):
            raise TypeError(
                "log_exception can only log derivatives of BaseException.")

        return self.log_message(LogMessage(
            log_level,
            message + "\n\n" + _("Exception was:") + "\n" + str(exception)),
                                timestamp=timestamp,
                                **kwargs)
Beispiel #10
0
def send_msg(message_queue, timeout, log_level, *args, delimiter=' ', end=''):
    """
    Puts message into message queue for a LogPrinter to present to the user.

    :param message_queue: The queue to put the message into and which the
                          LogPrinter reads.
    :param timeout:       The queue blocks at most timeout seconds for a free
                          slot to execute the put operation on. After the
                          timeout it returns queue Full exception.
    :param log_level:     The log_level i.e Error,Debug or Warning.It is sent
                          to the LogPrinter depending on the message.
    :param args:          This includes the elements of the message.
    :param delimiter:     It is the value placed between each arg. By default
                          it is a ' '.
    :param end:           It is the value placed at the end of the message.
    """
    output = str(delimiter).join(str(arg) for arg in args) + str(end)
    message_queue.put(LogMessage(log_level, output), timeout=timeout)
Beispiel #11
0
    def test_construction(self):
        # take a look if defaults are good
        self.assertEqual(self.uut.log_level, LOG_LEVEL.DEBUG)
        self.assertEqual(self.uut.message, "test message")
        self.assertEqual(self.uut.timestamp, self.timestamp)

        # see that arguments are processed right
        self.uut = LogMessage(LOG_LEVEL.WARNING,
                              "   a msg  ",
                              5,
                              "  ",
                              timestamp=self.timestamp)
        self.assertEqual(self.uut.log_level, LOG_LEVEL.WARNING)
        self.assertEqual(self.uut.message, "   a msg   5")
        self.assertEqual(self.uut.timestamp, self.timestamp)

        self.assertRaises(ValueError, LogMessage, LOG_LEVEL.DEBUG, "")
        self.assertRaises(ValueError, LogMessage, 5, "test")
Beispiel #12
0
    def log_exception(self,
                      message,
                      exception,
                      log_level=LOG_LEVEL.ERROR,
                      timestamp=None,
                      **kwargs):
        if not isinstance(exception, BaseException):
            raise TypeError("log_exception can only log derivatives of "
                            "BaseException.")

        traceback_str = "\n".join(
            traceback.format_exception(type(exception), exception,
                                       exception.__traceback__))

        return self.log_message(LogMessage(
            log_level,
            message + "\n\n" + _("Exception was:") + "\n" + traceback_str),
                                timestamp=timestamp,
                                **kwargs)
Beispiel #13
0
class LogMessageTest(unittest.TestCase):
    timestamp = datetime.today()

    def setUp(self):
        self.uut = LogMessage(LOG_LEVEL.DEBUG,
                              "test",
                              "message",
                              timestamp=self.timestamp)

    def test_construction(self):
        # take a look if defaults are good
        self.assertEqual(self.uut.log_level, LOG_LEVEL.DEBUG)
        self.assertEqual(self.uut.message, "test message")
        self.assertEqual(self.uut.timestamp, self.timestamp)

        # see that arguments are processed right
        self.uut = LogMessage(LOG_LEVEL.WARNING,
                              "   a msg  ",
                              5,
                              "  ",
                              timestamp=self.timestamp)
        self.assertEqual(self.uut.log_level, LOG_LEVEL.WARNING)
        self.assertEqual(self.uut.message, "   a msg   5")
        self.assertEqual(self.uut.timestamp, self.timestamp)

        self.assertRaises(ValueError, LogMessage, LOG_LEVEL.DEBUG, "")
        self.assertRaises(ValueError, LogMessage, 5, "test")

    def test_to_str(self):
        self.uut.message = Constants.COMPLEX_TEST_STRING
        self.uut.log_level = LOG_LEVEL.ERROR
        self.assertEqual(str(self.uut),
                         "[{}] {}".format(_("ERROR"),
                                          Constants.COMPLEX_TEST_STRING))
        self.uut.log_level = LOG_LEVEL.WARNING
        self.assertEqual(str(self.uut),
                         "[{}] {}".format(_("WARNING"),
                                          Constants.COMPLEX_TEST_STRING))
        self.uut.log_level = LOG_LEVEL.DEBUG
        self.assertEqual(str(self.uut),
                         "[{}] {}".format(_("DEBUG"),
                                          Constants.COMPLEX_TEST_STRING))
        self.uut.log_level = 5
        self.assertEqual(str(self.uut),
                         "[{}] {}".format(_("ERROR"),
                                          Constants.COMPLEX_TEST_STRING))

    def test_equals(self):
        self.assertEqual(LogMessage(LOG_LEVEL.DEBUG, "test message"),
                         LogMessage(LOG_LEVEL.DEBUG, "test message"))
        self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, "test message"),
                            LogMessage(LOG_LEVEL.WARNING, "test message"))
        self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, "test message"),
                            LogMessage(LOG_LEVEL.DEBUG, "test"))
        self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, "test message"), 5)

    def test_string_dict(self):
        self.uut.log_level = LOG_LEVEL.DEBUG
        self.uut.message = "test"
        self.assertEqual(
            self.uut.to_string_dict(),
            {"log_level": "DEBUG",
             "message": "test",
             "timestamp": self.timestamp.isoformat()})

        self.uut.timestamp = None
        self.uut.log_level = -9999  # invalid level
        self.assertEqual(
            self.uut.to_string_dict(),
            {"log_level": "", "message": "test", "timestamp": ""})
Beispiel #14
0
class LogPrinterTestCase(unittest.TestCase):
    log_message = LogMessage(LOG_LEVEL.ERROR,
                             StringConstants.COMPLEX_TEST_STRING)

    def test_interface(self):
        uut = LogPrinter()
        self.assertRaises(NotImplementedError, uut.log_message,
                          self.log_message)

    def test_logging(self):
        uut = TestLogPrinter(timestamp_format="")
        self.assertEqual((str(self.log_message), "special"),
                         uut.log_message(self.log_message,
                                         end="",
                                         special_arg="special"))

        uut = TestLogPrinter(log_level=LOG_LEVEL.DEBUG)
        ts = datetime.today()
        self.assertEqual(("[" + _("ERROR") + "][" + ts.strftime("%X") + "] " +
                          StringConstants.COMPLEX_TEST_STRING, "test"),
                         uut.log_message(self.log_message,
                                         timestamp=ts,
                                         end=""))
        self.assertEqual(("[" + _("ERROR") + "][" + ts.strftime("%X") + "] " +
                          StringConstants.COMPLEX_TEST_STRING, "test"),
                         uut.log(LOG_LEVEL.ERROR,
                                 StringConstants.COMPLEX_TEST_STRING,
                                 timestamp=ts,
                                 end=""))

        self.assertEqual(("[" + _("DEBUG") + "][" + ts.strftime("%X") + "] " +
                          StringConstants.COMPLEX_TEST_STRING, "test"),
                         uut.debug(StringConstants.COMPLEX_TEST_STRING,
                                   timestamp=ts,
                                   end=""))
        uut.log_level = LOG_LEVEL.WARNING
        self.assertEqual(
            None,
            uut.debug(StringConstants.COMPLEX_TEST_STRING,
                      timestamp=ts,
                      end=""))
        self.assertEqual(("[" + _("WARNING") + "][" + ts.strftime("%X") +
                          "] " + StringConstants.COMPLEX_TEST_STRING, "test"),
                         uut.warn(StringConstants.COMPLEX_TEST_STRING,
                                  timestamp=ts,
                                  end=""))
        self.assertEqual(("[" + _("ERROR") + "][" + ts.strftime("%X") + "] " +
                          StringConstants.COMPLEX_TEST_STRING, "test"),
                         uut.err(StringConstants.COMPLEX_TEST_STRING,
                                 timestamp=ts,
                                 end=""))

        logged = uut.log_exception("Something failed.",
                                   NotImplementedError(
                                       StringConstants.COMPLEX_TEST_STRING),
                                   timestamp=ts,
                                   end="")
        self.assertTrue(
            logged[0].startswith("[" + _("ERROR") + "][" + ts.strftime("%X") +
                                 "] Something failed.\n\n" +
                                 _("Exception was:") + "\n"))

    def test_raises(self):
        uut = LogPrinter()
        self.assertRaises(TypeError, uut.log, 5)
        self.assertRaises(TypeError, uut.log_exception, "message", 5)
        self.assertRaises(TypeError, uut.log_message, 5)
Beispiel #15
0
class LogMessageTest(unittest.TestCase):
    timestamp = datetime.today()

    def setUp(self):
        self.uut = LogMessage(LOG_LEVEL.DEBUG,
                              'test',
                              'message',
                              timestamp=self.timestamp)

    def test_construction(self):
        # take a look if defaults are good
        self.assertEqual(self.uut.log_level, LOG_LEVEL.DEBUG)
        self.assertEqual(self.uut.message, 'test message')
        self.assertEqual(self.uut.timestamp, self.timestamp)

        # see that arguments are processed right
        self.uut = LogMessage(LOG_LEVEL.WARNING,
                              '   a msg  ',
                              5,
                              '  ',
                              timestamp=self.timestamp)
        self.assertEqual(self.uut.log_level, LOG_LEVEL.WARNING)
        self.assertEqual(self.uut.message, '   a msg   5')
        self.assertEqual(self.uut.timestamp, self.timestamp)

        self.assertRaises(ValueError, LogMessage, LOG_LEVEL.DEBUG, '')
        self.assertRaises(ValueError, LogMessage, 5, 'test')

    def test_to_str(self):
        self.uut.message = Constants.COMPLEX_TEST_STRING
        self.uut.log_level = LOG_LEVEL.ERROR
        self.assertEqual(
            str(self.uut), '[{}] {}'.format('ERROR',
                                            Constants.COMPLEX_TEST_STRING))
        self.uut.log_level = LOG_LEVEL.WARNING
        self.assertEqual(
            str(self.uut), '[{}] {}'.format('WARNING',
                                            Constants.COMPLEX_TEST_STRING))
        self.uut.log_level = LOG_LEVEL.DEBUG
        self.assertEqual(
            str(self.uut), '[{}] {}'.format('DEBUG',
                                            Constants.COMPLEX_TEST_STRING))
        self.uut.log_level = 5
        self.assertEqual(
            str(self.uut), '[{}] {}'.format('ERROR',
                                            Constants.COMPLEX_TEST_STRING))

    def test_equals(self):
        self.assertEqual(LogMessage(LOG_LEVEL.DEBUG, 'test message'),
                         LogMessage(LOG_LEVEL.DEBUG, 'test message'))
        self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, 'test message'),
                            LogMessage(LOG_LEVEL.WARNING, 'test message'))
        self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, 'test message'),
                            LogMessage(LOG_LEVEL.DEBUG, 'test'))
        self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, 'test message'), 5)

    def test_string_dict(self):
        self.uut.log_level = LOG_LEVEL.DEBUG
        self.uut.message = 'test'
        self.assertEqual(
            self.uut.to_string_dict(), {
                'log_level': 'DEBUG',
                'message': 'test',
                'timestamp': self.timestamp.isoformat()
            })

        self.uut.timestamp = None
        self.uut.log_level = -9999  # invalid level
        self.assertEqual(self.uut.to_string_dict(), {
            'log_level': '',
            'message': 'test',
            'timestamp': ''
        })
Beispiel #16
0
 def log(self, log_level, message, timestamp=None, **kwargs):
     self.log_message(LogMessage(log_level, message, timestamp=timestamp),
                      **kwargs)
Beispiel #17
0
 def err(self, *messages, delimiter=" ", timestamp=None, **kwargs):
     self.log_message(
         LogMessage(LOG_LEVEL.ERROR,
                    *messages,
                    delimiter=delimiter,
                    timestamp=timestamp), **kwargs)
Beispiel #18
0
 def warn(self, *messages, delimiter=" ", timestamp=None, **kwargs):
     self.log_message(
         LogMessage(LOG_LEVEL.WARNING,
                    *messages,
                    delimiter=delimiter,
                    timestamp=timestamp), **kwargs)
Beispiel #19
0
 def log(self, log_level, message, timestamp=None, **kwargs):
     return self.log_message(LogMessage(log_level, message),
                             timestamp=timestamp,
                             **kwargs)
Beispiel #20
0
 def setUp(self):
     self.uut = LogMessage(LOG_LEVEL.DEBUG, "test message")
Beispiel #21
0
 def setUp(self):
     self.uut = LogMessage(LOG_LEVEL.DEBUG,
                           'test',
                           'message',
                           timestamp=self.timestamp)
Beispiel #22
0
 def setUp(self):
     self.uut = LogMessage(LOG_LEVEL.DEBUG,
                           "test",
                           "message",
                           timestamp=self.timestamp)
Beispiel #23
0
 def debug(self, message, timestamp=None, **kwargs):
     return self.log_message(LogMessage(LOG_LEVEL.DEBUG, message),
                             timestamp=timestamp,
                             **kwargs)
Beispiel #24
0
class LogMessageTest(unittest.TestCase):
    timestamp = datetime.today()

    def setUp(self):
        self.uut = LogMessage(LOG_LEVEL.DEBUG,
                              "test",
                              "message",
                              timestamp=self.timestamp)

    def test_construction(self):
        # take a look if defaults are good
        self.assertEqual(self.uut.log_level, LOG_LEVEL.DEBUG)
        self.assertEqual(self.uut.message, "test message")
        self.assertEqual(self.uut.timestamp, self.timestamp)

        # see that arguments are processed right
        self.uut = LogMessage(LOG_LEVEL.WARNING,
                              "   a msg  ",
                              5,
                              "  ",
                              timestamp=self.timestamp)
        self.assertEqual(self.uut.log_level, LOG_LEVEL.WARNING)
        self.assertEqual(self.uut.message, "   a msg   5")
        self.assertEqual(self.uut.timestamp, self.timestamp)

        self.assertRaises(ValueError, LogMessage, LOG_LEVEL.DEBUG, "")
        self.assertRaises(ValueError, LogMessage, 5, "test")

    def test_to_str(self):
        self.uut.message = Constants.COMPLEX_TEST_STRING
        self.uut.log_level = LOG_LEVEL.ERROR
        self.assertEqual(
            str(self.uut), "[{}] {}".format("ERROR",
                                            Constants.COMPLEX_TEST_STRING))
        self.uut.log_level = LOG_LEVEL.WARNING
        self.assertEqual(
            str(self.uut), "[{}] {}".format("WARNING",
                                            Constants.COMPLEX_TEST_STRING))
        self.uut.log_level = LOG_LEVEL.DEBUG
        self.assertEqual(
            str(self.uut), "[{}] {}".format("DEBUG",
                                            Constants.COMPLEX_TEST_STRING))
        self.uut.log_level = 5
        self.assertEqual(
            str(self.uut), "[{}] {}".format("ERROR",
                                            Constants.COMPLEX_TEST_STRING))

    def test_equals(self):
        self.assertEqual(LogMessage(LOG_LEVEL.DEBUG, "test message"),
                         LogMessage(LOG_LEVEL.DEBUG, "test message"))
        self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, "test message"),
                            LogMessage(LOG_LEVEL.WARNING, "test message"))
        self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, "test message"),
                            LogMessage(LOG_LEVEL.DEBUG, "test"))
        self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, "test message"), 5)

    def test_string_dict(self):
        self.uut.log_level = LOG_LEVEL.DEBUG
        self.uut.message = "test"
        self.assertEqual(
            self.uut.to_string_dict(), {
                "log_level": "DEBUG",
                "message": "test",
                "timestamp": self.timestamp.isoformat()
            })

        self.uut.timestamp = None
        self.uut.log_level = -9999  # invalid level
        self.assertEqual(self.uut.to_string_dict(), {
            "log_level": "",
            "message": "test",
            "timestamp": ""
        })
Beispiel #25
0
 def warn(self, message, timestamp=None, **kwargs):
     return self.log_message(LogMessage(LOG_LEVEL.WARNING, message),
                             timestamp=timestamp,
                             **kwargs)
Beispiel #26
0
 def setUp(self):
     self.uut = LogMessage(LOG_LEVEL.DEBUG,
                           "test",
                           "message",
                           timestamp=self.timestamp)
Beispiel #27
0
class LogMessageTest(unittest.TestCase):
    timestamp = datetime.today()

    def setUp(self):
        self.uut = LogMessage(LOG_LEVEL.DEBUG,
                              'test',
                              'message',
                              timestamp=self.timestamp)

    def test_construction(self):
        # take a look if defaults are good
        self.assertEqual(self.uut.log_level, LOG_LEVEL.DEBUG)
        self.assertEqual(self.uut.message, 'test message')
        self.assertEqual(self.uut.timestamp, self.timestamp)

        # see that arguments are processed right
        self.uut = LogMessage(LOG_LEVEL.WARNING,
                              '   a msg  ',
                              5,
                              '  ',
                              timestamp=self.timestamp)
        self.assertEqual(self.uut.log_level, LOG_LEVEL.WARNING)
        self.assertEqual(self.uut.message, '   a msg   5')
        self.assertEqual(self.uut.timestamp, self.timestamp)

        self.assertRaises(ValueError, LogMessage, LOG_LEVEL.DEBUG, '')
        self.assertRaises(ValueError, LogMessage, 5, 'test')

    def test_to_str(self):
        self.uut.message = Constants.COMPLEX_TEST_STRING
        self.uut.log_level = LOG_LEVEL.ERROR
        self.assertEqual(str(self.uut),
                         '[{}] {}'.format('ERROR',
                                          Constants.COMPLEX_TEST_STRING))
        self.uut.log_level = LOG_LEVEL.WARNING
        self.assertEqual(str(self.uut),
                         '[{}] {}'.format('WARNING',
                                          Constants.COMPLEX_TEST_STRING))
        self.uut.log_level = LOG_LEVEL.DEBUG
        self.assertEqual(str(self.uut),
                         '[{}] {}'.format('DEBUG',
                                          Constants.COMPLEX_TEST_STRING))
        self.uut.log_level = 5
        self.assertEqual(str(self.uut),
                         '[{}] {}'.format('ERROR',
                                          Constants.COMPLEX_TEST_STRING))

    def test_equals(self):
        self.assertEqual(LogMessage(LOG_LEVEL.DEBUG, 'test message'),
                         LogMessage(LOG_LEVEL.DEBUG, 'test message'))
        self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, 'test message'),
                            LogMessage(LOG_LEVEL.WARNING, 'test message'))
        self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, 'test message'),
                            LogMessage(LOG_LEVEL.DEBUG, 'test'))
        self.assertNotEqual(LogMessage(LOG_LEVEL.DEBUG, 'test message'), 5)

    def test_string_dict(self):
        self.uut.log_level = LOG_LEVEL.DEBUG
        self.uut.message = 'test'
        self.assertEqual(
            self.uut.to_string_dict(),
            {'log_level': 'DEBUG',
             'message': 'test',
             'timestamp': self.timestamp.isoformat()})

        self.uut.timestamp = None
        self.uut.log_level = -9999  # invalid level
        self.assertEqual(
            self.uut.to_string_dict(),
            {'log_level': '', 'message': 'test', 'timestamp': ''})
Beispiel #28
0
 def debug(self, *messages, delimiter=" ", timestamp=None, **kwargs):
     self.log_message(
         LogMessage(LOG_LEVEL.DEBUG,
                    *messages,
                    delimiter=delimiter,
                    timestamp=timestamp), **kwargs)
Beispiel #29
0
 def err(self, message, timestamp=None, **kwargs):
     return self.log_message(LogMessage(LOG_LEVEL.ERROR, message),
                             timestamp=timestamp,
                             **kwargs)
Beispiel #30
0
class LogPrinterTest(unittest.TestCase):
    timestamp = datetime.today()
    log_message = LogMessage(LOG_LEVEL.ERROR,
                             Constants.COMPLEX_TEST_STRING,
                             timestamp=timestamp)

    def test_interface(self):
        uut = LogPrinter(Printer())
        self.assertRaises(NotImplementedError,
                          uut.log_message,
                          self.log_message)

    def test_get_printer(self):
        self.assertIs(LogPrinter(None).printer, None)
        printer = Printer()
        self.assertIs(LogPrinter(printer).printer, printer)

    def test_logging(self):
        uut = LogPrinter(StringPrinter(), timestamp_format="")
        uut.log_message(self.log_message, end="")
        self.assertEqual(uut.printer.string, str(self.log_message))

        uut = LogPrinter(StringPrinter(), log_level=LOG_LEVEL.DEBUG)
        uut.log_message(self.log_message, end="")
        self.assertEqual(
            uut.printer.string,
            "[ERROR][" + self.timestamp.strftime("%X") + "] " +
            Constants.COMPLEX_TEST_STRING)

        uut.printer.clear()
        uut.log(LOG_LEVEL.ERROR,
                Constants.COMPLEX_TEST_STRING,
                timestamp=self.timestamp,
                end="")
        self.assertEqual(
            uut.printer.string,
            "[ERROR][" + self.timestamp.strftime("%X") + "] " +
            Constants.COMPLEX_TEST_STRING)

        uut.printer.clear()
        uut.debug(Constants.COMPLEX_TEST_STRING,
                  "d",
                  timestamp=self.timestamp,
                  end="")
        self.assertEqual(
            uut.printer.string,
            "[DEBUG][" + self.timestamp.strftime("%X") + "] " +
            Constants.COMPLEX_TEST_STRING + " d")

        uut.printer.clear()
        uut.log_level = LOG_LEVEL.INFO
        uut.debug(Constants.COMPLEX_TEST_STRING,
                  timestamp=self.timestamp,
                  end="")
        self.assertEqual(uut.printer.string, "")

        uut.printer.clear()
        uut.info(Constants.COMPLEX_TEST_STRING,
                 "d",
                 timestamp=self.timestamp,
                 end="")
        self.assertEqual(
            uut.printer.string,
            "[INFO][" + self.timestamp.strftime("%X") + "] " +
            Constants.COMPLEX_TEST_STRING + " d")

        uut.log_level = LOG_LEVEL.WARNING
        uut.printer.clear()
        uut.debug(Constants.COMPLEX_TEST_STRING,
                  timestamp=self.timestamp,
                  end="")
        self.assertEqual(uut.printer.string, "")

        uut.printer.clear()
        uut.warn(Constants.COMPLEX_TEST_STRING,
                 "d",
                 timestamp=self.timestamp,
                 end="")
        self.assertEqual(
            uut.printer.string,
            "[WARNING][" + self.timestamp.strftime("%X") + "] " +
            Constants.COMPLEX_TEST_STRING + " d")

        uut.printer.clear()
        uut.err(Constants.COMPLEX_TEST_STRING,
                "d",
                timestamp=self.timestamp,
                end="")
        self.assertEqual(
            uut.printer.string,
            "[ERROR][" + self.timestamp.strftime("%X") + "] " +
            Constants.COMPLEX_TEST_STRING + " d")

        uut.log_level = LOG_LEVEL.DEBUG
        uut.printer.clear()
        uut.log_exception(
            "Something failed.",
            NotImplementedError(Constants.COMPLEX_TEST_STRING),
            timestamp=self.timestamp)
        self.assertTrue(uut.printer.string.startswith(
            "[ERROR][" + self.timestamp.strftime("%X") +
            "] Something failed.\n" +
            "[DEBUG][" + self.timestamp.strftime("%X") +
            "] Exception was:"))

        uut.log_level = LOG_LEVEL.INFO
        uut.printer.clear()
        logged = uut.log_exception(
            "Something failed.",
            NotImplementedError(Constants.COMPLEX_TEST_STRING),
            timestamp=self.timestamp,
            end="")
        self.assertTrue(uut.printer.string.startswith(
            "[ERROR][" + self.timestamp.strftime("%X") +
            "] Something failed."))

    def test_raises(self):
        uut = LogPrinter(NullPrinter())
        self.assertRaises(TypeError, uut.log, 5)
        self.assertRaises(TypeError, uut.log_exception, "message", 5)
        self.assertRaises(TypeError, uut.log_message, 5)
Beispiel #31
0
 def info(self, *messages, delimiter=" ", timestamp=None, **kwargs):
     self.log_message(
         LogMessage(LOG_LEVEL.INFO,
                    *messages,
                    delimiter=delimiter,
                    timestamp=timestamp), **kwargs)
Beispiel #32
0
 def __send_msg(self, log_level, *args, delimiter=' ', end=''):
     output = str(delimiter).join(str(arg) for arg in args) + str(end)
     self.message_queue.put(LogMessage(log_level, output),
                            timeout=self.TIMEOUT)
Beispiel #33
0
 def setUp(self):
     self.uut = LogMessage(LOG_LEVEL.DEBUG,
                           'test',
                           'message',
                           timestamp=self.timestamp)