test_oauth2_auth.py 2.1 KB

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