test_common.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. # -*- coding: utf-8 -*-
  2. import oauthlib
  3. from oauthlib.common import (
  4. CaseInsensitiveDict, Request, add_params_to_uri, extract_params,
  5. generate_client_id, generate_nonce, generate_timestamp, generate_token,
  6. urldecode,
  7. )
  8. from tests.unittest import TestCase
  9. PARAMS_DICT = {'foo': 'bar', 'baz': '123', }
  10. PARAMS_TWOTUPLE = [('foo', 'bar'), ('baz', '123')]
  11. PARAMS_FORMENCODED = 'foo=bar&baz=123'
  12. URI = 'http://www.someuri.com'
  13. class EncodingTest(TestCase):
  14. def test_urldecode(self):
  15. self.assertCountEqual(urldecode(''), [])
  16. self.assertCountEqual(urldecode('='), [('', '')])
  17. self.assertCountEqual(urldecode('%20'), [(' ', '')])
  18. self.assertCountEqual(urldecode('+'), [(' ', '')])
  19. self.assertCountEqual(urldecode('c2'), [('c2', '')])
  20. self.assertCountEqual(urldecode('c2='), [('c2', '')])
  21. self.assertCountEqual(urldecode('foo=bar'), [('foo', 'bar')])
  22. self.assertCountEqual(urldecode('foo_%20~=.bar-'),
  23. [('foo_ ~', '.bar-')])
  24. self.assertCountEqual(urldecode('foo=1,2,3'), [('foo', '1,2,3')])
  25. self.assertCountEqual(urldecode('foo=(1,2,3)'), [('foo', '(1,2,3)')])
  26. self.assertCountEqual(urldecode('foo=bar.*'), [('foo', 'bar.*')])
  27. self.assertCountEqual(urldecode('foo=bar@spam'), [('foo', 'bar@spam')])
  28. self.assertCountEqual(urldecode('foo=bar/baz'), [('foo', 'bar/baz')])
  29. self.assertCountEqual(urldecode('foo=bar?baz'), [('foo', 'bar?baz')])
  30. self.assertCountEqual(urldecode('foo=bar\'s'), [('foo', 'bar\'s')])
  31. self.assertCountEqual(urldecode('foo=$'), [('foo', '$')])
  32. self.assertRaises(ValueError, urldecode, 'foo bar')
  33. self.assertRaises(ValueError, urldecode, '%R')
  34. self.assertRaises(ValueError, urldecode, '%RA')
  35. self.assertRaises(ValueError, urldecode, '%AR')
  36. self.assertRaises(ValueError, urldecode, '%RR')
  37. class ParameterTest(TestCase):
  38. def test_extract_params_dict(self):
  39. self.assertCountEqual(extract_params(PARAMS_DICT), PARAMS_TWOTUPLE)
  40. def test_extract_params_twotuple(self):
  41. self.assertCountEqual(extract_params(PARAMS_TWOTUPLE), PARAMS_TWOTUPLE)
  42. def test_extract_params_formencoded(self):
  43. self.assertCountEqual(extract_params(PARAMS_FORMENCODED),
  44. PARAMS_TWOTUPLE)
  45. def test_extract_params_blank_string(self):
  46. self.assertCountEqual(extract_params(''), [])
  47. def test_extract_params_empty_list(self):
  48. self.assertCountEqual(extract_params([]), [])
  49. def test_extract_non_formencoded_string(self):
  50. self.assertIsNone(extract_params('not a formencoded string'))
  51. def test_extract_invalid(self):
  52. self.assertIsNone(extract_params(object()))
  53. self.assertIsNone(extract_params([('')]))
  54. def test_add_params_to_uri(self):
  55. correct = '{}?{}'.format(URI, PARAMS_FORMENCODED)
  56. self.assertURLEqual(add_params_to_uri(URI, PARAMS_DICT), correct)
  57. self.assertURLEqual(add_params_to_uri(URI, PARAMS_TWOTUPLE), correct)
  58. class GeneratorTest(TestCase):
  59. def test_generate_timestamp(self):
  60. timestamp = generate_timestamp()
  61. self.assertIsInstance(timestamp, str)
  62. self.assertTrue(int(timestamp))
  63. self.assertGreater(int(timestamp), 1331672335)
  64. def test_generate_nonce(self):
  65. """Ping me (ib-lundgren) when you discover how to test randomness."""
  66. nonce = generate_nonce()
  67. for i in range(50):
  68. self.assertNotEqual(nonce, generate_nonce())
  69. def test_generate_token(self):
  70. token = generate_token()
  71. self.assertEqual(len(token), 30)
  72. token = generate_token(length=44)
  73. self.assertEqual(len(token), 44)
  74. token = generate_token(length=6, chars="python")
  75. self.assertEqual(len(token), 6)
  76. for c in token:
  77. self.assertIn(c, "python")
  78. def test_generate_client_id(self):
  79. client_id = generate_client_id()
  80. self.assertEqual(len(client_id), 30)
  81. client_id = generate_client_id(length=44)
  82. self.assertEqual(len(client_id), 44)
  83. client_id = generate_client_id(length=6, chars="python")
  84. self.assertEqual(len(client_id), 6)
  85. for c in client_id:
  86. self.assertIn(c, "python")
  87. class RequestTest(TestCase):
  88. def test_non_unicode_params(self):
  89. r = Request(
  90. b'http://a.b/path?query',
  91. http_method=b'GET',
  92. body=b'you=shall+pass',
  93. headers={
  94. b'a': b'b',
  95. }
  96. )
  97. self.assertEqual(r.uri, 'http://a.b/path?query')
  98. self.assertEqual(r.http_method, 'GET')
  99. self.assertEqual(r.body, 'you=shall+pass')
  100. self.assertEqual(r.decoded_body, [('you', 'shall pass')])
  101. self.assertEqual(r.headers, {'a': 'b'})
  102. def test_none_body(self):
  103. r = Request(URI)
  104. self.assertIsNone(r.decoded_body)
  105. def test_empty_list_body(self):
  106. r = Request(URI, body=[])
  107. self.assertEqual(r.decoded_body, [])
  108. def test_empty_dict_body(self):
  109. r = Request(URI, body={})
  110. self.assertEqual(r.decoded_body, [])
  111. def test_empty_string_body(self):
  112. r = Request(URI, body='')
  113. self.assertEqual(r.decoded_body, [])
  114. def test_non_formencoded_string_body(self):
  115. body = 'foo bar'
  116. r = Request(URI, body=body)
  117. self.assertIsNone(r.decoded_body)
  118. def test_param_free_sequence_body(self):
  119. body = [1, 1, 2, 3, 5, 8, 13]
  120. r = Request(URI, body=body)
  121. self.assertIsNone(r.decoded_body)
  122. def test_list_body(self):
  123. r = Request(URI, body=PARAMS_TWOTUPLE)
  124. self.assertCountEqual(r.decoded_body, PARAMS_TWOTUPLE)
  125. def test_dict_body(self):
  126. r = Request(URI, body=PARAMS_DICT)
  127. self.assertCountEqual(r.decoded_body, PARAMS_TWOTUPLE)
  128. def test_getattr_existing_attribute(self):
  129. r = Request(URI, body='foo bar')
  130. self.assertEqual('foo bar', getattr(r, 'body'))
  131. def test_getattr_return_default(self):
  132. r = Request(URI, body='')
  133. actual_value = getattr(r, 'does_not_exist', 'foo bar')
  134. self.assertEqual('foo bar', actual_value)
  135. def test_getattr_raise_attribute_error(self):
  136. r = Request(URI, body='foo bar')
  137. with self.assertRaises(AttributeError):
  138. getattr(r, 'does_not_exist')
  139. def test_sanitizing_authorization_header(self):
  140. r = Request(URI, headers={'Accept': 'application/json',
  141. 'Authorization': 'Basic Zm9vOmJhcg=='}
  142. )
  143. self.assertNotIn('Zm9vOmJhcg==', repr(r))
  144. self.assertIn('<SANITIZED>', repr(r))
  145. # Double-check we didn't modify the underlying object:
  146. self.assertEqual(r.headers['Authorization'], 'Basic Zm9vOmJhcg==')
  147. def test_token_body(self):
  148. payload = 'client_id=foo&refresh_token=bar'
  149. r = Request(URI, body=payload)
  150. self.assertNotIn('bar', repr(r))
  151. self.assertIn('<SANITIZED>', repr(r))
  152. payload = 'refresh_token=bar&client_id=foo'
  153. r = Request(URI, body=payload)
  154. self.assertNotIn('bar', repr(r))
  155. self.assertIn('<SANITIZED>', repr(r))
  156. def test_password_body(self):
  157. payload = 'username=foo&password=bar'
  158. r = Request(URI, body=payload)
  159. self.assertNotIn('bar', repr(r))
  160. self.assertIn('<SANITIZED>', repr(r))
  161. payload = 'password=bar&username=foo'
  162. r = Request(URI, body=payload)
  163. self.assertNotIn('bar', repr(r))
  164. self.assertIn('<SANITIZED>', repr(r))
  165. def test_headers_params(self):
  166. r = Request(URI, headers={'token': 'foobar'}, body='token=banana')
  167. self.assertEqual(r.headers['token'], 'foobar')
  168. self.assertEqual(r.token, 'banana')
  169. def test_sanitized_request_non_debug_mode(self):
  170. """make sure requests are sanitized when in non debug mode.
  171. For the debug mode, the other tests checking sanitization should prove
  172. that debug mode is working.
  173. """
  174. try:
  175. oauthlib.set_debug(False)
  176. r = Request(URI, headers={'token': 'foobar'}, body='token=banana')
  177. self.assertNotIn('token', repr(r))
  178. self.assertIn('SANITIZED', repr(r))
  179. finally:
  180. # set flag back for other tests
  181. oauthlib.set_debug(True)
  182. class CaseInsensitiveDictTest(TestCase):
  183. def test_basic(self):
  184. cid = CaseInsensitiveDict({})
  185. cid['a'] = 'b'
  186. cid['c'] = 'd'
  187. del cid['c']
  188. self.assertEqual(cid['A'], 'b')
  189. self.assertEqual(cid['a'], 'b')
  190. def test_update(self):
  191. cid = CaseInsensitiveDict({})
  192. cid.update({'KeY': 'value'})
  193. self.assertEqual(cid['kEy'], 'value')