Testing and request META data

272 views
Skip to first unread message

Phlip

unread,
Dec 9, 2009, 1:06:16 PM12/9/09
to Django users
On Aug 14 2008, 5:39 am, "Hajo Smulders" <hajosmuld...@gmail.com>
wrote:

> I need to set the HTTP_REFERER in the request.META data of a test client so
> that i can unit test a view.
> How do I do this? ie: How do i fake an HTTP header on a test client?

Bump? I just hit this problem, and the above question is the only
traffic on it...

Russell Keith-Magee

unread,
Dec 9, 2009, 6:12:15 PM12/9/09
to django...@googlegroups.com
From the testing docs [1]:

"""
The extra keyword arguments parameter can be used to specify headers
to be sent in the request. For example:

>>> c = Client()
>>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
... HTTP_X_REQUESTED_WITH='XMLHttpRequest')
"""

[1] http://docs.djangoproject.com/en/dev/topics/testing/#django.test.client.Client.get

Yours,
Russ Magee %-)

Phlip

unread,
Dec 22, 2009, 4:47:01 PM12/22/09
to Django users
> >>> c = Client()
> >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
>
> ...       HTTP_X_REQUESTED_WITH='XMLHttpRequest')

Thanks!

Now how do I test an action that must use SSL? (I want a 304 bounce
message if the user tries to use plain text.)

I couldn't find a HTTPS or similar header to use...

Phlip

unread,
Dec 28, 2009, 1:05:58 PM12/28/09
to Django users
> Now how do I test an action that must use SSL? (I want a 304 bounce
> message if the user tries to use plain text.)

This looks promising!

class SSLAwareClient(Client):
def __init__(self, *args, **kwargs):
super(SSLAwareClient, self).__init__(*args, **kwargs)
self.ssl = False

def request(self, **request):
path = request.get('PATH_INFO', '/')
if path.startswith('http://'):
self.ssl = False
path = path[path.find('/', 7):]
elif path.startswith('https://'):
self.ssl = True
path = path[path.find('/', 8):]
request['PATH_INFO'] = path
if self.ssl:
request['HTTP_X_FORWARDED_SSL'] = 'on'
ret = super(SSLAwareClient, self).request(**request)
if ret.status_code in (301, 302):
assert request['REQUEST_METHOD'] != 'POST', 'Cannot
redirect posts: %s' % path
if '?' in ret['Location']:
path, querystring = ret['Location'].split('?')
return self.get(path, QUERY_STRING=querystring)
return self.get(ret['Location'])
return ret

Reply all
Reply to author
Forward
0 new messages