Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django RequestFactory add HTTP_X_FORWARDED_FOR

I have this code block that I am trying to write tests for:

def get_client_ip(req):
    """
    This is used to get the user's IP from the request object.

    """
    x_forwarded_for = req.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = req.META.get('REMOTE_ADDR', "unknown")
    return ip

So far I have been able to test the else section of the if statement. This is what my test currently looks like:

def test_get_client_ip(self):
    """
    Test the get Client IP fuction with a request.

    """
    # Create an instance of a GET request.
    request = self.factory.get('/home')
    ip = get_client_ip(request)
    self.assertEqual(ip, '127.0.0.1')

How would I go about adding "HTTP_X_FORWARDED_FOR" to META of the request object?

like image 983
NeuroWinter Avatar asked Dec 18 '22 23:12

NeuroWinter


1 Answers

Turns out you can give the get request additional headers using the extra keyword in the get method: https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.Client.get

Working code is as follows:

    def test_get_client_ip(self):
    """
    Test the get Client IP fuction with a request.

    """
    # Create an instance of a GET request.
    request = self.factory.get('/home')
    ip = get_client_ip(request)
    self.assertEqual(ip, '127.0.0.1')
    request = self.factory.get('/home', HTTP_X_FORWARDED_FOR="8.8.8.8")
    ip = get_client_ip(request)
    self.assertEqual(ip, '8.8.8.8')
like image 169
NeuroWinter Avatar answered Jan 02 '23 02:01

NeuroWinter