"""logging_config.py 模块单元测试。"""
import unittest
import logging
import tempfile
from pathlib import Path

import sys

_ROOT = Path(__file__).resolve().parents[1]
_SRC = _ROOT / "src"
if str(_SRC) not in sys.path:
    sys.path.insert(0, str(_SRC))

from taolib.logging_config import configure_logging, get_logger


class TestConfigureLogging(unittest.TestCase):
    """测试 configure_logging 函数。"""

    def setUp(self) -> None:
        """每个测试前重置日志配置。"""
        logging.root.handlers.clear()

    def test_default_level(self) -> None:
        """测试默认日志级别。"""
        configure_logging()
        logger = get_logger("test")
        self.assertEqual(logger.level, logging.INFO)

    def test_custom_level(self) -> None:
        """测试自定义日志级别。"""
        configure_logging(level="DEBUG")
        logger = get_logger("test")
        self.assertEqual(logger.level, logging.DEBUG)

    def test_file_output(self) -> None:
        """测试文件输出。"""
        with tempfile.TemporaryDirectory() as temp_dir:
            log_file = Path(temp_dir) / "test.log"
            configure_logging(level="DEBUG", log_file=log_file)

            logger = get_logger("test_file")
            logger.debug("test message")

            self.assertTrue(log_file.exists())
            content = log_file.read_text(encoding="utf-8")
            self.assertIn("test message", content)

    def test_custom_format(self) -> None:
        """测试自定义格式。"""
        custom_format = "%(levelname)s: %(message)s"
        configure_logging(format_string=custom_format)

        logger = get_logger("test_format")
        handler = logger.handlers[0] if logger.handlers else logging.root.handlers[0]
        formatter = handler.formatter
        self.assertEqual(formatter._fmt, custom_format)

    def test_invalid_level_defaults_to_info(self) -> None:
        """测试无效级别默认为 INFO。"""
        configure_logging(level="INVALID")
        logger = get_logger("test")
        self.assertEqual(logger.level, logging.INFO)


class TestGetLogger(unittest.TestCase):
    """测试 get_logger 函数。"""

    def test_get_logger_returns_logger(self) -> None:
        """测试返回 Logger 实例。"""
        logger = get_logger("test_module")
        self.assertIsInstance(logger, logging.Logger)

    def test_get_logger_same_name_returns_same_instance(self) -> None:
        """测试相同名称返回相同实例。"""
        logger1 = get_logger("same_name")
        logger2 = get_logger("same_name")
        self.assertIs(logger1, logger2)

    def test_get_logger_different_names(self) -> None:
        """测试不同名称返回不同实例。"""
        logger1 = get_logger("name1")
        logger2 = get_logger("name2")
        self.assertIsNot(logger1, logger2)


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