Login

Add Extra Headers to Test Client Requests

Author:
luftyluft
Posted:
July 3, 2008
Language:
Python
Version:
.96
Tags:
testing request test headers
Score:
1 (after 1 ratings)

As Simon Willison mentions in his Debugging Django presentation, using the Test Client in the interpreter can be a great way to take a peek at the raw results from a view. In some cases you may need to add additional headers to the request (for instance a piece of middleware may rely on them).

Though it is not mentioned in the reference documentation, a quick peek at the code confirmed my hopes that it would be possible to add data to the request. The Client get and post methods both accept an extra kwargs parameter that allow you to populate the request with additional data.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
"""
example of using the **extra kwarg param to add headers to the test client request
"""
from django.test.utils import setup_test_environment
setup_test_environment()
from django.test.client import Client
c = Client()

#example using a query string param
c.get('/some/path/', {'qs_param':'foo'}, **{'HTTP_USER_AGENT':'silly-human', 'REMOTE_ADDR':'127.0.0.1'})

#example without a query string param
c.get('/some/path/', **{'HTTP_USER_AGENT':'silly-human', 'REMOTE_ADDR':'127.0.0.1'})

More like this

  1. Effective content caching for mass-load site using redirect feature by nnseva 3 years, 8 months ago
  2. Add get_addr() method to request object by nikmolnar 2 years, 3 months ago
  3. django soaplib test client by erny 5 years, 12 months ago
  4. Smart {% if %} template tag by SmileyChris 6 years ago
  5. Simple Exception Response for AJAX debugging by newmaniese 7 years ago

Comments

Please login first before commenting.