Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Properly handle post delete in transactions #308

Merged
merged 1 commit into from
Oct 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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, "pre_save")


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
Loading