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?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With