import logging
import unittest

from backend.bootstrap.runtime import configure_logging


class ConfigureLoggingTest(unittest.TestCase):
    def setUp(self) -> None:
        self._saved_handlers = logging.getLogger().handlers[:]
        self._saved_level = logging.getLogger().level
        logging.getLogger().handlers.clear()

    def tearDown(self) -> None:
        logging.getLogger().handlers[:] = self._saved_handlers
        logging.getLogger().setLevel(self._saved_level)

    def test_configures_root_logger_at_info(self) -> None:
        configure_logging()
        root = logging.getLogger()
        self.assertTrue(root.handlers)
        self.assertEqual(root.level, logging.INFO)
        with self.assertLogs("xiaobai.datahub", level="INFO") as captured:
            logging.getLogger("xiaobai.datahub").info("datahub shadow %s", {"dataset": "daily"})
        self.assertIn("datahub shadow", captured.output[0])

    def test_keeps_existing_configuration(self) -> None:
        handler = logging.NullHandler()
        logging.getLogger().addHandler(handler)
        configure_logging()
        self.assertEqual(logging.getLogger().handlers, [handler])


if __name__ == "__main__":
    unittest.main()
