api.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. from django.conf import settings
  2. from django.contrib.auth.models import User
  3. from django.contrib.contenttypes.models import ContentType
  4. from django.urls import reverse
  5. from django.test import override_settings
  6. from rest_framework import status
  7. from rest_framework.test import APIClient
  8. from users.models import ObjectPermission, Token
  9. from .utils import disable_warnings
  10. from .views import ModelTestCase
  11. __all__ = (
  12. 'APITestCase',
  13. 'APIViewTestCases',
  14. )
  15. #
  16. # REST API Tests
  17. #
  18. class APITestCase(ModelTestCase):
  19. """
  20. Base test case for API requests.
  21. client_class: Test client class
  22. view_namespace: Namespace for API views. If None, the model's app_label will be used.
  23. """
  24. client_class = APIClient
  25. view_namespace = None
  26. def setUp(self):
  27. """
  28. Create a superuser and token for API calls.
  29. """
  30. # Create the test user and assign permissions
  31. self.user = User.objects.create_user(username='testuser')
  32. self.add_permissions(*self.user_permissions)
  33. self.token = Token.objects.create(user=self.user)
  34. self.header = {'HTTP_AUTHORIZATION': 'Token {}'.format(self.token.key)}
  35. def _get_view_namespace(self):
  36. return f'{self.view_namespace or self.model._meta.app_label}-api'
  37. def _get_detail_url(self, instance):
  38. viewname = f'{self._get_view_namespace()}:{instance._meta.model_name}-detail'
  39. return reverse(viewname, kwargs={'pk': instance.pk})
  40. def _get_list_url(self):
  41. viewname = f'{self._get_view_namespace()}:{self.model._meta.model_name}-list'
  42. return reverse(viewname)
  43. class APIViewTestCases:
  44. class GetObjectViewTestCase(APITestCase):
  45. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  46. def test_get_object_anonymous(self):
  47. """
  48. GET a single object as an unauthenticated user.
  49. """
  50. url = self._get_detail_url(self._get_queryset().first())
  51. if (self.model._meta.app_label, self.model._meta.model_name) in settings.EXEMPT_EXCLUDE_MODELS:
  52. # Models listed in EXEMPT_EXCLUDE_MODELS should not be accessible to anonymous users
  53. with disable_warnings('django.request'):
  54. self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)
  55. else:
  56. response = self.client.get(url, **self.header)
  57. self.assertHttpStatus(response, status.HTTP_200_OK)
  58. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  59. def test_get_object_without_permission(self):
  60. """
  61. GET a single object as an authenticated user without the required permission.
  62. """
  63. url = self._get_detail_url(self._get_queryset().first())
  64. # Try GET without permission
  65. with disable_warnings('django.request'):
  66. self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)
  67. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  68. def test_get_object(self):
  69. """
  70. GET a single object as an authenticated user with permission to view the object.
  71. """
  72. self.assertGreaterEqual(self._get_queryset().count(), 2,
  73. f"Test requires the creation of at least two {self.model} instances")
  74. instance1, instance2 = self._get_queryset()[:2]
  75. # Add object-level permission
  76. obj_perm = ObjectPermission(
  77. name='Test permission',
  78. constraints={'pk': instance1.pk},
  79. actions=['view']
  80. )
  81. obj_perm.save()
  82. obj_perm.users.add(self.user)
  83. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  84. # Try GET to permitted object
  85. url = self._get_detail_url(instance1)
  86. self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_200_OK)
  87. # Try GET to non-permitted object
  88. url = self._get_detail_url(instance2)
  89. self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_404_NOT_FOUND)
  90. class ListObjectsViewTestCase(APITestCase):
  91. brief_fields = []
  92. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  93. def test_list_objects_anonymous(self):
  94. """
  95. GET a list of objects as an unauthenticated user.
  96. """
  97. url = self._get_list_url()
  98. if (self.model._meta.app_label, self.model._meta.model_name) in settings.EXEMPT_EXCLUDE_MODELS:
  99. # Models listed in EXEMPT_EXCLUDE_MODELS should not be accessible to anonymous users
  100. with disable_warnings('django.request'):
  101. self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)
  102. else:
  103. response = self.client.get(url, **self.header)
  104. self.assertHttpStatus(response, status.HTTP_200_OK)
  105. self.assertEqual(len(response.data['results']), self._get_queryset().count())
  106. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  107. def test_list_objects_brief(self):
  108. """
  109. GET a list of objects using the "brief" parameter.
  110. """
  111. self.add_permissions(f'{self.model._meta.app_label}.view_{self.model._meta.model_name}')
  112. url = f'{self._get_list_url()}?brief=1'
  113. response = self.client.get(url, **self.header)
  114. self.assertEqual(len(response.data['results']), self._get_queryset().count())
  115. self.assertEqual(sorted(response.data['results'][0]), self.brief_fields)
  116. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  117. def test_list_objects_without_permission(self):
  118. """
  119. GET a list of objects as an authenticated user without the required permission.
  120. """
  121. url = self._get_list_url()
  122. # Try GET without permission
  123. with disable_warnings('django.request'):
  124. self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)
  125. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  126. def test_list_objects(self):
  127. """
  128. GET a list of objects as an authenticated user with permission to view the objects.
  129. """
  130. self.assertGreaterEqual(self._get_queryset().count(), 3,
  131. f"Test requires the creation of at least three {self.model} instances")
  132. instance1, instance2 = self._get_queryset()[:2]
  133. # Add object-level permission
  134. obj_perm = ObjectPermission(
  135. name='Test permission',
  136. constraints={'pk__in': [instance1.pk, instance2.pk]},
  137. actions=['view']
  138. )
  139. obj_perm.save()
  140. obj_perm.users.add(self.user)
  141. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  142. # Try GET to permitted objects
  143. response = self.client.get(self._get_list_url(), **self.header)
  144. self.assertHttpStatus(response, status.HTTP_200_OK)
  145. self.assertEqual(len(response.data['results']), 2)
  146. class CreateObjectViewTestCase(APITestCase):
  147. create_data = []
  148. validation_excluded_fields = []
  149. def test_create_object_without_permission(self):
  150. """
  151. POST a single object without permission.
  152. """
  153. url = self._get_list_url()
  154. # Try POST without permission
  155. with disable_warnings('django.request'):
  156. response = self.client.post(url, self.create_data[0], format='json', **self.header)
  157. self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)
  158. def test_create_object(self):
  159. """
  160. POST a single object with permission.
  161. """
  162. # Add object-level permission
  163. obj_perm = ObjectPermission(
  164. name='Test permission',
  165. actions=['add']
  166. )
  167. obj_perm.save()
  168. obj_perm.users.add(self.user)
  169. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  170. initial_count = self._get_queryset().count()
  171. response = self.client.post(self._get_list_url(), self.create_data[0], format='json', **self.header)
  172. self.assertHttpStatus(response, status.HTTP_201_CREATED)
  173. self.assertEqual(self._get_queryset().count(), initial_count + 1)
  174. self.assertInstanceEqual(
  175. self._get_queryset().get(pk=response.data['id']),
  176. self.create_data[0],
  177. exclude=self.validation_excluded_fields,
  178. api=True
  179. )
  180. def test_bulk_create_objects(self):
  181. """
  182. POST a set of objects in a single request.
  183. """
  184. # Add object-level permission
  185. obj_perm = ObjectPermission(
  186. name='Test permission',
  187. actions=['add']
  188. )
  189. obj_perm.save()
  190. obj_perm.users.add(self.user)
  191. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  192. initial_count = self._get_queryset().count()
  193. response = self.client.post(self._get_list_url(), self.create_data, format='json', **self.header)
  194. self.assertHttpStatus(response, status.HTTP_201_CREATED)
  195. self.assertEqual(len(response.data), len(self.create_data))
  196. self.assertEqual(self._get_queryset().count(), initial_count + len(self.create_data))
  197. for i, obj in enumerate(response.data):
  198. for field in self.create_data[i]:
  199. if field not in self.validation_excluded_fields:
  200. self.assertIn(field, obj, f"Bulk create field '{field}' missing from object {i} in response")
  201. for i, obj in enumerate(response.data):
  202. self.assertInstanceEqual(
  203. self._get_queryset().get(pk=obj['id']),
  204. self.create_data[i],
  205. exclude=self.validation_excluded_fields,
  206. api=True
  207. )
  208. class UpdateObjectViewTestCase(APITestCase):
  209. update_data = {}
  210. bulk_update_data = None
  211. validation_excluded_fields = []
  212. def test_update_object_without_permission(self):
  213. """
  214. PATCH a single object without permission.
  215. """
  216. url = self._get_detail_url(self._get_queryset().first())
  217. update_data = self.update_data or getattr(self, 'create_data')[0]
  218. # Try PATCH without permission
  219. with disable_warnings('django.request'):
  220. response = self.client.patch(url, update_data, format='json', **self.header)
  221. self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)
  222. def test_update_object(self):
  223. """
  224. PATCH a single object identified by its numeric ID.
  225. """
  226. instance = self._get_queryset().first()
  227. url = self._get_detail_url(instance)
  228. update_data = self.update_data or getattr(self, 'create_data')[0]
  229. # Add object-level permission
  230. obj_perm = ObjectPermission(
  231. name='Test permission',
  232. actions=['change']
  233. )
  234. obj_perm.save()
  235. obj_perm.users.add(self.user)
  236. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  237. response = self.client.patch(url, update_data, format='json', **self.header)
  238. self.assertHttpStatus(response, status.HTTP_200_OK)
  239. instance.refresh_from_db()
  240. self.assertInstanceEqual(
  241. instance,
  242. update_data,
  243. exclude=self.validation_excluded_fields,
  244. api=True
  245. )
  246. def test_bulk_update_objects(self):
  247. """
  248. PATCH a set of objects in a single request.
  249. """
  250. if self.bulk_update_data is None:
  251. self.skipTest("Bulk update data not set")
  252. # Add object-level permission
  253. obj_perm = ObjectPermission(
  254. name='Test permission',
  255. actions=['change']
  256. )
  257. obj_perm.save()
  258. obj_perm.users.add(self.user)
  259. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  260. id_list = self._get_queryset().values_list('id', flat=True)[:3]
  261. self.assertEqual(len(id_list), 3, "Insufficient number of objects to test bulk update")
  262. data = [
  263. {'id': id, **self.bulk_update_data} for id in id_list
  264. ]
  265. response = self.client.patch(self._get_list_url(), data, format='json', **self.header)
  266. self.assertHttpStatus(response, status.HTTP_200_OK)
  267. for i, obj in enumerate(response.data):
  268. for field in self.bulk_update_data:
  269. self.assertIn(field, obj, f"Bulk update field '{field}' missing from object {i} in response")
  270. for instance in self._get_queryset().filter(pk__in=id_list):
  271. self.assertInstanceEqual(instance, self.bulk_update_data, api=True)
  272. class DeleteObjectViewTestCase(APITestCase):
  273. def test_delete_object_without_permission(self):
  274. """
  275. DELETE a single object without permission.
  276. """
  277. url = self._get_detail_url(self._get_queryset().first())
  278. # Try DELETE without permission
  279. with disable_warnings('django.request'):
  280. response = self.client.delete(url, **self.header)
  281. self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)
  282. def test_delete_object(self):
  283. """
  284. DELETE a single object identified by its numeric ID.
  285. """
  286. instance = self._get_queryset().first()
  287. url = self._get_detail_url(instance)
  288. # Add object-level permission
  289. obj_perm = ObjectPermission(
  290. name='Test permission',
  291. actions=['delete']
  292. )
  293. obj_perm.save()
  294. obj_perm.users.add(self.user)
  295. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  296. response = self.client.delete(url, **self.header)
  297. self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
  298. self.assertFalse(self._get_queryset().filter(pk=instance.pk).exists())
  299. def test_bulk_delete_objects(self):
  300. """
  301. DELETE a set of objects in a single request.
  302. """
  303. # Add object-level permission
  304. obj_perm = ObjectPermission(
  305. name='Test permission',
  306. actions=['delete']
  307. )
  308. obj_perm.save()
  309. obj_perm.users.add(self.user)
  310. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  311. # Target the three most recently created objects to avoid triggering recursive deletions
  312. # (e.g. with MPTT objects)
  313. id_list = self._get_queryset().order_by('-id').values_list('id', flat=True)[:3]
  314. self.assertEqual(len(id_list), 3, "Insufficient number of objects to test bulk deletion")
  315. data = [{"id": id} for id in id_list]
  316. initial_count = self._get_queryset().count()
  317. response = self.client.delete(self._get_list_url(), data, format='json', **self.header)
  318. self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
  319. self.assertEqual(self._get_queryset().count(), initial_count - 3)
  320. class APIViewTestCase(
  321. GetObjectViewTestCase,
  322. ListObjectsViewTestCase,
  323. CreateObjectViewTestCase,
  324. UpdateObjectViewTestCase,
  325. DeleteObjectViewTestCase
  326. ):
  327. pass