Skip to content

Instantly share code, notes, and snippets.

@doubleo2
Created May 20, 2014 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doubleo2/02205644ceff908361d9 to your computer and use it in GitHub Desktop.
Save doubleo2/02205644ceff908361d9 to your computer and use it in GitHub Desktop.
from django.db import transaction
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import ActionLogEntry
from .models import EventLogEntry
@receiver(post_save, sender=ActionLogEntry, dispatch_uid="event_logger")
def log_action_event(sender, instance, **kwargs):
try:
with transaction.atomic():
EventLogEntry.objects.get(my_model_id=instance.my_model_id)
except EventLogEntry.DoesNotExist:
from app.models import MyModel
m = MyModel.objects.get(pk=instance.my_model_id)
EventLogEntry.objects.create(my_model=m)
from django.test import TestCase
from .models import ActionLogEntry
from .models import EventLogEntry
class TestSignalReceivers(TestCase):
def test_action_triggers_event_log(self):
# Create an instance of my_model
m = MyModel.objects.create()
# Verify that no event logs exist for this instance
self.assertEqual(EventLogEntry.objects.filter(my_model=m).count(), 0)
# Log an event
EventLogEntry.objects.create(my_model=m, event="foo")
# Log an action
ActionLogEntry.objects.create(my_model=m, event="bar")
# Verify that an EventLogEntry was also created for the first action
self.assertEqual(EventLogEntry.objects.filter(my_model=m).count(), 2,
"Initial action did not generate an EventLogEntry entry")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment