minor infopages fixes
[wolnelektury.git] / apps / piston / test.py
1 # Django imports
2 import django.test.client as client
3 import django.test as test
4 from django.utils.http import urlencode
5
6 # Piston imports
7 from piston import oauth
8 from piston.models import Consumer, Token
9
10 # 3rd/Python party imports
11 import httplib2, urllib, cgi
12
13 URLENCODED_FORM_CONTENT = 'application/x-www-form-urlencoded'
14
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()
20
21         super(OAuthClient, self).__init__()
22
23     def request(self, **request):
24         # Figure out parameters from request['QUERY_STRING'] and FakePayload
25         params = {}
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)
31
32         url = "http://testserver" + request['PATH_INFO']
33
34         req = oauth.OAuthRequest.from_consumer_and_token(
35             self.consumer, token=self.token,
36             http_method=request['REQUEST_METHOD'], http_url=url,
37             parameters=params
38         )
39
40         req.sign_request(self.signature, self.consumer, self.token)
41         headers = req.to_header()
42         request['HTTP_AUTHORIZATION'] = headers['Authorization']
43
44         return super(OAuthClient, self).request(**request)
45
46     def post(self, path, data={}, content_type=None, follow=False, **extra):
47         if content_type is None:
48             content_type = URLENCODED_FORM_CONTENT
49
50         if isinstance(data, dict):
51             data = urlencode(data)
52
53         return super(OAuthClient, self).post(path, data, content_type, follow, **extra)
54
55 class TestCase(test.TestCase):
56     pass
57
58 class OAuthTestCase(TestCase):
59     @property
60     def oauth(self):
61         return OAuthClient(self.consumer, self.token)
62