Tests for models with/without get_additional_data defined

This commit is contained in:
Ann Paul 2015-06-01 11:01:40 -07:00
parent 72cdde6864
commit 5fb006b226
2 changed files with 52 additions and 2 deletions

View file

@ -82,8 +82,33 @@ class SimpleExcludeModel(models.Model):
history = AuditlogHistoryField()
class AdditionDataIncludedModel(models.Model):
"""
A model where get_additional_data is defined which allows for logging extra
information about the model in JSON
"""
label = models.CharField(max_length=100)
text = models.TextField(blank=True)
related = models.ForeignKey(SimpleModel)
history = AuditlogHistoryField()
def get_additional_data(self):
"""
Returns JSON that captures a snapshot of additional details of the
model instance. This method, if defined, is accessed by auditlog
manager and added to each logentry instance on creation.
"""
object_details = {
'related_model_id': self.related.id,
'related_model_text': self.related.text
}
return object_details
auditlog.register(SimpleModel)
auditlog.register(AltPrimaryKeyModel)
auditlog.register(ProxyModel)
auditlog.register(SimpleIncludeModel, include_fields=['label', ])
auditlog.register(SimpleExcludeModel, exclude_fields=['label', ])
auditlog.register(AdditionDataIncludedModel)

View file

@ -6,8 +6,8 @@ from django.http import HttpResponse
from django.test import TestCase, RequestFactory
from auditlog.middleware import AuditlogMiddleware
from auditlog.models import LogEntry
from testapp.models import SimpleModel, AltPrimaryKeyModel, ProxyModel, \
SimpleIncludeModel, SimpleExcludeModel
from testapp.models import (SimpleModel, AltPrimaryKeyModel, ProxyModel,
SimpleIncludeModel, SimpleExcludeModel, AdditionDataIncludedModel,)
class SimpleModelTest(TestCase):
@ -178,3 +178,28 @@ class SimpeExcludeModelTest(TestCase):
sem.text = 'Short text'
sem.save()
self.assertTrue(sem.history.count() == 2, msg="There are two log entries")
class AdditionalDataModelTest(TestCase):
"""Log additional data if get_additional_data is defined in the model"""
def test_model_without_additional_data(self):
obj_wo_additional_data = SimpleModel.objects.create(text='No additional '
'data')
obj_log_entry = obj_wo_additional_data.history.get()
self.assertIsNone(obj_log_entry.additional_data)
def test_model_with_additional_data(self):
related_model = SimpleModel.objects.create(text='Log my reference')
obj_with_additional_data = AdditionDataIncludedModel(
label='Additional data to log entries', related=related_model)
obj_with_additional_data.save()
self.assertTrue(obj_with_additional_data.history.count() == 1,
msg="There is 1 log entry")
log_entry = obj_with_additional_data.history.get()
self.assertIsNotNone(log_entry.additional_data)
extra_data = log_entry.additional_data
self.assertTrue(extra_data['related_model_text'] == related_model.text,
msg="Related model's text is logged")
self.assertTrue(extra_data['related_model_id'] == related_model.id,
msg="Related model's id is logged")