views.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. from django.contrib.auth.models import User
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.contrib.postgres.fields import ArrayField
  4. from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist
  5. from django.db.models import ManyToManyField
  6. from django.forms.models import model_to_dict
  7. from django.test import Client, TestCase as _TestCase, override_settings
  8. from django.urls import reverse, NoReverseMatch
  9. from django.utils.text import slugify
  10. from netaddr import IPNetwork
  11. from taggit.managers import TaggableManager
  12. from extras.models import Tag
  13. from users.models import ObjectPermission
  14. from utilities.permissions import resolve_permission_ct
  15. from .utils import disable_warnings, post_data
  16. __all__ = (
  17. 'TestCase',
  18. 'ModelTestCase',
  19. 'ModelViewTestCase',
  20. 'ViewTestCases',
  21. )
  22. class TestCase(_TestCase):
  23. user_permissions = ()
  24. def setUp(self):
  25. # Create the test user and assign permissions
  26. self.user = User.objects.create_user(username='testuser')
  27. self.add_permissions(*self.user_permissions)
  28. # Initialize the test client
  29. self.client = Client()
  30. self.client.force_login(self.user)
  31. def prepare_instance(self, instance):
  32. """
  33. Test cases can override this method to perform any necessary manipulation of an instance prior to its evaluation
  34. against test data. For example, it can be used to decrypt a Secret's plaintext attribute.
  35. """
  36. return instance
  37. def model_to_dict(self, instance, fields, api=False):
  38. """
  39. Return a dictionary representation of an instance.
  40. """
  41. # Prepare the instance and call Django's model_to_dict() to extract all fields
  42. model_dict = model_to_dict(self.prepare_instance(instance), fields=fields)
  43. # Map any additional (non-field) instance attributes that were specified
  44. for attr in fields:
  45. if hasattr(instance, attr) and attr not in model_dict:
  46. model_dict[attr] = getattr(instance, attr)
  47. for key, value in list(model_dict.items()):
  48. try:
  49. field = instance._meta.get_field(key)
  50. except FieldDoesNotExist:
  51. # Attribute is not a model field
  52. continue
  53. # Handle ManyToManyFields
  54. if value and type(field) in (ManyToManyField, TaggableManager):
  55. if field.related_model is ContentType:
  56. model_dict[key] = sorted([f'{ct.app_label}.{ct.model}' for ct in value])
  57. else:
  58. model_dict[key] = sorted([obj.pk for obj in value])
  59. if api:
  60. # Replace ContentType numeric IDs with <app_label>.<model>
  61. if type(getattr(instance, key)) is ContentType:
  62. ct = ContentType.objects.get(pk=value)
  63. model_dict[key] = f'{ct.app_label}.{ct.model}'
  64. # Convert IPNetwork instances to strings
  65. elif type(value) is IPNetwork:
  66. model_dict[key] = str(value)
  67. else:
  68. # Convert ArrayFields to CSV strings
  69. if type(instance._meta.get_field(key)) is ArrayField:
  70. model_dict[key] = ','.join([str(v) for v in value])
  71. return model_dict
  72. #
  73. # Permissions management
  74. #
  75. def add_permissions(self, *names):
  76. """
  77. Assign a set of permissions to the test user. Accepts permission names in the form <app>.<action>_<model>.
  78. """
  79. for name in names:
  80. ct, action = resolve_permission_ct(name)
  81. obj_perm = ObjectPermission(actions=[action])
  82. obj_perm.save()
  83. obj_perm.users.add(self.user)
  84. obj_perm.object_types.add(ct)
  85. #
  86. # Custom assertions
  87. #
  88. def assertHttpStatus(self, response, expected_status):
  89. """
  90. TestCase method. Provide more detail in the event of an unexpected HTTP response.
  91. """
  92. err_message = "Expected HTTP status {}; received {}: {}"
  93. self.assertEqual(response.status_code, expected_status, err_message.format(
  94. expected_status, response.status_code, getattr(response, 'data', 'No data')
  95. ))
  96. def assertInstanceEqual(self, instance, data, api=False):
  97. """
  98. Compare a model instance to a dictionary, checking that its attribute values match those specified
  99. in the dictionary.
  100. :instance: Python object instance
  101. :data: Dictionary of test data used to define the instance
  102. :api: Set to True is the data is a JSON representation of the instance
  103. """
  104. model_dict = self.model_to_dict(instance, fields=data.keys(), api=api)
  105. # Omit any dictionary keys which are not instance attributes
  106. relevant_data = {
  107. k: v for k, v in data.items() if hasattr(instance, k)
  108. }
  109. self.assertDictEqual(model_dict, relevant_data)
  110. #
  111. # Convenience methods
  112. #
  113. @classmethod
  114. def create_tags(cls, *names):
  115. """
  116. Create and return a Tag instance for each name given.
  117. """
  118. tags = [Tag(name=name, slug=slugify(name)) for name in names]
  119. Tag.objects.bulk_create(tags)
  120. return tags
  121. class ModelTestCase(TestCase):
  122. """
  123. Parent class for TestCases which deal with models.
  124. """
  125. model = None
  126. def _get_queryset(self):
  127. """
  128. Return a base queryset suitable for use in test methods. Call unrestricted() if RestrictedQuerySet is in use.
  129. """
  130. if hasattr(self.model.objects, 'restrict'):
  131. return self.model.objects.unrestricted()
  132. return self.model.objects.all()
  133. #
  134. # UI Tests
  135. #
  136. class ModelViewTestCase(ModelTestCase):
  137. """
  138. Base TestCase for model views. Subclass to test individual views.
  139. """
  140. def _get_base_url(self):
  141. """
  142. Return the base format for a URL for the test's model. Override this to test for a model which belongs
  143. to a different app (e.g. testing Interfaces within the virtualization app).
  144. """
  145. return '{}:{}_{{}}'.format(
  146. self.model._meta.app_label,
  147. self.model._meta.model_name
  148. )
  149. def _get_url(self, action, instance=None):
  150. """
  151. Return the URL name for a specific action and optionally a specific instance
  152. """
  153. url_format = self._get_base_url()
  154. # If no instance was provided, assume we don't need a unique identifier
  155. if instance is None:
  156. return reverse(url_format.format(action))
  157. # Attempt to resolve using slug as the unique identifier if one exists
  158. if hasattr(self.model, 'slug'):
  159. try:
  160. return reverse(url_format.format(action), kwargs={'slug': instance.slug})
  161. except NoReverseMatch:
  162. pass
  163. # Default to using the numeric PK to retrieve the URL for an object
  164. return reverse(url_format.format(action), kwargs={'pk': instance.pk})
  165. class ViewTestCases:
  166. """
  167. We keep any TestCases with test_* methods inside a class to prevent unittest from trying to run them.
  168. """
  169. class GetObjectViewTestCase(ModelViewTestCase):
  170. """
  171. Retrieve a single instance.
  172. """
  173. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  174. def test_get_object_anonymous(self):
  175. # Make the request as an unauthenticated user
  176. self.client.logout()
  177. response = self.client.get(self._get_queryset().first().get_absolute_url())
  178. self.assertHttpStatus(response, 200)
  179. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  180. def test_get_object_without_permission(self):
  181. instance = self._get_queryset().first()
  182. # Try GET without permission
  183. with disable_warnings('django.request'):
  184. self.assertHttpStatus(self.client.get(instance.get_absolute_url()), 403)
  185. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  186. def test_get_object_with_permission(self):
  187. instance = self._get_queryset().first()
  188. # Add model-level permission
  189. obj_perm = ObjectPermission(
  190. actions=['view']
  191. )
  192. obj_perm.save()
  193. obj_perm.users.add(self.user)
  194. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  195. # Try GET with model-level permission
  196. self.assertHttpStatus(self.client.get(instance.get_absolute_url()), 200)
  197. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  198. def test_get_object_with_constrained_permission(self):
  199. instance1, instance2 = self._get_queryset().all()[:2]
  200. # Add object-level permission
  201. obj_perm = ObjectPermission(
  202. constraints={'pk': instance1.pk},
  203. actions=['view']
  204. )
  205. obj_perm.save()
  206. obj_perm.users.add(self.user)
  207. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  208. # Try GET to permitted object
  209. self.assertHttpStatus(self.client.get(instance1.get_absolute_url()), 200)
  210. # Try GET to non-permitted object
  211. self.assertHttpStatus(self.client.get(instance2.get_absolute_url()), 404)
  212. class GetObjectChangelogViewTestCase(ModelViewTestCase):
  213. """
  214. View the changelog for an instance.
  215. """
  216. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  217. def test_get_object_changelog(self):
  218. url = self._get_url('changelog', self._get_queryset().first())
  219. response = self.client.get(url)
  220. self.assertHttpStatus(response, 200)
  221. class CreateObjectViewTestCase(ModelViewTestCase):
  222. """
  223. Create a single new instance.
  224. :form_data: Data to be used when creating a new object.
  225. """
  226. form_data = {}
  227. def test_create_object_without_permission(self):
  228. # Try GET without permission
  229. with disable_warnings('django.request'):
  230. self.assertHttpStatus(self.client.get(self._get_url('add')), 403)
  231. # Try POST without permission
  232. request = {
  233. 'path': self._get_url('add'),
  234. 'data': post_data(self.form_data),
  235. }
  236. response = self.client.post(**request)
  237. with disable_warnings('django.request'):
  238. self.assertHttpStatus(response, 403)
  239. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  240. def test_create_object_with_permission(self):
  241. initial_count = self._get_queryset().count()
  242. # Assign unconstrained permission
  243. obj_perm = ObjectPermission(
  244. actions=['add']
  245. )
  246. obj_perm.save()
  247. obj_perm.users.add(self.user)
  248. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  249. # Try GET with model-level permission
  250. self.assertHttpStatus(self.client.get(self._get_url('add')), 200)
  251. # Try POST with model-level permission
  252. request = {
  253. 'path': self._get_url('add'),
  254. 'data': post_data(self.form_data),
  255. }
  256. self.assertHttpStatus(self.client.post(**request), 302)
  257. self.assertEqual(initial_count + 1, self._get_queryset().count())
  258. self.assertInstanceEqual(self._get_queryset().order_by('pk').last(), self.form_data)
  259. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  260. def test_create_object_with_constrained_permission(self):
  261. initial_count = self._get_queryset().count()
  262. # Assign constrained permission
  263. obj_perm = ObjectPermission(
  264. constraints={'pk': 0}, # Dummy permission to deny all
  265. actions=['add']
  266. )
  267. obj_perm.save()
  268. obj_perm.users.add(self.user)
  269. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  270. # Try GET with object-level permission
  271. self.assertHttpStatus(self.client.get(self._get_url('add')), 200)
  272. # Try to create an object (not permitted)
  273. request = {
  274. 'path': self._get_url('add'),
  275. 'data': post_data(self.form_data),
  276. }
  277. self.assertHttpStatus(self.client.post(**request), 200)
  278. self.assertEqual(initial_count, self._get_queryset().count()) # Check that no object was created
  279. # Update the ObjectPermission to allow creation
  280. obj_perm.constraints = {'pk__gt': 0}
  281. obj_perm.save()
  282. # Try to create an object (permitted)
  283. request = {
  284. 'path': self._get_url('add'),
  285. 'data': post_data(self.form_data),
  286. }
  287. self.assertHttpStatus(self.client.post(**request), 302)
  288. self.assertEqual(initial_count + 1, self._get_queryset().count())
  289. self.assertInstanceEqual(self._get_queryset().order_by('pk').last(), self.form_data)
  290. class EditObjectViewTestCase(ModelViewTestCase):
  291. """
  292. Edit a single existing instance.
  293. :form_data: Data to be used when updating the first existing object.
  294. """
  295. form_data = {}
  296. def test_edit_object_without_permission(self):
  297. instance = self._get_queryset().first()
  298. # Try GET without permission
  299. with disable_warnings('django.request'):
  300. self.assertHttpStatus(self.client.get(self._get_url('edit', instance)), 403)
  301. # Try POST without permission
  302. request = {
  303. 'path': self._get_url('edit', instance),
  304. 'data': post_data(self.form_data),
  305. }
  306. with disable_warnings('django.request'):
  307. self.assertHttpStatus(self.client.post(**request), 403)
  308. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  309. def test_edit_object_with_permission(self):
  310. instance = self._get_queryset().first()
  311. # Assign model-level permission
  312. obj_perm = ObjectPermission(
  313. actions=['change']
  314. )
  315. obj_perm.save()
  316. obj_perm.users.add(self.user)
  317. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  318. # Try GET with model-level permission
  319. self.assertHttpStatus(self.client.get(self._get_url('edit', instance)), 200)
  320. # Try POST with model-level permission
  321. request = {
  322. 'path': self._get_url('edit', instance),
  323. 'data': post_data(self.form_data),
  324. }
  325. self.assertHttpStatus(self.client.post(**request), 302)
  326. self.assertInstanceEqual(self._get_queryset().get(pk=instance.pk), self.form_data)
  327. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  328. def test_edit_object_with_constrained_permission(self):
  329. instance1, instance2 = self._get_queryset().all()[:2]
  330. # Assign constrained permission
  331. obj_perm = ObjectPermission(
  332. constraints={'pk': instance1.pk},
  333. actions=['change']
  334. )
  335. obj_perm.save()
  336. obj_perm.users.add(self.user)
  337. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  338. # Try GET with a permitted object
  339. self.assertHttpStatus(self.client.get(self._get_url('edit', instance1)), 200)
  340. # Try GET with a non-permitted object
  341. self.assertHttpStatus(self.client.get(self._get_url('edit', instance2)), 404)
  342. # Try to edit a permitted object
  343. request = {
  344. 'path': self._get_url('edit', instance1),
  345. 'data': post_data(self.form_data),
  346. }
  347. self.assertHttpStatus(self.client.post(**request), 302)
  348. self.assertInstanceEqual(self._get_queryset().get(pk=instance1.pk), self.form_data)
  349. # Try to edit a non-permitted object
  350. request = {
  351. 'path': self._get_url('edit', instance2),
  352. 'data': post_data(self.form_data),
  353. }
  354. self.assertHttpStatus(self.client.post(**request), 404)
  355. class DeleteObjectViewTestCase(ModelViewTestCase):
  356. """
  357. Delete a single instance.
  358. """
  359. def test_delete_object_without_permission(self):
  360. instance = self._get_queryset().first()
  361. # Try GET without permission
  362. with disable_warnings('django.request'):
  363. self.assertHttpStatus(self.client.get(self._get_url('delete', instance)), 403)
  364. # Try POST without permission
  365. request = {
  366. 'path': self._get_url('delete', instance),
  367. 'data': post_data({'confirm': True}),
  368. }
  369. with disable_warnings('django.request'):
  370. self.assertHttpStatus(self.client.post(**request), 403)
  371. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  372. def test_delete_object_with_permission(self):
  373. instance = self._get_queryset().first()
  374. # Assign model-level permission
  375. obj_perm = ObjectPermission(
  376. actions=['delete']
  377. )
  378. obj_perm.save()
  379. obj_perm.users.add(self.user)
  380. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  381. # Try GET with model-level permission
  382. self.assertHttpStatus(self.client.get(self._get_url('delete', instance)), 200)
  383. # Try POST with model-level permission
  384. request = {
  385. 'path': self._get_url('delete', instance),
  386. 'data': post_data({'confirm': True}),
  387. }
  388. self.assertHttpStatus(self.client.post(**request), 302)
  389. with self.assertRaises(ObjectDoesNotExist):
  390. self._get_queryset().get(pk=instance.pk)
  391. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  392. def test_delete_object_with_constrained_permission(self):
  393. instance1, instance2 = self._get_queryset().all()[:2]
  394. # Assign object-level permission
  395. obj_perm = ObjectPermission(
  396. constraints={'pk': instance1.pk},
  397. actions=['delete']
  398. )
  399. obj_perm.save()
  400. obj_perm.users.add(self.user)
  401. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  402. # Try GET with a permitted object
  403. self.assertHttpStatus(self.client.get(self._get_url('delete', instance1)), 200)
  404. # Try GET with a non-permitted object
  405. self.assertHttpStatus(self.client.get(self._get_url('delete', instance2)), 404)
  406. # Try to delete a permitted object
  407. request = {
  408. 'path': self._get_url('delete', instance1),
  409. 'data': post_data({'confirm': True}),
  410. }
  411. self.assertHttpStatus(self.client.post(**request), 302)
  412. with self.assertRaises(ObjectDoesNotExist):
  413. self._get_queryset().get(pk=instance1.pk)
  414. # Try to delete a non-permitted object
  415. request = {
  416. 'path': self._get_url('delete', instance2),
  417. 'data': post_data({'confirm': True}),
  418. }
  419. self.assertHttpStatus(self.client.post(**request), 404)
  420. self.assertTrue(self._get_queryset().filter(pk=instance2.pk).exists())
  421. class ListObjectsViewTestCase(ModelViewTestCase):
  422. """
  423. Retrieve multiple instances.
  424. """
  425. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  426. def test_list_objects_anonymous(self):
  427. # Make the request as an unauthenticated user
  428. self.client.logout()
  429. response = self.client.get(self._get_url('list'))
  430. self.assertHttpStatus(response, 200)
  431. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  432. def test_list_objects_without_permission(self):
  433. # Try GET without permission
  434. with disable_warnings('django.request'):
  435. self.assertHttpStatus(self.client.get(self._get_url('list')), 403)
  436. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  437. def test_list_objects_with_permission(self):
  438. # Add model-level permission
  439. obj_perm = ObjectPermission(
  440. actions=['view']
  441. )
  442. obj_perm.save()
  443. obj_perm.users.add(self.user)
  444. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  445. # Try GET with model-level permission
  446. self.assertHttpStatus(self.client.get(self._get_url('list')), 200)
  447. # Built-in CSV export
  448. if hasattr(self.model, 'csv_headers'):
  449. response = self.client.get('{}?export'.format(self._get_url('list')))
  450. self.assertHttpStatus(response, 200)
  451. self.assertEqual(response.get('Content-Type'), 'text/csv')
  452. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  453. def test_list_objects_with_constrained_permission(self):
  454. instance1, instance2 = self._get_queryset().all()[:2]
  455. # Add object-level permission
  456. obj_perm = ObjectPermission(
  457. constraints={'pk': instance1.pk},
  458. actions=['view']
  459. )
  460. obj_perm.save()
  461. obj_perm.users.add(self.user)
  462. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  463. # Try GET with object-level permission
  464. response = self.client.get(self._get_url('list'))
  465. self.assertHttpStatus(response, 200)
  466. content = str(response.content)
  467. if hasattr(self.model, 'name'):
  468. self.assertIn(instance1.name, content)
  469. self.assertNotIn(instance2.name, content)
  470. else:
  471. self.assertIn(instance1.get_absolute_url(), content)
  472. self.assertNotIn(instance2.get_absolute_url(), content)
  473. class CreateMultipleObjectsViewTestCase(ModelViewTestCase):
  474. """
  475. Create multiple instances using a single form. Expects the creation of three new instances by default.
  476. :bulk_create_count: The number of objects expected to be created (default: 3).
  477. :bulk_create_data: A dictionary of data to be used for bulk object creation.
  478. """
  479. bulk_create_count = 3
  480. bulk_create_data = {}
  481. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  482. def test_create_multiple_objects_without_permission(self):
  483. request = {
  484. 'path': self._get_url('add'),
  485. 'data': post_data(self.bulk_create_data),
  486. }
  487. # Try POST without permission
  488. with disable_warnings('django.request'):
  489. self.assertHttpStatus(self.client.post(**request), 403)
  490. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  491. def test_create_multiple_objects_with_permission(self):
  492. initial_count = self._get_queryset().count()
  493. request = {
  494. 'path': self._get_url('add'),
  495. 'data': post_data(self.bulk_create_data),
  496. }
  497. # Assign non-constrained permission
  498. obj_perm = ObjectPermission(
  499. actions=['add'],
  500. )
  501. obj_perm.save()
  502. obj_perm.users.add(self.user)
  503. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  504. # Bulk create objects
  505. response = self.client.post(**request)
  506. self.assertHttpStatus(response, 302)
  507. self.assertEqual(initial_count + self.bulk_create_count, self._get_queryset().count())
  508. for instance in self._get_queryset().order_by('-pk')[:self.bulk_create_count]:
  509. self.assertInstanceEqual(instance, self.bulk_create_data)
  510. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  511. def test_create_multiple_objects_with_constrained_permission(self):
  512. initial_count = self._get_queryset().count()
  513. request = {
  514. 'path': self._get_url('add'),
  515. 'data': post_data(self.bulk_create_data),
  516. }
  517. # Assign constrained permission
  518. obj_perm = ObjectPermission(
  519. actions=['add'],
  520. constraints={'pk': 0} # Dummy constraint to deny all
  521. )
  522. obj_perm.save()
  523. obj_perm.users.add(self.user)
  524. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  525. # Attempt to make the request with unmet constraints
  526. self.assertHttpStatus(self.client.post(**request), 200)
  527. self.assertEqual(self._get_queryset().count(), initial_count)
  528. # Update the ObjectPermission to allow creation
  529. obj_perm.constraints = {'pk__gt': 0} # Dummy constraint to allow all
  530. obj_perm.save()
  531. response = self.client.post(**request)
  532. self.assertHttpStatus(response, 302)
  533. self.assertEqual(initial_count + self.bulk_create_count, self._get_queryset().count())
  534. for instance in self._get_queryset().order_by('-pk')[:self.bulk_create_count]:
  535. self.assertInstanceEqual(instance, self.bulk_create_data)
  536. class BulkImportObjectsViewTestCase(ModelViewTestCase):
  537. """
  538. Create multiple instances from imported data.
  539. :csv_data: A list of CSV-formatted lines (starting with the headers) to be used for bulk object import.
  540. """
  541. csv_data = ()
  542. def _get_csv_data(self):
  543. return '\n'.join(self.csv_data)
  544. def test_bulk_import_objects_without_permission(self):
  545. data = {
  546. 'csv': self._get_csv_data(),
  547. }
  548. # Test GET without permission
  549. with disable_warnings('django.request'):
  550. self.assertHttpStatus(self.client.get(self._get_url('import')), 403)
  551. # Try POST without permission
  552. response = self.client.post(self._get_url('import'), data)
  553. with disable_warnings('django.request'):
  554. self.assertHttpStatus(response, 403)
  555. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  556. def test_bulk_import_objects_with_permission(self):
  557. initial_count = self._get_queryset().count()
  558. data = {
  559. 'csv': self._get_csv_data(),
  560. }
  561. # Assign model-level permission
  562. obj_perm = ObjectPermission(
  563. actions=['add']
  564. )
  565. obj_perm.save()
  566. obj_perm.users.add(self.user)
  567. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  568. # Try GET with model-level permission
  569. self.assertHttpStatus(self.client.get(self._get_url('import')), 200)
  570. # Test POST with permission
  571. self.assertHttpStatus(self.client.post(self._get_url('import'), data), 200)
  572. self.assertEqual(self._get_queryset().count(), initial_count + len(self.csv_data) - 1)
  573. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  574. def test_bulk_import_objects_with_constrained_permission(self):
  575. initial_count = self._get_queryset().count()
  576. data = {
  577. 'csv': self._get_csv_data(),
  578. }
  579. # Assign constrained permission
  580. obj_perm = ObjectPermission(
  581. constraints={'pk': 0}, # Dummy permission to deny all
  582. actions=['add']
  583. )
  584. obj_perm.save()
  585. obj_perm.users.add(self.user)
  586. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  587. # Attempt to import non-permitted objects
  588. self.assertHttpStatus(self.client.post(self._get_url('import'), data), 200)
  589. self.assertEqual(self._get_queryset().count(), initial_count)
  590. # Update permission constraints
  591. obj_perm.constraints = {'pk__gt': 0} # Dummy permission to allow all
  592. obj_perm.save()
  593. # Import permitted objects
  594. self.assertHttpStatus(self.client.post(self._get_url('import'), data), 200)
  595. self.assertEqual(self._get_queryset().count(), initial_count + len(self.csv_data) - 1)
  596. class BulkEditObjectsViewTestCase(ModelViewTestCase):
  597. """
  598. Edit multiple instances.
  599. :bulk_edit_data: A dictionary of data to be used when bulk editing a set of objects. This data should differ
  600. from that used for initial object creation within setUpTestData().
  601. """
  602. bulk_edit_data = {}
  603. def test_bulk_edit_objects_without_permission(self):
  604. pk_list = self._get_queryset().values_list('pk', flat=True)[:3]
  605. data = {
  606. 'pk': pk_list,
  607. '_apply': True, # Form button
  608. }
  609. # Test GET without permission
  610. with disable_warnings('django.request'):
  611. self.assertHttpStatus(self.client.get(self._get_url('bulk_edit')), 403)
  612. # Try POST without permission
  613. with disable_warnings('django.request'):
  614. self.assertHttpStatus(self.client.post(self._get_url('bulk_edit'), data), 403)
  615. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  616. def test_bulk_edit_objects_with_permission(self):
  617. pk_list = self._get_queryset().values_list('pk', flat=True)[:3]
  618. data = {
  619. 'pk': pk_list,
  620. '_apply': True, # Form button
  621. }
  622. # Append the form data to the request
  623. data.update(post_data(self.bulk_edit_data))
  624. # Assign model-level permission
  625. obj_perm = ObjectPermission(
  626. actions=['change']
  627. )
  628. obj_perm.save()
  629. obj_perm.users.add(self.user)
  630. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  631. # Try POST with model-level permission
  632. self.assertHttpStatus(self.client.post(self._get_url('bulk_edit'), data), 302)
  633. for i, instance in enumerate(self._get_queryset().filter(pk__in=pk_list)):
  634. self.assertInstanceEqual(instance, self.bulk_edit_data)
  635. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  636. def test_bulk_edit_objects_with_constrained_permission(self):
  637. pk_list = list(self._get_queryset().values_list('pk', flat=True)[:3])
  638. data = {
  639. 'pk': pk_list,
  640. '_apply': True, # Form button
  641. }
  642. # Append the form data to the request
  643. data.update(post_data(self.bulk_edit_data))
  644. # Dynamically determine a constraint that will *not* be matched by the updated objects.
  645. attr_name = list(self.bulk_edit_data.keys())[0]
  646. field = self.model._meta.get_field(attr_name)
  647. value = field.value_from_object(self._get_queryset().first())
  648. # Assign constrained permission
  649. obj_perm = ObjectPermission(
  650. constraints={attr_name: value},
  651. actions=['change']
  652. )
  653. obj_perm.save()
  654. obj_perm.users.add(self.user)
  655. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  656. # Attempt to bulk edit permitted objects into a non-permitted state
  657. response = self.client.post(self._get_url('bulk_edit'), data)
  658. self.assertHttpStatus(response, 200)
  659. # Update permission constraints
  660. obj_perm.constraints = {'pk__gt': 0}
  661. obj_perm.save()
  662. # Bulk edit permitted objects
  663. self.assertHttpStatus(self.client.post(self._get_url('bulk_edit'), data), 302)
  664. for i, instance in enumerate(self._get_queryset().filter(pk__in=pk_list)):
  665. self.assertInstanceEqual(instance, self.bulk_edit_data)
  666. class BulkDeleteObjectsViewTestCase(ModelViewTestCase):
  667. """
  668. Delete multiple instances.
  669. """
  670. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  671. def test_bulk_delete_objects_without_permission(self):
  672. pk_list = self._get_queryset().values_list('pk', flat=True)[:3]
  673. data = {
  674. 'pk': pk_list,
  675. 'confirm': True,
  676. '_confirm': True, # Form button
  677. }
  678. # Test GET without permission
  679. with disable_warnings('django.request'):
  680. self.assertHttpStatus(self.client.get(self._get_url('bulk_delete')), 403)
  681. # Try POST without permission
  682. with disable_warnings('django.request'):
  683. self.assertHttpStatus(self.client.post(self._get_url('bulk_delete'), data), 403)
  684. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  685. def test_bulk_delete_objects_with_permission(self):
  686. pk_list = self._get_queryset().values_list('pk', flat=True)
  687. data = {
  688. 'pk': pk_list,
  689. 'confirm': True,
  690. '_confirm': True, # Form button
  691. }
  692. # Assign unconstrained permission
  693. obj_perm = ObjectPermission(
  694. actions=['delete']
  695. )
  696. obj_perm.save()
  697. obj_perm.users.add(self.user)
  698. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  699. # Try POST with model-level permission
  700. self.assertHttpStatus(self.client.post(self._get_url('bulk_delete'), data), 302)
  701. self.assertEqual(self._get_queryset().count(), 0)
  702. @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
  703. def test_bulk_delete_objects_with_constrained_permission(self):
  704. initial_count = self._get_queryset().count()
  705. pk_list = self._get_queryset().values_list('pk', flat=True)
  706. data = {
  707. 'pk': pk_list,
  708. 'confirm': True,
  709. '_confirm': True, # Form button
  710. }
  711. # Assign constrained permission
  712. obj_perm = ObjectPermission(
  713. constraints={'pk': 0}, # Dummy permission to deny all
  714. actions=['delete']
  715. )
  716. obj_perm.save()
  717. obj_perm.users.add(self.user)
  718. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  719. # Attempt to bulk delete non-permitted objects
  720. self.assertHttpStatus(self.client.post(self._get_url('bulk_delete'), data), 302)
  721. self.assertEqual(self._get_queryset().count(), initial_count)
  722. # Update permission constraints
  723. obj_perm.constraints = {'pk__gt': 0} # Dummy permission to allow all
  724. obj_perm.save()
  725. # Bulk delete permitted objects
  726. self.assertHttpStatus(self.client.post(self._get_url('bulk_delete'), data), 302)
  727. self.assertEqual(self._get_queryset().count(), 0)
  728. class BulkRenameObjectsViewTestCase(ModelViewTestCase):
  729. """
  730. Rename multiple instances.
  731. """
  732. rename_data = {
  733. 'find': '(.*)',
  734. 'replace': '\\1X', # Append an X to the original value
  735. 'use_regex': True,
  736. }
  737. def test_bulk_rename_objects_without_permission(self):
  738. pk_list = self._get_queryset().values_list('pk', flat=True)[:3]
  739. data = {
  740. 'pk': pk_list,
  741. '_apply': True, # Form button
  742. }
  743. data.update(self.rename_data)
  744. # Test GET without permission
  745. with disable_warnings('django.request'):
  746. self.assertHttpStatus(self.client.get(self._get_url('bulk_rename')), 403)
  747. # Try POST without permission
  748. with disable_warnings('django.request'):
  749. self.assertHttpStatus(self.client.post(self._get_url('bulk_rename'), data), 403)
  750. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  751. def test_bulk_rename_objects_with_permission(self):
  752. objects = self._get_queryset().all()[:3]
  753. pk_list = [obj.pk for obj in objects]
  754. data = {
  755. 'pk': pk_list,
  756. '_apply': True, # Form button
  757. }
  758. data.update(self.rename_data)
  759. # Assign model-level permission
  760. obj_perm = ObjectPermission(
  761. actions=['change']
  762. )
  763. obj_perm.save()
  764. obj_perm.users.add(self.user)
  765. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  766. # Try POST with model-level permission
  767. self.assertHttpStatus(self.client.post(self._get_url('bulk_rename'), data), 302)
  768. for i, instance in enumerate(self._get_queryset().filter(pk__in=pk_list)):
  769. self.assertEqual(instance.name, f'{objects[i].name}X')
  770. @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
  771. def test_bulk_rename_objects_with_constrained_permission(self):
  772. objects = self._get_queryset().all()[:3]
  773. pk_list = [obj.pk for obj in objects]
  774. data = {
  775. 'pk': pk_list,
  776. '_apply': True, # Form button
  777. }
  778. data.update(self.rename_data)
  779. # Assign constrained permission
  780. obj_perm = ObjectPermission(
  781. constraints={'name__regex': '[^X]$'},
  782. actions=['change']
  783. )
  784. obj_perm.save()
  785. obj_perm.users.add(self.user)
  786. obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
  787. # Attempt to bulk edit permitted objects into a non-permitted state
  788. response = self.client.post(self._get_url('bulk_rename'), data)
  789. self.assertHttpStatus(response, 200)
  790. # Update permission constraints
  791. obj_perm.constraints = {'pk__gt': 0}
  792. obj_perm.save()
  793. # Bulk rename permitted objects
  794. self.assertHttpStatus(self.client.post(self._get_url('bulk_rename'), data), 302)
  795. for i, instance in enumerate(self._get_queryset().filter(pk__in=pk_list)):
  796. self.assertEqual(instance.name, f'{objects[i].name}X')
  797. class PrimaryObjectViewTestCase(
  798. GetObjectViewTestCase,
  799. GetObjectChangelogViewTestCase,
  800. CreateObjectViewTestCase,
  801. EditObjectViewTestCase,
  802. DeleteObjectViewTestCase,
  803. ListObjectsViewTestCase,
  804. BulkImportObjectsViewTestCase,
  805. BulkEditObjectsViewTestCase,
  806. BulkDeleteObjectsViewTestCase,
  807. ):
  808. """
  809. TestCase suitable for testing all standard View functions for primary objects
  810. """
  811. maxDiff = None
  812. class OrganizationalObjectViewTestCase(
  813. GetObjectChangelogViewTestCase,
  814. CreateObjectViewTestCase,
  815. EditObjectViewTestCase,
  816. DeleteObjectViewTestCase,
  817. ListObjectsViewTestCase,
  818. BulkImportObjectsViewTestCase,
  819. BulkDeleteObjectsViewTestCase,
  820. ):
  821. """
  822. TestCase suitable for all organizational objects
  823. """
  824. maxDiff = None
  825. class DeviceComponentTemplateViewTestCase(
  826. EditObjectViewTestCase,
  827. DeleteObjectViewTestCase,
  828. CreateMultipleObjectsViewTestCase,
  829. BulkEditObjectsViewTestCase,
  830. BulkRenameObjectsViewTestCase,
  831. BulkDeleteObjectsViewTestCase,
  832. ):
  833. """
  834. TestCase suitable for testing device component template models (ConsolePortTemplates, InterfaceTemplates, etc.)
  835. """
  836. maxDiff = None
  837. class DeviceComponentViewTestCase(
  838. GetObjectViewTestCase,
  839. GetObjectChangelogViewTestCase,
  840. EditObjectViewTestCase,
  841. DeleteObjectViewTestCase,
  842. ListObjectsViewTestCase,
  843. CreateMultipleObjectsViewTestCase,
  844. BulkImportObjectsViewTestCase,
  845. BulkEditObjectsViewTestCase,
  846. BulkRenameObjectsViewTestCase,
  847. BulkDeleteObjectsViewTestCase,
  848. ):
  849. """
  850. TestCase suitable for testing device component models (ConsolePorts, Interfaces, etc.)
  851. """
  852. maxDiff = None