Преглед изворни кода

move check out of signals.py - check on logging

Arthur пре 9 часа
родитељ
комит
c7a04168c8

+ 0 - 7
netbox/core/signals.py

@@ -1,5 +1,4 @@
 import logging
-import sys
 from threading import local
 
 from django.contrib.contenttypes.models import ContentType
@@ -90,8 +89,6 @@ def update_object_types(sender, **kwargs):
 # Used to track received signals per object
 _signals_received = local()
 
-RUNNING_TESTS = 'test' in sys.argv
-
 
 @receiver(pre_save)
 def snapshot_unsnapshotted_object(sender, instance, raw=False, using=None, **kwargs):
@@ -151,10 +148,6 @@ def handle_changed_object(sender, instance, **kwargs):
         OBJECT_DELETED: ObjectChangeActionChoices.ACTION_DELETE,
     }[event_type]
     objectchange = instance.to_objectchange(action)
-    # Under test, fail any update recorded without a prechange snapshot
-    if RUNNING_TESTS and event_type == OBJECT_UPDATED and not m2m_changed:
-        from utilities.testing.changelog import assert_prechange_snapshot
-        assert_prechange_snapshot(instance)
     object_change_id = None
     # If this is a many-to-many field change, check for a previous ObjectChange instance recorded
     # for this object by this request and update it

+ 3 - 12
netbox/core/tests/test_signals.py

@@ -92,7 +92,7 @@ class HandleChangedObjectSignalTestCase(TestCase):
         site = Site.objects.create(name='Site 1', slug='site-1')
         request = _build_request(self.user)
 
-        with event_tracking(request), self.assertRaisesMessage(AssertionError, 'without calling snapshot()'):
+        with event_tracking(request), self.assertRaisesMessage(AssertionError, 'No pre-change snapshot taken'):
             site.description = 'updated'
             site.save()
 
@@ -101,11 +101,7 @@ class HandleChangedObjectSignalTestCase(TestCase):
         site = Site.objects.create(name='Site 1', slug='site-1')
         request = _build_request(self.user)
 
-        with (
-            patch('core.signals.RUNNING_TESTS', False),
-            self.assertLogs('netbox.models.features', level='WARNING'),
-            event_tracking(request),
-        ):
+        with self.assertLogs('netbox.models.features', level='WARNING'), event_tracking(request):
             site.description = 'first'
             site.save()
             site.description = 'second'
@@ -124,11 +120,7 @@ class HandleChangedObjectSignalTestCase(TestCase):
         site = Site.objects.create(name='Site 1', slug='site-1')
         request = _build_request(self.user)
 
-        with (
-            patch('core.signals.RUNNING_TESTS', False),
-            self.assertLogs('netbox.models.features', level='WARNING'),
-            event_tracking(request),
-        ):
+        with self.assertLogs('netbox.models.features', level='WARNING'), event_tracking(request):
             site.description = 'updated'
             site.save()
             snapshots = events_queue.get()[f'dcim.site:{site.pk}']['snapshots']
@@ -666,7 +658,6 @@ class HandleChangedObjectDirectHandlerTestCase(SimpleTestCase):
         instance = SimpleNamespace(
             pk=123,
             _meta=SimpleNamespace(model_name='device'),
-            _prechange_snapshot={'name': 'Device 1'},
             refresh_from_db=MagicMock(),
         )
         instance.to_objectchange = MagicMock(return_value=objectchange)

+ 3 - 15
netbox/dcim/tests/test_models.py

@@ -3520,11 +3520,7 @@ class CableDisconnectChangeLoggingTestCase(TestCase):
     @tag('regression')  # Ref: #23617
     def test_resaving_new_cable_records_current_prechange(self):
         # The creation snapshot must not be reused, so the re-save falls back to the database
-        with (
-            patch('core.signals.RUNNING_TESTS', False),
-            self.assertLogs('netbox.models.features', level='WARNING'),
-            event_tracking(self._request()),
-        ):
+        with self.assertLogs('netbox.models.features', level='WARNING'), event_tracking(self._request()):
             cable = Cable(a_terminations=[self.interface1], b_terminations=[self.interface2])
             cable.save()
             cable.label = 'x'
@@ -3538,11 +3534,7 @@ class CableDisconnectChangeLoggingTestCase(TestCase):
     @tag('regression')  # Ref: #23617
     def test_resaving_new_cable_with_preset_pk_records_current_prechange(self):
         # A new Cable with a preset pk (e.g. restored by deserialize_object()) must also discard its creation snapshot
-        with (
-            patch('core.signals.RUNNING_TESTS', False),
-            self.assertLogs('netbox.models.features', level='WARNING'),
-            event_tracking(self._request()),
-        ):
+        with self.assertLogs('netbox.models.features', level='WARNING'), event_tracking(self._request()):
             cable = Cable(pk=1000000, a_terminations=[self.interface1], b_terminations=[self.interface2])
             cable.save()
             cable.label = 'x'
@@ -3559,11 +3551,7 @@ class CableDisconnectChangeLoggingTestCase(TestCase):
         old_b_termination = CableTermination.objects.get(cable=cable, cable_end=CableEndChoices.SIDE_B)
 
         request = self._request()
-        with (
-            patch('core.signals.RUNNING_TESTS', False),
-            self.assertLogs('netbox.models.features', level='WARNING') as logs,
-            event_tracking(request),
-        ):
+        with self.assertLogs('netbox.models.features', level='WARNING') as logs, event_tracking(request):
             cable = Cable.objects.get(pk=cable.pk)
             cable.label = 'x'
             cable.b_terminations = [self.interface3]

+ 26 - 1
netbox/netbox/configuration_testing.py

@@ -3,6 +3,8 @@
 #  only. It is not intended for production use.                   #
 ###################################################################
 
+import logging
+
 ALLOWED_HOSTS = ['*']
 
 DATABASES = {
@@ -52,7 +54,30 @@ API_TOKEN_PEPPERS = {
     1: 'TEST-VALUE-DO-NOT-USE-TEST-VALUE-DO-NOT-USE-TEST-VALUE-DO-NOT-USE',
 }
 
+
+class MissingSnapshotHandler(logging.Handler):
+    """
+    Fail any update saved without calling snapshot() first, which would otherwise fall back to reading the
+    pre-change data from the database.
+    """
+    def emit(self, record):
+        if record.funcName == 'snapshot_from_db':
+            raise AssertionError(record.getMessage())
+
+
 LOGGING = {
     'version': 1,
-    'disable_existing_loggers': True
+    'disable_existing_loggers': True,
+    'handlers': {
+        'missing_snapshot': {
+            '()': MissingSnapshotHandler,
+        },
+    },
+    'loggers': {
+        'netbox.models.features': {
+            'handlers': ['missing_snapshot'],
+            'level': 'WARNING',
+            'propagate': False,
+        },
+    },
 }

+ 0 - 16
netbox/utilities/testing/changelog.py

@@ -1,16 +0,0 @@
-__all__ = (
-    'assert_prechange_snapshot',
-)
-
-
-def assert_prechange_snapshot(instance):
-    """
-    Raise AssertionError if an update to `instance` is being recorded without a prechange snapshot.
-    """
-    # A snapshot read from the database by the pre_save fallback does not count
-    if hasattr(instance, '_prechange_snapshot') and not instance.__dict__.get('_prechange_snapshot_from_db'):
-        return
-    raise AssertionError(
-        f"{instance._meta.label} {instance.pk} was updated without calling snapshot() first; its change record "
-        f"will have no prechange data."
-    )