test_oauth2_auth.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from __future__ import unicode_literals
  2. import unittest
  3. from oauthlib.oauth2 import WebApplicationClient, MobileApplicationClient
  4. from oauthlib.oauth2 import LegacyApplicationClient, BackendApplicationClient
  5. from requests import Request
  6. from requests_oauthlib import OAuth2
  7. class OAuth2AuthTest(unittest.TestCase):
  8. def setUp(self):
  9. self.token = {
  10. "token_type": "Bearer",
  11. "access_token": "asdfoiw37850234lkjsdfsdf",
  12. "expires_in": "3600",
  13. }
  14. self.client_id = "foo"
  15. self.clients = [
  16. WebApplicationClient(self.client_id),
  17. MobileApplicationClient(self.client_id),
  18. LegacyApplicationClient(self.client_id),
  19. BackendApplicationClient(self.client_id),
  20. ]
  21. def test_add_token_to_url(self):
  22. url = "https://example.com/resource?foo=bar"
  23. new_url = url + "&access_token=" + self.token["access_token"]
  24. for client in self.clients:
  25. client.default_token_placement = "query"
  26. auth = OAuth2(client=client, token=self.token)
  27. r = Request("GET", url, auth=auth).prepare()
  28. self.assertEqual(r.url, new_url)
  29. def test_add_token_to_headers(self):
  30. token = "Bearer " + self.token["access_token"]
  31. for client in self.clients:
  32. auth = OAuth2(client=client, token=self.token)
  33. r = Request("GET", "https://i.b", auth=auth).prepare()
  34. self.assertEqual(r.headers["Authorization"], token)
  35. def test_add_token_to_body(self):
  36. body = "foo=bar"
  37. new_body = body + "&access_token=" + self.token["access_token"]
  38. for client in self.clients:
  39. client.default_token_placement = "body"
  40. auth = OAuth2(client=client, token=self.token)
  41. r = Request("GET", "https://i.b", data=body, auth=auth).prepare()
  42. self.assertEqual(r.body, new_body)
  43. def test_add_nonexisting_token(self):
  44. for client in self.clients:
  45. auth = OAuth2(client=client)
  46. r = Request("GET", "https://i.b", auth=auth)
  47. self.assertRaises(ValueError, r.prepare)