audit: fix error when trying to save models with UUID as PK
This commit is contained in:
parent
865435fb25
commit
387f3c981f
|
@ -1,5 +1,6 @@
|
|||
"""passbook audit models"""
|
||||
from enum import Enum
|
||||
from uuid import UUID
|
||||
from inspect import getmodule, stack
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
|
@ -32,11 +33,15 @@ def sanitize_dict(source: Dict[Any, Any]) -> Dict[Any, Any]:
|
|||
source[key] = sanitize_dict(value)
|
||||
elif isinstance(value, models.Model):
|
||||
model_content_type = ContentType.objects.get_for_model(value)
|
||||
source[key] = {
|
||||
"app": model_content_type.app_label,
|
||||
"name": model_content_type.model,
|
||||
"pk": value.pk,
|
||||
}
|
||||
source[key] = sanitize_dict(
|
||||
{
|
||||
"app": model_content_type.app_label,
|
||||
"name": model_content_type.model,
|
||||
"pk": value.pk,
|
||||
}
|
||||
)
|
||||
elif isinstance(value, UUID):
|
||||
source[key] = value.hex
|
||||
return source
|
||||
|
||||
|
||||
|
|
|
@ -2,7 +2,9 @@
|
|||
|
||||
from django.test import TestCase
|
||||
from guardian.shortcuts import get_anonymous_user
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
|
||||
from passbook.core.models import Policy
|
||||
from passbook.audit.models import Event, EventAction
|
||||
|
||||
|
||||
|
@ -11,6 +13,21 @@ class TestAuditEvent(TestCase):
|
|||
|
||||
def test_new_with_model(self):
|
||||
"""Create a new Event passing a model as kwarg"""
|
||||
event = Event.new(EventAction.CUSTOM, model=get_anonymous_user())
|
||||
event.save()
|
||||
self.assertIsNotNone(event.pk)
|
||||
event = Event.new(EventAction.CUSTOM, test={"model": get_anonymous_user()})
|
||||
event.save() # We save to ensure nothing is un-saveable
|
||||
model_content_type = ContentType.objects.get_for_model(get_anonymous_user())
|
||||
self.assertEqual(
|
||||
event.context.get("test").get("model").get("app"),
|
||||
model_content_type.app_label,
|
||||
)
|
||||
|
||||
def test_new_with_uuid_model(self):
|
||||
"""Create a new Event passing a model (with UUID PK) as kwarg"""
|
||||
temp_model = Policy.objects.create()
|
||||
event = Event.new(EventAction.CUSTOM, model=temp_model)
|
||||
event.save() # We save to ensure nothing is un-saveable
|
||||
model_content_type = ContentType.objects.get_for_model(temp_model)
|
||||
self.assertEqual(
|
||||
event.context.get("model").get("app"), model_content_type.app_label
|
||||
)
|
||||
self.assertEqual(event.context.get("model").get("pk"), temp_model.pk.hex)
|
||||
|
|
Reference in a new issue