You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
2.2 KiB

2 years ago
2 years ago
2 years ago
2 years ago
  1. from rest_framework import status
  2. from rest_framework.reverse import reverse
  3. from rest_framework.test import APITestCase
  4. from .utils import make_user
  5. class TestUserAPI(APITestCase):
  6. @classmethod
  7. def setUpTestData(cls):
  8. cls.user = make_user(username="bob")
  9. cls.url = reverse(viewname="user_list")
  10. def test_allows_authenticated_user_to_get_users(self):
  11. self.client.force_login(self.user)
  12. response = self.client.get(self.url)
  13. self.assertEqual(response.status_code, status.HTTP_200_OK)
  14. self.assertEqual(len(response.data), 1)
  15. self.assertEqual(response.data[0]["username"], self.user.username)
  16. def test_denies_unauthenticated_user_to_get_users(self):
  17. response = self.client.get(self.url)
  18. self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
  19. class TestMeAPI(APITestCase):
  20. @classmethod
  21. def setUpTestData(cls):
  22. cls.user = make_user(username="bob")
  23. cls.url = reverse(viewname="me")
  24. def test_return_own_information(self):
  25. self.client.force_login(self.user)
  26. response = self.client.get(self.url)
  27. self.assertEqual(response.data["id"], self.user.id)
  28. self.assertEqual(response.data["username"], self.user.username)
  29. def test_does_not_return_information_to_unauthenticated_user(self):
  30. response = self.client.get(self.url)
  31. self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
  32. class TestUserCreationAPI(APITestCase):
  33. @classmethod
  34. def setUpTestData(cls):
  35. cls.staff = make_user(username="bob", is_staff=True)
  36. cls.non_staff = make_user(username="tom", is_staff=False)
  37. cls.url = reverse(viewname="user_create")
  38. cls.payload = {"username": "hironsan", "password1": "foobarbaz", "password2": "foobarbaz"}
  39. def test_staff_can_create_user(self):
  40. self.client.force_login(self.staff)
  41. response = self.client.post(self.url, data=self.payload)
  42. self.assertEqual(response.data["username"], "hironsan")
  43. def test_non_staff_cannot_create_user(self):
  44. self.client.force_login(self.non_staff)
  45. response = self.client.post(self.url, data=self.payload)
  46. self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)