如何在 Django 管理中测试重写函数?
How can I test overriden function in Django admin?
我在 admin
模块
中覆盖了函数
@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)
如何测试?
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)
# ???
我会对更改视图本身进行 post,这应该会触发更改的记录。
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())
...
我在 admin
模块
@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)
如何测试?
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)
# ???
我会对更改视图本身进行 post,这应该会触发更改的记录。
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())
...