from django.test import TestCase, RequestFactory
from django.http import HttpResponse
from bruce_django_requests_logger.middleware import BruceRequestsLoggerMiddleware
from bruce_django_requests_logger.utils import get_client_ip, format_duration


class BruceRequestsLoggerMiddlewareTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.middleware = BruceRequestsLoggerMiddleware(self.get_response)

    def get_response(self, request):
        return HttpResponse("OK", status=200)

    def test_middleware_initialization(self):
        """测试中间件初始化"""
        self.assertIsNotNone(self.middleware)
        self.assertTrue(callable(self.middleware))

    def test_middleware_processing(self):
        """测试中间件处理请求"""
        request = self.factory.get('/test-path')
        response = self.middleware(request)

        self.assertEqual(response.status_code, 200)
        self.assertIn('X-Request-Duration', response)

    def test_create_log_entry(self):
        """测试创建日志条目"""
        request = self.factory.get('/test-path')
        request.META['HTTP_USER_AGENT'] = 'Test Agent'
        response = HttpResponse("OK", status=200)
        response['Content-Type'] = 'text/html'
        response['Content-Length'] = '2'

        duration = 0.123
        log_entry = self.middleware._create_log_entry(request, response, duration)

        self.assertEqual(log_entry['method'], 'GET')
        self.assertEqual(log_entry['path'], '/test-path')
        self.assertEqual(log_entry['status_code'], 200)
        self.assertEqual(log_entry['duration'], duration)
        self.assertEqual(log_entry['user_agent'], 'Test Agent')
        self.assertEqual(log_entry['content_type'], 'text/html')
        self.assertEqual(log_entry['content_length'], '2')


class UtilsTest(TestCase):
    def test_get_client_ip(self):
        """测试获取客户端IP"""
        factory = RequestFactory()

        # 测试 REMOTE_ADDR
        request = factory.get('/')
        request.META['REMOTE_ADDR'] = '192.168.1.1'
        self.assertEqual(get_client_ip(request), '192.168.1.1')

        # 测试 X_FORWARDED_FOR
        request = factory.get('/')
        request.META['HTTP_X_FORWARDED_FOR'] = '10.0.0.1, 192.168.1.1'
        self.assertEqual(get_client_ip(request), '10.0.0.1')

    def test_format_duration(self):
        """测试格式化持续时间"""
        self.assertEqual(format_duration(0.0005), "500µs")  # 微秒
        self.assertEqual(format_duration(0.05), "50ms")  # 毫秒
        self.assertEqual(format_duration(1.234), "1.234s")  # 秒