tests.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from django.test import TestCase
  2. from django.urls import reverse
  3. from model_bakery import baker
  4. from glitchtip.test_utils import generators # noqa: F401
  5. class APITokenTests(TestCase):
  6. def setUp(self):
  7. self.user = baker.make("users.user")
  8. self.url = reverse("api:list_api_tokens")
  9. def get_detail_url(self, id: int):
  10. return reverse("api:delete_api_token", args=[id])
  11. def test_create(self):
  12. self.client.force_login(self.user)
  13. scope_name = "member:read"
  14. data = {"scopes": [scope_name]}
  15. res = self.client.post(self.url, data, content_type="application/json")
  16. self.assertContains(res, scope_name, status_code=201)
  17. def test_list(self):
  18. self.client.force_login(self.user)
  19. api_token = baker.make("api_tokens.APIToken", user=self.user)
  20. other_api_token = baker.make("api_tokens.APIToken")
  21. res = self.client.get(self.url)
  22. self.assertContains(res, api_token.token)
  23. self.assertNotContains(res, other_api_token.token)
  24. def test_destroy(self):
  25. self.client.force_login(self.user)
  26. api_token = baker.make("api_tokens.APIToken", user=self.user)
  27. url = self.get_detail_url(api_token.id)
  28. self.assertTrue(self.user.apitoken_set.exists())
  29. res = self.client.delete(url)
  30. self.assertEqual(res.status_code, 204)
  31. self.assertFalse(self.user.apitoken_set.exists())
  32. other_api_token = baker.make("api_tokens.APIToken")
  33. url = self.get_detail_url(other_api_token.id)
  34. res = self.client.delete(url)
  35. self.assertEqual(res.status_code, 404)
  36. def test_token_auth(self):
  37. """Token based auth should not be able to create it's own token"""
  38. organization = baker.make("organizations_ext.Organization")
  39. organization.add_user(self.user)
  40. auth_token = baker.make("api_tokens.APIToken", user=self.user)
  41. auth_headers = {"HTTP_AUTHORIZATION": f"Bearer {auth_token.token}"}
  42. scope_name = "member:read"
  43. data = {"scopes": [scope_name]}
  44. res = self.client.post(
  45. self.url, data, content_type="application/json", **auth_headers
  46. )
  47. self.assertEqual(res.status_code, 401) # Was 403, might be better as 403
  48. res = self.client.get(self.url, **auth_headers)
  49. self.assertEqual(res.status_code, 401)