Skip to content

Commit

Permalink
Properly handle the post delete signal in transactions
Browse files Browse the repository at this point in the history
If the model changes are committed in a transaction,
at the time when the post delete signal is handled
instance.pk returns None.

Store the instance's ID beforehand so that it is available
when creating the CRUDEvent.
  • Loading branch information
mschoettle authored and jheld committed Oct 9, 2024
1 parent 348d991 commit 5888702
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
10 changes: 7 additions & 3 deletions easyaudit/signals/crud_flows.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@ def get_current_user_details():
return user_id, user_pk_as_string


def log_event(event_type, instance, object_json_repr, **kwargs):
def log_event(event_type, instance, object_id, object_json_repr, **kwargs):
user_id, user_pk_as_string = get_current_user_details()
with transaction.atomic(using=DATABASE_ALIAS):
audit_logger.crud(
{
"content_type_id": ContentType.objects.get_for_model(instance).id,
"datetime": timezone.now(),
"event_type": event_type,
"object_id": instance.pk,
"object_id": object_id,
"object_json_repr": object_json_repr or "",
"object_repr": str(instance),
"user_id": user_id,
Expand All @@ -70,6 +70,7 @@ def pre_save_crud_flow(instance, object_json_repr, changed_fields):
log_event(
CRUDEvent.UPDATE,
instance,
instance.pk,
object_json_repr,
changed_fields=changed_fields,
)
Expand All @@ -82,6 +83,7 @@ def post_save_crud_flow(instance, object_json_repr):
log_event(
CRUDEvent.CREATE,
instance,
instance.pk,
object_json_repr,
)
except Exception:
Expand All @@ -102,18 +104,20 @@ def m2m_changed_crud_flow( # noqa: PLR0913
log_event(
event_type,
instance,
instance.pk,
object_json_repr,
changed_fields=changed_fields,
)
except Exception:
handle_flow_exception(instance, "m2m_changed")


def post_delete_crud_flow(instance, object_json_repr):
def post_delete_crud_flow(instance, object_id, object_json_repr):
try:
log_event(
CRUDEvent.DELETE,
instance,
object_id,
object_json_repr,
)

Expand Down
3 changes: 3 additions & 0 deletions easyaudit/signals/model_signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,10 +241,13 @@ def post_delete(sender, instance, using, **kwargs):

with transaction.atomic(using=using):
object_json_repr = serializers.serialize("json", [instance])
# instance.pk returns None if the changes are performed within a transaction
object_id = instance.pk

crud_flow = partial(
post_delete_crud_flow,
instance=instance,
object_id=object_id,
object_json_repr=object_json_repr,
)
if getattr(settings, "TEST", False):
Expand Down
23 changes: 23 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from asgiref.sync import sync_to_async
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.db import transaction
from django.urls import reverse
from django.utils.version import get_version
from pytest_django.asserts import assertInHTML
Expand Down Expand Up @@ -189,6 +190,28 @@ def test_delete(self, model):
)
assert crud_event_qs.count() == 2

@pytest.mark.django_db(transaction=True)
def test_delete_transaction(self, model, settings):
settings.TEST = False

with transaction.atomic():
obj = model.objects.create()
model.objects.all().delete()

crud_event_qs = CRUDEvent.objects.filter(
object_id=obj.id,
content_type=ContentType.objects.get_for_model(obj),
event_type=CRUDEvent.CREATE,
)
assert crud_event_qs.count() == 1

crud_event_qs = CRUDEvent.objects.filter(
object_id=obj.id,
content_type=ContentType.objects.get_for_model(obj),
event_type=CRUDEvent.DELETE,
)
assert crud_event_qs.count() == 1

@pytest.mark.usefixtures("_audit_logger")
def test_propagate_exceptions(self, model, settings):
with pytest.raises(ValueError, match="Test exception"):
Expand Down

4 comments on commit 5888702

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage

Coverage Report •
FileStmtsMissCoverMissing
easyaudit/signals
   crud_flows.py61690%77–78, 111–112, 124–125
   model_signals.py1222778%42–46, 82, 129–131, 137, 174–179, 185, 193–211, 232–234, 260–261
TOTAL83022173% 

Tests Skipped Failures Errors Time
53 0 💤 0 ❌ 0 🔥 3.684s ⏱️

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage

Coverage Report •
FileStmtsMissCoverMissing
easyaudit/signals
   crud_flows.py61690%77–78, 111–112, 124–125
   model_signals.py1222778%42–46, 82, 129–131, 137, 174–179, 185, 193–211, 232–234, 260–261
TOTAL83222173% 

Tests Skipped Failures Errors Time
53 0 💤 0 ❌ 0 🔥 3.708s ⏱️

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage

Coverage Report •
FileStmtsMissCoverMissing
easyaudit/signals
   crud_flows.py61690%77–78, 111–112, 124–125
   model_signals.py1222778%42–46, 82, 129–131, 137, 174–179, 185, 193–211, 232–234, 260–261
TOTAL83022173% 

Tests Skipped Failures Errors Time
53 0 💤 0 ❌ 0 🔥 4.057s ⏱️

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage

Coverage Report •
FileStmtsMissCoverMissing
easyaudit/signals
   crud_flows.py61690%77–78, 111–112, 124–125
   model_signals.py1222778%42–46, 82, 129–131, 137, 174–179, 185, 193–211, 232–234, 260–261
TOTAL83222173% 

Tests Skipped Failures Errors Time
53 0 💤 0 ❌ 0 🔥 4.715s ⏱️

Please sign in to comment.