import logging

from messageprocessorutil import LoggingProcessorCallback


class TestLog(object):
    def setup(self):
        self.file_name = "log_file.log"
        handler = logging.FileHandler(self.file_name)
        handler.setFormatter(logging.Formatter('%(levelname)s\n%(message)s'))
        self.get_logger = logging.getLogger(__name__)
        self.get_logger.addHandler(handler)
        self.get_logger.addHandler(logging.StreamHandler())

        self.logging_callback = LoggingProcessorCallback(self.get_logger)

    def teardown(self):
        self._clear_log_file(self.file_name)

    def test_log(self):
        self._do_parse_exception()

        self._assert_contains(self.file_name, ["ERROR\n", "ZeroDivisionError"])

    def test_ignored_exceptions(self):
        self.logging_callback = LoggingProcessorCallback(self.get_logger, ignored_exceptions=[ZeroDivisionError])

        self._do_parse_exception()

        self._assert_empty(self.file_name)

    def test_warn_exceptions(self):
        log_level_exceptions = {ZeroDivisionError: logging.WARN}
        self.logging_callback = LoggingProcessorCallback(self.get_logger, log_level_exceptions=log_level_exceptions)

        self._do_parse_exception()

        self._assert_contains(self.file_name, ["WARNING\n", "ZeroDivisionError"])

    def _do_parse_exception(self):
        try:
            1 / 0
        except Exception as e:
            self.logging_callback.parse_exception("any_event_name", "any_request_id", "any_data", e)

    @staticmethod
    def _clear_log_file(filename):
        f = open(filename, 'r+')
        f.truncate(0)

    @staticmethod
    def _assert_contains(file_name, texts):
        with open(file_name) as f:
            content = f.read()
            for text in texts:
                assert text in content

    @staticmethod
    def _assert_empty(file_name):
        with open(file_name) as f:
            content = f.read()
            assert content == ""
