|
22
|
1 |
#from django.test.client import Client as DClient |
|
|
2 |
from django.conf import settings |
|
|
3 |
from django.core.urlresolvers import reverse |
|
|
4 |
from django.http import HttpResponse, SimpleCookie |
|
63
|
5 |
from django.test.client import (encode_multipart, Client, BOUNDARY, |
|
|
6 |
MULTIPART_CONTENT, CONTENT_TYPE_RE) |
|
22
|
7 |
from django.utils.encoding import smart_str |
|
|
8 |
from django.utils.http import urlencode |
|
|
9 |
from ldt.utils import Property |
|
198
|
10 |
from oauth2 import Request, Consumer, Token, SignatureMethod_HMAC_SHA1#@UnresolvedImport |
|
22
|
11 |
from urlparse import urlsplit, urlunsplit, urlparse, urlunparse, parse_qs |
|
|
12 |
import httplib2 |
|
|
13 |
try: |
|
|
14 |
from cStringIO import StringIO |
|
|
15 |
except ImportError: |
|
|
16 |
from StringIO import StringIO |
|
|
17 |
|
|
|
18 |
|
|
|
19 |
class WebClient(object): |
|
|
20 |
""" |
|
|
21 |
A class that can act as a client for testing purposes. |
|
|
22 |
|
|
|
23 |
It allows the user to compose GET and POST requests, and |
|
|
24 |
obtain the response that the server gave to those requests. |
|
|
25 |
The server Response objects are annotated with the details |
|
|
26 |
of the contexts and templates that were rendered during the |
|
|
27 |
process of serving the request. |
|
|
28 |
|
|
|
29 |
Client objects are stateful - they will retain cookie (and |
|
|
30 |
thus session) details for the lifetime of the Client instance. |
|
|
31 |
|
|
|
32 |
This is not intended as a replacement for Twill/Selenium or |
|
|
33 |
the like - it is here to allow testing against the |
|
|
34 |
contexts and templates produced by a view, rather than the |
|
|
35 |
HTML rendered to the end-user. |
|
|
36 |
""" |
|
|
37 |
def __init__(self, **defaults): |
|
|
38 |
self.handler = httplib2.Http() |
|
|
39 |
#self.defaults = defaults |
|
|
40 |
self.cookies = SimpleCookie() |
|
|
41 |
#self.exc_info = None |
|
|
42 |
#self.errors = StringIO() |
|
|
43 |
self.__baseurltuple = () |
|
|
44 |
self.__login_url = None |
|
|
45 |
|
|
|
46 |
@Property |
|
63
|
47 |
def baseurl(): #@NoSelf |
|
22
|
48 |
|
|
|
49 |
def fget(self): |
|
|
50 |
return self.__baseurltuple |
|
|
51 |
|
|
|
52 |
def fset(self, value): |
|
|
53 |
if isinstance(value, tuple): |
|
|
54 |
self.__baseurltuple = value |
|
|
55 |
else: |
|
|
56 |
self.__baseurltuple = urlsplit(unicode(value)) |
|
|
57 |
|
|
|
58 |
return locals() |
|
|
59 |
|
|
|
60 |
@Property |
|
63
|
61 |
def login_url(): #@NoSelf |
|
22
|
62 |
|
|
|
63 |
def fget(self): |
|
|
64 |
return self.__login_url |
|
|
65 |
|
|
|
66 |
def fset(self, value): |
|
|
67 |
self.__login_url = value |
|
|
68 |
|
|
|
69 |
return locals() |
|
|
70 |
|
|
|
71 |
|
|
|
72 |
def _mergeurl(self, urltuple): |
|
|
73 |
res = ["" for i in range(5)] |
|
|
74 |
for i in range(min(len(self.baseurl), len(urltuple))): |
|
|
75 |
res[i] = self.baseurl[i] or urltuple[i] |
|
|
76 |
|
|
|
77 |
return urlunsplit(res) |
|
|
78 |
|
|
|
79 |
def _process_response(self, response, content): |
|
|
80 |
resp = HttpResponse(content=content, status=response.status, content_type=response['content-type']) |
|
|
81 |
if 'set-cookie' in response: |
|
|
82 |
self.cookies.load(response['set-cookie']) |
|
|
83 |
resp.cookies.load(response['set-cookie']) |
|
|
84 |
|
|
|
85 |
resp.client = self |
|
|
86 |
resp.raw_response = response |
|
63
|
87 |
for key, value in response.items(): |
|
22
|
88 |
resp[key] = value |
|
|
89 |
|
|
|
90 |
return resp |
|
|
91 |
|
|
|
92 |
def _handle_redirects(self, response): |
|
|
93 |
|
|
|
94 |
response.redirect_chain = [] |
|
|
95 |
|
|
|
96 |
r = response.raw_response.previous |
|
|
97 |
while not r is None: |
|
63
|
98 |
response.redirect_chain.append((r['content-location'], r.status)) |
|
22
|
99 |
r = r.previous |
|
|
100 |
|
|
|
101 |
return response |
|
|
102 |
|
|
|
103 |
|
|
|
104 |
def get(self, path, data={}, follow=False, **extra): |
|
|
105 |
""" |
|
|
106 |
Requests a response from the server using GET. |
|
|
107 |
""" |
|
|
108 |
parsed = list(urlsplit(path)) |
|
|
109 |
parsed[3] = urlencode(data, doseq=True) or parsed[3] |
|
|
110 |
|
|
|
111 |
fullpath = self._mergeurl(parsed) |
|
|
112 |
self.handler.follow_redirects = follow |
|
|
113 |
|
|
|
114 |
headers = {} |
|
|
115 |
if len(self.cookies) > 0: |
|
|
116 |
headers['Cookie'] = self.cookies.output() |
|
|
117 |
|
|
|
118 |
if extra: |
|
|
119 |
headers.update(extra) |
|
|
120 |
|
|
|
121 |
response, content = self.handler.request(fullpath, method="GET", headers=headers) |
|
|
122 |
|
|
|
123 |
resp = self._process_response(response, content) |
|
|
124 |
|
|
|
125 |
if follow: |
|
|
126 |
resp = self._handle_redirects(resp) |
|
|
127 |
return resp |
|
|
128 |
|
|
|
129 |
|
|
|
130 |
def post(self, path, data={}, content_type="application/x-www-form-urlencoded", |
|
|
131 |
follow=False, **extra): |
|
|
132 |
""" |
|
|
133 |
Requests a response from the server using POST. |
|
|
134 |
""" |
|
|
135 |
if content_type == MULTIPART_CONTENT: |
|
|
136 |
post_data = encode_multipart(BOUNDARY, data) |
|
63
|
137 |
elif content_type == "application/x-www-form-urlencoded": |
|
22
|
138 |
post_data = urlencode(data) |
|
|
139 |
else: |
|
|
140 |
# Encode the content so that the byte representation is correct. |
|
|
141 |
match = CONTENT_TYPE_RE.match(content_type) |
|
|
142 |
if match: |
|
|
143 |
charset = match.group(1) |
|
|
144 |
else: |
|
|
145 |
charset = settings.DEFAULT_CHARSET |
|
|
146 |
post_data = smart_str(data, encoding=charset) |
|
|
147 |
|
|
|
148 |
parsed = list(urlsplit(path)) |
|
|
149 |
fullpath = self._mergeurl(parsed) |
|
|
150 |
self.handler.follow_redirects = follow |
|
|
151 |
|
|
|
152 |
headers = {} |
|
|
153 |
headers['Content-type'] = content_type |
|
|
154 |
if len(self.cookies) > 0: |
|
|
155 |
headers['Cookie'] = self.cookies.output() |
|
|
156 |
|
|
|
157 |
if extra: |
|
|
158 |
headers.update(extra) |
|
|
159 |
|
|
63
|
160 |
response, content = self.handler.request(fullpath, method="POST", headers=headers, body=post_data) |
|
22
|
161 |
|
|
|
162 |
resp = self._process_response(response, content) |
|
|
163 |
|
|
|
164 |
if follow: |
|
|
165 |
resp = self._handle_redirects(response) |
|
|
166 |
return resp |
|
|
167 |
|
|
|
168 |
def login(self, **credentials): |
|
|
169 |
""" |
|
|
170 |
Sets the Client to appear as if it has successfully logged into a site. |
|
|
171 |
|
|
|
172 |
Returns True if login is possible; False if the provided credentials |
|
|
173 |
are incorrect, or the user is inactive, or if the sessions framework is |
|
|
174 |
not available. |
|
|
175 |
""" |
|
|
176 |
resp = self.post(path=self.login_url, data=credentials, follow=False, **{"X-Requested-With" : "XMLHttpRequest"}) |
|
|
177 |
return resp.status_code == 302 |
|
|
178 |
|
|
|
179 |
|
|
|
180 |
def logout(self): |
|
|
181 |
""" |
|
|
182 |
Removes the authenticated user's cookies and session object. |
|
|
183 |
|
|
|
184 |
Causes the authenticated user to be logged out. |
|
|
185 |
""" |
|
|
186 |
self.cookies = SimpleCookie() |
|
|
187 |
|
|
|
188 |
|
|
|
189 |
def head(self, path, data={}, follow=False, **extra): |
|
|
190 |
""" |
|
|
191 |
Request a response from the server using HEAD. |
|
|
192 |
""" |
|
|
193 |
parsed = list(urlsplit(path)) |
|
|
194 |
parsed[3] = urlencode(data, doseq=True) or parsed[3] |
|
|
195 |
|
|
|
196 |
fullpath = self._mergeurl(parsed) |
|
|
197 |
self.handler.follow_redirects = follow |
|
|
198 |
|
|
|
199 |
headers = {} |
|
|
200 |
if len(self.cookies) > 0: |
|
|
201 |
headers['Cookie'] = self.cookies.output() |
|
|
202 |
|
|
|
203 |
if extra: |
|
|
204 |
headers.update(extra) |
|
|
205 |
|
|
|
206 |
response, content = self.handler.request(fullpath, method="HEAD", headers=headers) |
|
|
207 |
|
|
|
208 |
resp = self._process_response(response, content) |
|
|
209 |
|
|
|
210 |
if follow: |
|
|
211 |
resp = self._handle_redirects(resp) |
|
|
212 |
return resp |
|
|
213 |
|
|
|
214 |
|
|
|
215 |
|
|
|
216 |
def options(self, path, data={}, follow=False, **extra): |
|
|
217 |
""" |
|
|
218 |
Request a response from the server using OPTIONS. |
|
|
219 |
""" |
|
|
220 |
parsed = list(urlsplit(path)) |
|
|
221 |
parsed[3] = urlencode(data, doseq=True) or parsed[3] |
|
|
222 |
|
|
|
223 |
fullpath = self._mergeurl(parsed) |
|
|
224 |
self.handler.follow_redirects = follow |
|
|
225 |
|
|
|
226 |
headers = {} |
|
|
227 |
if len(self.cookies) > 0: |
|
|
228 |
headers['Cookie'] = self.cookies.output() |
|
|
229 |
|
|
|
230 |
if extra: |
|
|
231 |
headers.update(extra) |
|
|
232 |
|
|
|
233 |
response, content = self.handler.request(fullpath, method="OPTIONS", headers=headers) |
|
|
234 |
|
|
|
235 |
resp = self._process_response(response, content) |
|
|
236 |
|
|
|
237 |
if follow: |
|
|
238 |
resp = self._handle_redirects(resp) |
|
|
239 |
return resp |
|
|
240 |
|
|
|
241 |
|
|
|
242 |
def put(self, path, data={}, content_type="application/x-www-form-urlencoded", |
|
|
243 |
follow=False, **extra): |
|
|
244 |
""" |
|
|
245 |
Send a resource to the server using PUT. |
|
|
246 |
""" |
|
|
247 |
if content_type is MULTIPART_CONTENT: |
|
|
248 |
put_data = encode_multipart(BOUNDARY, data) |
|
63
|
249 |
elif content_type == "application/x-www-form-urlencoded": |
|
22
|
250 |
put_data = urlencode(data) |
|
|
251 |
else: |
|
|
252 |
put_data = data |
|
|
253 |
|
|
|
254 |
parsed = list(urlsplit(path)) |
|
|
255 |
parsed[3] = urlencode(data, doseq=True) or parsed[3] |
|
|
256 |
fullpath = self._mergeurl(parsed) |
|
|
257 |
self.handler.follow_redirects = follow |
|
|
258 |
|
|
|
259 |
headers = {} |
|
|
260 |
headers['Content-type'] = content_type |
|
|
261 |
if len(self.cookies) > 0: |
|
|
262 |
headers['Cookie'] = self.cookies.output() |
|
|
263 |
|
|
|
264 |
if extra: |
|
|
265 |
headers.update(extra) |
|
|
266 |
|
|
63
|
267 |
response, content = self.handler.request(fullpath, method="PUT", headers=headers, body=put_data) |
|
22
|
268 |
|
|
|
269 |
resp = self._process_response(response, content) |
|
|
270 |
|
|
|
271 |
if follow: |
|
|
272 |
resp = self._handle_redirects(response) |
|
|
273 |
return resp |
|
|
274 |
|
|
|
275 |
|
|
|
276 |
def delete(self, path, data={}, follow=False, **extra): |
|
|
277 |
""" |
|
|
278 |
Send a DELETE request to the server. |
|
|
279 |
""" |
|
|
280 |
parsed = list(urlsplit(path)) |
|
|
281 |
parsed[3] = urlencode(data, doseq=True) or parsed[3] |
|
|
282 |
|
|
|
283 |
fullpath = self._mergeurl(parsed) |
|
|
284 |
self.handler.follow_redirects = follow |
|
|
285 |
|
|
|
286 |
headers = {} |
|
|
287 |
if len(self.cookies) > 0: |
|
|
288 |
headers['Cookie'] = self.cookies.output() |
|
|
289 |
|
|
|
290 |
if extra: |
|
|
291 |
headers.update(extra) |
|
|
292 |
|
|
|
293 |
response, content = self.handler.request(fullpath, method="DELETE", headers=headers) |
|
|
294 |
|
|
|
295 |
resp = self._process_response(response, content) |
|
|
296 |
|
|
|
297 |
if follow: |
|
|
298 |
resp = self._handle_redirects(resp) |
|
|
299 |
return resp |
|
|
300 |
|
|
|
301 |
|
|
|
302 |
|
|
|
303 |
|
|
|
304 |
class OAuthPayload(object): |
|
|
305 |
|
|
|
306 |
def __init__(self, servername="testserver"): |
|
|
307 |
self._token = None |
|
|
308 |
self._servername = servername |
|
|
309 |
self._oauth_parameters = { |
|
|
310 |
'oauth_version': '1.0' |
|
|
311 |
} |
|
|
312 |
self._oauth_parameters_extra = { |
|
|
313 |
'oauth_callback': 'http://127.0.0.1/callback', |
|
|
314 |
'scope':'all' |
|
|
315 |
} |
|
|
316 |
self.errors = StringIO() |
|
|
317 |
|
|
|
318 |
def _get_signed_request(self, method, path, params): |
|
|
319 |
|
|
|
320 |
parameters = params.copy() |
|
|
321 |
parameters.update(self._oauth_parameters) |
|
|
322 |
oauth_request = Request.from_consumer_and_token(consumer=self._consumer, token=self._token, http_method=method, http_url=path, parameters=parameters) |
|
|
323 |
oauth_request.sign_request(SignatureMethod_HMAC_SHA1(), consumer=self._consumer, token=self._token) |
|
|
324 |
|
|
|
325 |
return oauth_request |
|
|
326 |
|
|
|
327 |
|
|
|
328 |
def set_consumer(self, key, secret): |
|
|
329 |
self._consumer = Consumer(key, secret) |
|
|
330 |
self._oauth_parameters['oauth_consumer_key'] = key |
|
|
331 |
|
|
|
332 |
def set_scope(self, value): |
|
|
333 |
self._oauth_parameters_extra['scope'] = value |
|
|
334 |
|
|
|
335 |
def inject_oauth_data(self, path, method, data): |
|
|
336 |
|
|
|
337 |
path_parsed = urlparse(path) |
|
|
338 |
|
|
63
|
339 |
if method == 'GET' and (data is None or len(data) == 0): |
|
22
|
340 |
new_data = parse_qs(path_parsed[4]) |
|
|
341 |
elif data is None: |
|
|
342 |
new_data = {} |
|
|
343 |
else: |
|
|
344 |
new_data = data.copy() |
|
|
345 |
|
|
63
|
346 |
clean_path = [''] * 6 |
|
22
|
347 |
clean_path[0] = 'http' |
|
|
348 |
clean_path[1] = self._servername |
|
63
|
349 |
for i in range(0, 4): |
|
22
|
350 |
clean_path[i] = path_parsed[i] or clean_path[i] |
|
|
351 |
path = urlunparse(clean_path) |
|
|
352 |
|
|
|
353 |
oauth_request = self._get_signed_request(method, path, new_data) |
|
|
354 |
|
|
|
355 |
new_data.update(oauth_request) |
|
|
356 |
|
|
|
357 |
return new_data |
|
|
358 |
|
|
|
359 |
def login(self, client, login_method, **credential): |
|
|
360 |
|
|
|
361 |
|
|
|
362 |
self._oauth_parameters.update(self._oauth_parameters_extra) |
|
|
363 |
#Obtaining a Request Token |
|
|
364 |
resp = client.get(reverse('oauth_request_token'), follow=True) |
|
|
365 |
if resp.status_code == 200: |
|
|
366 |
self._token = Token.from_string(resp.content) |
|
|
367 |
else: |
|
|
368 |
self.errors.write("oauth_request_token response status code fail : " + repr(resp)) |
|
|
369 |
return False |
|
|
370 |
|
|
|
371 |
#Requesting User Authorization |
|
|
372 |
res = login_method(client, **credential) |
|
|
373 |
if not res: |
|
|
374 |
self.errors.write("login failed : " + repr(credential)) |
|
|
375 |
return False |
|
|
376 |
|
|
|
377 |
resp = client.get(reverse('oauth_user_authorization')) |
|
|
378 |
if resp.status_code != 200: |
|
|
379 |
self.errors.write("oauth_user_authorization get response status code fail : " + repr(resp)) |
|
|
380 |
return False |
|
|
381 |
|
|
|
382 |
#"X-Requested-With" : "XMLHttpRequest" |
|
|
383 |
resp = client.post(reverse('oauth_user_authorization'), {'authorize_access':1}, **{"X-Requested-With" : "XMLHttpRequest"}) |
|
|
384 |
if resp.status_code != 302: |
|
|
385 |
self.errors.write("oauth_user_authorization post response status code fail : " + repr(resp)) |
|
|
386 |
return False |
|
|
387 |
|
|
|
388 |
location_splitted = urlsplit(resp["Location"]) |
|
|
389 |
location_query_dict = parse_qs(location_splitted[3]) |
|
|
390 |
self._token.verifier = location_query_dict['oauth_verifier'] |
|
|
391 |
|
|
|
392 |
|
|
|
393 |
#Obtaining an Access Token |
|
|
394 |
resp = client.get(reverse('oauth_access_token')) |
|
|
395 |
if resp.status_code == 200: |
|
|
396 |
self._token = Token.from_string(resp.content) |
|
|
397 |
for key in self._oauth_parameters_extra.keys(): |
|
|
398 |
if key in self._oauth_parameters: |
|
|
399 |
del(self._oauth_parameters[key]) |
|
|
400 |
return True |
|
|
401 |
else: |
|
|
402 |
self.errors.write("oauth_access_token get response status code fail : " + repr(resp)) |
|
|
403 |
return False |
|
|
404 |
|
|
|
405 |
def logout(self): |
|
|
406 |
self._token = None |
|
|
407 |
|
|
|
408 |
METHOD_MAPPING = { |
|
|
409 |
'get' : 'GET', |
|
|
410 |
'post' : 'POST', |
|
|
411 |
'put' : 'PUT', |
|
|
412 |
'head' : 'HEAD', |
|
|
413 |
'options' : 'OPTIONS', |
|
|
414 |
'delete' : 'DELETE' |
|
|
415 |
} |
|
|
416 |
|
|
|
417 |
def _generate_request_wrapper(meth): |
|
|
418 |
def request_wrapper(inst, *args, **kwargs): |
|
63
|
419 |
path = args[0] if len(args) > 0 else kwargs.get('path', '') |
|
|
420 |
data = args[1] if len(args) > 1 else kwargs.get('data', {}) |
|
22
|
421 |
args = args[2:] |
|
|
422 |
if 'path' in kwargs: |
|
|
423 |
del(kwargs['path']) |
|
|
424 |
if 'data' in kwargs: |
|
|
425 |
del(kwargs['data']) |
|
|
426 |
data = inst._oauth_data.inject_oauth_data(path, METHOD_MAPPING[meth.__name__], data) |
|
63
|
427 |
return meth(inst, path=path, data=data, *args, **kwargs) |
|
22
|
428 |
return request_wrapper |
|
|
429 |
|
|
|
430 |
def _generate_login_wrapper(meth): |
|
|
431 |
def login_wrapper(inst, **credential): |
|
|
432 |
return inst._oauth_data.login(inst, meth, **credential) |
|
|
433 |
return login_wrapper |
|
|
434 |
|
|
|
435 |
def _generate_logout_wrapper(meth): |
|
|
436 |
def logout_wrapper(inst): |
|
|
437 |
inst._oauth_data.logout() |
|
|
438 |
meth(inst) |
|
|
439 |
return logout_wrapper |
|
|
440 |
|
|
|
441 |
class OAuthMetaclass(type): |
|
|
442 |
|
|
|
443 |
def __new__(cls, name, bases, attrs): |
|
|
444 |
newattrs = {} |
|
|
445 |
def set_consumer(inst, key, secret): |
|
63
|
446 |
inst._oauth_data.set_consumer(key, secret) |
|
22
|
447 |
newattrs['set_consumer'] = set_consumer |
|
|
448 |
def set_scope(inst, scope): |
|
|
449 |
inst._oauth_data.set_scope(scope) |
|
|
450 |
newattrs['set_scope'] = set_scope |
|
|
451 |
|
|
|
452 |
for attrname, attrvalue in attrs.iteritems(): |
|
|
453 |
if attrname in ('get', 'post', 'head', 'options', 'put', 'delete'): |
|
|
454 |
newattrs[attrname] = _generate_request_wrapper(attrvalue) |
|
|
455 |
elif attrname == 'login': |
|
|
456 |
newattrs[attrname] = _generate_login_wrapper(attrvalue) |
|
|
457 |
elif attrname == 'logout': |
|
|
458 |
newattrs[attrname] = _generate_logout_wrapper(attrvalue) |
|
|
459 |
else: |
|
|
460 |
newattrs[attrname] = attrvalue |
|
|
461 |
|
|
|
462 |
for klass in bases: |
|
|
463 |
for attrname, attrvalue in klass.__dict__.iteritems(): |
|
|
464 |
if attrname in newattrs: |
|
|
465 |
continue |
|
|
466 |
if attrname in ('get', 'post', 'head', 'options', 'put', 'delete'): |
|
|
467 |
newattrs[attrname] = _generate_request_wrapper(attrvalue) |
|
|
468 |
elif attrname == 'login': |
|
|
469 |
newattrs[attrname] = _generate_login_wrapper(attrvalue) |
|
|
470 |
elif attrname == 'logout': |
|
|
471 |
newattrs[attrname] = _generate_logout_wrapper(attrvalue) |
|
|
472 |
|
|
|
473 |
init_method = newattrs.get("__init__", None) |
|
|
474 |
|
|
|
475 |
def new_init(inst, *args, **kwargs): |
|
63
|
476 |
inst._oauth_data = OAuthPayload(attrs.get('servername', 'testserver')) |
|
22
|
477 |
if init_method is not None: |
|
63
|
478 |
init_method(*args, **kwargs) |
|
22
|
479 |
else: |
|
63
|
480 |
super(inst.__class__, inst).__init__(*args, **kwargs) |
|
22
|
481 |
newattrs["__init__"] = new_init |
|
|
482 |
|
|
|
483 |
return super(OAuthMetaclass, cls).__new__(cls, name, bases, newattrs) |
|
|
484 |
|
|
|
485 |
|
|
|
486 |
|
|
|
487 |
class OAuthClient(Client): |
|
|
488 |
__metaclass__ = OAuthMetaclass |
|
|
489 |
|
|
|
490 |
|
|
|
491 |
class OAuthWebClient(WebClient): |
|
|
492 |
__metaclass__ = OAuthMetaclass |
|
|
493 |
servername = '127.0.0.1:8000' |