How to write unit test for admin save function
Asked Answered
M

1

7

I have customized save_model admin i.e.

class MyModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        # some more question code here
        obj.save()

Now, I would like to test MyModelAdmin save_model function. I tried posting like:

class MyModelAdminSaveTestCase(TestCase):
    def setUp(self):

        # setup code here

    def test_save_model(self):
        '''Test add employee
        '''
        my_obj = {
            'name': 'Tester',
            'address': '12 test Test',
            'city': 'New York',
            'state': 'NY',
        }

        self.client.login(username=self.user, password=self.pwd)
        response = self.client.post(reverse('admin:mymodel_mymodel_add'), my_obj, follow=True)

        self.assertEqual(response.status_code, 200)

        self.assertEqual(MyModel.objects.count(), 1)

However, test fails:

self.assertEqual(MyModel.objects.count(), 1)
AssertionError: 0 != 1
Marilla answered 24/11, 2016 at 16:11 Comment(3)
can you write full code example? especially of this view : admin:mymodel_mymodel_addPapotto
actually you shouldn't follow redirects during save - 200 in your case might indicate some error in form (maybe some field is missing/invalid) - set follow=False and expect 302 status code.Vitrics
Print response.content in the test - that will show you whether there are any errors on the page. If the response is too long, you could try to get the form errors directly with something like response.context[' 'adminform'].form.errors.Ingrid
M
0

My answer is 5 years late, but maybe it helps someone else.

To access django admin users need to have is_staff=True. Non-staff users are redirected to login page (which is probably what happened in the example above).

Also, users need to have enough permissions to access specific admin pages (easy fix for this is to set is_superuser=True if you don't need to test permissions).

So client setup like this would have probably fixed the issue:

user = User.objects.create_superuser(username='super', 
                                     email='[email protected]', 
                                     password='pass')
client.login(username=user.username, password='pass')
# now you can access django admin

You can inspect response.context_data to get more information if something goes wrong.

But there's also a cleaner way to test save_model in my opinion, see this answer.

Music answered 5/4, 2022 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.