"""Logger 单元测试"""
import unittest
import time
from easy_log_sdk import Logger


class TestLogger(unittest.TestCase):
    """Logger 测试类"""
    
    def setUp(self):
        """测试前准备"""
        self.logger = Logger(
            app_name="test_app",
            server_url="http://localhost:8080",
            timeout=2.0
        )
    
    def test_basic_logging(self):
        """测试基础日志记录"""
        self.logger.info("测试日志", test=True)
        self.logger.error("错误日志", error_code=500)
        
        # 等待异步处理
        time.sleep(1)
        
        # 检查统计信息
        stats = self.logger.get_stats()
        self.assertIsNotNone(stats)
        self.assertIn('async_handler', stats)
    
    def test_log_levels(self):
        """测试不同日志级别"""
        self.logger.debug("Debug message")
        self.logger.info("Info message")
        self.logger.warning("Warning message")
        self.logger.error("Error message")
        self.logger.critical("Critical message")
        
        time.sleep(1)
    
    def test_metadata(self):
        """测试元数据"""
        metadata = {
            "user_id": 123,
            "action": "login",
            "ip": "192.168.1.1"
        }
        
        self.logger.info("用户操作", **metadata)
        time.sleep(1)
    
    def test_flush(self):
        """测试刷新缓冲区"""
        for i in range(10):
            self.logger.info(f"消息 {i}")
        
        # 强制刷新
        self.logger.flush()
        
        # 检查缓冲区是否为空
        stats = self.logger.get_stats()
        self.assertEqual(stats['async_handler']['buffer_size'], 0)
    
    def test_batch_logging(self):
        """测试批量日志"""
        count = 100
        
        for i in range(count):
            self.logger.info(f"批量消息 {i}", index=i)
        
        self.logger.flush()
        time.sleep(2)
        
        stats = self.logger.get_stats()
        self.assertGreater(stats['transport']['total_sent'], 0)


class TestCacheManager(unittest.TestCase):
    """缓存管理器测试"""
    
    def test_cache_creation(self):
        """测试缓存创建"""
        logger = Logger(
            app_name="cache_test",
            server_url="http://localhost:9999",  # 不存在的服务器
            timeout=1.0
        )
        
        # 发送日志（应该失败并缓存）
        for i in range(5):
            logger.error(f"缓存测试 {i}")
        
        time.sleep(3)
        
        # 检查缓存
        stats = logger.get_stats()
        self.assertGreater(stats['cache']['total_cached'], 0)


class TestCircuitBreaker(unittest.TestCase):
    """熔断器测试"""
    
    def test_circuit_breaker(self):
        """测试熔断器"""
        logger = Logger(
            app_name="circuit_test",
            server_url="http://localhost:9999",
            circuit_breaker_threshold=3,
            timeout=1.0
        )
        
        # 发送足够多的日志以触发熔断器
        for i in range(10):
            logger.error(f"熔断测试 {i}")
            time.sleep(0.5)
        
        # 检查熔断器状态
        stats = logger.get_stats()
        self.assertIn(stats['transport']['circuit_breaker_state'], ['open', 'half_open', 'closed'])


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