1

I have overriden function in admin module

@admin.register(Donation)
class DonationAdmin(admin.ModelAdmin):
    def log_change(self, request, object, message):
        log_obj = super().log_change(request, object, message)

        name_map = {name: value.label for name, value
                    in DonationForm.base_fields.items()}

        extended_log = ''
        if message:
            changed_fields = message[0].get('changed').get('fields')
            extended_log = {key: value for key, value in request.POST.items()
                            if key in changed_fields}
            extended_log = self.get_humanize_values(extended_log)

            extended_log = dict(
                zip(
                    map(lambda x: name_map[x], extended_log.keys()),
                    extended_log.values()
                )
            )

        return AdditionalLogEntry.objects.create(
            entry=log_obj, extended_log=extended_log)

How can I test it?

class DonationAdminTestCase(TestCase):
    def setUp(self) -> None:
        self.user = UserFactory()
        self.donation = DonationFactory()
        self.donation_admin = DonationAdmin(model=Donation, admin_site=AdminSite())

    def test_log_change(self) -> None:
        self.user.is_staff = True
        self.user.save()
        self.client.force_login(self.user)
        # ???
unknown
  • 252
  • 3
  • 12
  • 37
  • I would post to the change view itself to make a change to an object and then test whether there is an additional log entry. – dirkgroten Feb 11 '20 at 13:21

1 Answers1

1

I would make a post to the change view itself, which should trigger the logging of the change.

change_url = reverse('admin:myapp_donation_change', args=(self.donation.id,))
data = {...}  # dictionary with all the data required to make a successful change
self.client.post(change_url, data=data)
self.assertEqual(1, AdditionalLogEntry.objects.count())
...
dirkgroten
  • 20,112
  • 2
  • 29
  • 42
  • Thanks. I understand what you mean. An interesting solution. Tell me, what should the `data` dict look like to initiate a `log_change` call? E.g. the table `Donation` has a column `Note` (`CharField`), which I want to change. – unknown Feb 11 '20 at 13:44
  • It needs to contain all the fields that can be changed on a `Donation` object and are required, but basically you want it to contain all fields of the form. The easiest is to actually make a change in your browser and look at the POST data in your browser dev tools (network tab). `{'note': 'some_string'}` would be part of it, but if other fields are required, the form won't validate and therefore no change (and no `log_change()`) will be made. – dirkgroten Feb 11 '20 at 14:31