20

I am testing an API with Django test client. The API uses geo blocking so in my test I need to specify an IP address to make sure it works properly. How can I do that?

I am making a request in my test like this:

from django.test.client import Client as HttpClient
.
.
.
client = HttpClient()
response = client.get(uri + query_string)
ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
Richard Knop
  • 81,041
  • 149
  • 392
  • 552

4 Answers4

32

The Client.get() method has an extra keyword arguments parameter, which can be used to specify headers.

c.get(/my-url/, REMOTE_ADDR="127.0.0.1") 
Alasdair
  • 298,606
  • 55
  • 578
  • 516
10

Pass REMOTE_ADDR in constructor.

client = HttpClient(REMOTE_ADDR='127.0.0.1')

or

client.get('/path/', {'param':'foo'}, **{'HTTP_USER_AGENT':'firefox-22', 'REMOTE_ADDR':'127.0.0.1'})
baklarz2048
  • 10,699
  • 2
  • 31
  • 37
2

You can also set it for all future requests:

client.defaults['REMOTE_ADDR'] = '1.2.3.4'

Also with subclassing:

class DecoratedApiClient(Client):
    def set_ip_addr(self, ip_addr):
        self.defaults['REMOTE_ADDR'] = ip_addr

client = DecoratedApiClient()
client.set_ip_addr('1.2.3.4')
gak
  • 32,061
  • 28
  • 119
  • 154
-2

As simple like this:

client_address = request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('REMOTE_ADDR')
catherine
  • 22,492
  • 12
  • 61
  • 85
  • This does not answer the question. This is a way to check the header, not to set it in the test client. Thank you for reminding me I had to check HTTP_X_FORWARDED_FOR, however :) – Luis Sieira Dec 25 '19 at 23:08
  • Does not answer the question. – Ricardo Oct 07 '20 at 18:53