test_signals.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import uuid
  2. from unittest.mock import patch
  3. from django.contrib.contenttypes.models import ContentType
  4. from django.core.exceptions import ValidationError
  5. from django.test import RequestFactory, TestCase, override_settings
  6. from core.events import JOB_COMPLETED, JOB_STARTED, OBJECT_DELETED, OBJECT_UPDATED
  7. from core.models import Job, ObjectType
  8. from core.signals import job_end, job_start
  9. from dcim.choices import SiteStatusChoices
  10. from dcim.models import Region, Site
  11. from extras import signals
  12. from extras.choices import CustomFieldTypeChoices, EventRuleActionChoices
  13. from extras.models import CustomField, EventRule, Notification, Subscription, Tag, Webhook
  14. from extras.validators import CustomValidator
  15. from netbox.context_managers import event_tracking
  16. from users.models import User
  17. from utilities.exceptions import AbortRequest
  18. def _build_request(user=None):
  19. request = RequestFactory().get('/')
  20. request.id = uuid.uuid4()
  21. request.user = user
  22. return request
  23. class CustomFieldRenameSignalTestCase(TestCase):
  24. """
  25. Verify extras.signals.handle_cf_renamed migrates stored custom-field data when a
  26. CustomField is renamed.
  27. """
  28. def test_renaming_custom_field_moves_object_data(self):
  29. site_type = ContentType.objects.get_for_model(Site)
  30. cf = CustomField.objects.create(
  31. name='asset_tag',
  32. type=CustomFieldTypeChoices.TYPE_TEXT,
  33. )
  34. cf.object_types.set([site_type])
  35. site = Site.objects.create(name='Site 1', slug='site-1', custom_field_data={'asset_tag': 'A123'})
  36. cf.name = 'inventory_id'
  37. cf.save()
  38. site.refresh_from_db()
  39. self.assertNotIn('asset_tag', site.custom_field_data)
  40. self.assertEqual(site.custom_field_data['inventory_id'], 'A123')
  41. def test_creating_custom_field_does_not_attempt_rename(self):
  42. # Should not raise — newly-created custom fields have no prior name to migrate.
  43. site_type = ContentType.objects.get_for_model(Site)
  44. cf = CustomField.objects.create(
  45. name='cf1',
  46. type=CustomFieldTypeChoices.TYPE_TEXT,
  47. )
  48. cf.object_types.set([site_type])
  49. class CustomFieldDeletedSignalTestCase(TestCase):
  50. """
  51. Verify extras.signals.handle_cf_deleted strips stale data from associated objects
  52. when a CustomField is deleted.
  53. """
  54. def test_deleting_custom_field_clears_object_data(self):
  55. site_type = ContentType.objects.get_for_model(Site)
  56. cf = CustomField.objects.create(
  57. name='asset_tag',
  58. type=CustomFieldTypeChoices.TYPE_TEXT,
  59. )
  60. cf.object_types.set([site_type])
  61. site = Site.objects.create(name='Site 1', slug='site-1', custom_field_data={'asset_tag': 'A123'})
  62. cf.delete()
  63. site.refresh_from_db()
  64. self.assertNotIn('asset_tag', site.custom_field_data)
  65. class CustomFieldObjectTypeSignalTestCase(TestCase):
  66. """
  67. Verify extras.signals.handle_cf_object_types_changed populates or strips default values when a
  68. CustomField's object_types m2m changes.
  69. """
  70. def test_adding_object_type_populates_default_value(self):
  71. site_type = ContentType.objects.get_for_model(Site)
  72. Site.objects.create(name='Site 1', slug='site-1')
  73. cf = CustomField.objects.create(
  74. name='asset_tag',
  75. type=CustomFieldTypeChoices.TYPE_TEXT,
  76. default='UNTAGGED',
  77. )
  78. cf.object_types.set([site_type])
  79. site = Site.objects.get(slug='site-1')
  80. self.assertEqual(site.custom_field_data.get('asset_tag'), 'UNTAGGED')
  81. def test_removing_object_type_clears_stored_data(self):
  82. site_type = ContentType.objects.get_for_model(Site)
  83. cf = CustomField.objects.create(
  84. name='asset_tag',
  85. type=CustomFieldTypeChoices.TYPE_TEXT,
  86. )
  87. cf.object_types.set([site_type])
  88. site = Site.objects.create(name='Site 1', slug='site-1', custom_field_data={'asset_tag': 'A123'})
  89. cf.object_types.remove(site_type)
  90. site.refresh_from_db()
  91. self.assertNotIn('asset_tag', site.custom_field_data)
  92. class RunSaveValidatorsSignalTestCase(TestCase):
  93. """
  94. Verify extras.signals.run_save_validators invokes any configured CUSTOM_VALIDATORS
  95. when a model emits the post_clean signal.
  96. """
  97. @override_settings(CUSTOM_VALIDATORS={'dcim.site': [CustomValidator({'name': {'eq': 'allowed'}})]})
  98. def test_validation_failure_raises_validation_error(self):
  99. with self.assertRaises(ValidationError):
  100. Site(name='blocked', slug='blocked', status=SiteStatusChoices.STATUS_ACTIVE).clean()
  101. @override_settings(CUSTOM_VALIDATORS={'dcim.site': [CustomValidator({'name': {'eq': 'allowed'}})]})
  102. def test_validation_success_does_not_raise(self):
  103. Site(name='allowed', slug='allowed', status=SiteStatusChoices.STATUS_ACTIVE).clean()
  104. class ValidateAssignedTagsSignalTestCase(TestCase):
  105. """
  106. Verify extras.signals.validate_assigned_tags rejects Tags that are restricted to
  107. object types incompatible with the target object.
  108. """
  109. def test_restricted_tag_blocks_incompatible_object(self):
  110. region_type = ContentType.objects.get_for_model(Region)
  111. tag = Tag.objects.create(name='RegionOnly', slug='regiononly')
  112. tag.object_types.set([region_type])
  113. site = Site.objects.create(name='Site 1', slug='site-1')
  114. with self.assertRaises(AbortRequest):
  115. site.tags.add(tag)
  116. def test_restricted_tag_allows_compatible_object(self):
  117. site_type = ContentType.objects.get_for_model(Site)
  118. tag = Tag.objects.create(name='SiteOnly', slug='siteonly')
  119. tag.object_types.set([site_type])
  120. site = Site.objects.create(name='Site 1', slug='site-1')
  121. site.tags.add(tag)
  122. self.assertEqual(list(site.tags.all()), [tag])
  123. def test_unrestricted_tag_is_always_permitted(self):
  124. tag = Tag.objects.create(name='Anywhere', slug='anywhere')
  125. site = Site.objects.create(name='Site 1', slug='site-1')
  126. site.tags.add(tag)
  127. self.assertEqual(list(site.tags.all()), [tag])
  128. class JobEventRulesSignalTestCase(TestCase):
  129. """
  130. Verify extras.signals.process_job_start_event_rules and process_job_end_event_rules
  131. invoke any EventRule registered for JOB_STARTED / JOB_COMPLETED on the sender's
  132. object_type.
  133. """
  134. @classmethod
  135. def setUpTestData(cls):
  136. cls.site_type = ObjectType.objects.get_for_model(Site)
  137. webhook = Webhook.objects.create(
  138. name='Webhook',
  139. payload_url='http://localhost/',
  140. secret='secret',
  141. )
  142. webhook_type = ObjectType.objects.get_for_model(Webhook)
  143. cls.start_rule = EventRule.objects.create(
  144. name='Job Start Rule',
  145. event_types=[JOB_STARTED],
  146. action_type=EventRuleActionChoices.WEBHOOK,
  147. action_object_type=webhook_type,
  148. action_object_id=webhook.pk,
  149. )
  150. cls.start_rule.object_types.set([cls.site_type])
  151. cls.end_rule = EventRule.objects.create(
  152. name='Job End Rule',
  153. event_types=[JOB_COMPLETED],
  154. action_type=EventRuleActionChoices.WEBHOOK,
  155. action_object_type=webhook_type,
  156. action_object_id=webhook.pk,
  157. )
  158. cls.end_rule.object_types.set([cls.site_type])
  159. def _create_job(self):
  160. return Job.objects.create(
  161. object_type=self.site_type,
  162. name='test-job',
  163. job_id=uuid.uuid4(),
  164. data={'foo': 1},
  165. )
  166. def test_job_start_filters_to_matching_event_rules(self):
  167. sender = self._create_job()
  168. with patch('extras.signals.process_event_rules') as process_event_rules:
  169. job_start.send(sender=sender)
  170. process_event_rules.assert_called_once()
  171. rules_qs = process_event_rules.call_args.args[0]
  172. self.assertEqual(list(rules_qs.values_list('pk', flat=True)), [self.start_rule.pk])
  173. def test_job_end_filters_to_matching_event_rules(self):
  174. sender = self._create_job()
  175. with patch('extras.signals.process_event_rules') as process_event_rules:
  176. job_end.send(sender=sender)
  177. process_event_rules.assert_called_once()
  178. rules_qs = process_event_rules.call_args.args[0]
  179. self.assertEqual(list(rules_qs.values_list('pk', flat=True)), [self.end_rule.pk])
  180. class NotifyObjectChangedSignalTestCase(TestCase):
  181. """
  182. Verify extras.signals.notify_object_changed creates Notifications for subscribed
  183. users on object update and deletion, and skips creation otherwise.
  184. """
  185. @classmethod
  186. def setUpTestData(cls):
  187. cls.user = User.objects.create_user(username='alice', password='pw')
  188. def test_creating_object_does_not_create_notifications(self):
  189. # Subscribe a user to the object BEFORE invoking the handler so the
  190. # discriminating branch (created=True early return) is genuinely
  191. # exercised. Without the subscription this assertion passes trivially.
  192. site = Site.objects.create(name='Site 1', slug='site-1')
  193. site_type = ContentType.objects.get_for_model(Site)
  194. Subscription.objects.create(user=self.user, object_type=site_type, object_id=site.pk)
  195. Notification.objects.all().delete()
  196. signals.notify_object_changed(sender=Site, instance=site, created=True)
  197. self.assertFalse(Notification.objects.exists())
  198. def test_updating_subscribed_object_creates_update_notification(self):
  199. site = Site.objects.create(name='Site 1', slug='site-1')
  200. site_type = ContentType.objects.get_for_model(Site)
  201. Subscription.objects.create(user=self.user, object_type=site_type, object_id=site.pk)
  202. site.description = 'updated'
  203. site.save()
  204. notification = Notification.objects.get(user=self.user)
  205. self.assertEqual(notification.object_type, site_type)
  206. self.assertEqual(notification.object_id, site.pk)
  207. self.assertEqual(notification.event_type, OBJECT_UPDATED)
  208. def test_deleting_subscribed_object_creates_delete_notification(self):
  209. site = Site.objects.create(name='Site 1', slug='site-1')
  210. site_type = ContentType.objects.get_for_model(Site)
  211. Subscription.objects.create(user=self.user, object_type=site_type, object_id=site.pk)
  212. site.delete()
  213. notification = Notification.objects.get(user=self.user)
  214. self.assertEqual(notification.event_type, OBJECT_DELETED)
  215. def test_updating_unsubscribed_object_creates_no_notification(self):
  216. site = Site.objects.create(name='Site 1', slug='site-1')
  217. site.description = 'updated'
  218. site.save()
  219. self.assertEqual(Notification.objects.count(), 0)
  220. def test_updating_object_replaces_existing_notification(self):
  221. site = Site.objects.create(name='Site 1', slug='site-1')
  222. site_type = ContentType.objects.get_for_model(Site)
  223. Subscription.objects.create(user=self.user, object_type=site_type, object_id=site.pk)
  224. # Trigger two updates within a single request; only one Notification should remain.
  225. request = _build_request(user=self.user)
  226. with event_tracking(request):
  227. site.snapshot()
  228. site.description = 'first'
  229. site.save()
  230. site.snapshot()
  231. site.description = 'second'
  232. site.save()
  233. self.assertEqual(
  234. Notification.objects.filter(user=self.user, object_type=site_type, object_id=site.pk).count(),
  235. 1,
  236. )