2 import django.test.client as client
3 import django.test as test
4 from django.utils.http import urlencode
7 from piston import oauth
8 from piston.models import Consumer, Token
10 # 3rd/Python party imports
11 import httplib2, urllib, cgi
13 URLENCODED_FORM_CONTENT = 'application/x-www-form-urlencoded'
15 class OAuthClient(client.Client):
16 def __init__(self, consumer, token):
17 self.token = oauth.OAuthToken(token.key, token.secret)
18 self.consumer = oauth.OAuthConsumer(consumer.key, consumer.secret)
19 self.signature = oauth.OAuthSignatureMethod_HMAC_SHA1()
21 super(OAuthClient, self).__init__()
23 def request(self, **request):
24 # Figure out parameters from request['QUERY_STRING'] and FakePayload
26 if request['REQUEST_METHOD'] in ('POST', 'PUT'):
27 if request['CONTENT_TYPE'] == URLENCODED_FORM_CONTENT:
28 payload = request['wsgi.input'].read()
29 request['wsgi.input'] = client.FakePayload(payload)
30 params = cgi.parse_qs(payload)
32 url = "http://testserver" + request['PATH_INFO']
34 req = oauth.OAuthRequest.from_consumer_and_token(
35 self.consumer, token=self.token,
36 http_method=request['REQUEST_METHOD'], http_url=url,
40 req.sign_request(self.signature, self.consumer, self.token)
41 headers = req.to_header()
42 request['HTTP_AUTHORIZATION'] = headers['Authorization']
44 return super(OAuthClient, self).request(**request)
46 def post(self, path, data={}, content_type=None, follow=False, **extra):
47 if content_type is None:
48 content_type = URLENCODED_FORM_CONTENT
50 if isinstance(data, dict):
51 data = urlencode(data)
53 return super(OAuthClient, self).post(path, data, content_type, follow, **extra)
55 class TestCase(test.TestCase):
58 class OAuthTestCase(TestCase):
61 return OAuthClient(self.consumer, self.token)