forked from Lispython/human_curl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtests.py
executable file
·1178 lines (884 loc) · 47 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
human_curl.tests
~~~~~~~~~~~~~~~~
Unittests for human_curl
:copyright: (c) 2011 - 2012 by Alexandr Lispython ([email protected]).
:license: BSD, see LICENSE for more details.
"""
from __future__ import with_statement
import os
import time
import pycurl
import cookielib
from Cookie import Morsel
import json
import uuid
from random import randint, choice
from string import ascii_letters, digits
import logging
from urlparse import urljoin
import unittest
import urllib
from types import TupleType, ListType, FunctionType, DictType
from urllib import urlencode
import human_curl as requests
from human_curl import Request, Response
from human_curl import AsyncClient
from human_curl.auth import *
from human_curl.utils import *
from human_curl.exceptions import (CurlError, InterfaceError)
logger = logging.getLogger("human_curl.test")
## async_logger = logging.getLogger("human_curl.async")
## async_logger.setLevel(logging.DEBUG)
## # Add the log message handler to the logger
## # LOG_FILENAME = os.path.join(os.path.dirname(__file__), "debug.log")
## # handler = logging.handlers.FileHandler(LOG_FILENAME)
## handler = logging.StreamHandler()
## formatter = logging.Formatter("%(levelname)s %(asctime)s %(module)s [%(lineno)d] %(process)d %(thread)d | %(message)s ")
## handler.setFormatter(formatter)
## async_logger.addHandler(handler)
TEST_METHODS = (
('get', requests.get),
('post', requests.post),
('head', requests.head),
('delete', requests.delete),
('put', requests.put),
('options', requests.options))
# Use https://github.com/Lispython/httphq
HTTP_TEST_URL = os.environ.get('HTTP_TEST_URL', 'http://httpbin.org')
HTTPS_TEST_URL = os.environ.get('HTTPS_TEST_URL', 'https://httpbin.org')
print("Use {0} as test server".format(HTTP_TEST_URL))
def build_url(*parts):
return urljoin(HTTP_TEST_URL, "/".join(parts))
def build_url_secure(*parts):
return urljoin(HTTPS_TEST_URL, "/".join(parts))
TEST_SERVERS = (build_url, build_url_secure)
def stdout_debug(debug_type, debug_msg):
"""Print messages
"""
debug_types = ('I', '<', '>', '<', '>')
if debug_type == 0:
print('%s' % debug_msg.strip())
elif debug_type in (1, 2):
for line in debug_msg.splitlines():
print('%s %s' % (debug_types[debug_type], line))
elif debug_type == 4:
print('%s %r' % (debug_types[debug_type], debug_msg))
def random_string(num=10):
return ''.join([choice(ascii_letters + digits) for x in xrange(num)])
class BaseTestCase(unittest.TestCase):
@staticmethod
def random_string(num=10):
return random_string(10)
def random_dict(self, num=10):
return dict([(self.random_string(10), self.random_string(10))for x in xrange(10)])
def request_params(self):
data = self.random_dict(10)
data['url'] = build_url("get")
data['method'] = 'get'
return data
class RequestsTestCase(BaseTestCase):
def test_build_url(self):
self.assertEquals(build_url("get"), HTTP_TEST_URL + "/" + "get")
self.assertEquals(build_url("post"), HTTP_TEST_URL + "/" + "post")
self.assertEquals(build_url("redirect", "3"), HTTP_TEST_URL + "/" + "redirect" + "/" + "3")
def tests_invalid_url(self):
self.assertRaises(ValueError, requests.get, "wefwefwegrer")
def test_url(self):
self.assertEquals(requests.get(build_url("get")).url, build_url("get"))
def test_request(self):
for method, method_func in TEST_METHODS:
r = method_func(build_url(method))
self.assertTrue(isinstance(r, Response))
def test_HTTP_GET(self):
r = requests.get(build_url("get"))
self.assertEquals(r.status_code, 200)
def test_HTTP_POST(self):
r = requests.post(build_url("post"))
self.assertEquals(r.status_code, 200)
def test_HTTP_HEAD(self):
r = requests.head(build_url("get"))
self.assertEquals(r.status_code, 200)
def test_HTTP_PUT(self):
r = requests.put(build_url("put"))
self.assertEquals(r.status_code, 200)
r2 = requests.put(build_url("put"),
data='kcjbwefjhwbcelihbflwkh')
self.assertEquals(r2.status_code, 200)
def test_HTTP_DELETE(self):
r = requests.delete(build_url("delete"))
self.assertEquals(r.status_code, 200)
def test_HTTP_OPTIONS(self):
r = requests.options(build_url("get"))
self.assertEquals(r.status_code, 200)
def test_HEADERS(self):
headers = (("Test-Header", "test-header-value"),
("Another-Test-Header", "kjwbrlfjbwekjbf"))
r = requests.get(build_url("headers"), headers=headers)
self.assertEquals(r.status_code, 200)
r_json = json.loads(r.content)
self.assertDictContainsSubset(dict(headers), r_json['headers'])
def test_PARAMS(self):
params = {'q': 'test param'}
r = requests.get(build_url("get""?test=true"), params=params)
self.assertEquals(r.status_code, 200)
args = json.loads(r.content)['args']
self.assertEquals(args['q'], params['q'])
self.assertEquals(args["test"], "true")
def test_POST_DATA(self):
random_key = "key_" + uuid.uuid4().get_hex()[:10]
random_value = "value_" + uuid.uuid4().get_hex()
r = requests.post(build_url('post'),
data={random_key: random_value})
self.assertEquals(r.status_code, 200)
def test_PUT_DATA(self):
random_key = "key_" + uuid.uuid4().get_hex()[:10]
random_value = "value_" + uuid.uuid4().get_hex()
r = requests.put(build_url('put'),
data={random_key: random_value})
self.assertEquals(r.status_code, 200)
def test_POST_RAW_DATA(self):
random_key = "key_" + uuid.uuid4().get_hex()[:10]
random_value = "value_" + uuid.uuid4().get_hex()
data = "%s:%s" % (random_key, random_value)
r = requests.post(build_url('post'),
data=data)
self.assertEquals(r.status_code, 200)
self.assertTrue(data in r.content)
def test_PUT_RAW_DATA(self):
random_key = "key_" + uuid.uuid4().get_hex()[:10]
random_value = "value_" + uuid.uuid4().get_hex()
data = "%s:%s" % (random_key, random_value)
r = requests.put(build_url('put'),
data=data)
self.assertEquals(r.status_code, 200)
self.assertTrue(data in r.content)
def test_FILES(self):
files = {'test_file': open('tests.py'),
'test_file2': open('README.rst')}
r = requests.post(build_url('post'),
files=files)
json_response = json.loads(r.content)
self.assertEquals(r.status_code, 200)
for k, v in files.items():
self.assertTrue(k in json_response['files'].keys())
def test_POST_DATA_and_FILES(self):
files = {'test_file': open('tests.py'),
'test_file2': open('README.rst')}
random_key1 = "key_" + uuid.uuid4().get_hex()[:10]
random_value1 = "value_" + uuid.uuid4().get_hex()
random_key2 = "key_" + uuid.uuid4().get_hex()[:10]
random_value2 = "value_" + uuid.uuid4().get_hex()
r = requests.post(build_url('post'),
data={random_key1: random_value2,
random_key2: random_value2},
files=files)
self.assertEquals(r.status_code, 200)
def test_PUT_DATA_and_FILES(self):
files = {'test_file': open('tests.py'),
'test_file2': open('README.rst')}
random_key1 = "key_" + uuid.uuid4().get_hex()[:10]
random_key2 = "key_" + uuid.uuid4().get_hex()[:10]
random_value2 = "value_" + uuid.uuid4().get_hex()
r = requests.put(build_url('put'),
data={random_key1: random_value2,
random_key2: random_value2},
files=files)
self.assertEquals(r.status_code, 200)
def test_cookies_jar(self):
random_key = "key_" + uuid.uuid4().get_hex()[:10]
random_value = "value_" + uuid.uuid4().get_hex()
random_key2 = "key_" + uuid.uuid4().get_hex()[:10]
random_value2 = "value_" + uuid.uuid4().get_hex()
cookies = ((random_key, random_value),
(random_key2, random_value2))
cookies_jar = cookielib.CookieJar()
r1 = requests.get(build_url("cookies", "set", random_key, random_value),
cookies=cookies_jar)
self.assertEquals(r1.cookies[random_key], random_value)
rtmp = requests.get(build_url("cookies", "set", random_key2, random_value2),
cookies=cookies_jar)
for cookie in cookies_jar:
if cookie.name == random_key:
self.assertEquals(cookie.value, random_value)
r3 = requests.get(build_url('cookies'), cookies=cookies_jar)
json_response = json.loads(r3.content)
for k, v in cookies:
self.assertEquals(json_response['cookies'][k], v)
def test_send_cookies(self):
random_key = "key_" + uuid.uuid4().get_hex()[:10]
random_value = "value_" + uuid.uuid4().get_hex()
random_key2 = "key_" + uuid.uuid4().get_hex()[:10]
random_value2 = "value_" + uuid.uuid4().get_hex()
cookies = ((random_key, random_value),
(random_key2, random_value2))
r = requests.get(build_url('cookies'), cookies=cookies)
json_response = json.loads(r.content)
self.assertEquals(json_response['cookies'][random_key], random_value)
def test_basic_auth(self):
username = uuid.uuid4().get_hex()
password = uuid.uuid4().get_hex()
auth_manager = BasicAuth(username, password)
r = requests.get(build_url('basic-auth', username, password),
auth=auth_manager)
self.assertEquals(r.status_code, 200)
json_response = json.loads(r.content)
self.assertEquals(json_response['authenticated'], True)
self.assertEquals(json_response['user'], username)
def test_digest_auth(self):
username = uuid.uuid4().get_hex()
password = uuid.uuid4().get_hex()
auth_manager = DigestAuth(username, password)
r = requests.get(build_url('digest-auth/auth', username, password),
auth=auth_manager, allow_redirects=True)
self.assertEquals(r.status_code, 200)
json_response = json.loads(r.content)
self.assertEquals(json_response['authenticated'], True)
self.assertEquals(json_response['user'], username)
def test_auth_denied(self):
username = "hacker_username"
password = "hacker_password"
http_auth = (username, password)
r = requests.get(build_url('basic-auth', "username", "password"), auth=http_auth)
self.assertEquals(r.status_code, 401)
def test_multivalue_params(self):
random_key = "key_" + uuid.uuid4().get_hex()[:10]
random_value1 = "value_" + uuid.uuid4().get_hex()
random_value2 = "value_" + uuid.uuid4().get_hex()
r = requests.get(build_url("get"),
params={random_key: (random_value1, random_value2)})
self.assertEquals(build_url("get?%s" %
urlencode(((random_key, random_value1), (random_key, random_value2)))), r.url)
json_response = json.loads(r.content)
self.assertTrue(random_value1 in json_response['args'][random_key])
self.assertTrue(random_value2 in json_response['args'][random_key])
def test_multivalue_post_data(self):
random_key = "key_" + uuid.uuid4().get_hex()[:10]
random_value1 = "value_" + uuid.uuid4().get_hex()
random_value2 = "value_" + uuid.uuid4().get_hex()
r = requests.post(build_url("post"),
data={random_key: (random_value1, random_value2)})
json_response = json.loads(r.content)
self.assertListEqual([random_value1, random_value2], json_response['form'][random_key])
def test_multipart_post_data(self):
random_key = "key_" + uuid.uuid4().get_hex()[:10]
random_value = "value_" + uuid.uuid4().get_hex()
r = requests.post(
build_url("post"),
data={random_key: random_value},
headers={'Content-Type': 'multipart/form-data'})
json_response = json.loads(r.content)
content_type = json_response['headers']['Content-Type']
self.assertEquals(random_value, json_response['form'][random_key])
self.assertTrue('multipart/form-data; boundary=-' in content_type)
def test_redirect(self):
r = requests.get(build_url("redirect", '3'), allow_redirects=True)
self.assertEquals(r.status_code, 200)
self.assertEquals(len(r.history), 3)
self.assertEquals(r.url, build_url("get"))
self.assertEquals(r._request_url, build_url("redirect/3"))
self.assertRaises(CurlError, requests.get, build_url("redirect", '7'),
allow_redirects=True)
def test_gzip(self):
r = requests.get(build_url("gzip"), use_gzip=True)
self.assertEquals(r.headers['Content-Encoding'], 'gzip')
json_response = json.loads(r.content)
self.assertEquals(json_response['gzipped'], True)
def test_implicit_gzip(self):
r = requests.get(build_url("gzip"))
self.assertEquals(r.headers['Content-Encoding'], 'gzip')
json_response = json.loads(r.content)
self.assertEquals(json_response['gzipped'], True)
def test_response_info(self):
r = requests.get(build_url("get"))
def test_unicode_domains(self):
r = requests.get("http://➡.ws/pep8")
self.assertEquals(r.url, 'http://xn--hgi.ws/pep8')
def test_hooks(self):
def pre_hook(r):
r.pre_hook = True
def post_hook(r):
r.post_hook = True
def response_hook(r):
r._status_code = 700
return r
r1 = requests.get(build_url("get"), hooks={'pre_request': pre_hook,
'post_request': post_hook})
self.assertEquals(r1._request.pre_hook, True)
self.assertEquals(r1._request.post_hook, True)
r2 = requests.get(build_url("get"), hooks={'response_hook': response_hook})
self.assertEquals(r2._status_code, 700)
def test_json_response(self):
random_key = "key_" + uuid.uuid4().get_hex()[:10]
random_value1 = "value_" + uuid.uuid4().get_hex()
random_value2 = "value_" + uuid.uuid4().get_hex()
r = requests.get(build_url("get"),
params={random_key: (random_value1, random_value2)})
self.assertEquals(build_url("get?%s" %
urlencode(((random_key, random_value1), (random_key, random_value2)))), r.url)
json_response = json.loads(r.content)
self.assertTrue(isinstance(r.json, (dict, DictType)))
self.assertEquals(json_response, r.json)
self.assertTrue(random_value1 in r.json['args'][random_key])
self.assertTrue(random_value2 in r.json['args'][random_key])
def test_get_encode_query(self):
params = {'q': 'value with space and @'}
key, value = 'email', '[email protected]'
response = requests.get(build_url("get""?%s=%s" % (key, value)), params=params)
self.assertEquals(response.status_code, 200)
self.assertEqual("{0}/get?email=user%40domain.com&q=value+with+space+and+%40".format(HTTP_TEST_URL), response.request._url)
args = json.loads(response.content)['args']
self.assertEquals(args['q'], params['q'])
self.assertEquals(args[key], value)
def test_get_no_encode_query(self):
params = {'q': 'value with space and @'}
key, value = 'email', '[email protected]'
# Invalid by HTTP spec
try:
response = requests.get(build_url("get""?%s=%s" % (key, value)), params=params, encode_query=False)
except CurlError, e:
self.assertEqual(e.code, 52)
else:
self.assertEquals(response.status_code, 400)
self.assertEqual("{0}/[email protected]&q=value with space and @".format(HTTP_TEST_URL), response.request._url)
def test_request_key_with_empty_value(self):
key = "key"
value = ""
url = build_url("get""?%s=%s" % (key, value))
response = requests.get(url)
self.assertEqual(url, response.request.url)
def test_request_key_no_equal(self):
key = "key+"
url = build_url("get""?%s" % key)
response = requests.get(url)
self.assertEqual("{0}/get?key%2B".format(HTTP_TEST_URL), response.request.url)
def test_request_key_no_equal_and_params(self):
key = "key"
params = {"a": "b"}
url = build_url("get""?%s" % key)
response = requests.get(url, params=params)
self.assertEqual(url + "=" + "&a=b", response.request.url)
class ResponseTestCase(BaseTestCase):
def setUp(self):
pass
def tearDown(self):
pass
class RequestTestCase(BaseTestCase):
def setUp(self):
pass
def tearDown(self):
pass
class UtilsTestCase(BaseTestCase):
def test_case_insensitive_dict(self):
test_data = {
"lower-case-key": uuid.uuid4().hex,
"UPPER-CASE-KEY": uuid.uuid4().hex,
"CamelCaseKey": uuid.uuid4().hex}
cidict = CaseInsensitiveDict(test_data)
for k, v in test_data.items():
self.assertTrue(cidict[k], v)
def test_cookies_from_jar(self):
test_cookie_jar = cookielib.CookieJar()
cookies_dict = from_cookiejar(test_cookie_jar)
for cookie in test_cookie_jar:
self.assertEquals(cookies_dict[cookie.name], cookie.value)
def test_jar_from_cookies(self):
cookies_dict = dict([(uuid.uuid4().hex, uuid.uuid4().hex) for x in xrange(10)])
cookies_list = [(uuid.uuid4().hex, uuid.uuid4().hex) for x in xrange(10)]
cookiejar1 = to_cookiejar(cookies_dict)
cookiejar2 = to_cookiejar(cookies_list)
for cookie in cookiejar1:
self.assertEquals(cookie.value, cookies_dict[cookie.name])
for cookie in cookiejar2:
for k, v in cookies_list:
if k == cookie.name:
self.assertEquals(cookie.value, v)
def test_decode_gzip(self):
from gzip import GzipFile
try:
from cString import StringIO
except ImportError:
from StringIO import StringIO
data_for_gzip = Request.__doc__
tmp_buffer = StringIO()
gziped_buffer = GzipFile(
fileobj=tmp_buffer,
mode="wb",
compresslevel=7)
gziped_buffer.write(data_for_gzip)
gziped_buffer.close()
gzipped_data = tmp_buffer.getvalue()
tmp_buffer.close()
self.assertEquals(data_for_gzip, decode_gzip(gzipped_data))
def test_morsel_to_cookie(self):
from time import strftime, localtime
time_template = "%a, %d-%b-%Y %H:%M:%S GMT"
m = Morsel()
m['domain'] = ".yandex"
m['domain'] = ".yandex.ru"
m['path'] = "/"
m['expires'] = "Fri, 27-Aug-2021 17:43:25 GMT"
m.key = "dj2enbdj3w"
m.value = "fvjlrwnlkjnf"
c = morsel_to_cookie(m)
self.assertEquals(m.key, c.name)
self.assertEquals(m.value, c.value)
for x in ('expires', 'path', 'comment', 'domain',
'secure', 'version'):
if x == 'expires':
self.assertEquals(m[x], strftime(time_template, localtime(getattr(c, x, None))))
elif x == 'version':
self.assertTrue(isinstance(getattr(c, x, None), int))
else:
self.assertEquals(m[x], getattr(c, x, None))
def test_data_wrapper(self):
random_key1 = "key_" + uuid.uuid4().get_hex()[:10]
random_key2 = "key_" + uuid.uuid4().get_hex()[:10]
random_key3 = "key_" + uuid.uuid4().get_hex()[:10]
random_value1 = "value_" + uuid.uuid4().get_hex()
random_value2 = "value_" + uuid.uuid4().get_hex()
random_value3 = "value_" + uuid.uuid4().get_hex()
test_dict = {random_key1: random_value1,
random_key2: [random_value1, random_value2],
random_key3: (random_value2, random_value3)}
test_list = ((random_key1, random_value1),
(random_key2, [random_value1, random_value2]),
(random_key3, (random_value2, random_value3)))
control_list = ((random_key1, random_value1),
(random_key2, random_value1),
(random_key2, random_value2),
(random_key3, random_value2),
(random_key3, random_value3))
converted_dict = data_wrapper(test_dict)
for k, v in control_list:
tmp = []
for k2, v2 in converted_dict:
if k2 == k:
tmp.append(v2)
self.assertTrue(v in tmp)
converted_list = data_wrapper(test_list)
for k, v in control_list:
tmp = []
for k2, v2 in converted_list:
if k2 == k:
tmp.append(v2)
self.assertTrue(v in tmp)
def test_curl_post_files(self):
test_files = (('field_file_name', './README.rst'),
('field_file_name2', open('./setup.py')),
('multiple_files_field', (open("./README.rst"), "./setup.py")))
curl_files_dict = make_curl_post_files(test_files)
for k, v in curl_files_dict:
if isinstance(v, (TupleType, ListType)):
self.assertTrue(isinstance(v, (TupleType, ListType)))
self.assertTrue(os.path.exists(v[1]))
self.assertEquals(v[0], pycurl.FORM_FILE)
else:
assert False
class AuthManagersTestCase(BaseTestCase):
def test_parse_dict_header(self):
value = '''username="Mufasa",
realm="[email protected]",
nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
uri="/dir/index.html",
qop=auth,
nc=00000001,
cnonce="0a4f113b",
response="6629fae49393a05397450978507c4ef1",
opaque="5ccc069c403ebaf9f0171e9517f40e41"'''
parsed_header = parse_dict_header(value)
self.assertEquals(parsed_header['username'], "Mufasa")
self.assertEquals(parsed_header['realm'], "[email protected]")
self.assertEquals(parsed_header['nonce'], "dcd98b7102dd2f0e8b11d0f600bfb0c093")
self.assertEquals(parsed_header['uri'], "/dir/index.html")
self.assertEquals(parsed_header['qop'], "auth")
self.assertEquals(parsed_header['nc'], "00000001")
def test_parse_authorization_header(self):
test_digest_value = '''Digest username="Mufasa",
realm="[email protected]",
nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
uri="/dir/index.html",
qop=auth,
nc=00000001,
cnonce="0a4f113b",
response="6629fae49393a05397450978507c4ef1",
opaque="5ccc069c403ebaf9f0171e9517f40e41"'''
digest_authorization = parse_authorization_header(test_digest_value)
control_dict = {'username': 'Mufasa',
'nonce': 'dcd98b7102dd2f0e8b11d0f600bfb0c093',
'realm': '[email protected]',
'qop': 'auth',
'cnonce': '0a4f113b',
'nc': '00000001',
'opaque': '5ccc069c403ebaf9f0171e9517f40e41',
'uri': '/dir/index.html',
'response': '6629fae49393a05397450978507c4ef1'}
for k, v in control_dict.iteritems():
self.assertEquals(digest_authorization[k], v)
self.assertTrue(isinstance(digest_authorization, Authorization))
test_oauth_header_value = '''OAuth realm="Photos",
oauth_consumer_key="dpf43f3p2l4k3l03",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="137131200",
oauth_nonce="wIjqoS",
oauth_callback="http%3A%2F%2Fprinter.example.com%2Fready",
oauth_signature="74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D"'''
oauth_authorization = parse_authorization_header(test_oauth_header_value)
control_dict = {'realm': 'Photos',
'oauth_nonce': 'wIjqoS',
'oauth_timestamp': '137131200',
'oauth_signature': '74KNZJeDHnMBp0EMJ9ZHt/XKycU=',
'oauth_consumer_key': 'dpf43f3p2l4k3l03',
'oauth_signature_method': 'HMAC-SHA1',
'oauth_callback': 'http://printer.example.com/ready'}
for k, v in control_dict.iteritems():
self.assertEquals(oauth_authorization[k], v)
self.assertTrue(isinstance(digest_authorization, Authorization))
def test_escape(self):
self.assertEquals(urllib.unquote(url_escape("http://sp.example.com/")),
"http://sp.example.com/")
def test_parse_authentication_header(self):
test_digest_authenticate_header = '''Digest
realm="[email protected]",
qop="auth,auth-int",
nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
opaque="5ccc069c403ebaf9f0171e9517f40e41"'''
parsed_authentication = parse_authenticate_header(test_digest_authenticate_header)
control_dict = {'realm': '[email protected]',
'qop': 'auth,auth-int',
'nonce': "dcd98b7102dd2f0e8b11d0f600bfb0c093",
'opaque': "5ccc069c403ebaf9f0171e9517f40e41"}
for k, v in control_dict.iteritems():
self.assertEquals(parsed_authentication[k], v)
self.assertTrue(isinstance(parsed_authentication, WWWAuthenticate))
oauth_authentication_header_value = 'OAuth realm="http://sp.example.com/"'
parsed_oauth_authentication = parse_authenticate_header(oauth_authentication_header_value)
control_dict = {'realm': 'http://sp.example.com/'}
for k, v in control_dict.iteritems():
self.assertEquals(parsed_oauth_authentication[k], v)
self.assertTrue(isinstance(parsed_oauth_authentication, WWWAuthenticate))
def test_generate_nonce(self):
self.assertEquals(len(generate_nonce(8)), 8)
def test_generate_verifier(self):
self.assertEquals(len(generate_nonce(8)), 8)
def test_signature_HMAC_SHA1(self):
consumer_secret = "consumer_secret"
url = 'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisco,+CA&oauth_signature_method=HMAC-SHA1'
#url = u'https://www.google.com/m8/feeds/contacts/default/full/?alt=json&max-contacts=10'
request = {'method': 'GET',
'normalized_url': normalize_url(url),
'normalized_parameters': normalize_parameters(url)}
control_signature = 'W1dE5qAXk/+9bYYCH8P6ieE2F1I='
control_base_signature_string = 'GET&http%3A%2F%2Fapi.simplegeo.com%2F1.0%2Fplaces%2Faddress.json&address%3D41%2520Decatur%2520St%252C%2520San%2520Francisco%252C%2520CA%26category%3Danimal%26oauth_signature_method%3DHMAC-SHA1%26q%3Dmonkeys'
method = SignatureMethod_HMAC_SHA1()
self.assertEquals(method.signing_base(request, consumer_secret, None)[1], control_base_signature_string)
self.assertEquals(method.sign(request, consumer_secret, None), control_signature)
consumer_secret = 'kd94hf93k423kf44'
token_secret = 'pfkkdhi9sl3r4s00'
url = 'http://photos.example.net/photos?file=vacation.jpg&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1191242096&oauth_token=nnch734d00sl2jdk&oauth_version=1.0&size=original'
request = {'method': 'GET',
'normalized_url': normalize_url(url),
'normalized_parameters': normalize_parameters(url)}
control_signature = 'tR3+Ty81lMeYAr/Fid0kMTYa/WM='
control_base_signature_string = 'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal'
method = SignatureMethod_HMAC_SHA1()
self.assertEquals(method.signing_base(request, consumer_secret, token_secret)[1], control_base_signature_string)
self.assertEquals(method.sign(request, consumer_secret, token_secret), control_signature)
def test_signature_PLAIN_TEXT(self):
url = u'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\u2766,+CA'
request = {'method': 'POST',
'normalized_url': normalize_url(url),
'normalized_parameters': normalize_parameters(url)}
method = SignatureMethod_PLAINTEXT()
self.assertEquals(method.sign(request, "djr9rjt0jd78jf88", "jjd999tj88uiths3"), 'djr9rjt0jd78jf88%26jjd999tj88uiths3')
self.assertEquals(method.sign(request, "djr9rjt0jd78jf88", "jjd99$tj88uiths3"), 'djr9rjt0jd78jf88%26jjd99%2524tj88uiths3')
self.assertEquals(method.sign(request, "djr9rjt0jd78jf88", None), 'djr9rjt0jd78jf88%26')
def test_normalize_parameters(self):
url = u'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\u2766,+CA'
parameters = 'address=41%20Decatur%20St%2C%20San%20Francisc%E2%9D%A6%2C%20CA&category=animal&q=monkeys'
self.assertEquals(parameters, normalize_parameters(url))
url = u'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\u2766,+CA'
self.assertEquals(parameters, normalize_parameters(url))
url = 'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\xe2\x9d\xa6,+CA'
self.assertEquals(parameters, normalize_parameters(url))
url = 'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc%E2%9D%A6,+CA'
self.assertEquals(parameters, normalize_parameters(url))
url = u'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc%E2%9D%A6,+CA'
self.assertEquals(parameters, normalize_parameters(url))
def test_normalize_url(self):
url = u'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\u2766,+CA'
control_url = "http://api.simplegeo.com/1.0/places/address.json"
self.assertEquals(control_url, normalize_url(url))
url = u'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\u2766,+CA'
self.assertEquals(control_url, normalize_url(url))
url = 'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc\xe2\x9d\xa6,+CA'
self.assertEquals(control_url, normalize_url(url))
url = 'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc%E2%9D%A6,+CA'
self.assertEquals(control_url, normalize_url(url))
url = u'http://api.simplegeo.com:80/1.0/places/address.json?q=monkeys&category=animal&address=41+Decatur+St,+San+Francisc%E2%9D%A6,+CA'
self.assertEquals(control_url, normalize_url(url))
def test_oauth_consumer(self):
consumer_key = "ljdsfhwjkbnflkjfqkebr"
consumer_secret = "kjwbefpbnwefgwre"
consumer = OAuthConsumer(consumer_key, consumer_secret)
self.assertEquals(consumer_key, consumer._key)
self.assertEquals(consumer_secret, consumer._secret)
self.assertTrue(isinstance(consumer, OAuthConsumer))
def test_oauth_token(self):
token_key = "lfsjdafjnrbeflbwreferf"
token_secret = "fjrenlwkjbferlwerjuhiuyg"
token = OAuthToken(token_key, token_secret)
self.assertTrue(isinstance(token, OAuthToken))
def test_oauth_PLAINTEXT(self):
consumer_key = "be4b2eab12130803"
consumer_secret = "a2e0e39b27d08ee2f50c4d3ec06f"
token_key = "lfsjdafjnrbeflbwreferf"
token_secret = "fjrenlwkjbferlwerjuhiuyg"
tmp_token_key = "kfwbehlfbqlihrbwf"
tmp_token_secret = "dlewknfd3jkr4nbfklb5ihrlbfg"
verifier = ''.join(map(str, [randint(1, 40) for x in xrange(7)]))
request_token_url = build_url("oauth/1.0/request_token/%s/%s/%s/%s" % \
(consumer_key, consumer_secret, tmp_token_key, tmp_token_secret))
authorize_url = build_url("oauth/1.0/authorize/%s" % verifier)
access_token_url = build_url("oauth/1.0/access_token/%s/%s/%s/%s/%s/%s/%s" % \
(consumer_key, consumer_secret,
tmp_token_key, tmp_token_secret,
verifier, token_key, token_secret))
protected_resource = build_url("oauth/1.0/protected_resource/%s/%s" % (consumer_secret, token_secret))
r = Request("GET", protected_resource)
consumer = OAuthConsumer(consumer_key, consumer_secret)
self.assertRaises(RuntimeError, OAuthManager, consumer)
oauth_manager = OAuthManager(consumer, request_token_url=request_token_url,
authorize_url=authorize_url,
access_token_url=access_token_url,
signature_method=SignatureMethod_PLAINTEXT)
self.assertEquals(oauth_manager.state, 1)
self.assertTrue(isinstance(oauth_manager._signature_method, SignatureMethod))
oauth_manager.setup_request(r)
oauth_manager.request_token()
self.assertEquals(oauth_manager.state, 3)
self.assertEquals(oauth_manager._tmp_token_key, tmp_token_key)
self.assertEquals(oauth_manager._tmp_token_secret, tmp_token_secret)
self.assertEquals(oauth_manager.confirm_url, "%s?oauth_token=%s" % \
(oauth_manager._authorize_url, oauth_manager._tmp_token_key))
pin = json.loads(requests.get(oauth_manager.confirm_url
).content)['verifier']
oauth_manager.verify(pin)
self.assertEquals(oauth_manager.state, 5)
self.assertEquals(pin, oauth_manager._verifier)
self.assertEquals(tmp_token_key, oauth_manager._tmp_token_key)
self.assertEquals(tmp_token_secret, oauth_manager._tmp_token_secret)
oauth_manager.access_request()
self.assertTrue(isinstance(oauth_manager._token, OAuthToken))
self.assertEquals(oauth_manager._token._key, token_key)
self.assertEquals(oauth_manager._token._secret, token_secret)
self.assertEquals(oauth_manager.state, 7)
## opener, body_output, headers_output = r.build_opener(r._build_url())
## oauth_manager.setup(opener)
## opener.perform()
## response = Response(url=r._build_url(), curl_opener=opener,
## body_output=body_output,
## headers_output=headers_output, request=r,
## cookies=r._cookies)
## self.assertEquals(response.status_code, 200)
## self.assertEquals(json.loads(response.content)['success'], True)
def test_oauth_HMAC_SHA1(self):
consumer_key = "be4b2eab12130803"
consumer_secret = "a2e0e39b27d08ee2f50c4d3ec06f"
token_key = "lfsjdafjnrbeflbwreferf"
token_secret = "fjrenlwkjbferlwerjuhiuyg"
tmp_token_key = "kfwbehlfbqlihrbwf"
tmp_token_secret = "dlewknfd3jkr4nbfklb5ihrlbfg"
verifier = ''.join(map(str, [randint(1, 40) for x in xrange(7)]))
request_token_url = build_url("oauth/1.0/request_token/%s/%s/%s/%s" % \
(consumer_key, consumer_secret, tmp_token_key, tmp_token_secret))
authorize_url = build_url("oauth/1.0/authorize/%s" % verifier)
access_token_url = build_url("oauth/1.0/access_token/%s/%s/%s/%s/%s/%s/%s" % \
(consumer_key, consumer_secret,
tmp_token_key, tmp_token_secret,
verifier, token_key, token_secret))
protected_resource = build_url("oauth/1.0/protected_resource/%s/%s" % (consumer_secret, token_secret))
r = Request("GET", protected_resource,
headers=(("Test-header", "test-value"),)
)
consumer = OAuthConsumer(consumer_key, consumer_secret)
self.assertRaises(RuntimeError, OAuthManager, consumer)
oauth_manager = OAuthManager(consumer, request_token_url=request_token_url,
authorize_url=authorize_url,
access_token_url=access_token_url,
signature_method=SignatureMethod_HMAC_SHA1)
self.assertEquals(oauth_manager.state, 1)
self.assertTrue(isinstance(oauth_manager._signature_method, SignatureMethod))
oauth_manager.setup_request(r)
oauth_manager.request_token()
self.assertEquals(oauth_manager.state, 3)
self.assertEquals(oauth_manager._tmp_token_key, tmp_token_key)
self.assertEquals(oauth_manager._tmp_token_secret, tmp_token_secret)
self.assertEquals(oauth_manager.confirm_url, "%s?oauth_token=%s" % \
(oauth_manager._authorize_url, oauth_manager._tmp_token_key))
pin = json.loads(requests.get(oauth_manager.confirm_url
).content)['verifier']
oauth_manager.verify(pin)
self.assertEquals(oauth_manager.state, 5)
self.assertEquals(pin, oauth_manager._verifier)
self.assertEquals(tmp_token_key, oauth_manager._tmp_token_key)
self.assertEquals(tmp_token_secret, oauth_manager._tmp_token_secret)
oauth_manager.access_request()
self.assertTrue(isinstance(oauth_manager._token, OAuthToken))
self.assertEquals(oauth_manager._token._key, token_key)
self.assertEquals(oauth_manager._token._secret, token_secret)
self.assertEquals(oauth_manager.state, 7)
## opener, body_output, headers_output = r.build_opener(r._build_url())
## oauth_manager.setup(opener)
## opener.perform()
## response = Response(url=r._build_url(), curl_opener=opener,
## body_output=body_output,
## headers_output=headers_output, request=r,
## cookies=r._cookies)
## self.assertEquals(response.status_code, 200)
## self.assertEquals(json.loads(response.content)['success'], True)
def test_3_legged_oauth(self):
consumer_key = "be4b2eab12130803"
consumer_secret = "a2e0e39b27d08ee2f50c4d3ec06f"
token_key = "lfsjdafjnrbeflbwreferf"
token_secret = "fjrenlwkjbferlwerjuhiuyg"
tmp_token_key = "kfwbehlfbqlihrbwf"
tmp_token_secret = "dlewknfd3jkr4nbfklb5ihrlbfg"
verifier = ''.join(map(str, [randint(1, 40) for x in xrange(7)]))
request_token_url = build_url("oauth/1.0/request_token/%s/%s/%s/%s" % \
(consumer_key, consumer_secret, tmp_token_key, tmp_token_secret))