from django.test import TestCase, RequestFactory
from bruce_django_requests_logger.utils import (
    get_client_ip,
    format_duration,
    should_log_request,
    RequestLog
)
from django.utils import timezone


class UtilsFunctionTest(TestCase):
    def test_format_duration(self):
        """测试持续时间格式化"""
        self.assertEqual(format_duration(0.000123), "123µs")
        self.assertEqual(format_duration(0.123), "123ms")
        self.assertEqual(format_duration(1.234), "1.234s")

    def test_should_log_request(self):
        """测试是否应该记录请求"""
        factory = RequestFactory()

        # 应该记录的请求
        request = factory.get('/api/users/')
        self.assertTrue(should_log_request(request))

        # 不应该记录的请求（静态文件）
        request = factory.get('/static/css/style.css')
        self.assertFalse(should_log_request(request))

        request = factory.get('/media/uploads/image.jpg')
        self.assertFalse(should_log_request(request))

        request = factory.get('/favicon.ico')
        self.assertFalse(should_log_request(request))


class RequestLogTest(TestCase):
    def test_request_log_creation(self):
        """测试请求日志对象创建"""
        log = RequestLog(
            method='POST',
            path='/api/users/',
            status_code=201,
            duration=0.234,
            ip='192.168.1.100',
            user_agent='Test Agent'
        )

        self.assertEqual(log.method, 'POST')
        self.assertEqual(log.path, '/api/users/')
        self.assertEqual(log.status_code, 201)
        self.assertEqual(log.duration, 0.234)
        self.assertEqual(log.ip, '192.168.1.100')
        self.assertEqual(log.user_agent, 'Test Agent')
        self.assertIsNotNone(log.timestamp)

    def test_request_log_to_dict(self):
        """测试请求日志转换为字典"""
        log = RequestLog(
            method='GET',
            path='/',
            status_code=200,
            duration=0.123,
            ip='127.0.0.1',
            user_agent='Test'
        )

        log_dict = log.to_dict()

        self.assertEqual(log_dict['method'], 'GET')
        self.assertEqual(log_dict['path'], '/')
        self.assertEqual(log_dict['status_code'], 200)
        self.assertEqual(log_dict['duration'], 0.123)
        self.assertEqual(log_dict['ip_address'], '127.0.0.1')
        self.assertEqual(log_dict['user_agent'], 'Test')
        self.assertIn('duration_formatted', log_dict)
        self.assertIn('timestamp', log_dict)

    def test_request_log_string_representation(self):
        """测试请求日志的字符串表示"""
        log = RequestLog(
            method='DELETE',
            path='/api/users/123/',
            status_code=204,
            duration=0.456,
            ip='10.0.0.1',
            user_agent='Test'
        )

        log_str = str(log)
        self.assertIn('DELETE', log_str)
        self.assertIn('/api/users/123/', log_str)
        self.assertIn('204', log_str)
        self.assertIn('456ms', log_str)