tests.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from django.urls import reverse
  2. from model_bakery import baker
  3. from rest_framework.test import APITestCase
  4. from glitchtip import test_utils # pylint: disable=unused-import
  5. class APITokenTests(APITestCase):
  6. def setUp(self):
  7. self.user = baker.make("users.user")
  8. def test_create(self):
  9. self.client.force_login(self.user)
  10. url = reverse("api-tokens-list")
  11. scope_name = "member:read"
  12. data = {"scopes": [scope_name]}
  13. res = self.client.post(url, data, format="json")
  14. self.assertContains(res, scope_name, status_code=201)
  15. def test_list(self):
  16. self.client.force_login(self.user)
  17. api_token = baker.make("api_tokens.APIToken", user=self.user)
  18. other_api_token = baker.make("api_tokens.APIToken")
  19. url = reverse("api-tokens-list")
  20. res = self.client.get(url)
  21. self.assertContains(res, api_token.token)
  22. self.assertNotContains(res, other_api_token.token)
  23. def test_retrieve(self):
  24. self.client.force_login(self.user)
  25. api_token = baker.make("api_tokens.APIToken", user=self.user)
  26. url = reverse("api-tokens-detail", args=[api_token.id])
  27. res = self.client.get(url)
  28. self.assertContains(res, api_token.token)
  29. other_api_token = baker.make("api_tokens.APIToken")
  30. res = self.client.get(reverse("api-tokens-detail", args=[other_api_token.id]))
  31. self.assertEqual(res.status_code, 404)
  32. def test_destroy(self):
  33. self.client.force_login(self.user)
  34. api_token = baker.make("api_tokens.APIToken", user=self.user)
  35. url = reverse("api-tokens-detail", args=[api_token.id])
  36. self.assertTrue(self.user.apitoken_set.exists())
  37. res = self.client.delete(url)
  38. self.assertEqual(res.status_code, 204)
  39. self.assertFalse(self.user.apitoken_set.exists())
  40. other_api_token = baker.make("api_tokens.APIToken")
  41. url = reverse("api-tokens-detail", args=[other_api_token.id])
  42. res = self.client.delete(url)
  43. self.assertEqual(res.status_code, 404)
  44. def test_token_auth(self):
  45. """Token based auth should not be able to create it's own token"""
  46. organization = baker.make("organizations_ext.Organization")
  47. organization.add_user(self.user)
  48. auth_token = baker.make("api_tokens.APIToken", user=self.user)
  49. self.client.credentials(HTTP_AUTHORIZATION="Bearer " + auth_token.token)
  50. url = reverse("api-tokens-list")
  51. scope_name = "member:read"
  52. data = {"scopes": [scope_name]}
  53. res = self.client.post(url, data, format="json")
  54. self.assertEqual(res.status_code, 403)
  55. res = self.client.get(url)
  56. self.assertEqual(res.status_code, 403)