def test_log_exception_using_error_to_log(self, mock_config_file):
        """Test that the logging of exceptions appear as expected. """
        with patch('gtmcore.logging.LMLogger.CONFIG_INSTALLED_LOCATION',
                   new_callable=PropertyMock,
                   return_value=mock_config_file):
            lmlog = LMLogger()
            logger = LMLogger.get_logger()

        try:
            assert False
        except AssertionError as e:
            # Note, using exc_info=True additionally prints the current stack context.
            logger.error(e, exc_info=True)

        with open(lmlog.log_file, 'rt') as test_file:
            data = test_file.readlines()

            found = False
            for d in data:
                # Make sure it's JSON parseable
                n = json.loads(d)
                assert n, "Loaded JSON entry must not be None"

            assert any([
                'AssertionError' in (d['exc_info'] or "")
                for d in [json.loads(x) for x in data if x]
            ])
    def test_init(self, mock_config_file):
        """Test loading a config file explicitly"""
        lmlog = LMLogger(mock_config_file)

        assert type(lmlog) is LMLogger
        assert lmlog.config_file is mock_config_file
        assert type(lmlog.logger) is logging.Logger
    def test_log_exception(self, mock_config_file):
        """Test that the logging of exceptions appear as expected. """
        with patch('gtmcore.logging.LMLogger.CONFIG_INSTALLED_LOCATION',
                   new_callable=PropertyMock,
                   return_value=mock_config_file):
            # NOTE!! This should be the standard way to load the logger in each package.
            # Do NOT use LMLogger().logger because you will lose the stack context and knowledge
            # of source package, method, and line.
            lmlog = LMLogger()
            logger = LMLogger.get_logger()

        try:
            1 / 0
        except ZeroDivisionError as e:
            logger.exception(e)

        with open(lmlog.log_file, 'rt') as test_file:
            data = test_file.readlines()
            for d in data:
                # Make sure it's JSON parseable
                assert json.loads(d)
            # Note sometimes 'exec_info' returns None so we have to do (... or "") to make it an iterable.
            assert any([
                'Traceback (most recent call last)' in (d.get('exc_info')
                                                        or "")
                for d in [json.loads(x) for x in data if x]
            ])
    def test_log(self, mock_config_file):
        """Test logging"""
        with patch('gtmcore.logging.LMLogger.CONFIG_INSTALLED_LOCATION',
                   new_callable=PropertyMock,
                   return_value=mock_config_file):
            lmlog = LMLogger()

        assert type(lmlog) is LMLogger
        assert lmlog.config_file is mock_config_file
        assert type(lmlog.logger) is logging.Logger

        logger = lmlog.logger

        logger.debug("##DE_BUG##")
        logger.info("##IN_FO##")
        logger.warning("##WA_RN##")
        logger.error("##ER_ROR##")

        with open(lmlog.log_file, 'rt') as test_file:
            data = [json.loads(s) for s in test_file.readlines()]

            assert all([d['filename'] == 'test_logging.py' for d in data])

            assert "##IN_FO##" in data[0]['message']
            assert "INFO" == data[0]['levelname']
            assert "##WA_RN##" in data[1]['message']
            assert "WARNING" == data[1]['levelname']
            assert "##ER_ROR##" in data[2]['message']
            assert "ERROR" == data[2]['levelname']
    def test_init_load_from_install(self, mock_config_file):
        """Test loading the default file from the installed location"""
        with patch('gtmcore.logging.LMLogger.CONFIG_INSTALLED_LOCATION',
                   new_callable=PropertyMock,
                   return_value=mock_config_file):
            lmlog = LMLogger()

        assert type(lmlog) is LMLogger
        assert lmlog.config_file is mock_config_file
        assert type(lmlog.logger) is logging.Logger
    def test_init_load_from_package(self):
        """Test loading the default file from the package"""
        lmlog = LMLogger()

        assert type(lmlog) is LMLogger

        if os.path.exists(LMLogger.CONFIG_INSTALLED_LOCATION):
            assert lmlog.config_file.rsplit("/", 1)[1] == "logging.json"
        else:
            assert lmlog.config_file.rsplit("/",
                                            1)[1] == "logging.json.default"

        assert type(lmlog.logger) is logging.Logger
    def test_load_logger_by_name(self, mock_config_file):
        """Test loading the logger by name rather than by LMLogger.logger. """
        with patch('gtmcore.logging.LMLogger.CONFIG_INSTALLED_LOCATION',
                   new_callable=PropertyMock,
                   return_value=mock_config_file):
            lmlog = LMLogger()

        logger = logging.getLogger("labmanager")
        logger.warning('test_load_logger_by_name')

        with open(lmlog.log_file, 'rt') as test_file:
            data = test_file.readlines()
            for d in data:
                # Make sure it's JSON parseable
                assert json.loads(d)

            assert any(['test_load_logger_by_name' in d for d in data])
Beispiel #8
0
def get_logged_in_username() -> str:
    """A Method to get the current logged in user's username


    Returns:
        str
    """
    user = get_logged_in_user()

    if not user:
        logger = LMLogger()
        logger.logger.error(
            "Failed to load a user identity from request context.")
        raise ValueError(
            "Failed to load a user identity from request context.")

    return user.username
Beispiel #9
0
def get_logged_in_author():
    """A Method to get the current logged in user's GitAuthor instance


    Returns:
        GitAuthor
    """
    user = get_logged_in_user()

    if not user:
        logger = LMLogger()
        logger.logger.error(
            "Failed to load a user identity from request context.")
        raise ValueError(
            "Failed to load a user identity from request context.")

    # Create a GitAuthor instance if possible

    return GitAuthor(name=user.username, email=user.email)